#!/usr/bin/env node var gs=Object.create;var $n=Object.defineProperty;var ps=Object.getOwnPropertyDescriptor;var ms=Object.getOwnPropertyNames;var _s=Object.getPrototypeOf,ys=Object.prototype.hasOwnProperty;var m=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var ws=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ms(t))!ys.call(e,i)&&i!==n&&$n(e,i,{get:()=>t[i],enumerable:!(r=ps(t,i))||r.enumerable});return e};var J=(e,t,n)=>(n=e!=null?gs(_s(e)):{},ws(t||!e||!e.__esModule?$n(n,"default",{value:e,enumerable:!0}):n,e));var Tt=m((wc,Un)=>{Un.exports={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8}});var Dn=m((bc,Nn)=>{var bs=Tt();function On(e){this.mode=bs.MODE_8BIT_BYTE,this.data=e}On.prototype={getLength:function(){return this.data.length},write:function(e){for(var t=0;t{var z={glog:function(e){if(e<1)throw new Error("glog("+e+")");return z.LOG_TABLE[e]},gexp:function(e){for(;e<0;)e+=255;for(;e>=256;)e-=255;return z.EXP_TABLE[e]},EXP_TABLE:new Array(256),LOG_TABLE:new Array(256)};for(x=0;x<8;x++)z.EXP_TABLE[x]=1<{var ae=It();function je(e,t){if(e.length===void 0)throw new Error(e.length+"/"+t);for(var n=0;n{Wn.exports={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7}});var Yn=m((Cc,Gn)=>{var F=Tt(),zn=Ct(),Es=It(),X=Hn(),R={PATTERN_POSITION_TABLE:[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],G15:1335,G18:7973,G15_MASK:21522,getBCHTypeInfo:function(e){for(var t=e<<10;R.getBCHDigit(t)-R.getBCHDigit(R.G15)>=0;)t^=R.G15<=0;)t^=R.G18<>>=1;return t},getPatternPosition:function(e){return R.PATTERN_POSITION_TABLE[e-1]},getMask:function(e,t,n){switch(e){case X.PATTERN000:return(t+n)%2===0;case X.PATTERN001:return t%2===0;case X.PATTERN010:return n%3===0;case X.PATTERN011:return(t+n)%3===0;case X.PATTERN100:return(Math.floor(t/2)+Math.floor(n/3))%2===0;case X.PATTERN101:return t*n%2+t*n%3===0;case X.PATTERN110:return(t*n%2+t*n%3)%2===0;case X.PATTERN111:return(t*n%3+(t+n)%2)%2===0;default:throw new Error("bad maskPattern:"+e)}},getErrorCorrectPolynomial:function(e){for(var t=new zn([1],0),n=0;n5&&(n+=3+o-5)}for(r=0;r{Kn.exports={L:1,M:0,Q:3,H:2}});var jn=m((Ac,Vn)=>{var Qe=kt();function Y(e,t){this.totalCount=e,this.dataCount=t}Y.RS_BLOCK_TABLE=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]];Y.getRSBlocks=function(e,t){var n=Y.getRsBlockTable(e,t);if(n===void 0)throw new Error("bad rs block @ typeNumber:"+e+"/errorCorrectLevel:"+t);for(var r=n.length/3,i=[],o=0;o{function Qn(){this.buffer=[],this.length=0}Qn.prototype={get:function(e){var t=Math.floor(e/8);return(this.buffer[t]>>>7-e%8&1)==1},put:function(e,t){for(var n=0;n>>t-n-1&1)==1)},getLengthInBits:function(){return this.length},putBit:function(e){var t=Math.floor(this.length/8);this.buffer.length<=t&&this.buffer.push(0),e&&(this.buffer[t]|=128>>>this.length%8),this.length++}};Jn.exports=Qn});var nr=m((Lc,tr)=>{var Ts=Dn(),Z=Yn(),Is=Ct(),Zn=jn(),er=Xn();function K(e,t){this.typeNumber=e,this.errorCorrectLevel=t,this.modules=null,this.moduleCount=0,this.dataCache=null,this.dataList=[]}K.prototype={addData:function(e){var t=new Ts(e);this.dataList.push(t),this.dataCache=null},isDark:function(e,t){if(e<0||this.moduleCount<=e||t<0||this.moduleCount<=t)throw new Error(e+","+t);return this.modules[e][t]},getModuleCount:function(){return this.moduleCount},make:function(){if(this.typeNumber<1){var e=1;for(e=1;e<40;e++){for(var t=Zn.getRSBlocks(e,this.errorCorrectLevel),n=new er,r=0,i=0;i=7&&this.setupTypeNumber(e),this.dataCache===null&&(this.dataCache=K.createData(this.typeNumber,this.errorCorrectLevel,this.dataList)),this.mapData(this.dataCache,t)},setupPositionProbePattern:function(e,t){for(var n=-1;n<=7;n++)if(!(e+n<=-1||this.moduleCount<=e+n))for(var r=-1;r<=7;r++)t+r<=-1||this.moduleCount<=t+r||(0<=n&&n<=6&&(r===0||r===6)||0<=r&&r<=6&&(n===0||n===6)||2<=n&&n<=4&&2<=r&&r<=4?this.modules[e+n][t+r]=!0:this.modules[e+n][t+r]=!1)},getBestMaskPattern:function(){for(var e=0,t=0,n=0;n<8;n++){this.makeImpl(!0,n);var r=Z.getLostPoint(this);(n===0||e>r)&&(e=r,t=n)}return t},createMovieClip:function(e,t,n){var r=e.createEmptyMovieClip(t,n),i=1;this.make();for(var o=0;o>r&1)===1,this.modules[Math.floor(r/3)][r%3+this.moduleCount-8-3]=n;for(var i=0;i<18;i++)n=!e&&(t>>i&1)===1,this.modules[i%3+this.moduleCount-8-3][Math.floor(i/3)]=n},setupTypeInfo:function(e,t){for(var n=this.errorCorrectLevel<<3|t,r=Z.getBCHTypeInfo(n),i,o=0;o<15;o++)i=!e&&(r>>o&1)===1,o<6?this.modules[o][8]=i:o<8?this.modules[o+1][8]=i:this.modules[this.moduleCount-15+o][8]=i;for(var s=0;s<15;s++)i=!e&&(r>>s&1)===1,s<8?this.modules[8][this.moduleCount-s-1]=i:s<9?this.modules[8][15-s-1+1]=i:this.modules[8][15-s-1]=i;this.modules[this.moduleCount-8][8]=!e},mapData:function(e,t){for(var n=-1,r=this.moduleCount-1,i=7,o=0,s=this.moduleCount-1;s>0;s-=2)for(s===6&&s--;;){for(var a=0;a<2;a++)if(this.modules[r][s-a]===null){var l=!1;o>>i&1)===1);var u=Z.getMask(t,r,s-a);u&&(l=!l),this.modules[r][s-a]=l,i--,i===-1&&(o++,i=7)}if(r+=n,r<0||this.moduleCount<=r){r-=n,n=-n;break}}}};K.PAD0=236;K.PAD1=17;K.createData=function(e,t,n){for(var r=Zn.getRSBlocks(e,t),i=new er,o=0;oa*8)throw new Error("code length overflow. ("+i.getLengthInBits()+">"+a*8+")");for(i.getLengthInBits()+4<=a*8&&i.put(0,4);i.getLengthInBits()%8!==0;)i.putBit(!1);for(;!(i.getLengthInBits()>=a*8||(i.put(K.PAD0,8),i.getLengthInBits()>=a*8));)i.put(K.PAD1,8);return K.createBytes(i,r)};K.createBytes=function(e,t){for(var n=0,r=0,i=0,o=new Array(t.length),s=new Array(t.length),a=0;a=0?g.get(_):0}}for(var y=0,w=0;w{var Cs=nr(),rr=kt(),ks="\x1B[40m \x1B[0m",Je="\x1B[47m \x1B[0m",As=function(e){return e?ks:Je},At=function(e){return{times:function(t){return new Array(t).join(e)}}},Ss=function(e,t){for(var n=new Array(e),r=0;r{ti.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var ee=m(ce=>{var Wt,Ja=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];ce.getSymbolSize=function(t){if(!t)throw new Error('"version" cannot be null or undefined');if(t<1||t>40)throw new Error('"version" should be in range from 1 to 40');return t*4+17};ce.getSymbolTotalCodewords=function(t){return Ja[t]};ce.getBCHDigit=function(e){let t=0;for(;e!==0;)t++,e>>>=1;return t};ce.setToSJISFunction=function(t){if(typeof t!="function")throw new Error('"toSJISFunc" is not a valid function.');Wt=t};ce.isKanjiModeEnabled=function(){return typeof Wt<"u"};ce.toSJIS=function(t){return Wt(t)}});var st=m(W=>{W.L={bit:1};W.M={bit:0};W.Q={bit:3};W.H={bit:2};function Xa(e){if(typeof e!="string")throw new Error("Param is not a string");switch(e.toLowerCase()){case"l":case"low":return W.L;case"m":case"medium":return W.M;case"q":case"quartile":return W.Q;case"h":case"high":return W.H;default:throw new Error("Unknown EC Level: "+e)}}W.isValid=function(t){return t&&typeof t.bit<"u"&&t.bit>=0&&t.bit<4};W.from=function(t,n){if(W.isValid(t))return t;try{return Xa(t)}catch{return n}}});var ii=m((Uc,ri)=>{function ni(){this.buffer=[],this.length=0}ni.prototype={get:function(e){let t=Math.floor(e/8);return(this.buffer[t]>>>7-e%8&1)===1},put:function(e,t){for(let n=0;n>>t-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(e){let t=Math.floor(this.length/8);this.buffer.length<=t&&this.buffer.push(0),e&&(this.buffer[t]|=128>>>this.length%8),this.length++}};ri.exports=ni});var si=m((Oc,oi)=>{function Ue(e){if(!e||e<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=e,this.data=new Uint8Array(e*e),this.reservedBit=new Uint8Array(e*e)}Ue.prototype.set=function(e,t,n,r){let i=e*this.size+t;this.data[i]=n,r&&(this.reservedBit[i]=!0)};Ue.prototype.get=function(e,t){return this.data[e*this.size+t]};Ue.prototype.xor=function(e,t,n){this.data[e*this.size+t]^=n};Ue.prototype.isReserved=function(e,t){return this.reservedBit[e*this.size+t]};oi.exports=Ue});var ai=m(at=>{var Za=ee().getSymbolSize;at.getRowColCoords=function(t){if(t===1)return[];let n=Math.floor(t/7)+2,r=Za(t),i=r===145?26:Math.ceil((r-13)/(2*n-2))*2,o=[r-7];for(let s=1;s{var el=ee().getSymbolSize,li=7;ui.getPositions=function(t){let n=el(t);return[[0,0],[n-li,0],[0,n-li]]}});var fi=m(k=>{k.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var fe={N1:3,N2:3,N3:40,N4:10};k.isValid=function(t){return t!=null&&t!==""&&!isNaN(t)&&t>=0&&t<=7};k.from=function(t){return k.isValid(t)?parseInt(t,10):void 0};k.getPenaltyN1=function(t){let n=t.size,r=0,i=0,o=0,s=null,a=null;for(let l=0;l=5&&(r+=fe.N1+(i-5)),s=c,i=1),c=t.get(u,l),c===a?o++:(o>=5&&(r+=fe.N1+(o-5)),a=c,o=1)}i>=5&&(r+=fe.N1+(i-5)),o>=5&&(r+=fe.N1+(o-5))}return r};k.getPenaltyN2=function(t){let n=t.size,r=0;for(let i=0;i=10&&(i===1488||i===93)&&r++,o=o<<1&2047|t.get(a,s),a>=10&&(o===1488||o===93)&&r++}return r*fe.N3};k.getPenaltyN4=function(t){let n=0,r=t.data.length;for(let o=0;o{var te=st(),lt=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],ut=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];Ht.getBlocksCount=function(t,n){switch(n){case te.L:return lt[(t-1)*4+0];case te.M:return lt[(t-1)*4+1];case te.Q:return lt[(t-1)*4+2];case te.H:return lt[(t-1)*4+3];default:return}};Ht.getTotalCodewordsCount=function(t,n){switch(n){case te.L:return ut[(t-1)*4+0];case te.M:return ut[(t-1)*4+1];case te.Q:return ut[(t-1)*4+2];case te.H:return ut[(t-1)*4+3];default:return}}});var di=m(ft=>{var Oe=new Uint8Array(512),ct=new Uint8Array(256);(function(){let t=1;for(let n=0;n<255;n++)Oe[n]=t,ct[t]=n,t<<=1,t&256&&(t^=285);for(let n=255;n<512;n++)Oe[n]=Oe[n-255]})();ft.log=function(t){if(t<1)throw new Error("log("+t+")");return ct[t]};ft.exp=function(t){return Oe[t]};ft.mul=function(t,n){return t===0||n===0?0:Oe[ct[t]+ct[n]]}});var hi=m(Ne=>{var Gt=di();Ne.mul=function(t,n){let r=new Uint8Array(t.length+n.length-1);for(let i=0;i=0;){let i=r[0];for(let s=0;s{var gi=hi();function Yt(e){this.genPoly=void 0,this.degree=e,this.degree&&this.initialize(this.degree)}Yt.prototype.initialize=function(t){this.degree=t,this.genPoly=gi.generateECPolynomial(this.degree)};Yt.prototype.encode=function(t){if(!this.genPoly)throw new Error("Encoder not initialized");let n=new Uint8Array(t.length+this.degree);n.set(t);let r=gi.mod(n,this.genPoly),i=this.degree-r.length;if(i>0){let o=new Uint8Array(this.degree);return o.set(r,i),o}return r};pi.exports=Yt});var Kt=m(_i=>{_i.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}});var Vt=m(Q=>{var yi="[0-9]+",nl="[A-Z $%*+\\-./:]+",De="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";De=De.replace(/u/g,"\\u");var rl="(?:(?![A-Z0-9 $%*+\\-./:]|"+De+`)(?:.|[\r ]))+`;Q.KANJI=new RegExp(De,"g");Q.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");Q.BYTE=new RegExp(rl,"g");Q.NUMERIC=new RegExp(yi,"g");Q.ALPHANUMERIC=new RegExp(nl,"g");var il=new RegExp("^"+De+"$"),ol=new RegExp("^"+yi+"$"),sl=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");Q.testKanji=function(t){return il.test(t)};Q.testNumeric=function(t){return ol.test(t)};Q.testAlphanumeric=function(t){return sl.test(t)}});var ne=m(B=>{var al=Kt(),jt=Vt();B.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};B.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};B.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};B.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};B.MIXED={bit:-1};B.getCharCountIndicator=function(t,n){if(!t.ccBits)throw new Error("Invalid mode: "+t);if(!al.isValid(n))throw new Error("Invalid version: "+n);return n>=1&&n<10?t.ccBits[0]:n<27?t.ccBits[1]:t.ccBits[2]};B.getBestModeForData=function(t){return jt.testNumeric(t)?B.NUMERIC:jt.testAlphanumeric(t)?B.ALPHANUMERIC:jt.testKanji(t)?B.KANJI:B.BYTE};B.toString=function(t){if(t&&t.id)return t.id;throw new Error("Invalid mode")};B.isValid=function(t){return t&&t.bit&&t.ccBits};function ll(e){if(typeof e!="string")throw new Error("Param is not a string");switch(e.toLowerCase()){case"numeric":return B.NUMERIC;case"alphanumeric":return B.ALPHANUMERIC;case"kanji":return B.KANJI;case"byte":return B.BYTE;default:throw new Error("Unknown mode: "+e)}}B.from=function(t,n){if(B.isValid(t))return t;try{return ll(t)}catch{return n}}});var Ii=m(de=>{var dt=ee(),ul=zt(),wi=st(),re=ne(),Qt=Kt(),Ei=7973,bi=dt.getBCHDigit(Ei);function cl(e,t,n){for(let r=1;r<=40;r++)if(t<=de.getCapacity(r,n,e))return r}function Ti(e,t){return re.getCharCountIndicator(e,t)+4}function fl(e,t){let n=0;return e.forEach(function(r){let i=Ti(r.mode,t);n+=i+r.getBitsLength()}),n}function dl(e,t){for(let n=1;n<=40;n++)if(fl(e,n)<=de.getCapacity(n,t,re.MIXED))return n}de.from=function(t,n){return Qt.isValid(t)?parseInt(t,10):n};de.getCapacity=function(t,n,r){if(!Qt.isValid(t))throw new Error("Invalid QR Code version");typeof r>"u"&&(r=re.BYTE);let i=dt.getSymbolTotalCodewords(t),o=ul.getTotalCodewordsCount(t,n),s=(i-o)*8;if(r===re.MIXED)return s;let a=s-Ti(r,t);switch(r){case re.NUMERIC:return Math.floor(a/10*3);case re.ALPHANUMERIC:return Math.floor(a/11*2);case re.KANJI:return Math.floor(a/13);case re.BYTE:default:return Math.floor(a/8)}};de.getBestVersionForData=function(t,n){let r,i=wi.from(n,wi.M);if(Array.isArray(t)){if(t.length>1)return dl(t,i);if(t.length===0)return 1;r=t[0]}else r=t;return cl(r.mode,r.getLength(),i)};de.getEncodedBits=function(t){if(!Qt.isValid(t)||t<7)throw new Error("Invalid QR Code version");let n=t<<12;for(;dt.getBCHDigit(n)-bi>=0;)n^=Ei<{var Jt=ee(),ki=1335,hl=21522,Ci=Jt.getBCHDigit(ki);Ai.getEncodedBits=function(t,n){let r=t.bit<<3|n,i=r<<10;for(;Jt.getBCHDigit(i)-Ci>=0;)i^=ki<{var gl=ne();function we(e){this.mode=gl.NUMERIC,this.data=e.toString()}we.getBitsLength=function(t){return 10*Math.floor(t/3)+(t%3?t%3*3+1:0)};we.prototype.getLength=function(){return this.data.length};we.prototype.getBitsLength=function(){return we.getBitsLength(this.data.length)};we.prototype.write=function(t){let n,r,i;for(n=0;n+3<=this.data.length;n+=3)r=this.data.substr(n,3),i=parseInt(r,10),t.put(i,10);let o=this.data.length-n;o>0&&(r=this.data.substr(n),i=parseInt(r,10),t.put(i,o*3+1))};Li.exports=we});var vi=m((Jc,Bi)=>{var pl=ne(),Xt=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function be(e){this.mode=pl.ALPHANUMERIC,this.data=e}be.getBitsLength=function(t){return 11*Math.floor(t/2)+6*(t%2)};be.prototype.getLength=function(){return this.data.length};be.prototype.getBitsLength=function(){return be.getBitsLength(this.data.length)};be.prototype.write=function(t){let n;for(n=0;n+2<=this.data.length;n+=2){let r=Xt.indexOf(this.data[n])*45;r+=Xt.indexOf(this.data[n+1]),t.put(r,11)}this.data.length%2&&t.put(Xt.indexOf(this.data[n]),6)};Bi.exports=be});var Ri=m((Xc,Mi)=>{var ml=ne();function Ee(e){this.mode=ml.BYTE,typeof e=="string"?this.data=new TextEncoder().encode(e):this.data=new Uint8Array(e)}Ee.getBitsLength=function(t){return t*8};Ee.prototype.getLength=function(){return this.data.length};Ee.prototype.getBitsLength=function(){return Ee.getBitsLength(this.data.length)};Ee.prototype.write=function(e){for(let t=0,n=this.data.length;t{var _l=ne(),yl=ee();function Te(e){this.mode=_l.KANJI,this.data=e}Te.getBitsLength=function(t){return t*13};Te.prototype.getLength=function(){return this.data.length};Te.prototype.getBitsLength=function(){return Te.getBitsLength(this.data.length)};Te.prototype.write=function(e){let t;for(t=0;t=33088&&n<=40956)n-=33088;else if(n>=57408&&n<=60351)n-=49472;else throw new Error("Invalid SJIS character: "+this.data[t]+` Make sure your charset is UTF-8`);n=(n>>>8&255)*192+(n&255),e.put(n,13)}};Pi.exports=Te});var Ui=m((ef,Zt)=>{"use strict";var Fe={single_source_shortest_paths:function(e,t,n){var r={},i={};i[t]=0;var o=Fe.PriorityQueue.make();o.push(t,0);for(var s,a,l,u,c,f,h,g,p;!o.empty();){s=o.pop(),a=s.value,u=s.cost,c=e[a]||{};for(l in c)c.hasOwnProperty(l)&&(f=c[l],h=u+f,g=i[l],p=typeof i[l]>"u",(p||g>h)&&(i[l]=h,o.push(l,h),r[l]=a))}if(typeof n<"u"&&typeof i[n]>"u"){var _=["Could not find a path from ",t," to ",n,"."].join("");throw new Error(_)}return r},extract_shortest_path_from_predecessor_list:function(e,t){for(var n=[],r=t,i;r;)n.push(r),i=e[r],r=e[r];return n.reverse(),n},find_path:function(e,t,n){var r=Fe.single_source_shortest_paths(e,t,n);return Fe.extract_shortest_path_from_predecessor_list(r,n)},PriorityQueue:{make:function(e){var t=Fe.PriorityQueue,n={},r;e=e||{};for(r in t)t.hasOwnProperty(r)&&(n[r]=t[r]);return n.queue=[],n.sorter=e.sorter||t.default_sorter,n},default_sorter:function(e,t){return e.cost-t.cost},push:function(e,t){var n={value:e,cost:t};this.queue.push(n),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof Zt<"u"&&(Zt.exports=Fe)});var zi=m(Ie=>{var I=ne(),Di=xi(),Fi=vi(),qi=Ri(),Wi=$i(),qe=Vt(),ht=ee(),wl=Ui();function Oi(e){return unescape(encodeURIComponent(e)).length}function We(e,t,n){let r=[],i;for(;(i=e.exec(n))!==null;)r.push({data:i[0],index:i.index,mode:t,length:i[0].length});return r}function Hi(e){let t=We(qe.NUMERIC,I.NUMERIC,e),n=We(qe.ALPHANUMERIC,I.ALPHANUMERIC,e),r,i;return ht.isKanjiModeEnabled()?(r=We(qe.BYTE,I.BYTE,e),i=We(qe.KANJI,I.KANJI,e)):(r=We(qe.BYTE_KANJI,I.BYTE,e),i=[]),t.concat(n,r,i).sort(function(s,a){return s.index-a.index}).map(function(s){return{data:s.data,mode:s.mode,length:s.length}})}function en(e,t){switch(t){case I.NUMERIC:return Di.getBitsLength(e);case I.ALPHANUMERIC:return Fi.getBitsLength(e);case I.KANJI:return Wi.getBitsLength(e);case I.BYTE:return qi.getBitsLength(e)}}function bl(e){return e.reduce(function(t,n){let r=t.length-1>=0?t[t.length-1]:null;return r&&r.mode===n.mode?(t[t.length-1].data+=n.data,t):(t.push(n),t)},[])}function El(e){let t=[];for(let n=0;n{var pt=ee(),tn=st(),Il=ii(),Cl=si(),kl=ai(),Al=ci(),on=fi(),sn=zt(),Sl=mi(),gt=Ii(),Ll=Si(),xl=ne(),nn=zi();function Bl(e,t){let n=e.size,r=Al.getPositions(t);for(let i=0;i=0&&a<=6&&(l===0||l===6)||l>=0&&l<=6&&(a===0||a===6)||a>=2&&a<=4&&l>=2&&l<=4?e.set(o+a,s+l,!0,!0):e.set(o+a,s+l,!1,!0))}}function vl(e){let t=e.size;for(let n=8;n>a&1)===1,e.set(i,o,s,!0),e.set(o,i,s,!0)}function rn(e,t,n){let r=e.size,i=Ll.getEncodedBits(t,n),o,s;for(o=0;o<15;o++)s=(i>>o&1)===1,o<6?e.set(o,8,s,!0):o<8?e.set(o+1,8,s,!0):e.set(r-15+o,8,s,!0),o<8?e.set(8,r-o-1,s,!0):o<9?e.set(8,15-o-1+1,s,!0):e.set(8,15-o-1,s,!0);e.set(r-8,8,1,!0)}function Pl(e,t){let n=e.size,r=-1,i=n-1,o=7,s=0;for(let a=n-1;a>0;a-=2)for(a===6&&a--;;){for(let l=0;l<2;l++)if(!e.isReserved(i,a-l)){let u=!1;s>>o&1)===1),e.set(i,a-l,u),o--,o===-1&&(s++,o=7)}if(i+=r,i<0||n<=i){i-=r,r=-r;break}}}function $l(e,t,n){let r=new Il;n.forEach(function(l){r.put(l.mode.bit,4),r.put(l.getLength(),xl.getCharCountIndicator(l.mode,e)),l.write(r)});let i=pt.getSymbolTotalCodewords(e),o=sn.getTotalCodewordsCount(e,t),s=(i-o)*8;for(r.getLengthInBits()+4<=s&&r.put(0,4);r.getLengthInBits()%8!==0;)r.putBit(0);let a=(s-r.getLengthInBits())/8;for(let l=0;l=7&&Rl(l,t),Pl(l,s),isNaN(r)&&(r=on.getBestMask(l,rn.bind(null,l,n))),on.applyMask(r,l),rn(l,n,r),{modules:l,version:t,errorCorrectionLevel:n,maskPattern:r,segments:i}}Gi.create=function(t,n){if(typeof t>"u"||t==="")throw new Error("No input text");let r=tn.M,i,o;return typeof n<"u"&&(r=tn.from(n.errorCorrectionLevel,tn.M),i=gt.from(n.version),o=on.from(n.maskPattern),n.toSJISFunc&&pt.setToSJISFunction(n.toSJISFunc)),Ol(t,i,r,o)}});var ln=m((rf,Ki)=>{"use strict";var Nl=require("util"),Yi=require("stream"),G=Ki.exports=function(){Yi.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};Nl.inherits(G,Yi);G.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t}),process.nextTick(function(){this._process(),this._paused&&this._reads&&this._reads.length>0&&(this._paused=!1,this.emit("drain"))}.bind(this))};G.prototype.write=function(e,t){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let n;return Buffer.isBuffer(e)?n=e:n=Buffer.from(e,t||this._encoding),this._buffers.push(n),this._buffered+=n.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused};G.prototype.end=function(e,t){e&&this.write(e,t),this.writable=!1,this._buffers&&(this._buffers.length===0?this._end():(this._buffers.push(null),this._process()))};G.prototype.destroySoon=G.prototype.end;G.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};G.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};G.prototype._processReadAllowingLess=function(e){this._reads.shift();let t=this._buffers[0];t.length>e.length?(this._buffered-=e.length,this._buffers[0]=t.slice(e.length),e.func.call(this,t.slice(0,e.length))):(this._buffered-=t.length,this._buffers.shift(),e.func.call(this,t))};G.prototype._processRead=function(e){this._reads.shift();let t=0,n=0,r=Buffer.alloc(e.length);for(;t0&&this._buffers.splice(0,n),this._buffered-=e.length,e.func.call(this,r)};G.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){let e=this._reads[0];if(e.allowLess)this._processReadAllowingLess(e);else if(this._buffered>=e.length)this._processRead(e);else break}this._buffers&&!this.writable&&this._end()}catch(e){this.emit("error",e)}}});var cn=m(un=>{"use strict";var ie=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];un.getImagePasses=function(e,t){let n=[],r=e%8,i=t%8,o=(e-r)/8,s=(t-i)/8;for(let a=0;a0&&c>0&&n.push({width:u,height:c,index:a})}return n};un.getInterlaceIterator=function(e){return function(t,n,r){let i=t%ie[r].x.length,o=(t-i)/ie[r].x.length*8+ie[r].x[i],s=n%ie[r].y.length,a=(n-s)/ie[r].y.length*8+ie[r].y[s];return o*4+a*e*4}}});var fn=m((sf,Vi)=>{"use strict";Vi.exports=function(t,n,r){let i=t+n-r,o=Math.abs(i-t),s=Math.abs(i-n),a=Math.abs(i-r);return o<=s&&o<=a?t:s<=a?n:r}});var dn=m((af,Qi)=>{"use strict";var Dl=cn(),Fl=fn();function ji(e,t,n){let r=e*t;return n!==8&&(r=Math.ceil(r/(8/n))),r}var Ce=Qi.exports=function(e,t){let n=e.width,r=e.height,i=e.interlace,o=e.bpp,s=e.depth;if(this.read=t.read,this.write=t.write,this.complete=t.complete,this._imageIndex=0,this._images=[],i){let a=Dl.getImagePasses(n,r);for(let l=0;li?t[o-r]:0;t[o]=s+a}};Ce.prototype._unFilterType2=function(e,t,n){let r=this._lastLine;for(let i=0;ii?t[s-r]:0,c=Math.floor((u+l)/2);t[s]=a+c}};Ce.prototype._unFilterType4=function(e,t,n){let r=this._xComparison,i=r-1,o=this._lastLine;for(let s=0;si?t[s-r]:0,c=s>i&&o?o[s-r]:0,f=Fl(u,l,c);t[s]=a+f}};Ce.prototype._reverseFilterLine=function(e){let t=e[0],n,r=this._images[this._imageIndex],i=r.byteWidth;if(t===0)n=e.slice(1,i+1);else switch(n=Buffer.alloc(i),t){case 1:this._unFilterType1(e,n,i);break;case 2:this._unFilterType2(e,n,i);break;case 3:this._unFilterType3(e,n,i);break;case 4:this._unFilterType4(e,n,i);break;default:throw new Error("Unrecognised filter type - "+t)}this.write(n),r.lineIndex++,r.lineIndex>=r.height?(this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex]):this._lastLine=n,r?this.read(r.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var Zi=m((lf,Xi)=>{"use strict";var ql=require("util"),Ji=ln(),Wl=dn(),Hl=Xi.exports=function(e){Ji.call(this);let t=[],n=this;this._filter=new Wl(e,{read:this.read.bind(this),write:function(r){t.push(r)},complete:function(){n.emit("complete",Buffer.concat(t))}}),this._filter.start()};ql.inherits(Hl,Ji)});var ke=m((uf,eo)=>{"use strict";eo.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}});var pn=m((cf,to)=>{"use strict";var hn=[];(function(){for(let e=0;e<256;e++){let t=e;for(let n=0;n<8;n++)t&1?t=3988292384^t>>>1:t=t>>>1;hn[e]=t}})();var gn=to.exports=function(){this._crc=-1};gn.prototype.write=function(e){for(let t=0;t>>8;return!0};gn.prototype.crc32=function(){return this._crc^-1};gn.crc32=function(e){let t=-1;for(let n=0;n>>8;return t^-1}});var mn=m((ff,no)=>{"use strict";var v=ke(),zl=pn(),M=no.exports=function(e,t){this._options=e,e.checkCRC=e.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[v.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[v.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[v.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[v.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[v.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[v.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=t.read,this.error=t.error,this.metadata=t.metadata,this.gamma=t.gamma,this.transColor=t.transColor,this.palette=t.palette,this.parsed=t.parsed,this.inflateData=t.inflateData,this.finished=t.finished,this.simpleTransparency=t.simpleTransparency,this.headersFinished=t.headersFinished||function(){}};M.prototype.start=function(){this.read(v.PNG_SIGNATURE.length,this._parseSignature.bind(this))};M.prototype._parseSignature=function(e){let t=v.PNG_SIGNATURE;for(let n=0;nthis._palette.length){this.error(new Error("More transparent colors than palette size"));return}for(let t=0;t0?this._handleIDAT(n):this._handleChunkEnd()};M.prototype._handleIEND=function(e){this.read(e,this._parseIEND.bind(this))};M.prototype._parseIEND=function(e){this._crc.write(e),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var _n=m(io=>{"use strict";var ro=cn(),Gl=[function(){},function(e,t,n,r){if(r===t.length)throw new Error("Ran out of data");let i=t[r];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=255},function(e,t,n,r){if(r+1>=t.length)throw new Error("Ran out of data");let i=t[r];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=t[r+1]},function(e,t,n,r){if(r+2>=t.length)throw new Error("Ran out of data");e[n]=t[r],e[n+1]=t[r+1],e[n+2]=t[r+2],e[n+3]=255},function(e,t,n,r){if(r+3>=t.length)throw new Error("Ran out of data");e[n]=t[r],e[n+1]=t[r+1],e[n+2]=t[r+2],e[n+3]=t[r+3]}],Yl=[function(){},function(e,t,n,r){let i=t[0];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=r},function(e,t,n){let r=t[0];e[n]=r,e[n+1]=r,e[n+2]=r,e[n+3]=t[1]},function(e,t,n,r){e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e[n+3]=r},function(e,t,n){e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e[n+3]=t[3]}];function Kl(e,t){let n=[],r=0;function i(){if(r===e.length)throw new Error("Ran out of data");let o=e[r];r++;let s,a,l,u,c,f,h,g;switch(t){default:throw new Error("unrecognised depth");case 16:h=e[r],r++,n.push((o<<8)+h);break;case 4:h=o&15,g=o>>4,n.push(g,h);break;case 2:c=o&3,f=o>>2&3,h=o>>4&3,g=o>>6&3,n.push(g,h,f,c);break;case 1:s=o&1,a=o>>1&1,l=o>>2&1,u=o>>3&1,c=o>>4&1,f=o>>5&1,h=o>>6&1,g=o>>7&1,n.push(g,h,f,c,u,l,a,s);break}}return{get:function(o){for(;n.length{"use strict";function Ql(e,t,n,r,i){let o=0;for(let s=0;s{"use strict";var Zl=require("util"),wn=require("zlib"),so=ln(),eu=Zi(),tu=mn(),nu=_n(),ru=yn(),V=ao.exports=function(e){so.call(this),this._parser=new tu(e,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=e,this.writable=!0,this._parser.start()};Zl.inherits(V,so);V.prototype._handleError=function(e){this.emit("error",e),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy&&this._inflate.destroy(),this._filter&&(this._filter.destroy(),this._filter.on("error",function(){})),this.errord=!0};V.prototype._inflateData=function(e){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=wn.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let n=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,r=Math.max(n,wn.Z_MIN_CHUNK);this._inflate=wn.createInflate({chunkSize:r});let i=n,o=this.emit.bind(this,"error");this._inflate.on("error",function(a){i&&o(a)}),this._filter.on("complete",this._complete.bind(this));let s=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){i&&(a.length>i&&(a=a.slice(0,i)),i-=a.length,s(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(e)};V.prototype._handleMetaData=function(e){this._metaData=e,this._bitmapInfo=Object.create(e),this._filter=new eu(this._bitmapInfo)};V.prototype._handleTransColor=function(e){this._bitmapInfo.transColor=e};V.prototype._handlePalette=function(e){this._bitmapInfo.palette=e};V.prototype._simpleTransparency=function(){this._metaData.alpha=!0};V.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};V.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};V.prototype._complete=function(e){if(this.errord)return;let t;try{let n=nu.dataToBitMap(e,this._bitmapInfo);t=ru(n,this._bitmapInfo),n=null}catch(n){this._handleError(n);return}this.emit("parsed",t)}});var co=m((pf,uo)=>{"use strict";var H=ke();uo.exports=function(e,t,n,r){let i=[H.COLORTYPE_COLOR_ALPHA,H.COLORTYPE_ALPHA].indexOf(r.colorType)!==-1;if(r.colorType===r.inputColorType){let p=function(){let _=new ArrayBuffer(2);return new DataView(_).setInt16(0,256,!0),new Int16Array(_)[0]!==256}();if(r.bitDepth===8||r.bitDepth===16&&p)return e}let o=r.bitDepth!==16?e:new Uint16Array(e.buffer),s=255,a=H.COLORTYPE_TO_BPP_MAP[r.inputColorType];a===4&&!r.inputHasAlpha&&(a=3);let l=H.COLORTYPE_TO_BPP_MAP[r.colorType];r.bitDepth===16&&(s=65535,l*=2);let u=Buffer.alloc(t*n*l),c=0,f=0,h=r.bgColor||{};h.red===void 0&&(h.red=s),h.green===void 0&&(h.green=s),h.blue===void 0&&(h.blue=s);function g(){let p,_,y,w=s;switch(r.inputColorType){case H.COLORTYPE_COLOR_ALPHA:w=o[c+3],p=o[c],_=o[c+1],y=o[c+2];break;case H.COLORTYPE_COLOR:p=o[c],_=o[c+1],y=o[c+2];break;case H.COLORTYPE_ALPHA:w=o[c+1],p=o[c],_=p,y=p;break;case H.COLORTYPE_GRAYSCALE:p=o[c],_=p,y=p;break;default:throw new Error("input color type:"+r.inputColorType+" is not supported at present")}return r.inputHasAlpha&&(i||(w/=s,p=Math.min(Math.max(Math.round((1-w)*h.red+w*p),0),s),_=Math.min(Math.max(Math.round((1-w)*h.green+w*_),0),s),y=Math.min(Math.max(Math.round((1-w)*h.blue+w*y),0),s))),{red:p,green:_,blue:y,alpha:w}}for(let p=0;p{"use strict";var fo=fn();function iu(e,t,n,r,i){for(let o=0;o=o?e[t+s-o]:0,l=e[t+s]-a;r[i+s]=l}}function au(e,t,n,r){let i=0;for(let o=0;o=r?e[t+o-r]:0,a=e[t+o]-s;i+=Math.abs(a)}return i}function lu(e,t,n,r,i){for(let o=0;o0?e[t+o-n]:0,a=e[t+o]-s;r[i+o]=a}}function uu(e,t,n){let r=0,i=t+n;for(let o=t;o0?e[o-n]:0,a=e[o]-s;r+=Math.abs(a)}return r}function cu(e,t,n,r,i,o){for(let s=0;s=o?e[t+s-o]:0,l=t>0?e[t+s-n]:0,u=e[t+s]-(a+l>>1);r[i+s]=u}}function fu(e,t,n,r){let i=0;for(let o=0;o=r?e[t+o-r]:0,a=t>0?e[t+o-n]:0,l=e[t+o]-(s+a>>1);i+=Math.abs(l)}return i}function du(e,t,n,r,i,o){for(let s=0;s=o?e[t+s-o]:0,l=t>0?e[t+s-n]:0,u=t>0&&s>=o?e[t+s-(n+o)]:0,c=e[t+s]-fo(a,l,u);r[i+s]=c}}function hu(e,t,n,r){let i=0;for(let o=0;o=r?e[t+o-r]:0,a=t>0?e[t+o-n]:0,l=t>0&&o>=r?e[t+o-(n+r)]:0,u=e[t+o]-fo(s,a,l);i+=Math.abs(u)}return i}var gu={0:iu,1:su,2:lu,3:cu,4:du},pu={0:ou,1:au,2:uu,3:fu,4:hu};ho.exports=function(e,t,n,r,i){let o;if(!("filterType"in r)||r.filterType===-1)o=[0,1,2,3,4];else if(typeof r.filterType=="number")o=[r.filterType];else throw new Error("unrecognised filter types");r.bitDepth===16&&(i*=2);let s=t*i,a=0,l=0,u=Buffer.alloc((s+1)*n),c=o[0];for(let f=0;f1){let h=1/0;for(let g=0;g{"use strict";var U=ke(),mu=pn(),_u=co(),yu=go(),wu=require("zlib"),oe=po.exports=function(e){if(this._options=e,e.deflateChunkSize=e.deflateChunkSize||32*1024,e.deflateLevel=e.deflateLevel!=null?e.deflateLevel:9,e.deflateStrategy=e.deflateStrategy!=null?e.deflateStrategy:3,e.inputHasAlpha=e.inputHasAlpha!=null?e.inputHasAlpha:!0,e.deflateFactory=e.deflateFactory||wu.createDeflate,e.bitDepth=e.bitDepth||8,e.colorType=typeof e.colorType=="number"?e.colorType:U.COLORTYPE_COLOR_ALPHA,e.inputColorType=typeof e.inputColorType=="number"?e.inputColorType:U.COLORTYPE_COLOR_ALPHA,[U.COLORTYPE_GRAYSCALE,U.COLORTYPE_COLOR,U.COLORTYPE_COLOR_ALPHA,U.COLORTYPE_ALPHA].indexOf(e.colorType)===-1)throw new Error("option color type:"+e.colorType+" is not supported at present");if([U.COLORTYPE_GRAYSCALE,U.COLORTYPE_COLOR,U.COLORTYPE_COLOR_ALPHA,U.COLORTYPE_ALPHA].indexOf(e.inputColorType)===-1)throw new Error("option input color type:"+e.inputColorType+" is not supported at present");if(e.bitDepth!==8&&e.bitDepth!==16)throw new Error("option bit depth:"+e.bitDepth+" is not supported at present")};oe.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};oe.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};oe.prototype.filterData=function(e,t,n){let r=_u(e,t,n,this._options),i=U.COLORTYPE_TO_BPP_MAP[this._options.colorType];return yu(r,t,n,this._options,i)};oe.prototype._packChunk=function(e,t){let n=t?t.length:0,r=Buffer.alloc(n+12);return r.writeUInt32BE(n,0),r.writeUInt32BE(e,4),t&&t.copy(r,8),r.writeInt32BE(mu.crc32(r.slice(4,r.length-4)),r.length-4),r};oe.prototype.packGAMA=function(e){let t=Buffer.alloc(4);return t.writeUInt32BE(Math.floor(e*U.GAMMA_DIVISION),0),this._packChunk(U.TYPE_gAMA,t)};oe.prototype.packIHDR=function(e,t){let n=Buffer.alloc(13);return n.writeUInt32BE(e,0),n.writeUInt32BE(t,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(U.TYPE_IHDR,n)};oe.prototype.packIDAT=function(e){return this._packChunk(U.TYPE_IDAT,e)};oe.prototype.packIEND=function(){return this._packChunk(U.TYPE_IEND,null)}});var wo=m((yf,yo)=>{"use strict";var bu=require("util"),mo=require("stream"),Eu=ke(),Tu=bn(),_o=yo.exports=function(e){mo.call(this);let t=e||{};this._packer=new Tu(t),this._deflate=this._packer.createDeflate(),this.readable=!0};bu.inherits(_o,mo);_o.prototype.pack=function(e,t,n,r){this.emit("data",Buffer.from(Eu.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(t,n)),r&&this.emit("data",this._packer.packGAMA(r));let i=this._packer.filterData(e,t,n);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(o){this.emit("data",this._packer.packIDAT(o))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(i)}});var ko=m((He,Co)=>{"use strict";var bo=require("assert").ok,Ae=require("zlib"),Iu=require("util"),Eo=require("buffer").kMaxLength;function he(e){if(!(this instanceof he))return new he(e);e&&e.chunkSize=0,"have should not go down"),y>0){let w=r._buffer.slice(r._offset,r._offset+y);if(r._offset+=y,w.length>s&&(w=w.slice(0,s)),l.push(w),u+=w.length,s-=w.length,s===0)return!1}return(_===0||r._offset>=r._chunkSize)&&(o=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize)),_===0?(a+=i-p,i=p,!0):!1}bo(this._handle,"zlib binding closed");let h;do h=this._handle.writeSync(t,e,a,i,this._buffer,this._offset,o),h=h||this._writeState;while(!this._hadError&&f(h[0],h[1]));if(this._hadError)throw c;if(u>=Eo)throw To(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+Eo.toString(16)+" bytes");let g=Buffer.concat(l,u);return To(this),g};Iu.inherits(he,Ae.Inflate);function ku(e,t){if(typeof t=="string"&&(t=Buffer.from(t)),!(t instanceof Buffer))throw new TypeError("Not a string or buffer");let n=e._finishFlushFlag;return n==null&&(n=Ae.Z_FINISH),e._processChunk(t,n)}function Io(e,t){return ku(new he(t),e)}Co.exports=He=Io;He.Inflate=he;He.createInflate=Cu;He.inflateSync=Io});var En=m((wf,So)=>{"use strict";var Ao=So.exports=function(e){this._buffer=e,this._reads=[]};Ao.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t})};Ao.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){let e=this._reads[0];if(this._buffer.length&&(this._buffer.length>=e.length||e.allowLess)){this._reads.shift();let t=this._buffer;this._buffer=t.slice(e.length),e.func.call(this,t.slice(0,e.length))}else break}if(this._reads.length>0)return new Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)return new Error("unrecognised content at end of stream")}});var xo=m(Lo=>{"use strict";var Au=En(),Su=dn();Lo.process=function(e,t){let n=[],r=new Au(e);return new Su(t,{read:r.read.bind(r),write:function(o){n.push(o)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var Ro=m((Ef,Mo)=>{"use strict";var Bo=!0,vo=require("zlib"),Lu=ko();vo.deflateSync||(Bo=!1);var xu=En(),Bu=xo(),vu=mn(),Mu=_n(),Ru=yn();Mo.exports=function(e,t){if(!Bo)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n;function r(S){n=S}let i;function o(S){i=S}function s(S){i.transColor=S}function a(S){i.palette=S}function l(){i.alpha=!0}let u;function c(S){u=S}let f=[];function h(S){f.push(S)}let g=new xu(e);if(new vu(t,{read:g.read.bind(g),error:r,metadata:o,gamma:c,palette:a,transColor:s,inflateData:h,simpleTransparency:l}).start(),g.process(),n)throw n;let _=Buffer.concat(f);f.length=0;let y;if(i.interlace)y=vo.inflateSync(_);else{let C=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;y=Lu(_,{chunkSize:C,maxLength:C})}if(_=null,!y||!y.length)throw new Error("bad png - invalid inflate data response");let w=Bu.process(y,i);_=null;let P=Mu.dataToBitMap(w,i);w=null;let T=Ru(P,i);return i.data=T,i.gamma=u||0,i}});var Oo=m((Tf,Uo)=>{"use strict";var Po=!0,$o=require("zlib");$o.deflateSync||(Po=!1);var Pu=ke(),$u=bn();Uo.exports=function(e,t){if(!Po)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n=t||{},r=new $u(n),i=[];i.push(Buffer.from(Pu.PNG_SIGNATURE)),i.push(r.packIHDR(e.width,e.height)),e.gamma&&i.push(r.packGAMA(e.gamma));let o=r.filterData(e.data,e.width,e.height),s=$o.deflateSync(o,r.getDeflateOptions());if(o=null,!s||!s.length)throw new Error("bad png - invalid compressed data response");return i.push(r.packIDAT(s)),i.push(r.packIEND()),Buffer.concat(i)}});var No=m(Tn=>{"use strict";var Uu=Ro(),Ou=Oo();Tn.read=function(e,t){return Uu(e,t||{})};Tn.write=function(e,t){return Ou(e,t)}});var qo=m(Fo=>{"use strict";var Nu=require("util"),Do=require("stream"),Du=lo(),Fu=wo(),qu=No(),N=Fo.PNG=function(e){Do.call(this),e=e||{},this.width=e.width|0,this.height=e.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,e.fill&&this.data&&this.data.fill(0),this.gamma=0,this.readable=this.writable=!0,this._parser=new Du(e),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(t){this.data=t,this.emit("parsed",t)}.bind(this)),this._packer=new Fu(e),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};Nu.inherits(N,Do);N.sync=qu;N.prototype.pack=function(){return!this.data||!this.data.length?(this.emit("error","No data provided"),this):(process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this)};N.prototype.parse=function(e,t){if(t){let n,r;n=function(i){this.removeListener("error",r),this.data=i,t(null,this)}.bind(this),r=function(i){this.removeListener("parsed",n),t(i,null)}.bind(this),this.once("parsed",n),this.once("error",r)}return this.end(e),this};N.prototype.write=function(e){return this._parser.write(e),!0};N.prototype.end=function(e){this._parser.end(e)};N.prototype._metadata=function(e){this.width=e.width,this.height=e.height,this.emit("metadata",e)};N.prototype._gamma=function(e){this.gamma=e};N.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};N.bitblt=function(e,t,n,r,i,o,s,a){if(n|=0,r|=0,i|=0,o|=0,s|=0,a|=0,n>e.width||r>e.height||n+i>e.width||r+o>e.height)throw new Error("bitblt reading outside image");if(s>t.width||a>t.height||s+i>t.width||a+o>t.height)throw new Error("bitblt writing outside image");for(let l=0;l{function Wo(e){if(typeof e=="number"&&(e=e.toString()),typeof e!="string")throw new Error("Color should be defined as hex string");let t=e.slice().replace("#","").split("");if(t.length<3||t.length===5||t.length>8)throw new Error("Invalid hex color: "+e);(t.length===3||t.length===4)&&(t=Array.prototype.concat.apply([],t.map(function(r){return[r,r]}))),t.length===6&&t.push("F","F");let n=parseInt(t.join(""),16);return{r:n>>24&255,g:n>>16&255,b:n>>8&255,a:n&255,hex:"#"+t.slice(0,6).join("")}}ge.getOptions=function(t){t||(t={}),t.color||(t.color={});let n=typeof t.margin>"u"||t.margin===null||t.margin<0?4:t.margin,r=t.width&&t.width>=21?t.width:void 0,i=t.scale||4;return{width:r,scale:r?4:i,margin:n,color:{dark:Wo(t.color.dark||"#000000ff"),light:Wo(t.color.light||"#ffffffff")},type:t.type,rendererOpts:t.rendererOpts||{}}};ge.getScale=function(t,n){return n.width&&n.width>=t+n.margin*2?n.width/(t+n.margin*2):n.scale};ge.getImageWidth=function(t,n){let r=ge.getScale(t,n);return Math.floor((t+n.margin*2)*r)};ge.qrToImageData=function(t,n,r){let i=n.modules.size,o=n.modules.data,s=ge.getScale(i,r),a=Math.floor((i+r.margin*2)*s),l=r.margin*s,u=[r.color.light,r.color.dark];for(let c=0;c=l&&f>=l&&c{var Wu=require("fs"),Hu=qo().PNG,In=ze();j.render=function(t,n){let r=In.getOptions(n),i=r.rendererOpts,o=In.getImageWidth(t.modules.size,r);i.width=o,i.height=o;let s=new Hu(i);return In.qrToImageData(s.data,t,r),s};j.renderToDataURL=function(t,n,r){typeof r>"u"&&(r=n,n=void 0),j.renderToBuffer(t,n,function(i,o){i&&r(i);let s="data:image/png;base64,";s+=o.toString("base64"),r(null,s)})};j.renderToBuffer=function(t,n,r){typeof r>"u"&&(r=n,n=void 0);let i=j.render(t,n),o=[];i.on("error",r),i.on("data",function(s){o.push(s)}),i.on("end",function(){r(null,Buffer.concat(o))}),i.pack()};j.renderToFile=function(t,n,r,i){typeof i>"u"&&(i=r,r=void 0);let o=!1,s=(...l)=>{o||(o=!0,i.apply(null,l))},a=Wu.createWriteStream(t);a.on("error",s),a.on("close",s),j.renderToFileStream(a,n,r)};j.renderToFileStream=function(t,n,r){j.render(n,r).pack().pipe(t)}});var zo=m(mt=>{var zu=ze(),Gu={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},Yu={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function Ku(e,t,n){return e&&t?n.BB:e&&!t?n.BW:!e&&t?n.WB:n.WW}mt.render=function(e,t,n){let r=zu.getOptions(t),i=Gu;(r.color.dark.hex==="#ffffff"||r.color.light.hex==="#000000")&&(i=Yu);let o=e.modules.size,s=e.modules.data,a="",l=Array(o+r.margin*2+1).join(i.WW);l=Array(r.margin/2+1).join(l+` `);let u=Array(r.margin+1).join(i.WW);a+=l;for(let c=0;c"u"&&(i=r,r=void 0);let o=require("fs"),s=mt.render(n,r);o.writeFile(t,s,i)}});var Yo=m(Go=>{Go.render=function(e,t,n){let r=e.modules.size,i=e.modules.data,o="\x1B[40m \x1B[0m",s="\x1B[47m \x1B[0m",a="",l=Array(r+3).join(s),u=Array(2).join(s);a+=l+` `;for(let c=0;c{var Vu="\x1B[47m",ju="\x1B[40m",Cn="\x1B[37m",kn="\x1B[30m",pe="\x1B[0m",Qu=Vu+kn,Ju=ju+Cn,Xu=function(e,t,n){return{"00":pe+" "+e,"01":pe+t+"\u2584"+e,"02":pe+n+"\u2584"+e,10:pe+t+"\u2580"+e,11:" ",12:"\u2584",20:pe+n+"\u2580"+e,21:"\u2580",22:"\u2588"}},Ko=function(e,t,n,r){let i=t+1;if(n>=i||r>=i||r<-1||n<-1)return"0";if(n>=t||r>=t||r<0||n<0)return"1";let o=r*t+n;return e[o]?"2":"1"},Vo=function(e,t,n,r){return Ko(e,t,n,r)+Ko(e,t,n,r+1)};jo.render=function(e,t,n){let r=e.modules.size,i=e.modules.data,o=!!(t&&t.inverse),s=t&&t.inverse?Ju:Qu,u=Xu(s,o?kn:Cn,o?Cn:kn),c=pe+` `+s,f=s;for(let h=-1;h{var Zu=Yo(),ec=Qo();Jo.render=function(e,t,n){return t&&t.small?ec.render(e,t,n):Zu.render(e,t,n)}});var Sn=m(es=>{var tc=ze();function Zo(e,t){let n=e.a/255,r=t+'="'+e.hex+'"';return n<1?r+" "+t+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function An(e,t,n){let r=e+t;return typeof n<"u"&&(r+=" "+n),r}function nc(e,t,n){let r="",i=0,o=!1,s=0;for(let a=0;a0&&l>0&&e[a-1]||(r+=o?An("M",l+n,.5+u+n):An("m",i,0),i=0,o=!1),l+1':"",u="',c='viewBox="0 0 '+a+" "+a+'"',h=''+l+u+` `;return typeof r=="function"&&r(null,h),h}});var ts=m(_t=>{var rc=Sn();_t.render=rc.render;_t.renderToFile=function(t,n,r,i){typeof i>"u"&&(i=r,r=void 0);let o=require("fs"),a=''+_t.render(n,r);o.writeFile(t,a,i)}});var ns=m(yt=>{var Ln=ze();function ic(e,t,n){e.clearRect(0,0,t.width,t.height),t.style||(t.style={}),t.height=n,t.width=n,t.style.height=n+"px",t.style.width=n+"px"}function oc(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}yt.render=function(t,n,r){let i=r,o=n;typeof i>"u"&&(!n||!n.getContext)&&(i=n,n=void 0),n||(o=oc()),i=Ln.getOptions(i);let s=Ln.getImageWidth(t.modules.size,i),a=o.getContext("2d"),l=a.createImageData(s,s);return Ln.qrToImageData(l.data,t,i),ic(a,o,s),a.putImageData(l,0,0),o};yt.renderToDataURL=function(t,n,r){let i=r;typeof i>"u"&&(!n||!n.getContext)&&(i=n,n=void 0),i||(i={});let o=yt.render(t,n,i),s=i.type||"image/png",a=i.rendererOpts||{};return o.toDataURL(s,a.quality)}});var is=m(Ge=>{var sc=qt(),xn=an(),rs=ns(),ac=Sn();function Bn(e,t,n,r,i){let o=[].slice.call(arguments,1),s=o.length,a=typeof o[s-1]=="function";if(!a&&!sc())throw new Error("Callback required as last argument");if(a){if(s<2)throw new Error("Too few arguments provided");s===2?(i=n,n=t,t=r=void 0):s===3&&(t.getContext&&typeof i>"u"?(i=r,r=void 0):(i=r,r=n,n=t,t=void 0))}else{if(s<1)throw new Error("Too few arguments provided");return s===1?(n=t,t=r=void 0):s===2&&!t.getContext&&(r=n,n=t,t=void 0),new Promise(function(l,u){try{let c=xn.create(n,r);l(e(c,t,r))}catch(c){u(c)}})}try{let l=xn.create(n,r);i(null,e(l,t,r))}catch(l){i(l)}}Ge.create=xn.create;Ge.toCanvas=Bn.bind(null,rs.render);Ge.toDataURL=Bn.bind(null,rs.renderToDataURL);Ge.toString=Bn.bind(null,function(e,t,n){return ac.render(e,n)})});var ls=m(se=>{var os=qt(),vn=an(),lc=Ho(),ss=zo(),uc=Xo(),as=ts();function Ye(e,t,n){if(typeof e>"u")throw new Error("String required as first argument");if(typeof n>"u"&&(n=t,t={}),typeof n!="function")if(os())t=n||{},n=null;else throw new Error("Callback required as last argument");return{opts:t,cb:n}}function cc(e){return e.slice((e.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function wt(e){switch(e){case"svg":return as;case"txt":case"utf8":return ss;case"png":case"image/png":default:return lc}}function fc(e){switch(e){case"svg":return as;case"terminal":return uc;case"utf8":default:return ss}}function Ke(e,t,n){if(!n.cb)return new Promise(function(r,i){try{let o=vn.create(t,n.opts);return e(o,n.opts,function(s,a){return s?i(s):r(a)})}catch(o){i(o)}});try{let r=vn.create(t,n.opts);return e(r,n.opts,n.cb)}catch(r){n.cb(r)}}se.create=vn.create;se.toCanvas=is().toCanvas;se.toString=function(t,n,r){let i=Ye(t,n,r),o=i.opts?i.opts.type:void 0,s=fc(o);return Ke(s.render,t,i)};se.toDataURL=function(t,n,r){let i=Ye(t,n,r),o=wt(i.opts.type);return Ke(o.renderToDataURL,t,i)};se.toBuffer=function(t,n,r){let i=Ye(t,n,r),o=wt(i.opts.type);return Ke(o.renderToBuffer,t,i)};se.toFile=function(t,n,r,i){if(typeof t!="string"||!(typeof n=="string"||typeof n=="object"))throw new Error("Invalid argument");if(arguments.length<3&&!os())throw new Error("Too few arguments provided");let o=Ye(n,r,i),s=o.opts.type||cc(t),l=wt(s).renderToFile.bind(null,t);return Ke(l,n,o)};se.toFileStream=function(t,n,r){if(arguments.length<2)throw new Error("Too few arguments provided");let i=Ye(n,r,t.emit.bind(t,"error")),s=wt("png").renderToFileStream.bind(null,t);Ke(s,n,i)}});var cs=m((Uf,us)=>{us.exports=ls()});var _e=J(require("node:os"),1),b=J(require("node:path"),1),A=J(require("node:fs"),1),O=J(require("node:crypto"),1),mr=require("node:url"),me=J(require("node:fs/promises"),1),Qa={};function ye(){return process.env.OPENCLAW_STATE_DIR?.trim()||process.env.CLAWDBOT_STATE_DIR?.trim()||b.default.join(_e.default.homedir(),".openclaw")}var _r=(()=>{try{return process.env.IM_BRIDGE_CONFIG?JSON.parse(process.env.IM_BRIDGE_CONFIG):{}}catch{return{}}})(),Ls=_r.baseUrl,xs=_r.cdnBaseUrl;function Rt(e){return e.trim().toLowerCase().replace(/[@.]/g,"-")}function yr(e){if(e.endsWith("-im-bot"))return`${e.slice(0,-7)}@im.bot`;if(e.endsWith("-im-wechat"))return`${e.slice(0,-10)}@im.wechat`}function Pt(){return b.default.join(ye(),"openclaw-weixin")}function wr(){return b.default.join(Pt(),"accounts.json")}function Bs(){let e=wr();try{if(!A.default.existsSync(e))return[];let t=A.default.readFileSync(e,"utf-8"),n=JSON.parse(t);return Array.isArray(n)?n.filter(r=>typeof r=="string"&&r.trim()!==""):[]}catch{return[]}}function br(e){let t=Pt();A.default.mkdirSync(t,{recursive:!0}),A.default.writeFileSync(wr(),JSON.stringify([e],null,2),"utf-8")}function Er(){return b.default.join(Pt(),"accounts")}function Lt(e){return b.default.join(Er(),`${e}.json`)}function vs(){let e=b.default.join(ye(),"credentials","openclaw-weixin","credentials.json");try{if(!A.default.existsSync(e))return;let t=A.default.readFileSync(e,"utf-8"),n=JSON.parse(t);return typeof n.token=="string"?n.token:void 0}catch{return}}function sr(e){try{if(A.default.existsSync(e))return JSON.parse(A.default.readFileSync(e,"utf-8"))}catch{}return null}function Re(e){let t=sr(Lt(e));if(t)return t;let n=yr(e);if(n){let i=sr(Lt(n));if(i)return i}let r=vs();return r?{token:r}:null}function Tr(e,t){let n=Er();A.default.mkdirSync(n,{recursive:!0});let r=Re(e)??{},i=t.token?.trim()||r.token,o=t.baseUrl?.trim()||r.baseUrl,s=t.userId!==void 0?t.userId.trim()||void 0:r.userId?.trim()||void 0,a={...i?{token:i,savedAt:new Date().toISOString()}:{},...o?{baseUrl:o}:{},...s?{userId:s}:{}},l=Lt(e);A.default.writeFileSync(l,JSON.stringify(a,null,2),"utf-8");try{A.default.chmodSync(l,384)}catch{}}function Ms(){let e=process.env.OPENCLAW_CONFIG?.trim();return e||b.default.join(ye(),"openclaw.json")}function Rs(e){try{let t=Ms();if(!A.default.existsSync(t))return;let n=A.default.readFileSync(t,"utf-8"),r=JSON.parse(n).channels?.["openclaw-weixin"];if(!r)return;if(e){let i=r.accounts?.[e]?.routeTag;if(typeof i=="number")return String(i);if(typeof i=="string"&&i.trim())return i.trim()}return typeof r.routeTag=="number"?String(r.routeTag):typeof r.routeTag=="string"&&r.routeTag.trim()?r.routeTag.trim():void 0}catch{return}}function it(){return Bs()}function ot(e){let t=e?.trim();if(!t)throw new Error("weixin: accountId is required (no default account)");let n=Rt(t),r=Re(n),i=r?.token?.trim()||void 0;return{accountId:n,baseUrl:r?.baseUrl?.trim()||Ls,cdnBaseUrl:xs,token:i,enabled:!0,configured:!!i}}var Ir=b.default.join(_e.default.tmpdir(),"openclaw"),ar="gateway/channels/openclaw-weixin",Ps="node",$s=process.versions.node,Us=_e.default.hostname()||"unknown",Os=["openclaw"],le={TRACE:1,DEBUG:2,INFO:3,WARN:4,ERROR:5,FATAL:6},Ns="INFO";function Ds(){let e=process.env.OPENCLAW_LOG_LEVEL?.toUpperCase();return e&&e in le?le[e]:le[Ns]}var Fs=Ds();function Cr(e){let t=-e.getTimezoneOffset()*6e4,n=t>=0?"+":"-",r=Math.abs(e.getTimezoneOffset()),i=`${n}${String(Math.floor(r/60)).padStart(2,"0")}:${String(r%60).padStart(2,"0")}`;return new Date(e.getTime()+t).toISOString().replace("Z",i)}function qs(e){return Cr(e).slice(0,10)}function kr(){let e=qs(new Date);return b.default.join(Ir,`openclaw-${e}.log`)}var lr=!1;function Ws(e){return e?`${ar}/${e}`:ar}function Xe(e,t,n){if((le[e]??le.INFO)`:n}catch{return Gs(e,80)}}function Ys(){try{let e=b.default.dirname((0,mr.fileURLToPath)(Qa.url)),t=b.default.resolve(e,"..","..","package.json");return JSON.parse(A.default.readFileSync(t,"utf-8")).version??"unknown"}catch{return"unknown"}}var Ks=Ys();function Pe(){return{channel_version:Ks}}var Vs=35e3,Sr=15e3,Lr=1e4;function xr(e){return e.endsWith("/")?e:`${e}/`}function js(){let e=O.default.randomBytes(4).readUInt32BE(0);return Buffer.from(String(e),"utf-8").toString("base64")}function Br(){let e={},t=Rs();return t&&(e.SKRouteTag=t),e}function Qs(e){let t={"Content-Type":"application/json",AuthorizationType:"ilink_bot_token","Content-Length":String(Buffer.byteLength(e.body,"utf-8")),"X-WECHAT-UIN":js(),...Br()};return e.token?.trim()&&(t.Authorization=`Bearer ${e.token.trim()}`),d.debug(`requestHeaders: ${JSON.stringify({...t,Authorization:t.Authorization?"Bearer ***":void 0})}`),t}async function vr(e){let t=xr(e.baseUrl),n=new URL(e.endpoint,t),r=Br();d.debug(`GET ${$t(n.toString())}`);let i=new AbortController,o=setTimeout(()=>i.abort(),e.timeoutMs);try{let s=await fetch(n.toString(),{method:"GET",headers:r,signal:i.signal});clearTimeout(o);let a=await s.text();if(d.debug(`${e.label} status=${s.status} raw=${Bt(a)}`),!s.ok)throw new Error(`${e.label} ${s.status}: ${a}`);return a}catch(s){throw clearTimeout(o),s}}async function $e(e){let t=xr(e.baseUrl),n=new URL(e.endpoint,t),r=Qs({token:e.token,body:e.body});d.debug(`POST ${$t(n.toString())} body=${Bt(e.body)}`);let i=new AbortController,o=setTimeout(()=>i.abort(),e.timeoutMs),s=()=>i.abort();e.abortSignal?.addEventListener("abort",s,{once:!0});try{let a=await fetch(n.toString(),{method:"POST",headers:r,body:e.body,signal:i.signal});clearTimeout(o);let l=await a.text();if(d.debug(`${e.label} status=${a.status} raw=${Bt(l)}`),!a.ok)throw new Error(`${e.label} ${a.status}: ${l}`);return l}catch(a){throw clearTimeout(o),a}finally{e.abortSignal?.removeEventListener("abort",s)}}async function Js(e){let t=e.timeoutMs??Vs;try{let n=await $e({baseUrl:e.baseUrl,endpoint:"ilink/bot/getupdates",body:JSON.stringify({get_updates_buf:e.get_updates_buf??"",base_info:Pe()}),token:e.token,timeoutMs:t,label:"getUpdates",abortSignal:e.abortSignal});return JSON.parse(n)}catch(n){if(n instanceof Error&&n.name==="AbortError")return d.debug(`getUpdates: client-side timeout after ${t}ms, returning empty response`),{ret:0,msgs:[],get_updates_buf:e.get_updates_buf};throw n}}async function Xs(e){let t=await $e({baseUrl:e.baseUrl,endpoint:"ilink/bot/getuploadurl",body:JSON.stringify({filekey:e.filekey,media_type:e.media_type,to_user_id:e.to_user_id,rawsize:e.rawsize,rawfilemd5:e.rawfilemd5,filesize:e.filesize,thumb_rawsize:e.thumb_rawsize,thumb_rawfilemd5:e.thumb_rawfilemd5,thumb_filesize:e.thumb_filesize,no_need_thumb:e.no_need_thumb,aeskey:e.aeskey,base_info:Pe()}),token:e.token,timeoutMs:e.timeoutMs??Sr,label:"getUploadUrl"});return JSON.parse(t)}async function Mr(e){await $e({baseUrl:e.baseUrl,endpoint:"ilink/bot/sendmessage",body:JSON.stringify({...e.body,base_info:Pe()}),token:e.token,timeoutMs:e.timeoutMs??Sr,label:"sendMessage"})}async function Zs(e){let t=await $e({baseUrl:e.baseUrl,endpoint:"ilink/bot/getconfig",body:JSON.stringify({ilink_user_id:e.ilinkUserId,context_token:e.contextToken,base_info:Pe()}),token:e.token,timeoutMs:e.timeoutMs??Lr,label:"getConfig"});return JSON.parse(t)}async function ur(e){await $e({baseUrl:e.baseUrl,endpoint:"ilink/bot/sendtyping",body:JSON.stringify({...e.body,base_info:Pe()}),token:e.token,timeoutMs:e.timeoutMs??Lr,label:"sendTyping"})}var ea=5*6e4,ta=5e3,cr=35e3,Rr="https://ilinkai.weixin.qq.com",q=new Map;function Ut(e){return Date.now()-e.startedAtZe)return d.warn(`waitForWeixinLogin: QR expired ${Ze} times, giving up sessionKey=${e.sessionKey}`),q.delete(e.sessionKey),{connected:!1,message:"\u767B\u5F55\u8D85\u65F6\uFF1A\u4E8C\u7EF4\u7801\u591A\u6B21\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u5F00\u59CB\u767B\u5F55\u6D41\u7A0B\u3002"};process.stdout.write(` \u23F3 \u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\uFF0C\u6B63\u5728\u5237\u65B0...(${o}/${Ze}) `),d.info(`waitForWeixinLogin: QR expired, refreshing (${o}/${Ze})`);try{let l=await Pr(s,e.botType||"3");t.qrcode=l.qrcode,t.qrcodeUrl=l.qrcode_img_content,t.startedAt=Date.now(),i=!1,d.info(`waitForWeixinLogin: new QR code obtained qrcode=${xt(l.qrcode)}`),process.stdout.write(`\u{1F504} \u65B0\u4E8C\u7EF4\u7801\u5DF2\u751F\u6210\uFF0C\u8BF7\u91CD\u65B0\u626B\u63CF `);try{(await Promise.resolve().then(()=>J(or(),1))).default.generate(l.qrcode_img_content,{small:!0}),process.stdout.write(`\u5982\u679C\u4E8C\u7EF4\u7801\u672A\u80FD\u6210\u529F\u5C55\u793A\uFF0C\u8BF7\u7528\u6D4F\u89C8\u5668\u6253\u5F00\u4EE5\u4E0B\u94FE\u63A5\u626B\u7801\uFF1A `),process.stdout.write(`${l.qrcode_img_content} `)}catch{process.stdout.write(`\u4E8C\u7EF4\u7801\u672A\u52A0\u8F7D\u6210\u529F\uFF0C\u8BF7\u7528\u6D4F\u89C8\u5668\u6253\u5F00\u4EE5\u4E0B\u94FE\u63A5\u626B\u7801\uFF1A `),process.stdout.write(`${l.qrcode_img_content} `)}}catch(l){return d.error(`waitForWeixinLogin: failed to refresh QR code: ${String(l)}`),q.delete(e.sessionKey),{connected:!1,message:`\u5237\u65B0\u4E8C\u7EF4\u7801\u5931\u8D25: ${String(l)}`}}break;case"scaned_but_redirect":{let l=a.redirect_host;l?(t.currentApiBaseUrl=`https://${l}`,d.info(`waitForWeixinLogin: IDC redirect, switching polling host to ${l}`)):d.warn("waitForWeixinLogin: received scaned_but_redirect but redirect_host is missing, continuing with current host");break}case"confirmed":return a.ilink_bot_id?(t.botToken=a.bot_token,q.delete(e.sessionKey),d.info(`\u2705 Login confirmed! ilink_bot_id=${a.ilink_bot_id} ilink_user_id=${xt(a.ilink_user_id)}`),{connected:!0,botToken:a.bot_token,accountId:a.ilink_bot_id,baseUrl:a.baseurl,userId:a.ilink_user_id,message:"\u2705 \u4E0E\u5FAE\u4FE1\u8FDE\u63A5\u6210\u529F\uFF01"}):(q.delete(e.sessionKey),d.error("Login confirmed but ilink_bot_id missing from response"),{connected:!1,message:"\u767B\u5F55\u5931\u8D25\uFF1A\u670D\u52A1\u5668\u672A\u8FD4\u56DE ilink_bot_id\u3002"})}}catch(a){return d.error(`Error polling QR status: ${String(a)}`),q.delete(e.sessionKey),{connected:!1,message:`Login failed: ${String(a)}`}}await new Promise(a=>setTimeout(a,1e3))}return d.warn(`waitForWeixinLogin: timed out waiting for QR scan sessionKey=${e.sessionKey} timeoutMs=${n}`),q.delete(e.sessionKey),{connected:!1,message:"\u767B\u5F55\u8D85\u65F6\uFF0C\u8BF7\u91CD\u8BD5\u3002"}}function ia(e,t){let n=(0,O.createCipheriv)("aes-128-ecb",t,null);return Buffer.concat([n.update(e),n.final()])}function oa(e,t){let n=(0,O.createDecipheriv)("aes-128-ecb",t,null);return Buffer.concat([n.update(e),n.final()])}function sa(e){return Math.ceil((e+1)/16)*16}function Or(e,t){return`${t}/download?encrypted_query_param=${encodeURIComponent(e)}`}function aa(e){return`${e.cdnBaseUrl}/upload?encrypted_query_param=${encodeURIComponent(e.uploadParam)}&filekey=${encodeURIComponent(e.filekey)}`}var et=3;async function la(e){let{buf:t,uploadFullUrl:n,uploadParam:r,filekey:i,cdnBaseUrl:o,label:s,aeskey:a}=e,l=ia(t,a),u=n?.trim(),c;if(u)c=u;else if(r)c=aa({cdnBaseUrl:o,uploadParam:r,filekey:i});else throw new Error(`${s}: CDN upload URL missing (need upload_full_url or upload_param)`);d.debug(`${s}: CDN POST url=${$t(c)} ciphertextSize=${l.length}`);let f,h;for(let g=1;g<=et;g++)try{let p=await fetch(c,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:new Uint8Array(l)});if(p.status>=400&&p.status<500){let _=p.headers.get("x-error-message")??await p.text();throw d.error(`${s}: CDN client error attempt=${g} status=${p.status} errMsg=${_}`),new Error(`CDN upload client error ${p.status}: ${_}`)}if(p.status!==200){let _=p.headers.get("x-error-message")??`status ${p.status}`;throw d.error(`${s}: CDN server error attempt=${g} status=${p.status} errMsg=${_}`),new Error(`CDN upload server error: ${_}`)}if(f=p.headers.get("x-encrypted-param")??void 0,!f)throw d.error(`${s}: CDN response missing x-encrypted-param header attempt=${g}`),new Error("CDN upload response missing x-encrypted-param header");d.debug(`${s}: CDN upload success attempt=${g}`);break}catch(p){if(h=p,p instanceof Error&&p.message.includes("client error"))throw p;gr.trim()),t=t.replace(/!\[[^\]]*\]\([^)]*\)/g,""),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/^\|[\s:|-]+\|$/gm,""),t=t.replace(/^\|(.+)\|$/gm,(n,r)=>r.split("|").map(i=>i.trim()).join(" ")),t=t.replace(/\*\*(.+?)\*\*/g,"$1").replace(/\*(.+?)\*/g,"$1").replace(/__(.+?)__/g,"$1").replace(/_(.+?)_/g,"$1").replace(/~~(.+?)~~/g,"$1").replace(/`(.+?)`/g,"$1"),t}function _a(e){let{to:t,text:n,contextToken:r,clientId:i}=e,o=n?[{type:L.TEXT,text_item:{text:n}}]:[];return{msg:{from_user_id:"",to_user_id:t,client_id:i,message_type:qr.BOT,message_state:Wr.FINISH,item_list:o.length?o:void 0,context_token:r??void 0}}}function ya(e){let{to:t,contextToken:n,text:r,clientId:i}=e;return _a({to:t,text:r,contextToken:n,clientId:i})}async function ue(e){let{to:t,text:n,opts:r}=e;if(!r.contextToken)throw d.error(`sendMessageWeixin: contextToken missing, refusing to send to=${t}`),new Error("sendMessageWeixin: contextToken is required");let i=Kr(),o=ya({to:t,contextToken:r.contextToken,text:n,clientId:i});try{await Mr({baseUrl:r.baseUrl,token:r.token,timeoutMs:r.timeoutMs,body:o})}catch(s){throw d.error(`sendMessageWeixin: failed to=${t} clientId=${i} err=${String(s)}`),s}return{messageId:i}}async function Ft(e){let{to:t,text:n,mediaItem:r,opts:i,label:o}=e,s=[];n&&s.push({type:L.TEXT,text_item:{text:n}}),s.push(r);let a="";for(let l of s){a=Kr();let u={msg:{from_user_id:"",to_user_id:t,client_id:a,message_type:qr.BOT,message_state:Wr.FINISH,item_list:[l],context_token:i.contextToken??void 0}};try{await Mr({baseUrl:i.baseUrl,token:i.token,timeoutMs:i.timeoutMs,body:u})}catch(c){throw d.error(`${o}: failed to=${t} clientId=${a} err=${String(c)}`),c}}return d.debug(`${o}: success to=${t} clientId=${a}`),{messageId:a}}async function wa(e){let{to:t,text:n,uploaded:r,opts:i}=e;if(!i.contextToken)throw d.error(`sendImageMessageWeixin: contextToken missing, refusing to send to=${t}`),new Error("sendImageMessageWeixin: contextToken is required");return d.debug(`sendImageMessageWeixin: to=${t} filekey=${r.filekey} fileSize=${r.fileSize} aeskey=present`),Ft({to:t,text:n,mediaItem:{type:L.IMAGE,image_item:{media:{encrypt_query_param:r.downloadEncryptedQueryParam,aes_key:Buffer.from(r.aeskey).toString("base64"),encrypt_type:1},mid_size:r.fileSizeCiphertext}},opts:i,label:"sendImageMessageWeixin"})}async function ba(e){let{to:t,text:n,uploaded:r,opts:i}=e;if(!i.contextToken)throw d.error(`sendVideoMessageWeixin: contextToken missing, refusing to send to=${t}`),new Error("sendVideoMessageWeixin: contextToken is required");return Ft({to:t,text:n,mediaItem:{type:L.VIDEO,video_item:{media:{encrypt_query_param:r.downloadEncryptedQueryParam,aes_key:Buffer.from(r.aeskey).toString("base64"),encrypt_type:1},video_size:r.fileSizeCiphertext}},opts:i,label:"sendVideoMessageWeixin"})}async function Ea(e){let{to:t,text:n,fileName:r,uploaded:i,opts:o}=e;if(!o.contextToken)throw d.error(`sendFileMessageWeixin: contextToken missing, refusing to send to=${t}`),new Error("sendFileMessageWeixin: contextToken is required");return Ft({to:t,text:n,mediaItem:{type:L.FILE,file_item:{media:{encrypt_query_param:i.downloadEncryptedQueryParam,aes_key:Buffer.from(i.aeskey).toString("base64"),encrypt_type:1},file_name:r,len:String(i.fileSize)}},opts:o,label:"sendFileMessageWeixin"})}async function Vr(e){let{filePath:t,to:n,text:r,opts:i,cdnBaseUrl:o}=e,s=Dr(t),a={baseUrl:i.baseUrl,token:i.token};if(s.startsWith("video/")){d.info(`[weixin] sendWeixinMediaFile: uploading video filePath=${t} to=${n}`);let c=await ga({filePath:t,toUserId:n,opts:a,cdnBaseUrl:o});return d.info(`[weixin] sendWeixinMediaFile: video upload done filekey=${c.filekey} size=${c.fileSize}`),ba({to:n,text:r,uploaded:c,opts:i})}if(s.startsWith("image/")){d.info(`[weixin] sendWeixinMediaFile: uploading image filePath=${t} to=${n}`);let c=await ha({filePath:t,toUserId:n,opts:a,cdnBaseUrl:o});return d.info(`[weixin] sendWeixinMediaFile: image upload done filekey=${c.filekey} size=${c.fileSize}`),wa({to:n,text:r,uploaded:c,opts:i})}let l=b.default.basename(t);d.info(`[weixin] sendWeixinMediaFile: uploading file attachment filePath=${t} name=${l} to=${n}`);let u=await pa({filePath:t,fileName:l,toUserId:n,opts:a,cdnBaseUrl:o});return d.info(`[weixin] sendWeixinMediaFile: file upload done filekey=${u.filekey} size=${u.fileSize}`),Ea({to:n,text:r,fileName:l,uploaded:u,opts:i})}var Ta=1440*60*1e3,tt=2e3,Ia=3600*1e3,Ca=class{cache=new Map;constructor(e,t){this.apiOpts=e,this.log=t}async getForUser(e,t){let n=Date.now(),r=this.cache.get(e);if(!r||n>=r.nextFetchAt){let i=!1;try{let o=await Zs({baseUrl:this.apiOpts.baseUrl,token:this.apiOpts.token,ilinkUserId:e,contextToken:t});o.ret===0&&(this.cache.set(e,{config:{typingTicket:o.typing_ticket??""},everSucceeded:!0,nextFetchAt:n+Math.random()*Ta,retryDelayMs:tt}),this.log(`[weixin] config ${r?.everSucceeded?"refreshed":"cached"} for ${e}`),i=!0)}catch(o){this.log(`[weixin] getConfig failed for ${e} (ignored): ${String(o)}`)}if(!i){let o=r?.retryDelayMs??tt,s=Math.min(o*2,Ia);r?(r.nextFetchAt=n+s,r.retryDelayMs=s):this.cache.set(e,{config:{typingTicket:""},everSucceeded:!1,nextFetchAt:n+tt,retryDelayMs:tt})}}return this.cache.get(e)?.config??{typingTicket:""}}},dr=3600*1e3,Mt=new Map;function ka(e){let t=Date.now()+dr;Mt.set(e,t),d.info(`session-guard: paused accountId=${e} until=${new Date(t).toISOString()} (${dr/1e3}s)`)}function Aa(e){let t=Mt.get(e);if(t===void 0)return 0;let n=t-Date.now();return n<=0?(Mt.delete(e),0):n}async function jr(e,t){let n;try{n=await fetch(e)}catch(r){let i=r.cause??r.code??"(no cause)";throw d.error(`${t}: fetch network error url=${e} err=${String(r)} cause=${String(i)}`),r}if(d.debug(`${t}: response status=${n.status} ok=${n.ok}`),!n.ok){let r=await n.text().catch(()=>"(unreadable)"),i=`${t}: CDN download ${n.status} ${n.statusText} body=${r}`;throw d.error(i),new Error(i)}return Buffer.from(await n.arrayBuffer())}function Sa(e,t){let n=Buffer.from(e,"base64");if(n.length===16)return n;if(n.length===32&&/^[0-9a-fA-F]{32}$/.test(n.toString("ascii")))return Buffer.from(n.toString("ascii"),"hex");let r=`${t}: aes_key must decode to 16 raw bytes or 32-char hex string, got ${n.length} bytes (base64="${e}")`;throw d.error(r),new Error(r)}async function nt(e,t,n,r,i){let o=Sa(t,r),s=i||Or(e,n);d.debug(`${r}: fetching url=${s}`);let a=await jr(s,r);d.debug(`${r}: downloaded ${a.byteLength} bytes, decrypting`);let l=oa(a,o);return d.debug(`${r}: decrypted ${l.length} bytes`),l}async function La(e,t,n,r){let i=r||Or(e,t);return d.debug(`${n}: fetching url=${i}`),jr(i,n)}var hr=24e3;function xa(e,t){let n=e.byteLength,r=44+n,i=Buffer.allocUnsafe(r),o=0;return i.write("RIFF",o),o+=4,i.writeUInt32LE(r-8,o),o+=4,i.write("WAVE",o),o+=4,i.write("fmt ",o),o+=4,i.writeUInt32LE(16,o),o+=4,i.writeUInt16LE(1,o),o+=2,i.writeUInt16LE(1,o),o+=2,i.writeUInt32LE(t,o),o+=4,i.writeUInt32LE(t*2,o),o+=4,i.writeUInt16LE(2,o),o+=2,i.writeUInt16LE(16,o),o+=2,i.write("data",o),o+=4,i.writeUInt32LE(n,o),o+=4,Buffer.from(e.buffer,e.byteOffset,e.byteLength).copy(i,o),i}async function Ba(e){try{let{decode:t}=await import("silk-wasm");d.debug(`silkToWav: decoding ${e.length} bytes of SILK`);let n=await t(e,hr);d.debug(`silkToWav: decoded duration=${n.duration}ms pcmBytes=${n.data.byteLength}`);let r=xa(n.data,hr);return d.debug(`silkToWav: WAV size=${r.length}`),r}catch(t){return d.warn(`silkToWav: transcode failed, will use raw silk err=${String(t)}`),null}}var xe=100*1024*1024;async function va(e,t){let{cdnBaseUrl:n,saveMedia:r,log:i,errLog:o,label:s}=t,a={};if(e.type===L.IMAGE){let l=e.image_item;if(!l?.media?.encrypt_query_param&&!l?.media?.full_url)return a;let u=l.aeskey?Buffer.from(l.aeskey,"hex").toString("base64"):l.media.aes_key;d.debug(`${s} image: encrypt_query_param=${(l.media.encrypt_query_param??"").slice(0,40)}... hasAesKey=${!!u} aeskeySource=${l.aeskey?"image_item.aeskey":"media.aes_key"} full_url=${!!l.media.full_url}`);try{let c=await r(u?await nt(l.media.encrypt_query_param??"",u,n,`${s} image`,l.media.full_url):await La(l.media.encrypt_query_param??"",n,`${s} image-plain`,l.media.full_url),void 0,"inbound",xe);a.decryptedPicPath=c.path,d.debug(`${s} image saved: ${c.path}`)}catch(c){d.error(`${s} image download/decrypt failed: ${String(c)}`),o(`weixin ${s} image download/decrypt failed: ${String(c)}`)}}else if(e.type===L.VOICE){let l=e.voice_item;if(!l?.media?.encrypt_query_param&&!l?.media?.full_url||!l?.media?.aes_key)return a;try{let u=await nt(l.media.encrypt_query_param??"",l.media.aes_key,n,`${s} voice`,l.media.full_url);d.debug(`${s} voice: decrypted ${u.length} bytes, attempting silk transcode`);let c=await Ba(u);if(c){let f=await r(c,"audio/wav","inbound",xe);a.decryptedVoicePath=f.path,a.voiceMediaType="audio/wav",d.debug(`${s} voice: saved WAV to ${f.path}`)}else{let f=await r(u,"audio/silk","inbound",xe);a.decryptedVoicePath=f.path,a.voiceMediaType="audio/silk",d.debug(`${s} voice: silk transcode unavailable, saved raw SILK to ${f.path}`)}}catch(u){d.error(`${s} voice download/transcode failed: ${String(u)}`),o(`weixin ${s} voice download/transcode failed: ${String(u)}`)}}else if(e.type===L.FILE){let l=e.file_item;if(!l?.media?.encrypt_query_param&&!l?.media?.full_url||!l?.media?.aes_key)return a;try{let u=await nt(l.media.encrypt_query_param??"",l.media.aes_key,n,`${s} file`,l.media.full_url),c=Dr(l.file_name??"file.bin"),f=await r(u,c,"inbound",xe,l.file_name??void 0);a.decryptedFilePath=f.path,a.fileMediaType=c,d.debug(`${s} file: saved to ${f.path} mime=${c}`)}catch(u){d.error(`${s} file download failed: ${String(u)}`),o(`weixin ${s} file download failed: ${String(u)}`)}}else if(e.type===L.VIDEO){let l=e.video_item;if(!l?.media?.encrypt_query_param&&!l?.media?.full_url||!l?.media?.aes_key)return a;try{let u=await r(await nt(l.media.encrypt_query_param??"",l.media.aes_key,n,`${s} video`,l.media.full_url),"video/mp4","inbound",xe);a.decryptedVideoPath=u.path,d.debug(`${s} video: saved to ${u.path}`)}catch(u){d.error(`${s} video download failed: ${String(u)}`),o(`weixin ${s} video download failed: ${String(u)}`)}}return a}async function Ma(e){if(!e.contextToken){d.warn(`sendWeixinErrorNotice: no contextToken for to=${e.to}, cannot notify user`);return}try{await ue({to:e.to,text:e.message,opts:{baseUrl:e.baseUrl,token:e.token,contextToken:e.contextToken}}),d.debug(`sendWeixinErrorNotice: sent to=${e.to}`)}catch(t){e.errLog(`[weixin] sendWeixinErrorNotice failed to=${e.to}: ${String(t)}`)}}function Qr(){return b.default.join(ye(),"openclaw-weixin","debug-mode.json")}function Ra(){try{let e=A.default.readFileSync(Qr(),"utf-8"),t=JSON.parse(e);if(t&&typeof t.accounts=="object")return t}catch{}return{accounts:{}}}function Pa(e){let t=Qr();A.default.mkdirSync(b.default.dirname(t),{recursive:!0}),A.default.writeFileSync(t,JSON.stringify(e,null,2),"utf-8")}function $a(e){let t=Ra(),n=!t.accounts[e];t.accounts[e]=n;try{Pa(t)}catch(r){d.error(`debug-mode: failed to persist state: ${String(r)}`)}return n}async function Me(e,t){let n={baseUrl:e.baseUrl,token:e.token,contextToken:e.contextToken};await ue({to:e.to,text:t,opts:n})}async function Ua(e,t,n,r){let i=t.trim();i&&await Me(e,i);let o=r??0,s=o>0?`${n-o}ms`:"N/A";await Me(e,["\u23F1 \u901A\u9053\u8017\u65F6",`\u251C \u4E8B\u4EF6\u65F6\u95F4: ${o>0?new Date(o).toISOString():"N/A"}`,`\u251C \u5E73\u53F0\u2192\u63D2\u4EF6: ${s}`,`\u2514 \u63D2\u4EF6\u5904\u7406: ${Date.now()-n}ms`].join(` `))}async function Oa(e,t,n,r){let i=e.trim();if(!i.startsWith("/"))return{handled:!1};let o=i.indexOf(" "),s=o===-1?i.toLowerCase():i.slice(0,o).toLowerCase(),a=o===-1?"":i.slice(o+1);d.info(`[weixin] Slash command: ${s}, args: ${a.slice(0,50)}`);try{switch(s){case"/echo":return await Ua(t,a,n,r),{handled:!0};case"/toggle-debug":return await Me(t,$a(t.accountId)?"Debug \u6A21\u5F0F\u5DF2\u5F00\u542F":"Debug \u6A21\u5F0F\u5DF2\u5173\u95ED"),{handled:!0};case"/clear":return t.onClear?.(),await Me(t,"\u2705 \u4F1A\u8BDD\u5DF2\u6E05\u9664\uFF0C\u91CD\u65B0\u5F00\u59CB\u5BF9\u8BDD"),{handled:!0};default:return{handled:!1}}}catch(l){d.error(`[weixin] Slash command error: ${String(l)}`);try{await Me(t,`\u274C \u6307\u4EE4\u6267\u884C\u5931\u8D25: ${String(l).slice(0,200)}`)}catch{}return{handled:!0}}}var Jr=b.default.join(_e.default.tmpdir(),"weixin-agent/media");async function Na(e,t,n,r,i){let o=b.default.join(Jr,n??"");await me.default.mkdir(o,{recursive:!0});let s=".bin";i?s=b.default.extname(i)||".bin":t&&(s=Fr(t));let a=`${Date.now()}-${O.default.randomBytes(4).toString("hex")}${s}`,l=b.default.join(o,a);return await me.default.writeFile(l,e),{path:l}}function Da(e){if(!e?.length)return"";for(let t of e)if(t.type===L.TEXT&&t.text_item?.text!=null)return String(t.text_item.text);return""}function Fa(e){if(!e?.length)return;let t=r=>r?.encrypt_query_param||r?.full_url,n=e.find(r=>r.type===L.IMAGE&&t(r.image_item?.media))??e.find(r=>r.type===L.VIDEO&&t(r.video_item?.media))??e.find(r=>r.type===L.FILE&&t(r.file_item?.media))??e.find(r=>r.type===L.VOICE&&t(r.voice_item?.media)&&!r.voice_item?.text);return n||(e.find(r=>r.type===L.TEXT&&r.ref_msg?.message_item&&Gr(r.ref_msg.message_item))?.ref_msg?.message_item??void 0)}async function qa(e,t){let n=Date.now(),r=Da(e.item_list);if(r.startsWith("/")){let f=e.from_user_id??"";if((await Oa(r,{to:f,contextToken:e.context_token,baseUrl:t.baseUrl,token:t.token,accountId:t.accountId,log:t.log,errLog:t.errLog,onClear:()=>t.agent.clearSession?.(f)},n,e.create_time_ms)).handled)return}let i=e.context_token;i&&ma(t.accountId,e.from_user_id??"",i);let o,s=Fa(e.item_list);if(s)try{let f=await va(s,{cdnBaseUrl:t.cdnBaseUrl,saveMedia:Na,log:t.log,errLog:t.errLog,label:"inbound"});f.decryptedPicPath?o={type:"image",filePath:f.decryptedPicPath,mimeType:"image/*"}:f.decryptedVideoPath?o={type:"video",filePath:f.decryptedVideoPath,mimeType:"video/mp4"}:f.decryptedFilePath?o={type:"file",filePath:f.decryptedFilePath,mimeType:f.fileMediaType??"application/octet-stream",fileName:s.file_item?.file_name}:f.decryptedVoicePath&&(o={type:"audio",filePath:f.decryptedVoicePath,mimeType:f.voiceMediaType??"audio/wav"})}catch(f){d.error(`media download failed: ${String(f)}`)}let a={conversationId:e.from_user_id??"",text:Yr(e.item_list),media:o},l=e.from_user_id??"",u,c=()=>{t.typingTicket&&ur({baseUrl:t.baseUrl,token:t.token,body:{ilink_user_id:l,typing_ticket:t.typingTicket,status:fr.TYPING}}).catch(()=>{})};t.typingTicket&&(c(),u=setInterval(c,1e4));try{let f=await t.agent.chat(a);if(f.media){let h,g=f.media.url;g.startsWith("http://")||g.startsWith("https://")?h=await Hr(g,b.default.join(Jr,"outbound")):h=b.default.isAbsolute(g)?g:b.default.resolve(g),await Vr({filePath:h,to:l,text:f.text?rt(f.text):"",opts:{baseUrl:t.baseUrl,token:t.token,contextToken:i},cdnBaseUrl:t.cdnBaseUrl})}else f.text&&await ue({to:l,text:rt(f.text),opts:{baseUrl:t.baseUrl,token:t.token,contextToken:i}})}catch(f){d.error(`processOneMessage: agent or send failed: ${f instanceof Error?f.stack??f.message:JSON.stringify(f)}`),Ma({to:l,contextToken:i,message:`\u26A0\uFE0F \u5904\u7406\u6D88\u606F\u5931\u8D25\uFF1A${f instanceof Error?f.message:JSON.stringify(f)}`,baseUrl:t.baseUrl,token:t.token,errLog:t.errLog})}finally{u&&clearInterval(u),t.typingTicket&&ur({baseUrl:t.baseUrl,token:t.token,body:{ilink_user_id:l,typing_ticket:t.typingTicket,status:fr.CANCEL}}).catch(()=>{})}}function Xr(){return b.default.join(ye(),"openclaw-weixin","accounts")}function Wa(e){return b.default.join(Xr(),`${e}.sync.json`)}function Ha(){return b.default.join(ye(),"agents","default","sessions",".openclaw-weixin-sync","default.json")}function St(e){try{let t=A.default.readFileSync(e,"utf-8"),n=JSON.parse(t);if(typeof n.get_updates_buf=="string")return n.get_updates_buf}catch{}}function za(e){let t=St(e);if(t!==void 0)return t;let n=yr(b.default.basename(e,".sync.json"));if(n){let r=St(b.default.join(Xr(),`${n}.sync.json`));if(r!==void 0)return r}return St(Ha())}function Ga(e,t){let n=b.default.dirname(e);A.default.mkdirSync(n,{recursive:!0}),A.default.writeFileSync(e,JSON.stringify({get_updates_buf:t},null,0),"utf-8")}var Ya=35e3,Be=3,gr=3e4,pr=2e3;async function Ka(e){let{baseUrl:t,cdnBaseUrl:n,token:r,accountId:i,agent:o,abortSignal:s,longPollTimeoutMs:a,onConnectionStatusChange:l}=e,u=e.log??(T=>console.log(T)),c=T=>{u(T),d.error(T)},f=d.withAccount(i);u(`[weixin] monitor started (${t}, account=${i})`),f.info(`Monitor started: baseUrl=${t}`);let h=Wa(i),g=za(h),p=g??"";u(g?`[weixin] resuming from previous sync buf (${p.length} bytes)`:"[weixin] no previous sync buf, starting fresh");let _=new Ca({baseUrl:t,token:r},u),y=a??Ya,w=0,P=!0;for(;!s?.aborted;)try{let T=await Js({baseUrl:t,token:r,get_updates_buf:p,timeoutMs:y,abortSignal:s});if(T.longpolling_timeout_ms!=null&&T.longpolling_timeout_ms>0&&(y=T.longpolling_timeout_ms),T.ret!==void 0&&T.ret!==0||T.errcode!==void 0&&T.errcode!==0){if(T.errcode===-14||T.ret===-14){ka(i);let C=Aa(i);c(`[weixin] session expired (errcode -14), pausing for ${Math.ceil(C/6e4)} min. Please run \`npx weixin-acp login\` to re-login.`),w=0,P&&(P=!1,l?.("disconnected")),await ve(C,s);continue}w+=1,c(`[weixin] getUpdates failed: ret=${T.ret} errcode=${T.errcode} errmsg=${T.errmsg??""} (${w}/${Be})`),w>=Be?(c(`[weixin] ${Be} consecutive failures, backing off 30s`),P&&(P=!1,l?.("disconnected")),w=0,await ve(gr,s)):await ve(pr,s);continue}w=0,P||(P=!0,l?.("connected")),T.get_updates_buf!=null&&T.get_updates_buf!==""&&(Ga(h,T.get_updates_buf),p=T.get_updates_buf);let S=T.msgs??[];for(let C of S){f.info(`inbound: from=${C.from_user_id} types=${C.item_list?.map(D=>D.type).join(",")??"none"}`);let $=C.from_user_id??"";await qa(C,{accountId:i,agent:o,baseUrl:t,cdnBaseUrl:n,token:r,typingTicket:(await _.getForUser($,C.context_token)).typingTicket,log:u,errLog:c})}}catch(T){if(s?.aborted){f.info("Monitor stopped (aborted)");return}w+=1,c(`[weixin] getUpdates error (${w}/${Be}): ${String(T)}`),w>=Be?(P&&(P=!1,l?.("disconnected")),w=0,await ve(gr,s)):await ve(pr,s)}f.info("Monitor ended")}function ve(e,t){return new Promise((n,r)=>{let i=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(i),r(new Error("aborted"))},{once:!0})})}var Va=b.default.join(_e.default.tmpdir(),"weixin-agent/media");function Zr(){let e=it();return e.length===0?!1:ot(e[0]).configured}var ja=class{_accountId;_baseUrl;_cdnBaseUrl;_token;_userId;constructor(e){this._accountId=e.accountId,this._baseUrl=e.baseUrl,this._cdnBaseUrl=e.cdnBaseUrl,this._token=e.token,this._userId=e.userId}async sendMessage(e){let t=typeof e=="string"?{text:e}:e,n=Dt(this._accountId,this._userId);if(!n)throw new Error("\u6CA1\u6709\u627E\u5230 context_token\uFF0C\u9700\u8981\u5728 start() \u8FD0\u884C\u671F\u95F4\u81F3\u5C11\u6536\u5230\u8FC7\u4E00\u6761\u6D88\u606F");let r={baseUrl:this._baseUrl,token:this._token,contextToken:n};if(t.media){let i,o=t.media.url;o.startsWith("http://")||o.startsWith("https://")?i=await Hr(o,b.default.join(Va,"outbound")):i=b.default.isAbsolute(o)?o:b.default.resolve(o),await Vr({filePath:i,to:this._userId,text:t.text?rt(t.text):"",opts:r,cdnBaseUrl:this._cdnBaseUrl});return}if(t.text){await ue({to:this._userId,text:rt(t.text),opts:r});return}throw new Error("\u6D88\u606F\u5FC5\u987B\u5305\u542B text \u6216 media")}};async function ei(e,t){let n=t?.log??console.log,r=t?.accountId;if(!r){let a=it();if(a.length===0)throw new Error("\u6CA1\u6709\u5DF2\u767B\u5F55\u7684\u8D26\u53F7\uFF0C\u8BF7\u5148\u8FD0\u884C login");r=a[0],a.length>1&&n(`[weixin] \u68C0\u6D4B\u5230\u591A\u4E2A\u8D26\u53F7\uFF0C\u4F7F\u7528\u7B2C\u4E00\u4E2A: ${r}`)}let i=ot(r);if(!i.configured)throw new Error(`\u8D26\u53F7 ${r} \u672A\u914D\u7F6E (\u7F3A\u5C11 token)\uFF0C\u8BF7\u5148\u8FD0\u884C login`);let o=Re(i.accountId)?.userId;if(!o)throw new Error(`\u8D26\u53F7 ${r} \u6CA1\u6709\u5173\u8054\u7684\u7528\u6237 ID\uFF0C\u8BF7\u91CD\u65B0\u8FD0\u884C login`);n(`[weixin] \u542F\u52A8 bot, account=${i.accountId}`);let s=new ja({accountId:i.accountId,baseUrl:i.baseUrl,cdnBaseUrl:i.cdnBaseUrl,token:i.token,userId:o});return await Ka({baseUrl:i.baseUrl,cdnBaseUrl:i.cdnBaseUrl,token:i.token,accountId:i.accountId,agent:e,abortSignal:t?.abortSignal,log:n,onConnectionStatusChange:t?.onConnectionStatusChange}),s}var Mn=require("node:fs/promises"),dc=(()=>{try{return process.env.IM_BRIDGE_CONFIG?JSON.parse(process.env.IM_BRIDGE_CONFIG):{}}catch{return{}}})(),fs=dc.baseUrl,bt=null,Se=null,Rn=!1,Le=new Map;function hc(e){let t="";if(e.type==="AskUserQuestion"&&e.questions?.length){t+=`\u{1F4CB} AI has a question: `;for(let n of e.questions)n.header&&(t+=`\u3010${n.header}\u3011`),t+=`${n.question} `,n.options?.length&&n.options.forEach((r,i)=>{let o=i+1;t+=` ${o}. ${r.label}`,r.description&&(t+=` \u2014 ${r.description}`),t+=` `}),t+=` `;t+=`Reply with option number. Multiple questions separate answers with space (e.g. "1 1 2"). Or type your custom answer. Reply "skip" to skip.`}else if(e.type==="RunCommand")t+=`\u26A1 AI wants to run a command: `,t+=`$ ${e.command||""} `,e.cwd&&(t+=`\u{1F4C2} Working directory: ${e.cwd} `),t+=` Reply "confirm" to execute, or "skip" to cancel.`;else if(e.type==="ExitPlanMode"){if(t+=`\u{1F4CB} AI has generated an execution plan: `,e.plan&&(t+=e.plan+` `),e.filePaths?.length){t+=` Files: `;for(let n of e.filePaths)t+=` \u2022 ${n} `}t+=` Reply "confirm" to proceed, or "skip" to cancel.`}else e.type==="NotifyUser"?(t+=`\u{1F4DD} AI notification: `,t+=e.message||e.text||JSON.stringify(e)):(t+=`\u{1F514} AI interaction (${e.type||"unknown"}): `,t+=JSON.stringify(e,null,2));return t}function E(e,t){try{process.send&&process.send({type:e,payload:t})}catch{}}async function ds(){try{let e=await $r({apiBaseUrl:fs,botType:"3"});if(!e.qrcodeUrl){E("error",{message:e.message||"Failed to get QR code"});return}let n=await(await Promise.resolve().then(()=>J(cs(),1))).default.toDataURL(e.qrcodeUrl,{width:200});E("qrcode",{url:n});let r=await Ur({sessionKey:e.sessionKey,apiBaseUrl:fs,timeoutMs:48e4,botType:"3"});if(!r.connected||!r.botToken){E("error",{message:r.message||"Login failed"});return}let i=Rt(r.accountId??"");Tr(i,{token:r.botToken,baseUrl:r.baseUrl,userId:r.userId}),br(i),E("connected",{accountId:i}),await Pn()}catch(e){E("error",{message:String(e)})}}async function gc(){let e=Zr();if(E("log",{message:`[bridge] handleReconnect: isLoggedIn=${e}`}),e)try{E("log",{message:"[bridge] Found saved credentials, trying to reconnect..."}),E("connected",{accountId:"reconnected"}),Pn().catch(t=>{E("log",{message:`[bridge] Reconnect start failed: ${t}`})});return}catch(t){E("log",{message:`[bridge] Reconnect failed: ${t}, falling back to login`})}E("log",{message:"[bridge] No saved credentials, starting QR login..."}),await ds()}async function Pn(){if(bt){E("error",{message:"Bot already running"});return}try{Se=new AbortController,bt=await ei({async chat(t){if(Rn)return{text:""};let n={conversationId:t.conversationId,text:t.text};if(t.media){if(n.media={type:t.media.type,fileName:t.media.fileName,mimeType:t.media.mimeType,filePath:t.media.filePath},t.media.type==="image"&&t.media.filePath)try{n.media.base64=(await(0,Mn.readFile)(t.media.filePath)).toString("base64"),E("log",{message:`[bridge] Image base64 encoded, size: ${n.media.base64.length}`})}catch(r){E("log",{message:`[bridge] Failed to read image: ${r}`})}if((t.media.type==="file"||t.media.type==="audio"||t.media.type==="video")&&t.media.filePath){let r=(t.media.fileName||t.media.filePath).split(".").pop()?.toLowerCase()??"";if(["txt","md","json","js","ts","jsx","tsx","py","java","c","cpp","h","hpp","css","html","xml","yaml","yml","toml","ini","cfg","sh","bash","zsh","sql","csv","log","rs","go","rb","php","swift","kt","scala","r","lua","pl","diff","patch"].includes(r))try{let o=await(0,Mn.readFile)(t.media.filePath,"utf-8"),s=t.media.fileName||"file."+r;n.text=(n.text||"")+` --- File: ${s} --- ${o} --- End of File ---`,E("log",{message:`[bridge] File content embedded, size: ${o.length}`})}catch(o){E("log",{message:`[bridge] Failed to read file content: ${o}`})}}}return E("message",n),new Promise(r=>{let i=setTimeout(()=>{Le.delete(t.conversationId),r({text:"\u23F3 AI response timeout, please retry."})},3e5);Le.set(t.conversationId,o=>{clearTimeout(i),r(o)})})}},{abortSignal:Se.signal,log:t=>E("log",{message:t}),onConnectionStatusChange:t=>{t==="disconnected"?E("connection_lost",{}):E("connection_restored",{})}})}catch(e){E("error",{message:`Start failed: ${String(e)}`}),bt=null,Se=null}}function Ve(){Se&&(Se.abort(),Se=null),bt=null,E("disconnected",{reason:"stopped"})}function pc(e){let{conversationId:t,text:n,media:r}=e??{};if(!t||!n&&!r)return;let i=Le.get(t);if(i){Le.delete(t);let o={};n&&(o.text=n),r&&(o.media=r),i(o)}}function hs(){let e=it();if(!e.length)return null;let t=ot(e[0]);if(!t.configured)return null;let r=Re(e[0])?.userId||"";if(!r)return null;let i=Dt(t.accountId,r);return i?{baseUrl:t.baseUrl,token:t.token,contextToken:i,userId:r,cdnBaseUrl:t.cdnBaseUrl}:null}async function mc(e){let{interaction:t}=e||{};if(!t)return;E("log",{message:`[bridge] handleInteraction: type=${t.type}, toolCallId=${t.toolCallId}`});let n=hs();if(n)try{let r=hc(t);await ue({to:n.userId,text:r,opts:n}),E("log",{message:"[bridge] Interaction text sent to user via SDK"})}catch(r){E("log",{message:`[bridge] Failed to send interaction text: ${r}`})}else E("log",{message:"[bridge] Cannot send interaction text: no API opts (no context_token yet?)"})}async function _c(e){let{text:t,conversationId:n}=e||{};if(!t){E("log",{message:"[bridge] handlePushMessage: no text, ignoring"});return}E("log",{message:`[bridge] handlePushMessage: text="${t.slice(0,50)}", to=${n||"default"}`});let r=hs();if(!r){E("log",{message:"[bridge] handlePushMessage: no API opts (no context_token yet?)"});return}try{let i=n||r.userId;await ue({to:i,text:t,opts:r}),E("log",{message:`[bridge] Push message sent to ${i}`})}catch(i){E("log",{message:`[bridge] Failed to push message: ${i}`})}}process.on("message",e=>{let{command:t,payload:n}=e;switch(t){case"login":ds();break;case"reconnect":gc();break;case"start":Pn();break;case"stop":Ve();break;case"reply":pc(n);break;case"pause":Rn=!0;for(let[r,i]of Le.entries())Le.delete(r),i({text:""});break;case"resume":Rn=!1;break;case"interaction":mc(n);break;case"push":_c(n);break}});process.on("disconnect",()=>{Ve(),process.exit(0)});process.on("SIGTERM",()=>{Ve(),process.exit(0)});process.on("SIGINT",()=>{Ve(),process.exit(0)});process.on("unhandledRejection",e=>{console.error("[WeixinBridge] Unhandled rejection:",e),E("error",{message:String(e?.message||e)})});process.on("uncaughtException",e=>{console.error("[WeixinBridge] Uncaught exception:",e),E("error",{message:String(e?.message||e)}),Ve(),process.exit(1)});E("ready",{});