@openduo/channel-wechat 0.1.1 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/plugin.js +33 -33
- package/package.json +1 -1
package/dist/plugin.js
CHANGED
|
@@ -1,43 +1,43 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __createRequire } from "node:module";
|
|
3
3
|
const require = __createRequire(import.meta.url);
|
|
4
|
-
var
|
|
5
|
-
]))+`;de.KANJI=new RegExp(tt,"g");de.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");de.BYTE=new RegExp(
|
|
6
|
-
Make sure your charset is UTF-8`);r=(r>>>8&255)*192+(r&255),t.put(r,13)}};ki.exports=We});var Si=P((
|
|
7
|
-
Suggested mode is: `+M.toString(n));switch(r===M.KANJI&&!Tt.isKanjiModeEnabled()&&(r=M.BYTE),r){case M.NUMERIC:return new
|
|
4
|
+
var fa=Object.create;var Mn=Object.defineProperty;var ca=Object.getOwnPropertyDescriptor;var ha=Object.getOwnPropertyNames;var da=Object.getPrototypeOf,pa=Object.prototype.hasOwnProperty;var W=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var P=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var ga=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ha(e))!pa.call(t,i)&&i!==r&&Mn(t,i,{get:()=>e[i],enumerable:!(n=ca(e,i))||n.enumerable});return t};var er=(t,e,r)=>(r=t!=null?fa(da(t)):{},ga(e||!t||!t.__esModule?Mn(r,"default",{value:t,enumerable:!0}):r,t));var rr=P((wc,jn)=>{jn.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var ye=P(Ae=>{var nr,ba=[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];Ae.getSymbolSize=function(e){if(!e)throw new Error('"version" cannot be null or undefined');if(e<1||e>40)throw new Error('"version" should be in range from 1 to 40');return e*4+17};Ae.getSymbolTotalCodewords=function(e){return ba[e]};Ae.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};Ae.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');nr=e};Ae.isKanjiModeEnabled=function(){return typeof nr<"u"};Ae.toSJIS=function(e){return nr(e)}});var mt=P(te=>{te.L={bit:1};te.M={bit:0};te.Q={bit:3};te.H={bit:2};function Ca(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return te.L;case"m":case"medium":return te.M;case"q":case"quartile":return te.Q;case"h":case"high":return te.H;default:throw new Error("Unknown EC Level: "+t)}}te.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};te.from=function(e,r){if(te.isValid(e))return e;try{return Ca(e)}catch{return r}}});var Yn=P((Ec,Gn)=>{function Qn(){this.buffer=[],this.length=0}Qn.prototype={get:function(t){let e=Math.floor(t/8);return(this.buffer[e]>>>7-t%8&1)===1},put:function(t,e){for(let r=0;r<e;r++)this.putBit((t>>>e-r-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){let e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}};Gn.exports=Qn});var Jn=P((Tc,Vn)=>{function Ze(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}Ze.prototype.set=function(t,e,r,n){let i=t*this.size+e;this.data[i]=r,n&&(this.reservedBit[i]=!0)};Ze.prototype.get=function(t,e){return this.data[t*this.size+e]};Ze.prototype.xor=function(t,e,r){this.data[t*this.size+e]^=r};Ze.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};Vn.exports=Ze});var Kn=P(yt=>{var Ea=ye().getSymbolSize;yt.getRowColCoords=function(e){if(e===1)return[];let r=Math.floor(e/7)+2,n=Ea(e),i=n===145?26:Math.ceil((n-13)/(2*r-2))*2,s=[n-7];for(let o=1;o<r-1;o++)s[o]=s[o-1]-i;return s.push(6),s.reverse()};yt.getPositions=function(e){let r=[],n=yt.getRowColCoords(e),i=n.length;for(let s=0;s<i;s++)for(let o=0;o<i;o++)s===0&&o===0||s===0&&o===i-1||s===i-1&&o===0||r.push([n[s],n[o]]);return r}});var ei=P(Xn=>{var Ta=ye().getSymbolSize,Zn=7;Xn.getPositions=function(e){let r=Ta(e);return[[0,0],[r-Zn,0],[0,r-Zn]]}});var ti=P($=>{$.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var Ie={N1:3,N2:3,N3:40,N4:10};$.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};$.from=function(e){return $.isValid(e)?parseInt(e,10):void 0};$.getPenaltyN1=function(e){let r=e.size,n=0,i=0,s=0,o=null,a=null;for(let u=0;u<r;u++){i=s=0,o=a=null;for(let c=0;c<r;c++){let h=e.get(u,c);h===o?i++:(i>=5&&(n+=Ie.N1+(i-5)),o=h,i=1),h=e.get(c,u),h===a?s++:(s>=5&&(n+=Ie.N1+(s-5)),a=h,s=1)}i>=5&&(n+=Ie.N1+(i-5)),s>=5&&(n+=Ie.N1+(s-5))}return n};$.getPenaltyN2=function(e){let r=e.size,n=0;for(let i=0;i<r-1;i++)for(let s=0;s<r-1;s++){let o=e.get(i,s)+e.get(i,s+1)+e.get(i+1,s)+e.get(i+1,s+1);(o===4||o===0)&&n++}return n*Ie.N2};$.getPenaltyN3=function(e){let r=e.size,n=0,i=0,s=0;for(let o=0;o<r;o++){i=s=0;for(let a=0;a<r;a++)i=i<<1&2047|e.get(o,a),a>=10&&(i===1488||i===93)&&n++,s=s<<1&2047|e.get(a,o),a>=10&&(s===1488||s===93)&&n++}return n*Ie.N3};$.getPenaltyN4=function(e){let r=0,n=e.data.length;for(let s=0;s<n;s++)r+=e.data[s];return Math.abs(Math.ceil(r*100/n/5)-10)*Ie.N4};function ka(t,e,r){switch(t){case $.Patterns.PATTERN000:return(e+r)%2===0;case $.Patterns.PATTERN001:return e%2===0;case $.Patterns.PATTERN010:return r%3===0;case $.Patterns.PATTERN011:return(e+r)%3===0;case $.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(r/3))%2===0;case $.Patterns.PATTERN101:return e*r%2+e*r%3===0;case $.Patterns.PATTERN110:return(e*r%2+e*r%3)%2===0;case $.Patterns.PATTERN111:return(e*r%3+(e+r)%2)%2===0;default:throw new Error("bad maskPattern:"+t)}}$.applyMask=function(e,r){let n=r.size;for(let i=0;i<n;i++)for(let s=0;s<n;s++)r.isReserved(s,i)||r.xor(s,i,ka(e,s,i))};$.getBestMask=function(e,r){let n=Object.keys($.Patterns).length,i=0,s=1/0;for(let o=0;o<n;o++){r(o),$.applyMask(o,e);let a=$.getPenaltyN1(e)+$.getPenaltyN2(e)+$.getPenaltyN3(e)+$.getPenaltyN4(e);$.applyMask(o,e),a<s&&(s=a,i=o)}return i}});var sr=P(ir=>{var _e=mt(),_t=[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],wt=[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];ir.getBlocksCount=function(e,r){switch(r){case _e.L:return _t[(e-1)*4+0];case _e.M:return _t[(e-1)*4+1];case _e.Q:return _t[(e-1)*4+2];case _e.H:return _t[(e-1)*4+3];default:return}};ir.getTotalCodewordsCount=function(e,r){switch(r){case _e.L:return wt[(e-1)*4+0];case _e.M:return wt[(e-1)*4+1];case _e.Q:return wt[(e-1)*4+2];case _e.H:return wt[(e-1)*4+3];default:return}}});var ri=P(Ct=>{var Xe=new Uint8Array(512),bt=new Uint8Array(256);(function(){let e=1;for(let r=0;r<255;r++)Xe[r]=e,bt[e]=r,e<<=1,e&256&&(e^=285);for(let r=255;r<512;r++)Xe[r]=Xe[r-255]})();Ct.log=function(e){if(e<1)throw new Error("log("+e+")");return bt[e]};Ct.exp=function(e){return Xe[e]};Ct.mul=function(e,r){return e===0||r===0?0:Xe[bt[e]+bt[r]]}});var ni=P(et=>{var or=ri();et.mul=function(e,r){let n=new Uint8Array(e.length+r.length-1);for(let i=0;i<e.length;i++)for(let s=0;s<r.length;s++)n[i+s]^=or.mul(e[i],r[s]);return n};et.mod=function(e,r){let n=new Uint8Array(e);for(;n.length-r.length>=0;){let i=n[0];for(let o=0;o<r.length;o++)n[o]^=or.mul(r[o],i);let s=0;for(;s<n.length&&n[s]===0;)s++;n=n.slice(s)}return n};et.generateECPolynomial=function(e){let r=new Uint8Array([1]);for(let n=0;n<e;n++)r=et.mul(r,new Uint8Array([1,or.exp(n)]));return r}});var oi=P((Ac,si)=>{var ii=ni();function ar(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}ar.prototype.initialize=function(e){this.degree=e,this.genPoly=ii.generateECPolynomial(this.degree)};ar.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");let r=new Uint8Array(e.length+this.degree);r.set(e);let n=ii.mod(r,this.genPoly),i=this.degree-n.length;if(i>0){let s=new Uint8Array(this.degree);return s.set(n,i),s}return n};si.exports=ar});var lr=P(ai=>{ai.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var ur=P(de=>{var li="[0-9]+",Pa="[A-Z $%*+\\-./:]+",tt="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";tt=tt.replace(/u/g,"\\u");var Sa="(?:(?![A-Z0-9 $%*+\\-./:]|"+tt+`)(?:.|[\r
|
|
5
|
+
]))+`;de.KANJI=new RegExp(tt,"g");de.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");de.BYTE=new RegExp(Sa,"g");de.NUMERIC=new RegExp(li,"g");de.ALPHANUMERIC=new RegExp(Pa,"g");var xa=new RegExp("^"+tt+"$"),Ba=new RegExp("^"+li+"$"),Ra=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");de.testKanji=function(e){return xa.test(e)};de.testNumeric=function(e){return Ba.test(e)};de.testAlphanumeric=function(e){return Ra.test(e)}});var we=P(H=>{var Aa=lr(),fr=ur();H.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};H.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};H.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};H.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};H.MIXED={bit:-1};H.getCharCountIndicator=function(e,r){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!Aa.isValid(r))throw new Error("Invalid version: "+r);return r>=1&&r<10?e.ccBits[0]:r<27?e.ccBits[1]:e.ccBits[2]};H.getBestModeForData=function(e){return fr.testNumeric(e)?H.NUMERIC:fr.testAlphanumeric(e)?H.ALPHANUMERIC:fr.testKanji(e)?H.KANJI:H.BYTE};H.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};H.isValid=function(e){return e&&e.bit&&e.ccBits};function Ia(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return H.NUMERIC;case"alphanumeric":return H.ALPHANUMERIC;case"kanji":return H.KANJI;case"byte":return H.BYTE;default:throw new Error("Unknown mode: "+t)}}H.from=function(e,r){if(H.isValid(e))return e;try{return Ia(e)}catch{return r}}});var di=P(ve=>{var Et=ye(),va=sr(),ui=mt(),be=we(),cr=lr(),ci=7973,fi=Et.getBCHDigit(ci);function Oa(t,e,r){for(let n=1;n<=40;n++)if(e<=ve.getCapacity(n,r,t))return n}function hi(t,e){return be.getCharCountIndicator(t,e)+4}function La(t,e){let r=0;return t.forEach(function(n){let i=hi(n.mode,e);r+=i+n.getBitsLength()}),r}function Ma(t,e){for(let r=1;r<=40;r++)if(La(t,r)<=ve.getCapacity(r,e,be.MIXED))return r}ve.from=function(e,r){return cr.isValid(e)?parseInt(e,10):r};ve.getCapacity=function(e,r,n){if(!cr.isValid(e))throw new Error("Invalid QR Code version");typeof n>"u"&&(n=be.BYTE);let i=Et.getSymbolTotalCodewords(e),s=va.getTotalCodewordsCount(e,r),o=(i-s)*8;if(n===be.MIXED)return o;let a=o-hi(n,e);switch(n){case be.NUMERIC:return Math.floor(a/10*3);case be.ALPHANUMERIC:return Math.floor(a/11*2);case be.KANJI:return Math.floor(a/13);case be.BYTE:default:return Math.floor(a/8)}};ve.getBestVersionForData=function(e,r){let n,i=ui.from(r,ui.M);if(Array.isArray(e)){if(e.length>1)return Ma(e,i);if(e.length===0)return 1;n=e[0]}else n=e;return Oa(n.mode,n.getLength(),i)};ve.getEncodedBits=function(e){if(!cr.isValid(e)||e<7)throw new Error("Invalid QR Code version");let r=e<<12;for(;Et.getBCHDigit(r)-fi>=0;)r^=ci<<Et.getBCHDigit(r)-fi;return e<<12|r}});var yi=P(mi=>{var hr=ye(),gi=1335,Na=21522,pi=hr.getBCHDigit(gi);mi.getEncodedBits=function(e,r){let n=e.bit<<3|r,i=n<<10;for(;hr.getBCHDigit(i)-pi>=0;)i^=gi<<hr.getBCHDigit(i)-pi;return(n<<10|i)^Na}});var wi=P((Nc,_i)=>{var $a=we();function Fe(t){this.mode=$a.NUMERIC,this.data=t.toString()}Fe.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};Fe.prototype.getLength=function(){return this.data.length};Fe.prototype.getBitsLength=function(){return Fe.getBitsLength(this.data.length)};Fe.prototype.write=function(e){let r,n,i;for(r=0;r+3<=this.data.length;r+=3)n=this.data.substr(r,3),i=parseInt(n,10),e.put(i,10);let s=this.data.length-r;s>0&&(n=this.data.substr(r),i=parseInt(n,10),e.put(i,s*3+1))};_i.exports=Fe});var Ci=P(($c,bi)=>{var Ua=we(),dr=["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 qe(t){this.mode=Ua.ALPHANUMERIC,this.data=t}qe.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};qe.prototype.getLength=function(){return this.data.length};qe.prototype.getBitsLength=function(){return qe.getBitsLength(this.data.length)};qe.prototype.write=function(e){let r;for(r=0;r+2<=this.data.length;r+=2){let n=dr.indexOf(this.data[r])*45;n+=dr.indexOf(this.data[r+1]),e.put(n,11)}this.data.length%2&&e.put(dr.indexOf(this.data[r]),6)};bi.exports=qe});var Ti=P((Uc,Ei)=>{var Fa=we();function De(t){this.mode=Fa.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}De.getBitsLength=function(e){return e*8};De.prototype.getLength=function(){return this.data.length};De.prototype.getBitsLength=function(){return De.getBitsLength(this.data.length)};De.prototype.write=function(t){for(let e=0,r=this.data.length;e<r;e++)t.put(this.data[e],8)};Ei.exports=De});var Pi=P((Fc,ki)=>{var qa=we(),Da=ye();function We(t){this.mode=qa.KANJI,this.data=t}We.getBitsLength=function(e){return e*13};We.prototype.getLength=function(){return this.data.length};We.prototype.getBitsLength=function(){return We.getBitsLength(this.data.length)};We.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let r=Da.toSJIS(this.data[e]);if(r>=33088&&r<=40956)r-=33088;else if(r>=57408&&r<=60351)r-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+`
|
|
6
|
+
Make sure your charset is UTF-8`);r=(r>>>8&255)*192+(r&255),t.put(r,13)}};ki.exports=We});var Si=P((qc,pr)=>{"use strict";var rt={single_source_shortest_paths:function(t,e,r){var n={},i={};i[e]=0;var s=rt.PriorityQueue.make();s.push(e,0);for(var o,a,u,c,h,y,_,b,g;!s.empty();){o=s.pop(),a=o.value,c=o.cost,h=t[a]||{};for(u in h)h.hasOwnProperty(u)&&(y=h[u],_=c+y,b=i[u],g=typeof i[u]>"u",(g||b>_)&&(i[u]=_,s.push(u,_),n[u]=a))}if(typeof r<"u"&&typeof i[r]>"u"){var w=["Could not find a path from ",e," to ",r,"."].join("");throw new Error(w)}return n},extract_shortest_path_from_predecessor_list:function(t,e){for(var r=[],n=e,i;n;)r.push(n),i=t[n],n=t[n];return r.reverse(),r},find_path:function(t,e,r){var n=rt.single_source_shortest_paths(t,e,r);return rt.extract_shortest_path_from_predecessor_list(n,r)},PriorityQueue:{make:function(t){var e=rt.PriorityQueue,r={},n;t=t||{};for(n in e)e.hasOwnProperty(n)&&(r[n]=e[n]);return r.queue=[],r.sorter=t.sorter||e.default_sorter,r},default_sorter:function(t,e){return t.cost-e.cost},push:function(t,e){var r={value:t,cost:e};this.queue.push(r),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof pr<"u"&&(pr.exports=rt)});var Li=P(He=>{var M=we(),Ri=wi(),Ai=Ci(),Ii=Ti(),vi=Pi(),nt=ur(),Tt=ye(),Wa=Si();function xi(t){return unescape(encodeURIComponent(t)).length}function it(t,e,r){let n=[],i;for(;(i=t.exec(r))!==null;)n.push({data:i[0],index:i.index,mode:e,length:i[0].length});return n}function Oi(t){let e=it(nt.NUMERIC,M.NUMERIC,t),r=it(nt.ALPHANUMERIC,M.ALPHANUMERIC,t),n,i;return Tt.isKanjiModeEnabled()?(n=it(nt.BYTE,M.BYTE,t),i=it(nt.KANJI,M.KANJI,t)):(n=it(nt.BYTE_KANJI,M.BYTE,t),i=[]),e.concat(r,n,i).sort(function(o,a){return o.index-a.index}).map(function(o){return{data:o.data,mode:o.mode,length:o.length}})}function gr(t,e){switch(e){case M.NUMERIC:return Ri.getBitsLength(t);case M.ALPHANUMERIC:return Ai.getBitsLength(t);case M.KANJI:return vi.getBitsLength(t);case M.BYTE:return Ii.getBitsLength(t)}}function Ha(t){return t.reduce(function(e,r){let n=e.length-1>=0?e[e.length-1]:null;return n&&n.mode===r.mode?(e[e.length-1].data+=r.data,e):(e.push(r),e)},[])}function za(t){let e=[];for(let r=0;r<t.length;r++){let n=t[r];switch(n.mode){case M.NUMERIC:e.push([n,{data:n.data,mode:M.ALPHANUMERIC,length:n.length},{data:n.data,mode:M.BYTE,length:n.length}]);break;case M.ALPHANUMERIC:e.push([n,{data:n.data,mode:M.BYTE,length:n.length}]);break;case M.KANJI:e.push([n,{data:n.data,mode:M.BYTE,length:xi(n.data)}]);break;case M.BYTE:e.push([{data:n.data,mode:M.BYTE,length:xi(n.data)}])}}return e}function ja(t,e){let r={},n={start:{}},i=["start"];for(let s=0;s<t.length;s++){let o=t[s],a=[];for(let u=0;u<o.length;u++){let c=o[u],h=""+s+u;a.push(h),r[h]={node:c,lastCount:0},n[h]={};for(let y=0;y<i.length;y++){let _=i[y];r[_]&&r[_].node.mode===c.mode?(n[_][h]=gr(r[_].lastCount+c.length,c.mode)-gr(r[_].lastCount,c.mode),r[_].lastCount+=c.length):(r[_]&&(r[_].lastCount=c.length),n[_][h]=gr(c.length,c.mode)+4+M.getCharCountIndicator(c.mode,e))}}i=a}for(let s=0;s<i.length;s++)n[i[s]].end=0;return{map:n,table:r}}function Bi(t,e){let r,n=M.getBestModeForData(t);if(r=M.from(e,n),r!==M.BYTE&&r.bit<n.bit)throw new Error('"'+t+'" cannot be encoded with mode '+M.toString(r)+`.
|
|
7
|
+
Suggested mode is: `+M.toString(n));switch(r===M.KANJI&&!Tt.isKanjiModeEnabled()&&(r=M.BYTE),r){case M.NUMERIC:return new Ri(t);case M.ALPHANUMERIC:return new Ai(t);case M.KANJI:return new vi(t);case M.BYTE:return new Ii(t)}}He.fromArray=function(e){return e.reduce(function(r,n){return typeof n=="string"?r.push(Bi(n,null)):n.data&&r.push(Bi(n.data,n.mode)),r},[])};He.fromString=function(e,r){let n=Oi(e,Tt.isKanjiModeEnabled()),i=za(n),s=ja(i,r),o=Wa.find_path(s.map,"start","end"),a=[];for(let u=1;u<o.length-1;u++)a.push(s.table[o[u]].node);return He.fromArray(Ha(a))};He.rawSplit=function(e){return He.fromArray(Oi(e,Tt.isKanjiModeEnabled()))}});var Cr=P(Mi=>{var Pt=ye(),mr=mt(),Qa=Yn(),Ga=Jn(),Ya=Kn(),Va=ei(),wr=ti(),br=sr(),Ja=oi(),kt=di(),Ka=yi(),Za=we(),yr=Li();function Xa(t,e){let r=t.size,n=Va.getPositions(e);for(let i=0;i<n.length;i++){let s=n[i][0],o=n[i][1];for(let a=-1;a<=7;a++)if(!(s+a<=-1||r<=s+a))for(let u=-1;u<=7;u++)o+u<=-1||r<=o+u||(a>=0&&a<=6&&(u===0||u===6)||u>=0&&u<=6&&(a===0||a===6)||a>=2&&a<=4&&u>=2&&u<=4?t.set(s+a,o+u,!0,!0):t.set(s+a,o+u,!1,!0))}}function el(t){let e=t.size;for(let r=8;r<e-8;r++){let n=r%2===0;t.set(r,6,n,!0),t.set(6,r,n,!0)}}function tl(t,e){let r=Ya.getPositions(e);for(let n=0;n<r.length;n++){let i=r[n][0],s=r[n][1];for(let o=-2;o<=2;o++)for(let a=-2;a<=2;a++)o===-2||o===2||a===-2||a===2||o===0&&a===0?t.set(i+o,s+a,!0,!0):t.set(i+o,s+a,!1,!0)}}function rl(t,e){let r=t.size,n=kt.getEncodedBits(e),i,s,o;for(let a=0;a<18;a++)i=Math.floor(a/3),s=a%3+r-8-3,o=(n>>a&1)===1,t.set(i,s,o,!0),t.set(s,i,o,!0)}function _r(t,e,r){let n=t.size,i=Ka.getEncodedBits(e,r),s,o;for(s=0;s<15;s++)o=(i>>s&1)===1,s<6?t.set(s,8,o,!0):s<8?t.set(s+1,8,o,!0):t.set(n-15+s,8,o,!0),s<8?t.set(8,n-s-1,o,!0):s<9?t.set(8,15-s-1+1,o,!0):t.set(8,15-s-1,o,!0);t.set(n-8,8,1,!0)}function nl(t,e){let r=t.size,n=-1,i=r-1,s=7,o=0;for(let a=r-1;a>0;a-=2)for(a===6&&a--;;){for(let u=0;u<2;u++)if(!t.isReserved(i,a-u)){let c=!1;o<e.length&&(c=(e[o]>>>s&1)===1),t.set(i,a-u,c),s--,s===-1&&(o++,s=7)}if(i+=n,i<0||r<=i){i-=n,n=-n;break}}}function il(t,e,r){let n=new Qa;r.forEach(function(u){n.put(u.mode.bit,4),n.put(u.getLength(),Za.getCharCountIndicator(u.mode,t)),u.write(n)});let i=Pt.getSymbolTotalCodewords(t),s=br.getTotalCodewordsCount(t,e),o=(i-s)*8;for(n.getLengthInBits()+4<=o&&n.put(0,4);n.getLengthInBits()%8!==0;)n.putBit(0);let a=(o-n.getLengthInBits())/8;for(let u=0;u<a;u++)n.put(u%2?17:236,8);return sl(n,t,e)}function sl(t,e,r){let n=Pt.getSymbolTotalCodewords(e),i=br.getTotalCodewordsCount(e,r),s=n-i,o=br.getBlocksCount(e,r),a=n%o,u=o-a,c=Math.floor(n/o),h=Math.floor(s/o),y=h+1,_=c-h,b=new Ja(_),g=0,w=new Array(o),C=new Array(o),E=0,x=new Uint8Array(t.buffer);for(let L=0;L<o;L++){let G=L<u?h:y;w[L]=x.slice(g,g+G),C[L]=b.encode(w[L]),g+=G,E=Math.max(E,G)}let I=new Uint8Array(n),O=0,N,v;for(N=0;N<E;N++)for(v=0;v<o;v++)N<w[v].length&&(I[O++]=w[v][N]);for(N=0;N<_;N++)for(v=0;v<o;v++)I[O++]=C[v][N];return I}function ol(t,e,r,n){let i;if(Array.isArray(t))i=yr.fromArray(t);else if(typeof t=="string"){let c=e;if(!c){let h=yr.rawSplit(t);c=kt.getBestVersionForData(h,r)}i=yr.fromString(t,c||40)}else throw new Error("Invalid data");let s=kt.getBestVersionForData(i,r);if(!s)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=s;else if(e<s)throw new Error(`
|
|
8
8
|
The chosen QR Code version cannot contain this amount of data.
|
|
9
9
|
Minimum version required to store current data is: `+s+`.
|
|
10
|
-
`);let o=nl(e,r,i),a=Pt.getSymbolSize(e),u=new Qa(a);return Za(u,e),Xa(u),el(u,e),yr(u,r,0),e>=7&&tl(u,e),rl(u,o),isNaN(n)&&(n=_r.getBestMask(u,yr.bind(null,u,r))),_r.applyMask(n,u),yr(u,r,n),{modules:u,version:e,errorCorrectionLevel:r,maskPattern:n,segments:i}}Mi.create=function(e,r){if(typeof e>"u"||e==="")throw new Error("No input text");let n=gr.M,i,s;return typeof r<"u"&&(n=gr.from(r.errorCorrectionLevel,gr.M),i=kt.from(r.version),s=_r.from(r.maskPattern),r.toSJISFunc&&Pt.setToSJISFunction(r.toSJISFunc)),sl(e,i,n,s)}});var Cr=P((Hc,Ui)=>{"use strict";var ol=W("util"),Ni=W("stream"),oe=Ui.exports=function(){Ni.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};ol.inherits(oe,Ni);oe.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e}),process.nextTick(function(){this._process(),this._paused&&this._reads&&this._reads.length>0&&(this._paused=!1,this.emit("drain"))}.bind(this))};oe.prototype.write=function(t,e){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let r;return Buffer.isBuffer(t)?r=t:r=Buffer.from(t,e||this._encoding),this._buffers.push(r),this._buffered+=r.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused};oe.prototype.end=function(t,e){t&&this.write(t,e),this.writable=!1,this._buffers&&(this._buffers.length===0?this._end():(this._buffers.push(null),this._process()))};oe.prototype.destroySoon=oe.prototype.end;oe.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};oe.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};oe.prototype._processReadAllowingLess=function(t){this._reads.shift();let e=this._buffers[0];e.length>t.length?(this._buffered-=t.length,this._buffers[0]=e.slice(t.length),t.func.call(this,e.slice(0,t.length))):(this._buffered-=e.length,this._buffers.shift(),t.func.call(this,e))};oe.prototype._processRead=function(t){this._reads.shift();let e=0,r=0,n=Buffer.alloc(t.length);for(;e<t.length;){let i=this._buffers[r++],s=Math.min(i.length,t.length-e);i.copy(n,e,0,s),e+=s,s!==i.length&&(this._buffers[--r]=i.slice(s))}r>0&&this._buffers.splice(0,r),this._buffered-=t.length,t.func.call(this,n)};oe.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){let t=this._reads[0];if(t.allowLess)this._processReadAllowingLess(t);else if(this._buffered>=t.length)this._processRead(t);else break}this._buffers&&!this.writable&&this._end()}catch(t){this.emit("error",t)}}});var Tr=P(Er=>{"use strict";var Ce=[{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]}];Er.getImagePasses=function(t,e){let r=[],n=t%8,i=e%8,s=(t-n)/8,o=(e-i)/8;for(let a=0;a<Ce.length;a++){let u=Ce[a],c=s*u.x.length,h=o*u.y.length;for(let y=0;y<u.x.length&&u.x[y]<n;y++)c++;for(let y=0;y<u.y.length&&u.y[y]<i;y++)h++;c>0&&h>0&&r.push({width:c,height:h,index:a})}return r};Er.getInterlaceIterator=function(t){return function(e,r,n){let i=e%Ce[n].x.length,s=(e-i)/Ce[n].x.length*8+Ce[n].x[i],o=r%Ce[n].y.length,a=(r-o)/Ce[n].y.length*8+Ce[n].y[o];return s*4+a*t*4}}});var kr=P((jc,$i)=>{"use strict";$i.exports=function(e,r,n){let i=e+r-n,s=Math.abs(i-e),o=Math.abs(i-r),a=Math.abs(i-n);return s<=o&&s<=a?e:o<=a?r:n}});var Pr=P((Qc,Di)=>{"use strict";var al=Tr(),ll=kr();function Fi(t,e,r){let n=t*e;return r!==8&&(n=Math.ceil(n/(8/r))),n}var ze=Di.exports=function(t,e){let r=t.width,n=t.height,i=t.interlace,s=t.bpp,o=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],i){let a=al.getImagePasses(r,n);for(let u=0;u<a.length;u++)this._images.push({byteWidth:Fi(a[u].width,s,o),height:a[u].height,lineIndex:0})}else this._images.push({byteWidth:Fi(r,s,o),height:n,lineIndex:0});o===8?this._xComparison=s:o===16?this._xComparison=s*2:this._xComparison=1};ze.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};ze.prototype._unFilterType1=function(t,e,r){let n=this._xComparison,i=n-1;for(let s=0;s<r;s++){let o=t[1+s],a=s>i?e[s-n]:0;e[s]=o+a}};ze.prototype._unFilterType2=function(t,e,r){let n=this._lastLine;for(let i=0;i<r;i++){let s=t[1+i],o=n?n[i]:0;e[i]=s+o}};ze.prototype._unFilterType3=function(t,e,r){let n=this._xComparison,i=n-1,s=this._lastLine;for(let o=0;o<r;o++){let a=t[1+o],u=s?s[o]:0,c=o>i?e[o-n]:0,h=Math.floor((c+u)/2);e[o]=a+h}};ze.prototype._unFilterType4=function(t,e,r){let n=this._xComparison,i=n-1,s=this._lastLine;for(let o=0;o<r;o++){let a=t[1+o],u=s?s[o]:0,c=o>i?e[o-n]:0,h=o>i&&s?s[o-n]:0,y=ll(c,u,h);e[o]=a+y}};ze.prototype._reverseFilterLine=function(t){let e=t[0],r,n=this._images[this._imageIndex],i=n.byteWidth;if(e===0)r=t.slice(1,i+1);else switch(r=Buffer.alloc(i),e){case 1:this._unFilterType1(t,r,i);break;case 2:this._unFilterType2(t,r,i);break;case 3:this._unFilterType3(t,r,i);break;case 4:this._unFilterType4(t,r,i);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(r),n.lineIndex++,n.lineIndex>=n.height?(this._lastLine=null,this._imageIndex++,n=this._images[this._imageIndex]):this._lastLine=r,n?this.read(n.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var Hi=P((Gc,Wi)=>{"use strict";var ul=W("util"),qi=Cr(),fl=Pr(),cl=Wi.exports=function(t){qi.call(this);let e=[],r=this;this._filter=new fl(t,{read:this.read.bind(this),write:function(n){e.push(n)},complete:function(){r.emit("complete",Buffer.concat(e))}}),this._filter.start()};ul.inherits(cl,qi)});var je=P((Yc,zi)=>{"use strict";zi.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 Br=P((Vc,ji)=>{"use strict";var Sr=[];(function(){for(let t=0;t<256;t++){let e=t;for(let r=0;r<8;r++)e&1?e=3988292384^e>>>1:e=e>>>1;Sr[t]=e}})();var xr=ji.exports=function(){this._crc=-1};xr.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=Sr[(this._crc^t[e])&255]^this._crc>>>8;return!0};xr.prototype.crc32=function(){return this._crc^-1};xr.crc32=function(t){let e=-1;for(let r=0;r<t.length;r++)e=Sr[(e^t[r])&255]^e>>>8;return e^-1}});var Ar=P((Kc,Qi)=>{"use strict";var j=je(),hl=Br(),Q=Qi.exports=function(t,e){this._options=t,t.checkCRC=t.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[j.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[j.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[j.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[j.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[j.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[j.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=e.read,this.error=e.error,this.metadata=e.metadata,this.gamma=e.gamma,this.transColor=e.transColor,this.palette=e.palette,this.parsed=e.parsed,this.inflateData=e.inflateData,this.finished=e.finished,this.simpleTransparency=e.simpleTransparency,this.headersFinished=e.headersFinished||function(){}};Q.prototype.start=function(){this.read(j.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Q.prototype._parseSignature=function(t){let e=j.PNG_SIGNATURE;for(let r=0;r<e.length;r++)if(t[r]!==e[r]){this.error(new Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};Q.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),r=t.readUInt32BE(4),n="";for(let s=4;s<8;s++)n+=String.fromCharCode(t[s]);let i=!!(t[4]&32);if(!this._hasIHDR&&r!==j.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new hl,this._crc.write(Buffer.from(n)),this._chunks[r])return this._chunks[r](e);if(!i){this.error(new Error("Unsupported critical chunk type "+n));return}this.read(e+4,this._skipChunk.bind(this))};Q.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Q.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Q.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),r=this._crc.crc32();if(this._options.checkCRC&&r!==e){this.error(new Error("Crc error - "+e+" - "+r));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))};Q.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};Q.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),r=t.readUInt32BE(4),n=t[8],i=t[9],s=t[10],o=t[11],a=t[12];if(n!==8&&n!==4&&n!==2&&n!==1&&n!==16){this.error(new Error("Unsupported bit depth "+n));return}if(!(i in j.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(s!==0){this.error(new Error("Unsupported compression method"));return}if(o!==0){this.error(new Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=i;let u=j.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:r,depth:n,interlace:!!a,palette:!!(i&j.COLORTYPE_PALETTE),color:!!(i&j.COLORTYPE_COLOR),alpha:!!(i&j.COLORTYPE_ALPHA),bpp:u,colorType:i}),this._handleChunkEnd()};Q.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};Q.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let r=0;r<e;r++)this._palette.push([t[r*3],t[r*3+1],t[r*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};Q.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};Q.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===j.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(new Error("Transparency chunk must be after palette"));return}if(t.length>this._palette.length){this.error(new Error("More transparent colors than palette size"));return}for(let e=0;e<t.length;e++)this._palette[e][3]=t[e];this.palette(this._palette)}this._colorType===j.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===j.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};Q.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};Q.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/j.GAMMA_DIVISION),this._handleChunkEnd()};Q.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};Q.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===j.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw new Error("Expected palette not found");this.inflateData(e);let r=t-e.length;r>0?this._handleIDAT(r):this._handleChunkEnd()};Q.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};Q.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var Rr=P(Yi=>{"use strict";var Gi=Tr(),dl=[function(){},function(t,e,r,n){if(n===e.length)throw new Error("Ran out of data");let i=e[n];t[r]=i,t[r+1]=i,t[r+2]=i,t[r+3]=255},function(t,e,r,n){if(n+1>=e.length)throw new Error("Ran out of data");let i=e[n];t[r]=i,t[r+1]=i,t[r+2]=i,t[r+3]=e[n+1]},function(t,e,r,n){if(n+2>=e.length)throw new Error("Ran out of data");t[r]=e[n],t[r+1]=e[n+1],t[r+2]=e[n+2],t[r+3]=255},function(t,e,r,n){if(n+3>=e.length)throw new Error("Ran out of data");t[r]=e[n],t[r+1]=e[n+1],t[r+2]=e[n+2],t[r+3]=e[n+3]}],pl=[function(){},function(t,e,r,n){let i=e[0];t[r]=i,t[r+1]=i,t[r+2]=i,t[r+3]=n},function(t,e,r){let n=e[0];t[r]=n,t[r+1]=n,t[r+2]=n,t[r+3]=e[1]},function(t,e,r,n){t[r]=e[0],t[r+1]=e[1],t[r+2]=e[2],t[r+3]=n},function(t,e,r){t[r]=e[0],t[r+1]=e[1],t[r+2]=e[2],t[r+3]=e[3]}];function gl(t,e){let r=[],n=0;function i(){if(n===t.length)throw new Error("Ran out of data");let s=t[n];n++;let o,a,u,c,h,y,_,b;switch(e){default:throw new Error("unrecognised depth");case 16:_=t[n],n++,r.push((s<<8)+_);break;case 4:_=s&15,b=s>>4,r.push(b,_);break;case 2:h=s&3,y=s>>2&3,_=s>>4&3,b=s>>6&3,r.push(b,_,y,h);break;case 1:o=s&1,a=s>>1&1,u=s>>2&1,c=s>>3&1,h=s>>4&1,y=s>>5&1,_=s>>6&1,b=s>>7&1,r.push(b,_,y,h,c,u,a,o);break}}return{get:function(s){for(;r.length<s;)i();let o=r.slice(0,s);return r=r.slice(s),o},resetAfterLine:function(){r.length=0},end:function(){if(n!==t.length)throw new Error("extra data found")}}}function ml(t,e,r,n,i,s){let o=t.width,a=t.height,u=t.index;for(let c=0;c<a;c++)for(let h=0;h<o;h++){let y=r(h,c,u);dl[n](e,i,y,s),s+=n}return s}function yl(t,e,r,n,i,s){let o=t.width,a=t.height,u=t.index;for(let c=0;c<a;c++){for(let h=0;h<o;h++){let y=i.get(n),_=r(h,c,u);pl[n](e,y,_,s)}i.resetAfterLine()}}Yi.dataToBitMap=function(t,e){let r=e.width,n=e.height,i=e.depth,s=e.bpp,o=e.interlace,a;i!==8&&(a=gl(t,i));let u;i<=8?u=Buffer.alloc(r*n*4):u=new Uint16Array(r*n*4);let c=Math.pow(2,i)-1,h=0,y,_;if(o)y=Gi.getImagePasses(r,n),_=Gi.getInterlaceIterator(r,n);else{let b=0;_=function(){let g=b;return b+=4,g},y=[{width:r,height:n}]}for(let b=0;b<y.length;b++)i===8?h=ml(y[b],u,_,s,t,h):yl(y[b],u,_,s,a,c);if(i===8){if(h!==t.length)throw new Error("extra data found")}else a.end();return u}});var Ir=P((Zc,Vi)=>{"use strict";function _l(t,e,r,n,i){let s=0;for(let o=0;o<n;o++)for(let a=0;a<r;a++){let u=i[t[s]];if(!u)throw new Error("index "+t[s]+" not in palette");for(let c=0;c<4;c++)e[s+c]=u[c];s+=4}}function wl(t,e,r,n,i){let s=0;for(let o=0;o<n;o++)for(let a=0;a<r;a++){let u=!1;if(i.length===1?i[0]===t[s]&&(u=!0):i[0]===t[s]&&i[1]===t[s+1]&&i[2]===t[s+2]&&(u=!0),u)for(let c=0;c<4;c++)e[s+c]=0;s+=4}}function bl(t,e,r,n,i){let s=255,o=Math.pow(2,i)-1,a=0;for(let u=0;u<n;u++)for(let c=0;c<r;c++){for(let h=0;h<4;h++)e[a+h]=Math.floor(t[a+h]*s/o+.5);a+=4}}Vi.exports=function(t,e){let r=e.depth,n=e.width,i=e.height,s=e.colorType,o=e.transColor,a=e.palette,u=t;return s===3?_l(t,u,n,i,a):(o&&wl(t,u,n,i,o),r!==8&&(r===16&&(u=Buffer.alloc(n*i*4)),bl(t,u,n,i,r))),u}});var Zi=P((Xc,Ji)=>{"use strict";var Cl=W("util"),vr=W("zlib"),Ki=Cr(),El=Hi(),Tl=Ar(),kl=Rr(),Pl=Ir(),ue=Ji.exports=function(t){Ki.call(this),this._parser=new Tl(t,{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=t,this.writable=!0,this._parser.start()};Cl.inherits(ue,Ki);ue.prototype._handleError=function(t){this.emit("error",t),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};ue.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=vr.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 r=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,n=Math.max(r,vr.Z_MIN_CHUNK);this._inflate=vr.createInflate({chunkSize:n});let i=r,s=this.emit.bind(this,"error");this._inflate.on("error",function(a){i&&s(a)}),this._filter.on("complete",this._complete.bind(this));let o=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){i&&(a.length>i&&(a=a.slice(0,i)),i-=a.length,o(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};ue.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new El(this._bitmapInfo)};ue.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};ue.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};ue.prototype._simpleTransparency=function(){this._metaData.alpha=!0};ue.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};ue.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};ue.prototype._complete=function(t){if(this.errord)return;let e;try{let r=kl.dataToBitMap(t,this._bitmapInfo);e=Pl(r,this._bitmapInfo),r=null}catch(r){this._handleError(r);return}this.emit("parsed",e)}});var es=P((eh,Xi)=>{"use strict";var re=je();Xi.exports=function(t,e,r,n){let i=[re.COLORTYPE_COLOR_ALPHA,re.COLORTYPE_ALPHA].indexOf(n.colorType)!==-1;if(n.colorType===n.inputColorType){let g=(function(){let w=new ArrayBuffer(2);return new DataView(w).setInt16(0,256,!0),new Int16Array(w)[0]!==256})();if(n.bitDepth===8||n.bitDepth===16&&g)return t}let s=n.bitDepth!==16?t:new Uint16Array(t.buffer),o=255,a=re.COLORTYPE_TO_BPP_MAP[n.inputColorType];a===4&&!n.inputHasAlpha&&(a=3);let u=re.COLORTYPE_TO_BPP_MAP[n.colorType];n.bitDepth===16&&(o=65535,u*=2);let c=Buffer.alloc(e*r*u),h=0,y=0,_=n.bgColor||{};_.red===void 0&&(_.red=o),_.green===void 0&&(_.green=o),_.blue===void 0&&(_.blue=o);function b(){let g,w,C,E=o;switch(n.inputColorType){case re.COLORTYPE_COLOR_ALPHA:E=s[h+3],g=s[h],w=s[h+1],C=s[h+2];break;case re.COLORTYPE_COLOR:g=s[h],w=s[h+1],C=s[h+2];break;case re.COLORTYPE_ALPHA:E=s[h+1],g=s[h],w=g,C=g;break;case re.COLORTYPE_GRAYSCALE:g=s[h],w=g,C=g;break;default:throw new Error("input color type:"+n.inputColorType+" is not supported at present")}return n.inputHasAlpha&&(i||(E/=o,g=Math.min(Math.max(Math.round((1-E)*_.red+E*g),0),o),w=Math.min(Math.max(Math.round((1-E)*_.green+E*w),0),o),C=Math.min(Math.max(Math.round((1-E)*_.blue+E*C),0),o))),{red:g,green:w,blue:C,alpha:E}}for(let g=0;g<r;g++)for(let w=0;w<e;w++){let C=b(s,h);switch(n.colorType){case re.COLORTYPE_COLOR_ALPHA:case re.COLORTYPE_COLOR:n.bitDepth===8?(c[y]=C.red,c[y+1]=C.green,c[y+2]=C.blue,i&&(c[y+3]=C.alpha)):(c.writeUInt16BE(C.red,y),c.writeUInt16BE(C.green,y+2),c.writeUInt16BE(C.blue,y+4),i&&c.writeUInt16BE(C.alpha,y+6));break;case re.COLORTYPE_ALPHA:case re.COLORTYPE_GRAYSCALE:{let E=(C.red+C.green+C.blue)/3;n.bitDepth===8?(c[y]=E,i&&(c[y+1]=C.alpha)):(c.writeUInt16BE(E,y),i&&c.writeUInt16BE(C.alpha,y+2));break}default:throw new Error("unrecognised color Type "+n.colorType)}h+=a,y+=u}return c}});var ns=P((th,rs)=>{"use strict";var ts=kr();function Sl(t,e,r,n,i){for(let s=0;s<r;s++)n[i+s]=t[e+s]}function xl(t,e,r){let n=0,i=e+r;for(let s=e;s<i;s++)n+=Math.abs(t[s]);return n}function Bl(t,e,r,n,i,s){for(let o=0;o<r;o++){let a=o>=s?t[e+o-s]:0,u=t[e+o]-a;n[i+o]=u}}function Al(t,e,r,n){let i=0;for(let s=0;s<r;s++){let o=s>=n?t[e+s-n]:0,a=t[e+s]-o;i+=Math.abs(a)}return i}function Rl(t,e,r,n,i){for(let s=0;s<r;s++){let o=e>0?t[e+s-r]:0,a=t[e+s]-o;n[i+s]=a}}function Il(t,e,r){let n=0,i=e+r;for(let s=e;s<i;s++){let o=e>0?t[s-r]:0,a=t[s]-o;n+=Math.abs(a)}return n}function vl(t,e,r,n,i,s){for(let o=0;o<r;o++){let a=o>=s?t[e+o-s]:0,u=e>0?t[e+o-r]:0,c=t[e+o]-(a+u>>1);n[i+o]=c}}function Ol(t,e,r,n){let i=0;for(let s=0;s<r;s++){let o=s>=n?t[e+s-n]:0,a=e>0?t[e+s-r]:0,u=t[e+s]-(o+a>>1);i+=Math.abs(u)}return i}function Ll(t,e,r,n,i,s){for(let o=0;o<r;o++){let a=o>=s?t[e+o-s]:0,u=e>0?t[e+o-r]:0,c=e>0&&o>=s?t[e+o-(r+s)]:0,h=t[e+o]-ts(a,u,c);n[i+o]=h}}function Ml(t,e,r,n){let i=0;for(let s=0;s<r;s++){let o=s>=n?t[e+s-n]:0,a=e>0?t[e+s-r]:0,u=e>0&&s>=n?t[e+s-(r+n)]:0,c=t[e+s]-ts(o,a,u);i+=Math.abs(c)}return i}var Nl={0:Sl,1:Bl,2:Rl,3:vl,4:Ll},Ul={0:xl,1:Al,2:Il,3:Ol,4:Ml};rs.exports=function(t,e,r,n,i){let s;if(!("filterType"in n)||n.filterType===-1)s=[0,1,2,3,4];else if(typeof n.filterType=="number")s=[n.filterType];else throw new Error("unrecognised filter types");n.bitDepth===16&&(i*=2);let o=e*i,a=0,u=0,c=Buffer.alloc((o+1)*r),h=s[0];for(let y=0;y<r;y++){if(s.length>1){let _=1/0;for(let b=0;b<s.length;b++){let g=Ul[s[b]](t,u,o,i);g<_&&(h=s[b],_=g)}}c[a]=h,a++,Nl[h](t,u,o,c,a,i),a+=o,u+=o}return c}});var Or=P((rh,is)=>{"use strict";var Y=je(),$l=Br(),Fl=es(),Dl=ns(),ql=W("zlib"),Ee=is.exports=function(t){if(this._options=t,t.deflateChunkSize=t.deflateChunkSize||32*1024,t.deflateLevel=t.deflateLevel!=null?t.deflateLevel:9,t.deflateStrategy=t.deflateStrategy!=null?t.deflateStrategy:3,t.inputHasAlpha=t.inputHasAlpha!=null?t.inputHasAlpha:!0,t.deflateFactory=t.deflateFactory||ql.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:Y.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:Y.COLORTYPE_COLOR_ALPHA,[Y.COLORTYPE_GRAYSCALE,Y.COLORTYPE_COLOR,Y.COLORTYPE_COLOR_ALPHA,Y.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([Y.COLORTYPE_GRAYSCALE,Y.COLORTYPE_COLOR,Y.COLORTYPE_COLOR_ALPHA,Y.COLORTYPE_ALPHA].indexOf(t.inputColorType)===-1)throw new Error("option input color type:"+t.inputColorType+" is not supported at present");if(t.bitDepth!==8&&t.bitDepth!==16)throw new Error("option bit depth:"+t.bitDepth+" is not supported at present")};Ee.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Ee.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Ee.prototype.filterData=function(t,e,r){let n=Fl(t,e,r,this._options),i=Y.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Dl(n,e,r,this._options,i)};Ee.prototype._packChunk=function(t,e){let r=e?e.length:0,n=Buffer.alloc(r+12);return n.writeUInt32BE(r,0),n.writeUInt32BE(t,4),e&&e.copy(n,8),n.writeInt32BE($l.crc32(n.slice(4,n.length-4)),n.length-4),n};Ee.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*Y.GAMMA_DIVISION),0),this._packChunk(Y.TYPE_gAMA,e)};Ee.prototype.packIHDR=function(t,e){let r=Buffer.alloc(13);return r.writeUInt32BE(t,0),r.writeUInt32BE(e,4),r[8]=this._options.bitDepth,r[9]=this._options.colorType,r[10]=0,r[11]=0,r[12]=0,this._packChunk(Y.TYPE_IHDR,r)};Ee.prototype.packIDAT=function(t){return this._packChunk(Y.TYPE_IDAT,t)};Ee.prototype.packIEND=function(){return this._packChunk(Y.TYPE_IEND,null)}});var ls=P((nh,as)=>{"use strict";var Wl=W("util"),ss=W("stream"),Hl=je(),zl=Or(),os=as.exports=function(t){ss.call(this);let e=t||{};this._packer=new zl(e),this._deflate=this._packer.createDeflate(),this.readable=!0};Wl.inherits(os,ss);os.prototype.pack=function(t,e,r,n){this.emit("data",Buffer.from(Hl.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,r)),n&&this.emit("data",this._packer.packGAMA(n));let i=this._packer.filterData(t,e,r);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(s){this.emit("data",this._packer.packIDAT(s))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(i)}});var ps=P((st,ds)=>{"use strict";var us=W("assert").ok,Qe=W("zlib"),jl=W("util"),fs=W("buffer").kMaxLength;function Oe(t){if(!(this instanceof Oe))return new Oe(t);t&&t.chunkSize<Qe.Z_MIN_CHUNK&&(t.chunkSize=Qe.Z_MIN_CHUNK),Qe.Inflate.call(this,t),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,t&&t.maxLength!=null&&(this._maxLength=t.maxLength)}function Ql(t){return new Oe(t)}function cs(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Oe.prototype._processChunk=function(t,e,r){if(typeof r=="function")return Qe.Inflate._processChunk.call(this,t,e,r);let n=this,i=t&&t.length,s=this._chunkSize-this._offset,o=this._maxLength,a=0,u=[],c=0,h;this.on("error",function(g){h=g});function y(g,w){if(n._hadError)return;let C=s-w;if(us(C>=0,"have should not go down"),C>0){let E=n._buffer.slice(n._offset,n._offset+C);if(n._offset+=C,E.length>o&&(E=E.slice(0,o)),u.push(E),c+=E.length,o-=E.length,o===0)return!1}return(w===0||n._offset>=n._chunkSize)&&(s=n._chunkSize,n._offset=0,n._buffer=Buffer.allocUnsafe(n._chunkSize)),w===0?(a+=i-g,i=g,!0):!1}us(this._handle,"zlib binding closed");let _;do _=this._handle.writeSync(e,t,a,i,this._buffer,this._offset,s),_=_||this._writeState;while(!this._hadError&&y(_[0],_[1]));if(this._hadError)throw h;if(c>=fs)throw cs(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+fs.toString(16)+" bytes");let b=Buffer.concat(u,c);return cs(this),b};jl.inherits(Oe,Qe.Inflate);function Gl(t,e){if(typeof e=="string"&&(e=Buffer.from(e)),!(e instanceof Buffer))throw new TypeError("Not a string or buffer");let r=t._finishFlushFlag;return r==null&&(r=Qe.Z_FINISH),t._processChunk(e,r)}function hs(t,e){return Gl(new Oe(e),t)}ds.exports=st=hs;st.Inflate=Oe;st.createInflate=Ql;st.inflateSync=hs});var Lr=P((ih,ms)=>{"use strict";var gs=ms.exports=function(t){this._buffer=t,this._reads=[]};gs.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};gs.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){let t=this._reads[0];if(this._buffer.length&&(this._buffer.length>=t.length||t.allowLess)){this._reads.shift();let e=this._buffer;this._buffer=e.slice(t.length),t.func.call(this,e.slice(0,t.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 _s=P(ys=>{"use strict";var Yl=Lr(),Vl=Pr();ys.process=function(t,e){let r=[],n=new Yl(t);return new Vl(e,{read:n.read.bind(n),write:function(s){r.push(s)},complete:function(){}}).start(),n.process(),Buffer.concat(r)}});var Es=P((oh,Cs)=>{"use strict";var ws=!0,bs=W("zlib"),Kl=ps();bs.deflateSync||(ws=!1);var Jl=Lr(),Zl=_s(),Xl=Ar(),eu=Rr(),tu=Ir();Cs.exports=function(t,e){if(!ws)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r;function n(O){r=O}let i;function s(O){i=O}function o(O){i.transColor=O}function a(O){i.palette=O}function u(){i.alpha=!0}let c;function h(O){c=O}let y=[];function _(O){y.push(O)}let b=new Jl(t);if(new Xl(e,{read:b.read.bind(b),error:n,metadata:s,gamma:h,palette:a,transColor:o,inflateData:_,simpleTransparency:u}).start(),b.process(),r)throw r;let w=Buffer.concat(y);y.length=0;let C;if(i.interlace)C=bs.inflateSync(w);else{let N=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;C=Kl(w,{chunkSize:N,maxLength:N})}if(w=null,!C||!C.length)throw new Error("bad png - invalid inflate data response");let E=Zl.process(C,i);w=null;let x=eu.dataToBitMap(E,i);E=null;let I=tu(x,i);return i.data=I,i.gamma=c||0,i}});var Ss=P((ah,Ps)=>{"use strict";var Ts=!0,ks=W("zlib");ks.deflateSync||(Ts=!1);var ru=je(),nu=Or();Ps.exports=function(t,e){if(!Ts)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r=e||{},n=new nu(r),i=[];i.push(Buffer.from(ru.PNG_SIGNATURE)),i.push(n.packIHDR(t.width,t.height)),t.gamma&&i.push(n.packGAMA(t.gamma));let s=n.filterData(t.data,t.width,t.height),o=ks.deflateSync(s,n.getDeflateOptions());if(s=null,!o||!o.length)throw new Error("bad png - invalid compressed data response");return i.push(n.packIDAT(o)),i.push(n.packIEND()),Buffer.concat(i)}});var xs=P(Mr=>{"use strict";var iu=Es(),su=Ss();Mr.read=function(t,e){return iu(t,e||{})};Mr.write=function(t,e){return su(t,e)}});var Rs=P(As=>{"use strict";var ou=W("util"),Bs=W("stream"),au=Zi(),lu=ls(),uu=xs(),V=As.PNG=function(t){Bs.call(this),t=t||{},this.width=t.width|0,this.height=t.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,t.fill&&this.data&&this.data.fill(0),this.gamma=0,this.readable=this.writable=!0,this._parser=new au(t),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(e){this.data=e,this.emit("parsed",e)}.bind(this)),this._packer=new lu(t),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"))};ou.inherits(V,Bs);V.sync=uu;V.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)};V.prototype.parse=function(t,e){if(e){let r,n;r=function(i){this.removeListener("error",n),this.data=i,e(null,this)}.bind(this),n=function(i){this.removeListener("parsed",r),e(i,null)}.bind(this),this.once("parsed",r),this.once("error",n)}return this.end(t),this};V.prototype.write=function(t){return this._parser.write(t),!0};V.prototype.end=function(t){this._parser.end(t)};V.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};V.prototype._gamma=function(t){this.gamma=t};V.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};V.bitblt=function(t,e,r,n,i,s,o,a){if(r|=0,n|=0,i|=0,s|=0,o|=0,a|=0,r>t.width||n>t.height||r+i>t.width||n+s>t.height)throw new Error("bitblt reading outside image");if(o>e.width||a>e.height||o+i>e.width||a+s>e.height)throw new Error("bitblt writing outside image");for(let u=0;u<s;u++)t.data.copy(e.data,(a+u)*e.width+o<<2,(n+u)*t.width+r<<2,(n+u)*t.width+r+i<<2)};V.prototype.bitblt=function(t,e,r,n,i,s,o){return V.bitblt(this,t,e,r,n,i,s,o),this};V.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let r=0;r<t.width;r++){let n=t.width*e+r<<2;for(let i=0;i<3;i++){let s=t.data[n+i]/255;s=Math.pow(s,1/2.2/t.gamma),t.data[n+i]=Math.round(s*255)}}t.gamma=0}};V.prototype.adjustGamma=function(){V.adjustGamma(this)}});var ot=P(Le=>{function Is(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let e=t.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+t);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(n){return[n,n]}))),e.length===6&&e.push("F","F");let r=parseInt(e.join(""),16);return{r:r>>24&255,g:r>>16&255,b:r>>8&255,a:r&255,hex:"#"+e.slice(0,6).join("")}}Le.getOptions=function(e){e||(e={}),e.color||(e.color={});let r=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,n=e.width&&e.width>=21?e.width:void 0,i=e.scale||4;return{width:n,scale:n?4:i,margin:r,color:{dark:Is(e.color.dark||"#000000ff"),light:Is(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};Le.getScale=function(e,r){return r.width&&r.width>=e+r.margin*2?r.width/(e+r.margin*2):r.scale};Le.getImageWidth=function(e,r){let n=Le.getScale(e,r);return Math.floor((e+r.margin*2)*n)};Le.qrToImageData=function(e,r,n){let i=r.modules.size,s=r.modules.data,o=Le.getScale(i,n),a=Math.floor((i+n.margin*2)*o),u=n.margin*o,c=[n.color.light,n.color.dark];for(let h=0;h<a;h++)for(let y=0;y<a;y++){let _=(h*a+y)*4,b=n.color.light;if(h>=u&&y>=u&&h<a-u&&y<a-u){let g=Math.floor((h-u)/o),w=Math.floor((y-u)/o);b=c[s[g*i+w]?1:0]}e[_++]=b.r,e[_++]=b.g,e[_++]=b.b,e[_]=b.a}}});var vs=P(fe=>{var fu=W("fs"),cu=Rs().PNG,Nr=ot();fe.render=function(e,r){let n=Nr.getOptions(r),i=n.rendererOpts,s=Nr.getImageWidth(e.modules.size,n);i.width=s,i.height=s;let o=new cu(i);return Nr.qrToImageData(o.data,e,n),o};fe.renderToDataURL=function(e,r,n){typeof n>"u"&&(n=r,r=void 0),fe.renderToBuffer(e,r,function(i,s){i&&n(i);let o="data:image/png;base64,";o+=s.toString("base64"),n(null,o)})};fe.renderToBuffer=function(e,r,n){typeof n>"u"&&(n=r,r=void 0);let i=fe.render(e,r),s=[];i.on("error",n),i.on("data",function(o){s.push(o)}),i.on("end",function(){n(null,Buffer.concat(s))}),i.pack()};fe.renderToFile=function(e,r,n,i){typeof i>"u"&&(i=n,n=void 0);let s=!1,o=(...u)=>{s||(s=!0,i.apply(null,u))},a=fu.createWriteStream(e);a.on("error",o),a.on("close",o),fe.renderToFileStream(a,r,n)};fe.renderToFileStream=function(e,r,n){fe.render(r,n).pack().pipe(e)}});var Os=P(St=>{var hu=ot(),du={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},pu={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function gu(t,e,r){return t&&e?r.BB:t&&!e?r.BW:!t&&e?r.WB:r.WW}St.render=function(t,e,r){let n=hu.getOptions(e),i=du;(n.color.dark.hex==="#ffffff"||n.color.light.hex==="#000000")&&(i=pu);let s=t.modules.size,o=t.modules.data,a="",u=Array(s+n.margin*2+1).join(i.WW);u=Array(n.margin/2+1).join(u+`
|
|
11
|
-
`);let c=Array(n.margin+1).join(i.WW);a+=u;for(let h=0;h<s;h+=2){a+=c;for(let y=0;y<s;y++){let _=o[h*s+y],b=o[(h+1)*s+y];a+=
|
|
10
|
+
`);let o=il(e,r,i),a=Pt.getSymbolSize(e),u=new Ga(a);return Xa(u,e),el(u),tl(u,e),_r(u,r,0),e>=7&&rl(u,e),nl(u,o),isNaN(n)&&(n=wr.getBestMask(u,_r.bind(null,u,r))),wr.applyMask(n,u),_r(u,r,n),{modules:u,version:e,errorCorrectionLevel:r,maskPattern:n,segments:i}}Mi.create=function(e,r){if(typeof e>"u"||e==="")throw new Error("No input text");let n=mr.M,i,s;return typeof r<"u"&&(n=mr.from(r.errorCorrectionLevel,mr.M),i=kt.from(r.version),s=wr.from(r.maskPattern),r.toSJISFunc&&Pt.setToSJISFunction(r.toSJISFunc)),ol(e,i,n,s)}});var Er=P((Hc,$i)=>{"use strict";var al=W("util"),Ni=W("stream"),oe=$i.exports=function(){Ni.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};al.inherits(oe,Ni);oe.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e}),process.nextTick(function(){this._process(),this._paused&&this._reads&&this._reads.length>0&&(this._paused=!1,this.emit("drain"))}.bind(this))};oe.prototype.write=function(t,e){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let r;return Buffer.isBuffer(t)?r=t:r=Buffer.from(t,e||this._encoding),this._buffers.push(r),this._buffered+=r.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused};oe.prototype.end=function(t,e){t&&this.write(t,e),this.writable=!1,this._buffers&&(this._buffers.length===0?this._end():(this._buffers.push(null),this._process()))};oe.prototype.destroySoon=oe.prototype.end;oe.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};oe.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};oe.prototype._processReadAllowingLess=function(t){this._reads.shift();let e=this._buffers[0];e.length>t.length?(this._buffered-=t.length,this._buffers[0]=e.slice(t.length),t.func.call(this,e.slice(0,t.length))):(this._buffered-=e.length,this._buffers.shift(),t.func.call(this,e))};oe.prototype._processRead=function(t){this._reads.shift();let e=0,r=0,n=Buffer.alloc(t.length);for(;e<t.length;){let i=this._buffers[r++],s=Math.min(i.length,t.length-e);i.copy(n,e,0,s),e+=s,s!==i.length&&(this._buffers[--r]=i.slice(s))}r>0&&this._buffers.splice(0,r),this._buffered-=t.length,t.func.call(this,n)};oe.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){let t=this._reads[0];if(t.allowLess)this._processReadAllowingLess(t);else if(this._buffered>=t.length)this._processRead(t);else break}this._buffers&&!this.writable&&this._end()}catch(t){this.emit("error",t)}}});var kr=P(Tr=>{"use strict";var Ce=[{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]}];Tr.getImagePasses=function(t,e){let r=[],n=t%8,i=e%8,s=(t-n)/8,o=(e-i)/8;for(let a=0;a<Ce.length;a++){let u=Ce[a],c=s*u.x.length,h=o*u.y.length;for(let y=0;y<u.x.length&&u.x[y]<n;y++)c++;for(let y=0;y<u.y.length&&u.y[y]<i;y++)h++;c>0&&h>0&&r.push({width:c,height:h,index:a})}return r};Tr.getInterlaceIterator=function(t){return function(e,r,n){let i=e%Ce[n].x.length,s=(e-i)/Ce[n].x.length*8+Ce[n].x[i],o=r%Ce[n].y.length,a=(r-o)/Ce[n].y.length*8+Ce[n].y[o];return s*4+a*t*4}}});var Pr=P((jc,Ui)=>{"use strict";Ui.exports=function(e,r,n){let i=e+r-n,s=Math.abs(i-e),o=Math.abs(i-r),a=Math.abs(i-n);return s<=o&&s<=a?e:o<=a?r:n}});var Sr=P((Qc,qi)=>{"use strict";var ll=kr(),ul=Pr();function Fi(t,e,r){let n=t*e;return r!==8&&(n=Math.ceil(n/(8/r))),n}var ze=qi.exports=function(t,e){let r=t.width,n=t.height,i=t.interlace,s=t.bpp,o=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],i){let a=ll.getImagePasses(r,n);for(let u=0;u<a.length;u++)this._images.push({byteWidth:Fi(a[u].width,s,o),height:a[u].height,lineIndex:0})}else this._images.push({byteWidth:Fi(r,s,o),height:n,lineIndex:0});o===8?this._xComparison=s:o===16?this._xComparison=s*2:this._xComparison=1};ze.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};ze.prototype._unFilterType1=function(t,e,r){let n=this._xComparison,i=n-1;for(let s=0;s<r;s++){let o=t[1+s],a=s>i?e[s-n]:0;e[s]=o+a}};ze.prototype._unFilterType2=function(t,e,r){let n=this._lastLine;for(let i=0;i<r;i++){let s=t[1+i],o=n?n[i]:0;e[i]=s+o}};ze.prototype._unFilterType3=function(t,e,r){let n=this._xComparison,i=n-1,s=this._lastLine;for(let o=0;o<r;o++){let a=t[1+o],u=s?s[o]:0,c=o>i?e[o-n]:0,h=Math.floor((c+u)/2);e[o]=a+h}};ze.prototype._unFilterType4=function(t,e,r){let n=this._xComparison,i=n-1,s=this._lastLine;for(let o=0;o<r;o++){let a=t[1+o],u=s?s[o]:0,c=o>i?e[o-n]:0,h=o>i&&s?s[o-n]:0,y=ul(c,u,h);e[o]=a+y}};ze.prototype._reverseFilterLine=function(t){let e=t[0],r,n=this._images[this._imageIndex],i=n.byteWidth;if(e===0)r=t.slice(1,i+1);else switch(r=Buffer.alloc(i),e){case 1:this._unFilterType1(t,r,i);break;case 2:this._unFilterType2(t,r,i);break;case 3:this._unFilterType3(t,r,i);break;case 4:this._unFilterType4(t,r,i);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(r),n.lineIndex++,n.lineIndex>=n.height?(this._lastLine=null,this._imageIndex++,n=this._images[this._imageIndex]):this._lastLine=r,n?this.read(n.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var Hi=P((Gc,Wi)=>{"use strict";var fl=W("util"),Di=Er(),cl=Sr(),hl=Wi.exports=function(t){Di.call(this);let e=[],r=this;this._filter=new cl(t,{read:this.read.bind(this),write:function(n){e.push(n)},complete:function(){r.emit("complete",Buffer.concat(e))}}),this._filter.start()};fl.inherits(hl,Di)});var je=P((Yc,zi)=>{"use strict";zi.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 Rr=P((Vc,ji)=>{"use strict";var xr=[];(function(){for(let t=0;t<256;t++){let e=t;for(let r=0;r<8;r++)e&1?e=3988292384^e>>>1:e=e>>>1;xr[t]=e}})();var Br=ji.exports=function(){this._crc=-1};Br.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=xr[(this._crc^t[e])&255]^this._crc>>>8;return!0};Br.prototype.crc32=function(){return this._crc^-1};Br.crc32=function(t){let e=-1;for(let r=0;r<t.length;r++)e=xr[(e^t[r])&255]^e>>>8;return e^-1}});var Ar=P((Jc,Qi)=>{"use strict";var j=je(),dl=Rr(),Q=Qi.exports=function(t,e){this._options=t,t.checkCRC=t.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[j.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[j.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[j.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[j.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[j.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[j.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=e.read,this.error=e.error,this.metadata=e.metadata,this.gamma=e.gamma,this.transColor=e.transColor,this.palette=e.palette,this.parsed=e.parsed,this.inflateData=e.inflateData,this.finished=e.finished,this.simpleTransparency=e.simpleTransparency,this.headersFinished=e.headersFinished||function(){}};Q.prototype.start=function(){this.read(j.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Q.prototype._parseSignature=function(t){let e=j.PNG_SIGNATURE;for(let r=0;r<e.length;r++)if(t[r]!==e[r]){this.error(new Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};Q.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),r=t.readUInt32BE(4),n="";for(let s=4;s<8;s++)n+=String.fromCharCode(t[s]);let i=!!(t[4]&32);if(!this._hasIHDR&&r!==j.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new dl,this._crc.write(Buffer.from(n)),this._chunks[r])return this._chunks[r](e);if(!i){this.error(new Error("Unsupported critical chunk type "+n));return}this.read(e+4,this._skipChunk.bind(this))};Q.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Q.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Q.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),r=this._crc.crc32();if(this._options.checkCRC&&r!==e){this.error(new Error("Crc error - "+e+" - "+r));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))};Q.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};Q.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),r=t.readUInt32BE(4),n=t[8],i=t[9],s=t[10],o=t[11],a=t[12];if(n!==8&&n!==4&&n!==2&&n!==1&&n!==16){this.error(new Error("Unsupported bit depth "+n));return}if(!(i in j.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(s!==0){this.error(new Error("Unsupported compression method"));return}if(o!==0){this.error(new Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=i;let u=j.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:r,depth:n,interlace:!!a,palette:!!(i&j.COLORTYPE_PALETTE),color:!!(i&j.COLORTYPE_COLOR),alpha:!!(i&j.COLORTYPE_ALPHA),bpp:u,colorType:i}),this._handleChunkEnd()};Q.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};Q.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let r=0;r<e;r++)this._palette.push([t[r*3],t[r*3+1],t[r*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};Q.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};Q.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===j.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(new Error("Transparency chunk must be after palette"));return}if(t.length>this._palette.length){this.error(new Error("More transparent colors than palette size"));return}for(let e=0;e<t.length;e++)this._palette[e][3]=t[e];this.palette(this._palette)}this._colorType===j.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===j.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};Q.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};Q.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/j.GAMMA_DIVISION),this._handleChunkEnd()};Q.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};Q.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===j.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw new Error("Expected palette not found");this.inflateData(e);let r=t-e.length;r>0?this._handleIDAT(r):this._handleChunkEnd()};Q.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};Q.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var Ir=P(Yi=>{"use strict";var Gi=kr(),pl=[function(){},function(t,e,r,n){if(n===e.length)throw new Error("Ran out of data");let i=e[n];t[r]=i,t[r+1]=i,t[r+2]=i,t[r+3]=255},function(t,e,r,n){if(n+1>=e.length)throw new Error("Ran out of data");let i=e[n];t[r]=i,t[r+1]=i,t[r+2]=i,t[r+3]=e[n+1]},function(t,e,r,n){if(n+2>=e.length)throw new Error("Ran out of data");t[r]=e[n],t[r+1]=e[n+1],t[r+2]=e[n+2],t[r+3]=255},function(t,e,r,n){if(n+3>=e.length)throw new Error("Ran out of data");t[r]=e[n],t[r+1]=e[n+1],t[r+2]=e[n+2],t[r+3]=e[n+3]}],gl=[function(){},function(t,e,r,n){let i=e[0];t[r]=i,t[r+1]=i,t[r+2]=i,t[r+3]=n},function(t,e,r){let n=e[0];t[r]=n,t[r+1]=n,t[r+2]=n,t[r+3]=e[1]},function(t,e,r,n){t[r]=e[0],t[r+1]=e[1],t[r+2]=e[2],t[r+3]=n},function(t,e,r){t[r]=e[0],t[r+1]=e[1],t[r+2]=e[2],t[r+3]=e[3]}];function ml(t,e){let r=[],n=0;function i(){if(n===t.length)throw new Error("Ran out of data");let s=t[n];n++;let o,a,u,c,h,y,_,b;switch(e){default:throw new Error("unrecognised depth");case 16:_=t[n],n++,r.push((s<<8)+_);break;case 4:_=s&15,b=s>>4,r.push(b,_);break;case 2:h=s&3,y=s>>2&3,_=s>>4&3,b=s>>6&3,r.push(b,_,y,h);break;case 1:o=s&1,a=s>>1&1,u=s>>2&1,c=s>>3&1,h=s>>4&1,y=s>>5&1,_=s>>6&1,b=s>>7&1,r.push(b,_,y,h,c,u,a,o);break}}return{get:function(s){for(;r.length<s;)i();let o=r.slice(0,s);return r=r.slice(s),o},resetAfterLine:function(){r.length=0},end:function(){if(n!==t.length)throw new Error("extra data found")}}}function yl(t,e,r,n,i,s){let o=t.width,a=t.height,u=t.index;for(let c=0;c<a;c++)for(let h=0;h<o;h++){let y=r(h,c,u);pl[n](e,i,y,s),s+=n}return s}function _l(t,e,r,n,i,s){let o=t.width,a=t.height,u=t.index;for(let c=0;c<a;c++){for(let h=0;h<o;h++){let y=i.get(n),_=r(h,c,u);gl[n](e,y,_,s)}i.resetAfterLine()}}Yi.dataToBitMap=function(t,e){let r=e.width,n=e.height,i=e.depth,s=e.bpp,o=e.interlace,a;i!==8&&(a=ml(t,i));let u;i<=8?u=Buffer.alloc(r*n*4):u=new Uint16Array(r*n*4);let c=Math.pow(2,i)-1,h=0,y,_;if(o)y=Gi.getImagePasses(r,n),_=Gi.getInterlaceIterator(r,n);else{let b=0;_=function(){let g=b;return b+=4,g},y=[{width:r,height:n}]}for(let b=0;b<y.length;b++)i===8?h=yl(y[b],u,_,s,t,h):_l(y[b],u,_,s,a,c);if(i===8){if(h!==t.length)throw new Error("extra data found")}else a.end();return u}});var vr=P((Zc,Vi)=>{"use strict";function wl(t,e,r,n,i){let s=0;for(let o=0;o<n;o++)for(let a=0;a<r;a++){let u=i[t[s]];if(!u)throw new Error("index "+t[s]+" not in palette");for(let c=0;c<4;c++)e[s+c]=u[c];s+=4}}function bl(t,e,r,n,i){let s=0;for(let o=0;o<n;o++)for(let a=0;a<r;a++){let u=!1;if(i.length===1?i[0]===t[s]&&(u=!0):i[0]===t[s]&&i[1]===t[s+1]&&i[2]===t[s+2]&&(u=!0),u)for(let c=0;c<4;c++)e[s+c]=0;s+=4}}function Cl(t,e,r,n,i){let s=255,o=Math.pow(2,i)-1,a=0;for(let u=0;u<n;u++)for(let c=0;c<r;c++){for(let h=0;h<4;h++)e[a+h]=Math.floor(t[a+h]*s/o+.5);a+=4}}Vi.exports=function(t,e){let r=e.depth,n=e.width,i=e.height,s=e.colorType,o=e.transColor,a=e.palette,u=t;return s===3?wl(t,u,n,i,a):(o&&bl(t,u,n,i,o),r!==8&&(r===16&&(u=Buffer.alloc(n*i*4)),Cl(t,u,n,i,r))),u}});var Zi=P((Xc,Ki)=>{"use strict";var El=W("util"),Or=W("zlib"),Ji=Er(),Tl=Hi(),kl=Ar(),Pl=Ir(),Sl=vr(),ue=Ki.exports=function(t){Ji.call(this),this._parser=new kl(t,{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=t,this.writable=!0,this._parser.start()};El.inherits(ue,Ji);ue.prototype._handleError=function(t){this.emit("error",t),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};ue.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Or.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 r=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,n=Math.max(r,Or.Z_MIN_CHUNK);this._inflate=Or.createInflate({chunkSize:n});let i=r,s=this.emit.bind(this,"error");this._inflate.on("error",function(a){i&&s(a)}),this._filter.on("complete",this._complete.bind(this));let o=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){i&&(a.length>i&&(a=a.slice(0,i)),i-=a.length,o(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};ue.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new Tl(this._bitmapInfo)};ue.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};ue.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};ue.prototype._simpleTransparency=function(){this._metaData.alpha=!0};ue.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};ue.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};ue.prototype._complete=function(t){if(this.errord)return;let e;try{let r=Pl.dataToBitMap(t,this._bitmapInfo);e=Sl(r,this._bitmapInfo),r=null}catch(r){this._handleError(r);return}this.emit("parsed",e)}});var es=P((eh,Xi)=>{"use strict";var re=je();Xi.exports=function(t,e,r,n){let i=[re.COLORTYPE_COLOR_ALPHA,re.COLORTYPE_ALPHA].indexOf(n.colorType)!==-1;if(n.colorType===n.inputColorType){let g=(function(){let w=new ArrayBuffer(2);return new DataView(w).setInt16(0,256,!0),new Int16Array(w)[0]!==256})();if(n.bitDepth===8||n.bitDepth===16&&g)return t}let s=n.bitDepth!==16?t:new Uint16Array(t.buffer),o=255,a=re.COLORTYPE_TO_BPP_MAP[n.inputColorType];a===4&&!n.inputHasAlpha&&(a=3);let u=re.COLORTYPE_TO_BPP_MAP[n.colorType];n.bitDepth===16&&(o=65535,u*=2);let c=Buffer.alloc(e*r*u),h=0,y=0,_=n.bgColor||{};_.red===void 0&&(_.red=o),_.green===void 0&&(_.green=o),_.blue===void 0&&(_.blue=o);function b(){let g,w,C,E=o;switch(n.inputColorType){case re.COLORTYPE_COLOR_ALPHA:E=s[h+3],g=s[h],w=s[h+1],C=s[h+2];break;case re.COLORTYPE_COLOR:g=s[h],w=s[h+1],C=s[h+2];break;case re.COLORTYPE_ALPHA:E=s[h+1],g=s[h],w=g,C=g;break;case re.COLORTYPE_GRAYSCALE:g=s[h],w=g,C=g;break;default:throw new Error("input color type:"+n.inputColorType+" is not supported at present")}return n.inputHasAlpha&&(i||(E/=o,g=Math.min(Math.max(Math.round((1-E)*_.red+E*g),0),o),w=Math.min(Math.max(Math.round((1-E)*_.green+E*w),0),o),C=Math.min(Math.max(Math.round((1-E)*_.blue+E*C),0),o))),{red:g,green:w,blue:C,alpha:E}}for(let g=0;g<r;g++)for(let w=0;w<e;w++){let C=b(s,h);switch(n.colorType){case re.COLORTYPE_COLOR_ALPHA:case re.COLORTYPE_COLOR:n.bitDepth===8?(c[y]=C.red,c[y+1]=C.green,c[y+2]=C.blue,i&&(c[y+3]=C.alpha)):(c.writeUInt16BE(C.red,y),c.writeUInt16BE(C.green,y+2),c.writeUInt16BE(C.blue,y+4),i&&c.writeUInt16BE(C.alpha,y+6));break;case re.COLORTYPE_ALPHA:case re.COLORTYPE_GRAYSCALE:{let E=(C.red+C.green+C.blue)/3;n.bitDepth===8?(c[y]=E,i&&(c[y+1]=C.alpha)):(c.writeUInt16BE(E,y),i&&c.writeUInt16BE(C.alpha,y+2));break}default:throw new Error("unrecognised color Type "+n.colorType)}h+=a,y+=u}return c}});var ns=P((th,rs)=>{"use strict";var ts=Pr();function xl(t,e,r,n,i){for(let s=0;s<r;s++)n[i+s]=t[e+s]}function Bl(t,e,r){let n=0,i=e+r;for(let s=e;s<i;s++)n+=Math.abs(t[s]);return n}function Rl(t,e,r,n,i,s){for(let o=0;o<r;o++){let a=o>=s?t[e+o-s]:0,u=t[e+o]-a;n[i+o]=u}}function Al(t,e,r,n){let i=0;for(let s=0;s<r;s++){let o=s>=n?t[e+s-n]:0,a=t[e+s]-o;i+=Math.abs(a)}return i}function Il(t,e,r,n,i){for(let s=0;s<r;s++){let o=e>0?t[e+s-r]:0,a=t[e+s]-o;n[i+s]=a}}function vl(t,e,r){let n=0,i=e+r;for(let s=e;s<i;s++){let o=e>0?t[s-r]:0,a=t[s]-o;n+=Math.abs(a)}return n}function Ol(t,e,r,n,i,s){for(let o=0;o<r;o++){let a=o>=s?t[e+o-s]:0,u=e>0?t[e+o-r]:0,c=t[e+o]-(a+u>>1);n[i+o]=c}}function Ll(t,e,r,n){let i=0;for(let s=0;s<r;s++){let o=s>=n?t[e+s-n]:0,a=e>0?t[e+s-r]:0,u=t[e+s]-(o+a>>1);i+=Math.abs(u)}return i}function Ml(t,e,r,n,i,s){for(let o=0;o<r;o++){let a=o>=s?t[e+o-s]:0,u=e>0?t[e+o-r]:0,c=e>0&&o>=s?t[e+o-(r+s)]:0,h=t[e+o]-ts(a,u,c);n[i+o]=h}}function Nl(t,e,r,n){let i=0;for(let s=0;s<r;s++){let o=s>=n?t[e+s-n]:0,a=e>0?t[e+s-r]:0,u=e>0&&s>=n?t[e+s-(r+n)]:0,c=t[e+s]-ts(o,a,u);i+=Math.abs(c)}return i}var $l={0:xl,1:Rl,2:Il,3:Ol,4:Ml},Ul={0:Bl,1:Al,2:vl,3:Ll,4:Nl};rs.exports=function(t,e,r,n,i){let s;if(!("filterType"in n)||n.filterType===-1)s=[0,1,2,3,4];else if(typeof n.filterType=="number")s=[n.filterType];else throw new Error("unrecognised filter types");n.bitDepth===16&&(i*=2);let o=e*i,a=0,u=0,c=Buffer.alloc((o+1)*r),h=s[0];for(let y=0;y<r;y++){if(s.length>1){let _=1/0;for(let b=0;b<s.length;b++){let g=Ul[s[b]](t,u,o,i);g<_&&(h=s[b],_=g)}}c[a]=h,a++,$l[h](t,u,o,c,a,i),a+=o,u+=o}return c}});var Lr=P((rh,is)=>{"use strict";var Y=je(),Fl=Rr(),ql=es(),Dl=ns(),Wl=W("zlib"),Ee=is.exports=function(t){if(this._options=t,t.deflateChunkSize=t.deflateChunkSize||32*1024,t.deflateLevel=t.deflateLevel!=null?t.deflateLevel:9,t.deflateStrategy=t.deflateStrategy!=null?t.deflateStrategy:3,t.inputHasAlpha=t.inputHasAlpha!=null?t.inputHasAlpha:!0,t.deflateFactory=t.deflateFactory||Wl.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:Y.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:Y.COLORTYPE_COLOR_ALPHA,[Y.COLORTYPE_GRAYSCALE,Y.COLORTYPE_COLOR,Y.COLORTYPE_COLOR_ALPHA,Y.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([Y.COLORTYPE_GRAYSCALE,Y.COLORTYPE_COLOR,Y.COLORTYPE_COLOR_ALPHA,Y.COLORTYPE_ALPHA].indexOf(t.inputColorType)===-1)throw new Error("option input color type:"+t.inputColorType+" is not supported at present");if(t.bitDepth!==8&&t.bitDepth!==16)throw new Error("option bit depth:"+t.bitDepth+" is not supported at present")};Ee.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Ee.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Ee.prototype.filterData=function(t,e,r){let n=ql(t,e,r,this._options),i=Y.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Dl(n,e,r,this._options,i)};Ee.prototype._packChunk=function(t,e){let r=e?e.length:0,n=Buffer.alloc(r+12);return n.writeUInt32BE(r,0),n.writeUInt32BE(t,4),e&&e.copy(n,8),n.writeInt32BE(Fl.crc32(n.slice(4,n.length-4)),n.length-4),n};Ee.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*Y.GAMMA_DIVISION),0),this._packChunk(Y.TYPE_gAMA,e)};Ee.prototype.packIHDR=function(t,e){let r=Buffer.alloc(13);return r.writeUInt32BE(t,0),r.writeUInt32BE(e,4),r[8]=this._options.bitDepth,r[9]=this._options.colorType,r[10]=0,r[11]=0,r[12]=0,this._packChunk(Y.TYPE_IHDR,r)};Ee.prototype.packIDAT=function(t){return this._packChunk(Y.TYPE_IDAT,t)};Ee.prototype.packIEND=function(){return this._packChunk(Y.TYPE_IEND,null)}});var ls=P((nh,as)=>{"use strict";var Hl=W("util"),ss=W("stream"),zl=je(),jl=Lr(),os=as.exports=function(t){ss.call(this);let e=t||{};this._packer=new jl(e),this._deflate=this._packer.createDeflate(),this.readable=!0};Hl.inherits(os,ss);os.prototype.pack=function(t,e,r,n){this.emit("data",Buffer.from(zl.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,r)),n&&this.emit("data",this._packer.packGAMA(n));let i=this._packer.filterData(t,e,r);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(s){this.emit("data",this._packer.packIDAT(s))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(i)}});var ps=P((st,ds)=>{"use strict";var us=W("assert").ok,Qe=W("zlib"),Ql=W("util"),fs=W("buffer").kMaxLength;function Oe(t){if(!(this instanceof Oe))return new Oe(t);t&&t.chunkSize<Qe.Z_MIN_CHUNK&&(t.chunkSize=Qe.Z_MIN_CHUNK),Qe.Inflate.call(this,t),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,t&&t.maxLength!=null&&(this._maxLength=t.maxLength)}function Gl(t){return new Oe(t)}function cs(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Oe.prototype._processChunk=function(t,e,r){if(typeof r=="function")return Qe.Inflate._processChunk.call(this,t,e,r);let n=this,i=t&&t.length,s=this._chunkSize-this._offset,o=this._maxLength,a=0,u=[],c=0,h;this.on("error",function(g){h=g});function y(g,w){if(n._hadError)return;let C=s-w;if(us(C>=0,"have should not go down"),C>0){let E=n._buffer.slice(n._offset,n._offset+C);if(n._offset+=C,E.length>o&&(E=E.slice(0,o)),u.push(E),c+=E.length,o-=E.length,o===0)return!1}return(w===0||n._offset>=n._chunkSize)&&(s=n._chunkSize,n._offset=0,n._buffer=Buffer.allocUnsafe(n._chunkSize)),w===0?(a+=i-g,i=g,!0):!1}us(this._handle,"zlib binding closed");let _;do _=this._handle.writeSync(e,t,a,i,this._buffer,this._offset,s),_=_||this._writeState;while(!this._hadError&&y(_[0],_[1]));if(this._hadError)throw h;if(c>=fs)throw cs(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+fs.toString(16)+" bytes");let b=Buffer.concat(u,c);return cs(this),b};Ql.inherits(Oe,Qe.Inflate);function Yl(t,e){if(typeof e=="string"&&(e=Buffer.from(e)),!(e instanceof Buffer))throw new TypeError("Not a string or buffer");let r=t._finishFlushFlag;return r==null&&(r=Qe.Z_FINISH),t._processChunk(e,r)}function hs(t,e){return Yl(new Oe(e),t)}ds.exports=st=hs;st.Inflate=Oe;st.createInflate=Gl;st.inflateSync=hs});var Mr=P((ih,ms)=>{"use strict";var gs=ms.exports=function(t){this._buffer=t,this._reads=[]};gs.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};gs.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){let t=this._reads[0];if(this._buffer.length&&(this._buffer.length>=t.length||t.allowLess)){this._reads.shift();let e=this._buffer;this._buffer=e.slice(t.length),t.func.call(this,e.slice(0,t.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 _s=P(ys=>{"use strict";var Vl=Mr(),Jl=Sr();ys.process=function(t,e){let r=[],n=new Vl(t);return new Jl(e,{read:n.read.bind(n),write:function(s){r.push(s)},complete:function(){}}).start(),n.process(),Buffer.concat(r)}});var Es=P((oh,Cs)=>{"use strict";var ws=!0,bs=W("zlib"),Kl=ps();bs.deflateSync||(ws=!1);var Zl=Mr(),Xl=_s(),eu=Ar(),tu=Ir(),ru=vr();Cs.exports=function(t,e){if(!ws)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r;function n(O){r=O}let i;function s(O){i=O}function o(O){i.transColor=O}function a(O){i.palette=O}function u(){i.alpha=!0}let c;function h(O){c=O}let y=[];function _(O){y.push(O)}let b=new Zl(t);if(new eu(e,{read:b.read.bind(b),error:n,metadata:s,gamma:h,palette:a,transColor:o,inflateData:_,simpleTransparency:u}).start(),b.process(),r)throw r;let w=Buffer.concat(y);y.length=0;let C;if(i.interlace)C=bs.inflateSync(w);else{let N=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;C=Kl(w,{chunkSize:N,maxLength:N})}if(w=null,!C||!C.length)throw new Error("bad png - invalid inflate data response");let E=Xl.process(C,i);w=null;let x=tu.dataToBitMap(E,i);E=null;let I=ru(x,i);return i.data=I,i.gamma=c||0,i}});var Ss=P((ah,Ps)=>{"use strict";var Ts=!0,ks=W("zlib");ks.deflateSync||(Ts=!1);var nu=je(),iu=Lr();Ps.exports=function(t,e){if(!Ts)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r=e||{},n=new iu(r),i=[];i.push(Buffer.from(nu.PNG_SIGNATURE)),i.push(n.packIHDR(t.width,t.height)),t.gamma&&i.push(n.packGAMA(t.gamma));let s=n.filterData(t.data,t.width,t.height),o=ks.deflateSync(s,n.getDeflateOptions());if(s=null,!o||!o.length)throw new Error("bad png - invalid compressed data response");return i.push(n.packIDAT(o)),i.push(n.packIEND()),Buffer.concat(i)}});var xs=P(Nr=>{"use strict";var su=Es(),ou=Ss();Nr.read=function(t,e){return su(t,e||{})};Nr.write=function(t,e){return ou(t,e)}});var As=P(Rs=>{"use strict";var au=W("util"),Bs=W("stream"),lu=Zi(),uu=ls(),fu=xs(),V=Rs.PNG=function(t){Bs.call(this),t=t||{},this.width=t.width|0,this.height=t.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,t.fill&&this.data&&this.data.fill(0),this.gamma=0,this.readable=this.writable=!0,this._parser=new lu(t),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(e){this.data=e,this.emit("parsed",e)}.bind(this)),this._packer=new uu(t),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"))};au.inherits(V,Bs);V.sync=fu;V.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)};V.prototype.parse=function(t,e){if(e){let r,n;r=function(i){this.removeListener("error",n),this.data=i,e(null,this)}.bind(this),n=function(i){this.removeListener("parsed",r),e(i,null)}.bind(this),this.once("parsed",r),this.once("error",n)}return this.end(t),this};V.prototype.write=function(t){return this._parser.write(t),!0};V.prototype.end=function(t){this._parser.end(t)};V.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};V.prototype._gamma=function(t){this.gamma=t};V.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};V.bitblt=function(t,e,r,n,i,s,o,a){if(r|=0,n|=0,i|=0,s|=0,o|=0,a|=0,r>t.width||n>t.height||r+i>t.width||n+s>t.height)throw new Error("bitblt reading outside image");if(o>e.width||a>e.height||o+i>e.width||a+s>e.height)throw new Error("bitblt writing outside image");for(let u=0;u<s;u++)t.data.copy(e.data,(a+u)*e.width+o<<2,(n+u)*t.width+r<<2,(n+u)*t.width+r+i<<2)};V.prototype.bitblt=function(t,e,r,n,i,s,o){return V.bitblt(this,t,e,r,n,i,s,o),this};V.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let r=0;r<t.width;r++){let n=t.width*e+r<<2;for(let i=0;i<3;i++){let s=t.data[n+i]/255;s=Math.pow(s,1/2.2/t.gamma),t.data[n+i]=Math.round(s*255)}}t.gamma=0}};V.prototype.adjustGamma=function(){V.adjustGamma(this)}});var ot=P(Le=>{function Is(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let e=t.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+t);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(n){return[n,n]}))),e.length===6&&e.push("F","F");let r=parseInt(e.join(""),16);return{r:r>>24&255,g:r>>16&255,b:r>>8&255,a:r&255,hex:"#"+e.slice(0,6).join("")}}Le.getOptions=function(e){e||(e={}),e.color||(e.color={});let r=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,n=e.width&&e.width>=21?e.width:void 0,i=e.scale||4;return{width:n,scale:n?4:i,margin:r,color:{dark:Is(e.color.dark||"#000000ff"),light:Is(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};Le.getScale=function(e,r){return r.width&&r.width>=e+r.margin*2?r.width/(e+r.margin*2):r.scale};Le.getImageWidth=function(e,r){let n=Le.getScale(e,r);return Math.floor((e+r.margin*2)*n)};Le.qrToImageData=function(e,r,n){let i=r.modules.size,s=r.modules.data,o=Le.getScale(i,n),a=Math.floor((i+n.margin*2)*o),u=n.margin*o,c=[n.color.light,n.color.dark];for(let h=0;h<a;h++)for(let y=0;y<a;y++){let _=(h*a+y)*4,b=n.color.light;if(h>=u&&y>=u&&h<a-u&&y<a-u){let g=Math.floor((h-u)/o),w=Math.floor((y-u)/o);b=c[s[g*i+w]?1:0]}e[_++]=b.r,e[_++]=b.g,e[_++]=b.b,e[_]=b.a}}});var vs=P(fe=>{var cu=W("fs"),hu=As().PNG,$r=ot();fe.render=function(e,r){let n=$r.getOptions(r),i=n.rendererOpts,s=$r.getImageWidth(e.modules.size,n);i.width=s,i.height=s;let o=new hu(i);return $r.qrToImageData(o.data,e,n),o};fe.renderToDataURL=function(e,r,n){typeof n>"u"&&(n=r,r=void 0),fe.renderToBuffer(e,r,function(i,s){i&&n(i);let o="data:image/png;base64,";o+=s.toString("base64"),n(null,o)})};fe.renderToBuffer=function(e,r,n){typeof n>"u"&&(n=r,r=void 0);let i=fe.render(e,r),s=[];i.on("error",n),i.on("data",function(o){s.push(o)}),i.on("end",function(){n(null,Buffer.concat(s))}),i.pack()};fe.renderToFile=function(e,r,n,i){typeof i>"u"&&(i=n,n=void 0);let s=!1,o=(...u)=>{s||(s=!0,i.apply(null,u))},a=cu.createWriteStream(e);a.on("error",o),a.on("close",o),fe.renderToFileStream(a,r,n)};fe.renderToFileStream=function(e,r,n){fe.render(r,n).pack().pipe(e)}});var Os=P(St=>{var du=ot(),pu={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},gu={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function mu(t,e,r){return t&&e?r.BB:t&&!e?r.BW:!t&&e?r.WB:r.WW}St.render=function(t,e,r){let n=du.getOptions(e),i=pu;(n.color.dark.hex==="#ffffff"||n.color.light.hex==="#000000")&&(i=gu);let s=t.modules.size,o=t.modules.data,a="",u=Array(s+n.margin*2+1).join(i.WW);u=Array(n.margin/2+1).join(u+`
|
|
11
|
+
`);let c=Array(n.margin+1).join(i.WW);a+=u;for(let h=0;h<s;h+=2){a+=c;for(let y=0;y<s;y++){let _=o[h*s+y],b=o[(h+1)*s+y];a+=mu(_,b,i)}a+=c+`
|
|
12
12
|
`}return a+=u.slice(0,-1),typeof r=="function"&&r(null,a),a};St.renderToFile=function(e,r,n,i){typeof i>"u"&&(i=n,n=void 0);let s=W("fs"),o=St.render(r,n);s.writeFile(e,o,i)}});var Ms=P(Ls=>{Ls.render=function(t,e,r){let n=t.modules.size,i=t.modules.data,s="\x1B[40m \x1B[0m",o="\x1B[47m \x1B[0m",a="",u=Array(n+3).join(o),c=Array(2).join(o);a+=u+`
|
|
13
13
|
`;for(let h=0;h<n;++h){a+=o;for(let y=0;y<n;y++)a+=i[h*n+y]?s:o;a+=c+`
|
|
14
14
|
`}return a+=u+`
|
|
15
|
-
`,typeof r=="function"&&r(null,a),a}});var Fs=P(
|
|
16
|
-
`+o,y=o;for(let _=-1;_<n+1;_+=2){for(let b=-1;b<n;b++)y+=c[
|
|
17
|
-
`;return typeof n=="function"&&n(null,_),_}});var zs=P(xt=>{var Pu=Dr();xt.render=Pu.render;xt.renderToFile=function(e,r,n,i){typeof i>"u"&&(i=n,n=void 0);let s=W("fs"),a='<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'+xt.render(r,n);s.writeFile(e,a,i)}});var js=P(Bt=>{var qr=ot();function Su(t,e,r){t.clearRect(0,0,e.width,e.height),e.style||(e.style={}),e.height=r,e.width=r,e.style.height=r+"px",e.style.width=r+"px"}function xu(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}Bt.render=function(e,r,n){let i=n,s=r;typeof i>"u"&&(!r||!r.getContext)&&(i=r,r=void 0),r||(s=xu()),i=qr.getOptions(i);let o=qr.getImageWidth(e.modules.size,i),a=s.getContext("2d"),u=a.createImageData(o,o);return qr.qrToImageData(u.data,e,i),Su(a,s,o),a.putImageData(u,0,0),s};Bt.renderToDataURL=function(e,r,n){let i=n;typeof i>"u"&&(!r||!r.getContext)&&(i=r,r=void 0),i||(i={});let s=Bt.render(e,r,i),o=i.type||"image/png",a=i.rendererOpts||{};return s.toDataURL(o,a.quality)}});var Gs=P(at=>{var Bu=tr(),Wr=br(),Qs=js(),Au=Dr();function Hr(t,e,r,n,i){let s=[].slice.call(arguments,1),o=s.length,a=typeof s[o-1]=="function";if(!a&&!Bu())throw new Error("Callback required as last argument");if(a){if(o<2)throw new Error("Too few arguments provided");o===2?(i=r,r=e,e=n=void 0):o===3&&(e.getContext&&typeof i>"u"?(i=n,n=void 0):(i=n,n=r,r=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(r=e,e=n=void 0):o===2&&!e.getContext&&(n=r,r=e,e=void 0),new Promise(function(u,c){try{let h=Wr.create(r,n);u(t(h,e,n))}catch(h){c(h)}})}try{let u=Wr.create(r,n);i(null,t(u,e,n))}catch(u){i(u)}}at.create=Wr.create;at.toCanvas=Hr.bind(null,Qs.render);at.toDataURL=Hr.bind(null,Qs.renderToDataURL);at.toString=Hr.bind(null,function(t,e,r){return Au.render(t,r)})});var Js=P(Te=>{var Ys=tr(),zr=br(),Ru=vs(),Vs=Os(),Iu=qs(),Ks=zs();function lt(t,e,r){if(typeof t>"u")throw new Error("String required as first argument");if(typeof r>"u"&&(r=e,e={}),typeof r!="function")if(Ys())e=r||{},r=null;else throw new Error("Callback required as last argument");return{opts:e,cb:r}}function vu(t){return t.slice((t.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function At(t){switch(t){case"svg":return Ks;case"txt":case"utf8":return Vs;default:return Ru}}function Ou(t){switch(t){case"svg":return Ks;case"terminal":return Iu;default:return Vs}}function ut(t,e,r){if(!r.cb)return new Promise(function(n,i){try{let s=zr.create(e,r.opts);return t(s,r.opts,function(o,a){return o?i(o):n(a)})}catch(s){i(s)}});try{let n=zr.create(e,r.opts);return t(n,r.opts,r.cb)}catch(n){r.cb(n)}}Te.create=zr.create;Te.toCanvas=Gs().toCanvas;Te.toString=function(e,r,n){let i=lt(e,r,n),s=i.opts?i.opts.type:void 0,o=Ou(s);return ut(o.render,e,i)};Te.toDataURL=function(e,r,n){let i=lt(e,r,n),s=At(i.opts.type);return ut(s.renderToDataURL,e,i)};Te.toBuffer=function(e,r,n){let i=lt(e,r,n),s=At(i.opts.type);return ut(s.renderToBuffer,e,i)};Te.toFile=function(e,r,n,i){if(typeof e!="string"||!(typeof r=="string"||typeof r=="object"))throw new Error("Invalid argument");if(arguments.length<3&&!Ys())throw new Error("Too few arguments provided");let s=lt(r,n,i),o=s.opts.type||vu(e),u=At(o).renderToFile.bind(null,e);return ut(u,r,s)};Te.toFileStream=function(e,r,n){if(arguments.length<2)throw new Error("Too few arguments provided");let i=lt(r,n,e.emit.bind(e,"error")),o=At("png").renderToFileStream.bind(null,e);ut(o,r,i)}});var jr=P((Ch,Zs)=>{Zs.exports=Js()});var _o=P((Cd,yo)=>{"use strict";var rn=Object.defineProperty,rf=Object.getOwnPropertyDescriptor,nf=Object.getOwnPropertyNames,sf=Object.prototype.hasOwnProperty,of=(t,e)=>{for(var r in e)rn(t,r,{get:e[r],enumerable:!0})},af=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of nf(e))!sf.call(t,i)&&i!==r&&rn(t,i,{get:()=>e[i],enumerable:!(n=rf(e,i))||n.enumerable});return t},lf=t=>af(rn({},"__esModule",{value:!0}),t),co={};of(co,{decode:()=>Pf,encode:()=>kf,getDuration:()=>Sf,getWavFileInfo:()=>Bf,isSilk:()=>Af,isWav:()=>xf});yo.exports=lf(co);var en=W("url").pathToFileURL(__filename).href,uf=async function(t={}){var e,r=t,n,i,s=new Promise((l,f)=>{n=l,i=f}),o=typeof window=="object",a=typeof WorkerGlobalScope<"u",u=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string"&&process.type!="renderer";if(u){let{createRequire:l}=await import("module");var c=l(en)}var h=(l,f)=>{throw f},y=en,_="",b,g;if(u){var w=c("fs"),C=c("path");y.startsWith("file:")&&(_=C.dirname(c("url").fileURLToPath(y))+"/"),g=l=>(l=Se(l)?new URL(l):l,w.readFileSync(l)),b=async l=>(l=Se(l)?new URL(l):l,w.readFileSync(l,void 0)),process.argv.slice(2),h=(l,f)=>{throw process.exitCode=l,f}}else if(o||a){try{_=new URL(".",y).href}catch{}a&&(g=l=>{var f=new XMLHttpRequest;return f.open("GET",l,!1),f.responseType="arraybuffer",f.send(null),new Uint8Array(f.response)}),b=async l=>{if(Se(l))return new Promise((p,d)=>{var m=new XMLHttpRequest;m.open("GET",l,!0),m.responseType="arraybuffer",m.onload=()=>{m.status==200||m.status==0&&m.response?p(m.response):d(m.status)},m.onerror=d,m.send(null)});var f=await fetch(l,{credentials:"same-origin"});if(f.ok)return f.arrayBuffer();throw Error(f.status+" : "+f.url)}}console.log.bind(console);var E=console.error.bind(console),x,I,O=!1,N,v,L,G,z,$,F,X,Ne,K,Ue,Se=l=>l.startsWith("file://");function hn(){var l=I.buffer;v=new Int8Array(l),G=new Int16Array(l),L=new Uint8Array(l),z=new Uint16Array(l),$=new Int32Array(l),F=new Uint32Array(l),X=new Float32Array(l),Ue=new Float64Array(l),Ne=new BigInt64Array(l),K=new BigUint64Array(l)}var xe=0,Ge=null;function dn(l){throw r.onAbort?.(l),l="Aborted("+l+")",E(l),O=!0,l=new WebAssembly.RuntimeError(l+". Build with -sASSERTIONS for more info."),i(l),l}var Wt;async function Ro(l){if(!x)try{var f=await b(l);return new Uint8Array(f)}catch{}if(l==Wt&&x)l=new Uint8Array(x);else if(g)l=g(l);else throw"both async and sync fetching of the wasm failed";return l}async function Io(l,f){try{var p=await Ro(l);return await WebAssembly.instantiate(p,f)}catch(d){E(`failed to asynchronously prepare wasm: ${d}`),dn(d)}}async function vo(l){var f=Wt;if(!x&&typeof WebAssembly.instantiateStreaming=="function"&&!Se(f)&&!u)try{var p=fetch(f,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(p,l)}catch(d){E(`wasm streaming compile failed: ${d}`),E("falling back to ArrayBuffer instantiation")}return Io(f,l)}class Ht{name="ExitStatus";constructor(f){this.message=`Program terminated with exit(${f})`,this.status=f}}var pn=l=>{for(;0<l.length;)l.shift()(r)},gn=[],mn=[],Oo=()=>{var l=r.preRun.shift();mn.push(l)},dt=!0;class Lo{constructor(f){this.I=f-24}}var yn=0,Mo=0,_n,ne=l=>{for(var f="";L[l];)f+=_n[L[l++]];return f},$e={},Be={},pt={},ee=r.BindingError=class extends Error{constructor(l){super(l),this.name="BindingError"}},No=l=>{throw new ee(l)};function Uo(l,f,p={}){var d=f.name;if(!l)throw new ee(`type "${d}" must have a positive integer typeid pointer`);if(Be.hasOwnProperty(l)){if(p.K)return;throw new ee(`Cannot register type '${d}' twice`)}Be[l]=f,delete pt[l],$e.hasOwnProperty(l)&&(f=$e[l],delete $e[l],f.forEach(m=>m()))}function ie(l,f,p={}){return Uo(l,f,p)}var wn=(l,f,p)=>{switch(f){case 1:return p?d=>v[d]:d=>L[d];case 2:return p?d=>G[d>>1]:d=>z[d>>1];case 4:return p?d=>$[d>>2]:d=>F[d>>2];case 8:return p?d=>Ne[d>>3]:d=>K[d>>3];default:throw new TypeError(`invalid integer width (${f}): ${l}`)}},zt=[],ce=[],jt=l=>{9<l&&--ce[l+1]===0&&(ce[l]=void 0,zt.push(l))},Qt=l=>{if(!l)throw new ee(`Cannot use deleted val. handle = ${l}`);return ce[l]},Gt=l=>{switch(l){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let f=zt.pop()||ce.length;return ce[f]=l,ce[f+1]=1,f}};function Yt(l){return this.fromWireType(F[l>>2])}var bn={name:"emscripten::val",fromWireType:l=>{var f=Qt(l);return jt(l),f},toWireType:(l,f)=>Gt(f),H:8,readValueFromPointer:Yt,G:null},$o=(l,f)=>{switch(f){case 4:return function(p){return this.fromWireType(X[p>>2])};case 8:return function(p){return this.fromWireType(Ue[p>>3])};default:throw new TypeError(`invalid float width (${f}): ${l}`)}},Cn=l=>{for(;l.length;){var f=l.pop();l.pop()(f)}};function En(l){for(var f=1;f<l.length;++f)if(l[f]!==null&&l[f].G===void 0)return!0;return!1}var Fo=(l,f)=>{if(r[l].F===void 0){var p=r[l];r[l]=function(...d){if(!r[l].F.hasOwnProperty(d.length))throw new ee(`Function '${f}' called with an invalid number of arguments (${d.length}) - expects one of (${r[l].F})!`);return r[l].F[d.length].apply(this,d)},r[l].F=[],r[l].F[p.J]=p}},Do=(l,f,p)=>{if(r.hasOwnProperty(l)){if(p===void 0||r[l].F!==void 0&&r[l].F[p]!==void 0)throw new ee(`Cannot register public name '${l}' twice`);if(Fo(l,l),r[l].F.hasOwnProperty(p))throw new ee(`Cannot register multiple overloads of a function with the same number of arguments (${p})!`);r[l].F[p]=f}else r[l]=f,r[l].J=p},qo=(l,f)=>{for(var p=[],d=0;d<l;d++)p.push(F[f+4*d>>2]);return p},Tn=r.InternalError=class extends Error{constructor(l){super(l),this.name="InternalError"}},kn=[],Pn,Wo=(l,f)=>{l=ne(l);var p;if((p=kn[f])||(kn[f]=p=Pn.get(f)),typeof p!="function")throw new ee(`unknown function pointer with signature ${l}: ${f}`);return p};class Ho extends Error{}for(var Sn=l=>{l=sa(l);var f=ne(l);return Ae(l),f},zo=(l,f)=>{function p(T){m[T]||Be[T]||(pt[T]?pt[T].forEach(p):(d.push(T),m[T]=!0))}var d=[],m={};throw f.forEach(p),new Ho(`${l}: `+d.map(Sn).join([", "]))},jo=(l,f)=>{function p(k){if(k=f(k),k.length!==d.length)throw new Tn("Mismatched type converter count");for(var B=0;B<d.length;++B)ie(d[B],k[B])}var d=[];d.forEach(k=>pt[k]=l);var m=Array(l.length),T=[],A=0;l.forEach((k,B)=>{Be.hasOwnProperty(k)?m[B]=Be[k]:(T.push(k),$e.hasOwnProperty(k)||($e[k]=[]),$e[k].push(()=>{m[B]=Be[k],++A,A===T.length&&p(m)}))}),T.length===0&&p(m)},Qo=l=>{l=l.trim();let f=l.indexOf("(");return f===-1?l:l.slice(0,f)},xn=typeof TextDecoder<"u"?new TextDecoder:void 0,Go=(l=0,f=NaN)=>{var p=L,d=l+f;for(f=l;p[f]&&!(f>=d);)++f;if(16<f-l&&p.buffer&&xn)return xn.decode(p.subarray(l,f));for(d="";l<f;){var m=p[l++];if(m&128){var T=p[l++]&63;if((m&224)==192)d+=String.fromCharCode((m&31)<<6|T);else{var A=p[l++]&63;m=(m&240)==224?(m&15)<<12|T<<6|A:(m&7)<<18|T<<12|A<<6|p[l++]&63,65536>m?d+=String.fromCharCode(m):(m-=65536,d+=String.fromCharCode(55296|m>>10,56320|m&1023))}}else d+=String.fromCharCode(m)}return d},Bn=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Yo=(l,f)=>{for(var p=l>>1,d=p+f/2;!(p>=d)&&z[p];)++p;if(p<<=1,32<p-l&&Bn)return Bn.decode(L.subarray(l,p));for(p="",d=0;!(d>=f/2);++d){var m=G[l+2*d>>1];if(m==0)break;p+=String.fromCharCode(m)}return p},Vo=(l,f,p)=>{if(p??=2147483647,2>p)return 0;p-=2;var d=f;p=p<2*l.length?p/2:l.length;for(var m=0;m<p;++m)G[f>>1]=l.charCodeAt(m),f+=2;return G[f>>1]=0,f-d},Ko=l=>2*l.length,Jo=(l,f)=>{for(var p=0,d="";!(p>=f/4);){var m=$[l+4*p>>2];if(m==0)break;++p,65536<=m?(m-=65536,d+=String.fromCharCode(55296|m>>10,56320|m&1023)):d+=String.fromCharCode(m)}return d},Zo=(l,f,p)=>{if(p??=2147483647,4>p)return 0;var d=f;p=d+p-4;for(var m=0;m<l.length;++m){var T=l.charCodeAt(m);if(55296<=T&&57343>=T){var A=l.charCodeAt(++m);T=65536+((T&1023)<<10)|A&1023}if($[f>>2]=T,f+=4,f+4>p)break}return $[f>>2]=0,f-d},Xo=l=>{for(var f=0,p=0;p<l.length;++p){var d=l.charCodeAt(p);55296<=d&&57343>=d&&++p,f+=4}return f},Vt=0,Kt=[],ea=l=>{var f=Kt.length;return Kt.push(l),f},An=(l,f)=>{var p=Be[l];if(p===void 0)throw l=`${f} has unknown type ${Sn(l)}`,new ee(l);return p},ta=(l,f)=>{for(var p=Array(l),d=0;d<l;++d)p[d]=An(F[f+4*d>>2],`parameter ${d}`);return p},ra=(l,f,p)=>{var d=[];return l=l.toWireType(d,p),d.length&&(F[f>>2]=Gt(d)),l},Ye={},Rn=l=>{N=l,dt||0<Vt||(r.onExit?.(l),O=!0),h(l,new Ht(l))},na=l=>{if(!O)try{if(l(),!(dt||0<Vt))try{N=l=N,Rn(l)}catch(f){f instanceof Ht||f=="unwind"||h(1,f)}}catch(f){f instanceof Ht||f=="unwind"||h(1,f)}},In=Array(256),gt=0;256>gt;++gt)In[gt]=String.fromCharCode(gt);_n=In,ce.push(0,1,void 0,1,null,1,!0,1,!1,1),r.count_emval_handles=()=>ce.length/2-5-zt.length,r.noExitRuntime&&(dt=r.noExitRuntime),r.printErr&&(E=r.printErr),r.wasmBinary&&(x=r.wasmBinary);var ia={u:(l,f,p)=>{var d=new Lo(l);throw F[d.I+16>>2]=0,F[d.I+4>>2]=f,F[d.I+8>>2]=p,yn=l,Mo++,yn},v:()=>dn(""),l:(l,f,p)=>{f=ne(f),ie(l,{name:f,fromWireType:d=>d,toWireType:function(d,m){if(typeof m!="bigint"&&typeof m!="number")throw m===null?m="null":(d=typeof m,m=d==="object"||d==="array"||d==="function"?m.toString():""+m),new TypeError(`Cannot convert "${m}" to ${this.name}`);return typeof m=="number"&&(m=BigInt(m)),m},H:8,readValueFromPointer:wn(f,p,f.indexOf("u")==-1),G:null})},o:(l,f,p,d)=>{f=ne(f),ie(l,{name:f,fromWireType:function(m){return!!m},toWireType:function(m,T){return T?p:d},H:8,readValueFromPointer:function(m){return this.fromWireType(L[m])},G:null})},m:l=>ie(l,bn),k:(l,f,p)=>{f=ne(f),ie(l,{name:f,fromWireType:d=>d,toWireType:(d,m)=>m,H:8,readValueFromPointer:$o(f,p),G:null})},c:(l,f,p,d,m,T,A)=>{var k=qo(f,p);l=ne(l),l=Qo(l),m=Wo(d,m),Do(l,function(){zo(`Cannot call ${l} due to unbound types`,k)},f-1),jo(k,B=>{var S=[B[0],null].concat(B.slice(1));B=l;var q=l,ae=m,D=S.length;if(2>D)throw new ee("argTypes array size mismatch! Must at least get return value and 'this' types!");var me=S[1]!==null&&!1,Ve=En(S),On=S[0].name!=="void";ae=[q,No,ae,T,Cn,S[0],S[1]];for(var se=0;se<D-2;++se)ae.push(S[se+2]);if(!Ve)for(se=me?1:2;se<S.length;++se)S[se].G!==null&&ae.push(S[se].G);Ve=En(S),se=S.length-2;var J=[],Ke=["fn"];for(me&&Ke.push("thisWired"),D=0;D<se;++D)J.push(`arg${D}`),Ke.push(`arg${D}Wired`);J=J.join(","),Ke=Ke.join(","),J=`return function (${J}) {
|
|
18
|
-
`,Ve&&(
|
|
19
|
-
`);var Ln=Ve?"destructors":"null",
|
|
20
|
-
`),
|
|
21
|
-
`,
|
|
22
|
-
`,Ve)
|
|
23
|
-
`;else for(
|
|
24
|
-
`,
|
|
15
|
+
`,typeof r=="function"&&r(null,a),a}});var Fs=P(Us=>{var yu="\x1B[47m",_u="\x1B[40m",Ur="\x1B[37m",Fr="\x1B[30m",Me="\x1B[0m",wu=yu+Fr,bu=_u+Ur,Cu=function(t,e,r){return{"00":Me+" "+t,"01":Me+e+"\u2584"+t,"02":Me+r+"\u2584"+t,10:Me+e+"\u2580"+t,11:" ",12:"\u2584",20:Me+r+"\u2580"+t,21:"\u2580",22:"\u2588"}},Ns=function(t,e,r,n){let i=e+1;if(r>=i||n>=i||n<-1||r<-1)return"0";if(r>=e||n>=e||n<0||r<0)return"1";let s=n*e+r;return t[s]?"2":"1"},$s=function(t,e,r,n){return Ns(t,e,r,n)+Ns(t,e,r,n+1)};Us.render=function(t,e,r){let n=t.modules.size,i=t.modules.data,s=!!(e&&e.inverse),o=e&&e.inverse?bu:wu,c=Cu(o,s?Fr:Ur,s?Ur:Fr),h=Me+`
|
|
16
|
+
`+o,y=o;for(let _=-1;_<n+1;_+=2){for(let b=-1;b<n;b++)y+=c[$s(i,n,b,_)];y+=c[$s(i,n,n,_)]+h}return y+=Me,typeof r=="function"&&r(null,y),y}});var Ds=P(qs=>{var Eu=Ms(),Tu=Fs();qs.render=function(t,e,r){return e&&e.small?Tu.render(t,e,r):Eu.render(t,e,r)}});var Dr=P(Hs=>{var ku=ot();function Ws(t,e){let r=t.a/255,n=e+'="'+t.hex+'"';return r<1?n+" "+e+'-opacity="'+r.toFixed(2).slice(1)+'"':n}function qr(t,e,r){let n=t+e;return typeof r<"u"&&(n+=" "+r),n}function Pu(t,e,r){let n="",i=0,s=!1,o=0;for(let a=0;a<t.length;a++){let u=Math.floor(a%e),c=Math.floor(a/e);!u&&!s&&(s=!0),t[a]?(o++,a>0&&u>0&&t[a-1]||(n+=s?qr("M",u+r,.5+c+r):qr("m",i,0),i=0,s=!1),u+1<e&&t[a+1]||(n+=qr("h",o),o=0)):i++}return n}Hs.render=function(e,r,n){let i=ku.getOptions(r),s=e.modules.size,o=e.modules.data,a=s+i.margin*2,u=i.color.light.a?"<path "+Ws(i.color.light,"fill")+' d="M0 0h'+a+"v"+a+'H0z"/>':"",c="<path "+Ws(i.color.dark,"stroke")+' d="'+Pu(o,s,i.margin)+'"/>',h='viewBox="0 0 '+a+" "+a+'"',_='<svg xmlns="http://www.w3.org/2000/svg" '+(i.width?'width="'+i.width+'" height="'+i.width+'" ':"")+h+' shape-rendering="crispEdges">'+u+c+`</svg>
|
|
17
|
+
`;return typeof n=="function"&&n(null,_),_}});var zs=P(xt=>{var Su=Dr();xt.render=Su.render;xt.renderToFile=function(e,r,n,i){typeof i>"u"&&(i=n,n=void 0);let s=W("fs"),a='<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'+xt.render(r,n);s.writeFile(e,a,i)}});var js=P(Bt=>{var Wr=ot();function xu(t,e,r){t.clearRect(0,0,e.width,e.height),e.style||(e.style={}),e.height=r,e.width=r,e.style.height=r+"px",e.style.width=r+"px"}function Bu(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}Bt.render=function(e,r,n){let i=n,s=r;typeof i>"u"&&(!r||!r.getContext)&&(i=r,r=void 0),r||(s=Bu()),i=Wr.getOptions(i);let o=Wr.getImageWidth(e.modules.size,i),a=s.getContext("2d"),u=a.createImageData(o,o);return Wr.qrToImageData(u.data,e,i),xu(a,s,o),a.putImageData(u,0,0),s};Bt.renderToDataURL=function(e,r,n){let i=n;typeof i>"u"&&(!r||!r.getContext)&&(i=r,r=void 0),i||(i={});let s=Bt.render(e,r,i),o=i.type||"image/png",a=i.rendererOpts||{};return s.toDataURL(o,a.quality)}});var Gs=P(at=>{var Ru=rr(),Hr=Cr(),Qs=js(),Au=Dr();function zr(t,e,r,n,i){let s=[].slice.call(arguments,1),o=s.length,a=typeof s[o-1]=="function";if(!a&&!Ru())throw new Error("Callback required as last argument");if(a){if(o<2)throw new Error("Too few arguments provided");o===2?(i=r,r=e,e=n=void 0):o===3&&(e.getContext&&typeof i>"u"?(i=n,n=void 0):(i=n,n=r,r=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(r=e,e=n=void 0):o===2&&!e.getContext&&(n=r,r=e,e=void 0),new Promise(function(u,c){try{let h=Hr.create(r,n);u(t(h,e,n))}catch(h){c(h)}})}try{let u=Hr.create(r,n);i(null,t(u,e,n))}catch(u){i(u)}}at.create=Hr.create;at.toCanvas=zr.bind(null,Qs.render);at.toDataURL=zr.bind(null,Qs.renderToDataURL);at.toString=zr.bind(null,function(t,e,r){return Au.render(t,r)})});var Ks=P(Te=>{var Ys=rr(),jr=Cr(),Iu=vs(),Vs=Os(),vu=Ds(),Js=zs();function lt(t,e,r){if(typeof t>"u")throw new Error("String required as first argument");if(typeof r>"u"&&(r=e,e={}),typeof r!="function")if(Ys())e=r||{},r=null;else throw new Error("Callback required as last argument");return{opts:e,cb:r}}function Ou(t){return t.slice((t.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function Rt(t){switch(t){case"svg":return Js;case"txt":case"utf8":return Vs;default:return Iu}}function Lu(t){switch(t){case"svg":return Js;case"terminal":return vu;default:return Vs}}function ut(t,e,r){if(!r.cb)return new Promise(function(n,i){try{let s=jr.create(e,r.opts);return t(s,r.opts,function(o,a){return o?i(o):n(a)})}catch(s){i(s)}});try{let n=jr.create(e,r.opts);return t(n,r.opts,r.cb)}catch(n){r.cb(n)}}Te.create=jr.create;Te.toCanvas=Gs().toCanvas;Te.toString=function(e,r,n){let i=lt(e,r,n),s=i.opts?i.opts.type:void 0,o=Lu(s);return ut(o.render,e,i)};Te.toDataURL=function(e,r,n){let i=lt(e,r,n),s=Rt(i.opts.type);return ut(s.renderToDataURL,e,i)};Te.toBuffer=function(e,r,n){let i=lt(e,r,n),s=Rt(i.opts.type);return ut(s.renderToBuffer,e,i)};Te.toFile=function(e,r,n,i){if(typeof e!="string"||!(typeof r=="string"||typeof r=="object"))throw new Error("Invalid argument");if(arguments.length<3&&!Ys())throw new Error("Too few arguments provided");let s=lt(r,n,i),o=s.opts.type||Ou(e),u=Rt(o).renderToFile.bind(null,e);return ut(u,r,s)};Te.toFileStream=function(e,r,n){if(arguments.length<2)throw new Error("Too few arguments provided");let i=lt(r,n,e.emit.bind(e,"error")),o=Rt("png").renderToFileStream.bind(null,e);ut(o,r,i)}});var Qr=P((Ch,Zs)=>{Zs.exports=Ks()});var wo=P((Cd,_o)=>{"use strict";var rn=Object.defineProperty,rf=Object.getOwnPropertyDescriptor,nf=Object.getOwnPropertyNames,sf=Object.prototype.hasOwnProperty,of=(t,e)=>{for(var r in e)rn(t,r,{get:e[r],enumerable:!0})},af=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of nf(e))!sf.call(t,i)&&i!==r&&rn(t,i,{get:()=>e[i],enumerable:!(n=rf(e,i))||n.enumerable});return t},lf=t=>af(rn({},"__esModule",{value:!0}),t),ho={};of(ho,{decode:()=>Pf,encode:()=>kf,getDuration:()=>Sf,getWavFileInfo:()=>Bf,isSilk:()=>Rf,isWav:()=>xf});_o.exports=lf(ho);var en=W("url").pathToFileURL(__filename).href,uf=async function(t={}){var e,r=t,n,i,s=new Promise((l,f)=>{n=l,i=f}),o=typeof window=="object",a=typeof WorkerGlobalScope<"u",u=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string"&&process.type!="renderer";if(u){let{createRequire:l}=await import("module");var c=l(en)}var h=(l,f)=>{throw f},y=en,_="",b,g;if(u){var w=c("fs"),C=c("path");y.startsWith("file:")&&(_=C.dirname(c("url").fileURLToPath(y))+"/"),g=l=>(l=Se(l)?new URL(l):l,w.readFileSync(l)),b=async l=>(l=Se(l)?new URL(l):l,w.readFileSync(l,void 0)),process.argv.slice(2),h=(l,f)=>{throw process.exitCode=l,f}}else if(o||a){try{_=new URL(".",y).href}catch{}a&&(g=l=>{var f=new XMLHttpRequest;return f.open("GET",l,!1),f.responseType="arraybuffer",f.send(null),new Uint8Array(f.response)}),b=async l=>{if(Se(l))return new Promise((p,d)=>{var m=new XMLHttpRequest;m.open("GET",l,!0),m.responseType="arraybuffer",m.onload=()=>{m.status==200||m.status==0&&m.response?p(m.response):d(m.status)},m.onerror=d,m.send(null)});var f=await fetch(l,{credentials:"same-origin"});if(f.ok)return f.arrayBuffer();throw Error(f.status+" : "+f.url)}}console.log.bind(console);var E=console.error.bind(console),x,I,O=!1,N,v,L,G,z,U,F,X,Ne,J,$e,Se=l=>l.startsWith("file://");function hn(){var l=I.buffer;v=new Int8Array(l),G=new Int16Array(l),L=new Uint8Array(l),z=new Uint16Array(l),U=new Int32Array(l),F=new Uint32Array(l),X=new Float32Array(l),$e=new Float64Array(l),Ne=new BigInt64Array(l),J=new BigUint64Array(l)}var xe=0,Ge=null;function dn(l){throw r.onAbort?.(l),l="Aborted("+l+")",E(l),O=!0,l=new WebAssembly.RuntimeError(l+". Build with -sASSERTIONS for more info."),i(l),l}var Ht;async function Io(l){if(!x)try{var f=await b(l);return new Uint8Array(f)}catch{}if(l==Ht&&x)l=new Uint8Array(x);else if(g)l=g(l);else throw"both async and sync fetching of the wasm failed";return l}async function vo(l,f){try{var p=await Io(l);return await WebAssembly.instantiate(p,f)}catch(d){E(`failed to asynchronously prepare wasm: ${d}`),dn(d)}}async function Oo(l){var f=Ht;if(!x&&typeof WebAssembly.instantiateStreaming=="function"&&!Se(f)&&!u)try{var p=fetch(f,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(p,l)}catch(d){E(`wasm streaming compile failed: ${d}`),E("falling back to ArrayBuffer instantiation")}return vo(f,l)}class zt{name="ExitStatus";constructor(f){this.message=`Program terminated with exit(${f})`,this.status=f}}var pn=l=>{for(;0<l.length;)l.shift()(r)},gn=[],mn=[],Lo=()=>{var l=r.preRun.shift();mn.push(l)},dt=!0;class Mo{constructor(f){this.I=f-24}}var yn=0,No=0,_n,ne=l=>{for(var f="";L[l];)f+=_n[L[l++]];return f},Ue={},Be={},pt={},ee=r.BindingError=class extends Error{constructor(l){super(l),this.name="BindingError"}},$o=l=>{throw new ee(l)};function Uo(l,f,p={}){var d=f.name;if(!l)throw new ee(`type "${d}" must have a positive integer typeid pointer`);if(Be.hasOwnProperty(l)){if(p.K)return;throw new ee(`Cannot register type '${d}' twice`)}Be[l]=f,delete pt[l],Ue.hasOwnProperty(l)&&(f=Ue[l],delete Ue[l],f.forEach(m=>m()))}function ie(l,f,p={}){return Uo(l,f,p)}var wn=(l,f,p)=>{switch(f){case 1:return p?d=>v[d]:d=>L[d];case 2:return p?d=>G[d>>1]:d=>z[d>>1];case 4:return p?d=>U[d>>2]:d=>F[d>>2];case 8:return p?d=>Ne[d>>3]:d=>J[d>>3];default:throw new TypeError(`invalid integer width (${f}): ${l}`)}},jt=[],ce=[],Qt=l=>{9<l&&--ce[l+1]===0&&(ce[l]=void 0,jt.push(l))},Gt=l=>{if(!l)throw new ee(`Cannot use deleted val. handle = ${l}`);return ce[l]},Yt=l=>{switch(l){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let f=jt.pop()||ce.length;return ce[f]=l,ce[f+1]=1,f}};function Vt(l){return this.fromWireType(F[l>>2])}var bn={name:"emscripten::val",fromWireType:l=>{var f=Gt(l);return Qt(l),f},toWireType:(l,f)=>Yt(f),H:8,readValueFromPointer:Vt,G:null},Fo=(l,f)=>{switch(f){case 4:return function(p){return this.fromWireType(X[p>>2])};case 8:return function(p){return this.fromWireType($e[p>>3])};default:throw new TypeError(`invalid float width (${f}): ${l}`)}},Cn=l=>{for(;l.length;){var f=l.pop();l.pop()(f)}};function En(l){for(var f=1;f<l.length;++f)if(l[f]!==null&&l[f].G===void 0)return!0;return!1}var qo=(l,f)=>{if(r[l].F===void 0){var p=r[l];r[l]=function(...d){if(!r[l].F.hasOwnProperty(d.length))throw new ee(`Function '${f}' called with an invalid number of arguments (${d.length}) - expects one of (${r[l].F})!`);return r[l].F[d.length].apply(this,d)},r[l].F=[],r[l].F[p.J]=p}},Do=(l,f,p)=>{if(r.hasOwnProperty(l)){if(p===void 0||r[l].F!==void 0&&r[l].F[p]!==void 0)throw new ee(`Cannot register public name '${l}' twice`);if(qo(l,l),r[l].F.hasOwnProperty(p))throw new ee(`Cannot register multiple overloads of a function with the same number of arguments (${p})!`);r[l].F[p]=f}else r[l]=f,r[l].J=p},Wo=(l,f)=>{for(var p=[],d=0;d<l;d++)p.push(F[f+4*d>>2]);return p},Tn=r.InternalError=class extends Error{constructor(l){super(l),this.name="InternalError"}},kn=[],Pn,Ho=(l,f)=>{l=ne(l);var p;if((p=kn[f])||(kn[f]=p=Pn.get(f)),typeof p!="function")throw new ee(`unknown function pointer with signature ${l}: ${f}`);return p};class zo extends Error{}for(var Sn=l=>{l=oa(l);var f=ne(l);return Re(l),f},jo=(l,f)=>{function p(T){m[T]||Be[T]||(pt[T]?pt[T].forEach(p):(d.push(T),m[T]=!0))}var d=[],m={};throw f.forEach(p),new zo(`${l}: `+d.map(Sn).join([", "]))},Qo=(l,f)=>{function p(k){if(k=f(k),k.length!==d.length)throw new Tn("Mismatched type converter count");for(var B=0;B<d.length;++B)ie(d[B],k[B])}var d=[];d.forEach(k=>pt[k]=l);var m=Array(l.length),T=[],R=0;l.forEach((k,B)=>{Be.hasOwnProperty(k)?m[B]=Be[k]:(T.push(k),Ue.hasOwnProperty(k)||(Ue[k]=[]),Ue[k].push(()=>{m[B]=Be[k],++R,R===T.length&&p(m)}))}),T.length===0&&p(m)},Go=l=>{l=l.trim();let f=l.indexOf("(");return f===-1?l:l.slice(0,f)},xn=typeof TextDecoder<"u"?new TextDecoder:void 0,Yo=(l=0,f=NaN)=>{var p=L,d=l+f;for(f=l;p[f]&&!(f>=d);)++f;if(16<f-l&&p.buffer&&xn)return xn.decode(p.subarray(l,f));for(d="";l<f;){var m=p[l++];if(m&128){var T=p[l++]&63;if((m&224)==192)d+=String.fromCharCode((m&31)<<6|T);else{var R=p[l++]&63;m=(m&240)==224?(m&15)<<12|T<<6|R:(m&7)<<18|T<<12|R<<6|p[l++]&63,65536>m?d+=String.fromCharCode(m):(m-=65536,d+=String.fromCharCode(55296|m>>10,56320|m&1023))}}else d+=String.fromCharCode(m)}return d},Bn=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Vo=(l,f)=>{for(var p=l>>1,d=p+f/2;!(p>=d)&&z[p];)++p;if(p<<=1,32<p-l&&Bn)return Bn.decode(L.subarray(l,p));for(p="",d=0;!(d>=f/2);++d){var m=G[l+2*d>>1];if(m==0)break;p+=String.fromCharCode(m)}return p},Jo=(l,f,p)=>{if(p??=2147483647,2>p)return 0;p-=2;var d=f;p=p<2*l.length?p/2:l.length;for(var m=0;m<p;++m)G[f>>1]=l.charCodeAt(m),f+=2;return G[f>>1]=0,f-d},Ko=l=>2*l.length,Zo=(l,f)=>{for(var p=0,d="";!(p>=f/4);){var m=U[l+4*p>>2];if(m==0)break;++p,65536<=m?(m-=65536,d+=String.fromCharCode(55296|m>>10,56320|m&1023)):d+=String.fromCharCode(m)}return d},Xo=(l,f,p)=>{if(p??=2147483647,4>p)return 0;var d=f;p=d+p-4;for(var m=0;m<l.length;++m){var T=l.charCodeAt(m);if(55296<=T&&57343>=T){var R=l.charCodeAt(++m);T=65536+((T&1023)<<10)|R&1023}if(U[f>>2]=T,f+=4,f+4>p)break}return U[f>>2]=0,f-d},ea=l=>{for(var f=0,p=0;p<l.length;++p){var d=l.charCodeAt(p);55296<=d&&57343>=d&&++p,f+=4}return f},Jt=0,Kt=[],ta=l=>{var f=Kt.length;return Kt.push(l),f},Rn=(l,f)=>{var p=Be[l];if(p===void 0)throw l=`${f} has unknown type ${Sn(l)}`,new ee(l);return p},ra=(l,f)=>{for(var p=Array(l),d=0;d<l;++d)p[d]=Rn(F[f+4*d>>2],`parameter ${d}`);return p},na=(l,f,p)=>{var d=[];return l=l.toWireType(d,p),d.length&&(F[f>>2]=Yt(d)),l},Ye={},An=l=>{N=l,dt||0<Jt||(r.onExit?.(l),O=!0),h(l,new zt(l))},ia=l=>{if(!O)try{if(l(),!(dt||0<Jt))try{N=l=N,An(l)}catch(f){f instanceof zt||f=="unwind"||h(1,f)}}catch(f){f instanceof zt||f=="unwind"||h(1,f)}},In=Array(256),gt=0;256>gt;++gt)In[gt]=String.fromCharCode(gt);_n=In,ce.push(0,1,void 0,1,null,1,!0,1,!1,1),r.count_emval_handles=()=>ce.length/2-5-jt.length,r.noExitRuntime&&(dt=r.noExitRuntime),r.printErr&&(E=r.printErr),r.wasmBinary&&(x=r.wasmBinary);var sa={u:(l,f,p)=>{var d=new Mo(l);throw F[d.I+16>>2]=0,F[d.I+4>>2]=f,F[d.I+8>>2]=p,yn=l,No++,yn},v:()=>dn(""),l:(l,f,p)=>{f=ne(f),ie(l,{name:f,fromWireType:d=>d,toWireType:function(d,m){if(typeof m!="bigint"&&typeof m!="number")throw m===null?m="null":(d=typeof m,m=d==="object"||d==="array"||d==="function"?m.toString():""+m),new TypeError(`Cannot convert "${m}" to ${this.name}`);return typeof m=="number"&&(m=BigInt(m)),m},H:8,readValueFromPointer:wn(f,p,f.indexOf("u")==-1),G:null})},o:(l,f,p,d)=>{f=ne(f),ie(l,{name:f,fromWireType:function(m){return!!m},toWireType:function(m,T){return T?p:d},H:8,readValueFromPointer:function(m){return this.fromWireType(L[m])},G:null})},m:l=>ie(l,bn),k:(l,f,p)=>{f=ne(f),ie(l,{name:f,fromWireType:d=>d,toWireType:(d,m)=>m,H:8,readValueFromPointer:Fo(f,p),G:null})},c:(l,f,p,d,m,T,R)=>{var k=Wo(f,p);l=ne(l),l=Go(l),m=Ho(d,m),Do(l,function(){jo(`Cannot call ${l} due to unbound types`,k)},f-1),Qo(k,B=>{var S=[B[0],null].concat(B.slice(1));B=l;var D=l,ae=m,q=S.length;if(2>q)throw new ee("argTypes array size mismatch! Must at least get return value and 'this' types!");var me=S[1]!==null&&!1,Ve=En(S),On=S[0].name!=="void";ae=[D,$o,ae,T,Cn,S[0],S[1]];for(var se=0;se<q-2;++se)ae.push(S[se+2]);if(!Ve)for(se=me?1:2;se<S.length;++se)S[se].G!==null&&ae.push(S[se].G);Ve=En(S),se=S.length-2;var K=[],Je=["fn"];for(me&&Je.push("thisWired"),q=0;q<se;++q)K.push(`arg${q}`),Je.push(`arg${q}Wired`);K=K.join(","),Je=Je.join(","),K=`return function (${K}) {
|
|
18
|
+
`,Ve&&(K+=`var destructors = [];
|
|
19
|
+
`);var Ln=Ve?"destructors":"null",Xt="humanName throwBindingError invoker fn runDestructors retType classParam".split(" ");for(me&&(K+=`var thisWired = classParam['toWireType'](${Ln}, this);
|
|
20
|
+
`),q=0;q<se;++q)K+=`var arg${q}Wired = argType${q}['toWireType'](${Ln}, arg${q});
|
|
21
|
+
`,Xt.push(`argType${q}`);if(K+=(On||R?"var rv = ":"")+`invoker(${Je});
|
|
22
|
+
`,Ve)K+=`runDestructors(destructors);
|
|
23
|
+
`;else for(q=me?1:2;q<S.length;++q)me=q===1?"thisWired":"arg"+(q-2)+"Wired",S[q].G!==null&&(K+=`${me}_dtor(${me});
|
|
24
|
+
`,Xt.push(`${me}_dtor`));On&&(K+=`var ret = retType['fromWireType'](rv);
|
|
25
25
|
return ret;
|
|
26
|
-
`);let[
|
|
27
|
-
`];if(S=new Function(...
|
|
28
|
-
`,T=0,
|
|
29
|
-
`,T+=f[S].H;return m+=` var rv = ${p===1?"new func":"func.call"}(${
|
|
30
|
-
`,d.L||(k.push("emval_returnValue"),B.push(
|
|
26
|
+
`);let[la,ua]=[Xt,K+`}
|
|
27
|
+
`];if(S=new Function(...la,ua)(...ae),D=Object.defineProperty(S,"name",{value:D}),S=f-1,!r.hasOwnProperty(B))throw new Tn("Replacing nonexistent public symbol");return r[B].F!==void 0&&S!==void 0?r[B].F[S]=D:(r[B]=D,r[B].J=S),[]})},b:(l,f,p,d,m)=>{if(f=ne(f),m===-1&&(m=4294967295),m=k=>k,d===0){var T=32-8*p;m=k=>k<<T>>>T}var R=f.includes("unsigned")?function(k,B){return B>>>0}:function(k,B){return B};ie(l,{name:f,fromWireType:m,toWireType:R,H:8,readValueFromPointer:wn(f,p,d!==0),G:null})},a:(l,f,p)=>{function d(T){return new m(v.buffer,F[T+4>>2],F[T>>2])}var m=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][f];p=ne(p),ie(l,{name:p,fromWireType:d,H:8,readValueFromPointer:d},{K:!0})},n:(l,f)=>{f=ne(f),ie(l,{name:f,fromWireType:function(p){for(var d=F[p>>2],m=p+4,T,R=m,k=0;k<=d;++k){var B=m+k;(k==d||L[B]==0)&&(R=R?Yo(R,B-R):"",T===void 0?T=R:(T+="\0",T+=R),R=B+1)}return Re(p),T},toWireType:function(p,d){d instanceof ArrayBuffer&&(d=new Uint8Array(d));var m,T=typeof d=="string";if(!(T||ArrayBuffer.isView(d)&&d.BYTES_PER_ELEMENT==1))throw new ee("Cannot pass non-string to std::string");var R;if(T)for(m=R=0;m<d.length;++m){var k=d.charCodeAt(m);127>=k?R++:2047>=k?R+=2:55296<=k&&57343>=k?(R+=4,++m):R+=3}else R=d.length;if(m=R,R=vn(4+m+1),k=R+4,F[R>>2]=m,T){if(T=k,k=m+1,m=L,0<k){k=T+k-1;for(var B=0;B<d.length;++B){var S=d.charCodeAt(B);if(55296<=S&&57343>=S){var D=d.charCodeAt(++B);S=65536+((S&1023)<<10)|D&1023}if(127>=S){if(T>=k)break;m[T++]=S}else{if(2047>=S){if(T+1>=k)break;m[T++]=192|S>>6}else{if(65535>=S){if(T+2>=k)break;m[T++]=224|S>>12}else{if(T+3>=k)break;m[T++]=240|S>>18,m[T++]=128|S>>12&63}m[T++]=128|S>>6&63}m[T++]=128|S&63}}m[T]=0}}else L.set(d,k);return p!==null&&p.push(Re,R),R},H:8,readValueFromPointer:Vt,G(p){Re(p)}})},e:(l,f,p)=>{if(p=ne(p),f===2)var d=Vo,m=Jo,T=Ko,R=k=>z[k>>1];else f===4&&(d=Zo,m=Xo,T=ea,R=k=>F[k>>2]);ie(l,{name:p,fromWireType:k=>{for(var B=F[k>>2],S,D=k+4,ae=0;ae<=B;++ae){var q=k+4+ae*f;(ae==B||R(q)==0)&&(D=d(D,q-D),S===void 0?S=D:(S+="\0",S+=D),D=q+f)}return Re(k),S},toWireType:(k,B)=>{if(typeof B!="string")throw new ee(`Cannot pass non-string to C++ string type ${p}`);var S=T(B),D=vn(4+S+f);return F[D>>2]=S/f,m(B,D+4,S+f),k!==null&&k.push(Re,D),D},H:8,readValueFromPointer:Vt,G(k){Re(k)}})},f:l=>{ie(l,bn)},p:(l,f)=>{f=ne(f),ie(l,{L:!0,name:f,H:0,fromWireType:()=>{},toWireType:()=>{}})},s:()=>{dt=!1,Jt=0},i:(l,f,p,d)=>(l=Kt[l],f=Gt(f),l(null,f,p,d)),d:Qt,h:(l,f,p)=>{f=ra(l,f);var d=f.shift();l--;var m=`return function (obj, func, destructorsRef, args) {
|
|
28
|
+
`,T=0,R=[];p===0&&R.push("obj");for(var k=["retType"],B=[d],S=0;S<l;++S)R.push(`arg${S}`),k.push(`argType${S}`),B.push(f[S]),m+=` var arg${S} = argType${S}.readValueFromPointer(args${T?"+"+T:""});
|
|
29
|
+
`,T+=f[S].H;return m+=` var rv = ${p===1?"new func":"func.call"}(${R.join(", ")});
|
|
30
|
+
`,d.L||(k.push("emval_returnValue"),B.push(na),m+=` return emval_returnValue(retType, destructorsRef, rv);
|
|
31
31
|
`),l=new Function(...k,m+`};
|
|
32
|
-
`)(...B),p=`methodCaller<(${f.map(q=>q.name).join(", ")}) => ${d.name}>`,ea(Object.defineProperty(l,"name",{value:p}))},q:l=>{9<l&&(ce[l+1]+=1)},g:l=>{var f=Qt(l);Cn(f),jt(l)},j:(l,f)=>(l=An(l,"_emval_take_value"),l=l.readValueFromPointer(f),Gt(l)),t:(l,f)=>{if(Ye[l]&&(clearTimeout(Ye[l].id),delete Ye[l]),!f)return 0;var p=setTimeout(()=>{delete Ye[l],na(()=>oa(l,performance.now()))},f);return Ye[l]={id:p,M:f},0},w:l=>{var f=L.length;if(l>>>=0,2147483648<l)return!1;for(var p=1;4>=p;p*=2){var d=f*(1+.2/p);d=Math.min(d,l+100663296);e:{d=(Math.min(2147483648,65536*Math.ceil(Math.max(l,d)/65536))-I.buffer.byteLength+65535)/65536|0;try{I.grow(d),hn();var m=1;break e}catch{}m=void 0}if(m)return!0}return!1},r:Rn},he=await(async function(){function l(d){return he=d.exports,I=he.x,hn(),Pn=he.D,xe--,r.monitorRunDependencies?.(xe),xe==0&&Ge&&(d=Ge,Ge=null,d()),he}xe++,r.monitorRunDependencies?.(xe);var f={a:ia};if(r.instantiateWasm)return new Promise(d=>{r.instantiateWasm(f,(m,T)=>{d(l(m,T))})});Wt??=r.locateFile?r.locateFile?r.locateFile("silk.wasm",_):_+"silk.wasm":new URL("silk.wasm",en).href;try{var p=await vo(f);return l(p.instance)}catch(d){return i(d),Promise.reject(d)}})(),sa=he.z,vn=he.A,Ae=he.B,oa=he.C;function Jt(){function l(){if(r.calledRun=!0,!O){if(he.y(),n(r),r.onRuntimeInitialized?.(),r.postRun)for(typeof r.postRun=="function"&&(r.postRun=[r.postRun]);r.postRun.length;){var f=r.postRun.shift();gn.push(f)}pn(gn)}}if(0<xe)Ge=Jt;else{if(r.preRun)for(typeof r.preRun=="function"&&(r.preRun=[r.preRun]);r.preRun.length;)Oo();pn(mn),0<xe?Ge=Jt:r.setStatus?(r.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>r.setStatus(""),1),l()},1)):l()}}if(r.preInit)for(typeof r.preInit=="function"&&(r.preInit=[r.preInit]);0<r.preInit.length;)r.preInit.shift()();return Jt(),e=s,e},ho=uf;function po(t){try{let e=nn(t),r=sn(e.get("fmt")),n=e.get("data");return go(r),mo(n,r),!0}catch{return!1}}var ff=["int","float"],cf=[0,0,0,1];function hf(t){let e=nn(t),r=sn(e.get("fmt")),n=e.get("data"),i=go(r),s=cf[i],o=ff[s]+r.bitsPerSample;return mo(n,r),{channelData:pf(n,r,i),sampleRate:r.sampleRate,numberOfChannels:r.numberOfChannels,audioEncoding:s,bitsPerSample:r.bitsPerSample,wavFileTypeName:o}}function nn(t){let e;t instanceof ArrayBuffer?e=new DataView(t):e=new DataView(t.buffer,t.byteOffset,t.byteLength);let r=e.byteLength;if(r<20)throw new Error("WAV file is too short.");if(tn(e,0,4)!="RIFF")throw new Error("Not a valid WAV file (no RIFF header).");let n=e.getUint32(4,!0);if(8+n!=r)throw new Error(`Main chunk length of WAV file (${8+n}) does not match file size (${r}).`);if(tn(e,8,4)!="WAVE")throw new Error("RIFF file is not a WAV file.");let i=new Map,s=12;for(;s<r;){if(s+8>r)throw new Error(`Incomplete chunk prefix in WAV file at offset ${s}.`);let o=tn(e,s,4).trim(),a=e.getUint32(s+4,!0);if(s+8+a>r)throw new Error(`Incomplete chunk data in WAV file at offset ${s}.`);let u=new DataView(e.buffer,e.byteOffset+s+8,a);i.set(o,u);let c=a%2;s+=8+a+c}return i}function tn(t,e,r){let n=new Uint8Array(t.buffer,t.byteOffset+e,r);return String.fromCharCode.apply(null,n)}function df(t,e){let r=t.getInt8(e+2)*65536,n=t.getUint16(e,!0);return r+n}function sn(t){if(!t)throw new Error("No format chunk found in WAV file.");if(t.byteLength<16)throw new Error("Format chunk of WAV file is too short.");let e={};return e.formatCode=t.getUint16(0,!0),e.numberOfChannels=t.getUint16(2,!0),e.sampleRate=t.getUint32(4,!0),e.bytesPerSec=t.getUint32(8,!0),e.bytesPerFrame=t.getUint16(12,!0),e.bitsPerSample=t.getUint16(14,!0),e}function go(t){if(t.numberOfChannels<1||t.numberOfChannels>999)throw new Error("Invalid number of channels in WAV file.");let e=Math.ceil(t.bitsPerSample/8),r=t.numberOfChannels*e;if(t.formatCode==1&&t.bitsPerSample>=1&&t.bitsPerSample<=8&&t.bytesPerFrame==r)return 0;if(t.formatCode==1&&t.bitsPerSample>=9&&t.bitsPerSample<=16&&t.bytesPerFrame==r)return 1;if(t.formatCode==1&&t.bitsPerSample>=17&&t.bitsPerSample<=24&&t.bytesPerFrame==r)return 2;if(t.formatCode==3&&t.bitsPerSample==32&&t.bytesPerFrame==r)return 3;throw new Error(`Unsupported WAV file type, formatCode=${t.formatCode}, bitsPerSample=${t.bitsPerSample}, bytesPerFrame=${t.bytesPerFrame}, numberOfChannels=${t.numberOfChannels}.`)}function pf(t,e,r){switch(r){case 0:return mf(t,e);case 1:return gf(t,e);case 2:return yf(t,e);case 3:return _f(t,e);default:throw new Error("No decoder.")}}function gf(t,e){let r=Ot(t.byteLength,e),n=e.numberOfChannels,i=r[0].length,s=0;for(let o=0;o<i;o++)for(let a=0;a<n;a++){let u=t.getInt16(s,!0)/32768;r[a][o]=u,s+=2}return r}function mf(t,e){let r=Ot(t.byteLength,e),n=e.numberOfChannels,i=r[0].length,s=0;for(let o=0;o<i;o++)for(let a=0;a<n;a++){let u=(t.getUint8(s)-128)/128;r[a][o]=u,s+=1}return r}function yf(t,e){let r=Ot(t.byteLength,e),n=e.numberOfChannels,i=r[0].length,s=0;for(let o=0;o<i;o++)for(let a=0;a<n;a++){let u=df(t,s)/8388608;r[a][o]=u,s+=3}return r}function _f(t,e){let r=Ot(t.byteLength,e),n=e.numberOfChannels,i=r[0].length,s=0;for(let o=0;o<i;o++)for(let a=0;a<n;a++){let u=t.getFloat32(s,!0);r[a][o]=u,s+=4}return r}function Ot(t,e){let r=Math.floor(t/e.bytesPerFrame),n=new Array(e.numberOfChannels);for(let i=0;i<e.numberOfChannels;i++)n[i]=new Float32Array(r);return n}function mo(t,e){if(!t)throw new Error("No data chunk found in WAV file.");if(t.byteLength%e.bytesPerFrame!=0)throw new Error("WAV file data chunk length is not a multiple of frame size.")}function wf(t){let e=nn(t),r=bf(e),n=sn(e.get("fmt"));return{chunkInfo:r,fmt:n}}function bf(t){let e=[];for(let r of t){let n={};n.chunkId=r[0],n.dataOffset=r[1].byteOffset,n.dataLength=r[1].byteLength,e.push(n)}return e.sort((r,n)=>r.dataOffset-n.dataOffset),e}function Cf(t){let{length:e}=t;if(e===1)return t[0];let r=new Float32Array(t[0].length);for(let n=0;n<r.length;n++){let i=0;for(let s=0;s<e;s++)i+=t[s][n];r[n]=i/e}return r}function Ef(t){let e=new Int16Array(t.length);for(let r=0;r<t.length;r++){let n=~~(t[r]*32768);e[r]=n>32767?32767:n}return e.buffer}function Tf(t,e=0,r=t.byteLength){return new TextDecoder().decode(t.slice(e,r))}function Lt(t){return ArrayBuffer.isView(t)?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength):t}async function kf(t,e){let r=await ho(),n=Lt(t);if(!n?.byteLength)throw new Error("input data length is 0");if(po(t)){let{channelData:o,sampleRate:a}=hf(t);e||=a,n=Ef(Cf(o))}let i=new Uint8Array,s=r.silk_encode(n,e,o=>{i=o.slice()});if(s===0)throw new Error("silk encoding failure");return{data:i,duration:s}}async function Pf(t,e){let r=await ho(),n=Lt(t);if(!n?.byteLength)throw new Error("input data length is 0");let i=new Uint8Array,s=r.silk_decode(n,e,o=>{o.length>0&&(i=o.slice())});if(s===0)throw new Error("silk decoding failure");return{data:i,duration:s}}function Sf(t,e=20){let r=Lt(t),n=new DataView(r),i=n.byteLength,s=n.getUint8(0)===2?10:9,o=0;for(;s<i;){let a=n.getUint16(s,!0);o+=1,s+=a+2}return o*e}function xf(t){return po(t)}function Bf(t){return wf(t)}function Af(t){let e=Lt(t);return e.byteLength<7?!1:Tf(e,0,7).includes("#!SILK")}});import{writeFileSync as tc,readFileSync as rc,unlinkSync as nc,existsSync as ic}from"node:fs";import{join as sc}from"node:path";import{pathToFileURL as oc}from"node:url";import{homedir as ga}from"node:os";import{resolve as Nn}from"node:path";function er(t=process.env){let e=t.WECHAT_STATE_DIR??"~/.aladuo/channel-wechat";return e.startsWith("~")?Nn(ga(),e.slice(2)):Nn(e)}function Un(){let t=process.env.WECHAT_DM_POLICY??"open";if(t!=="open"&&t!=="allowlist")throw new Error(`WECHAT_DM_POLICY must be 'open' or 'allowlist', got: ${t}`);let r=(process.env.WECHAT_ALLOW_FROM??"").split(",").map(s=>s.trim()).filter(Boolean);if(t==="allowlist"&&r.length===0)throw new Error("WECHAT_DM_POLICY=allowlist requires WECHAT_ALLOW_FROM to be set");let n=er(),i=process.env.WECHAT_LOG_LEVEL??"info";if(!["error","warn","info","debug"].includes(i))throw new Error(`WECHAT_LOG_LEVEL must be one of error|warn|info|debug, got: ${i}`);return{daemonUrl:process.env.ALADUO_DAEMON_URL??"http://127.0.0.1:20233",apiBase:process.env.WECHAT_API_BASE??"https://ilinkai.weixin.qq.com",cdnBase:process.env.WECHAT_CDN_BASE??"https://novac2c.cdn.weixin.qq.com/c2c",dmPolicy:t,allowFrom:r,stateDir:n,logLevel:i}}import{mkdir as qu,readFile as io,writeFile as so,chmod as Wu,unlink as Hu}from"node:fs/promises";import{existsSync as zu}from"node:fs";import{resolve as oo}from"node:path";import{randomBytes as Fn}from"node:crypto";var ma=4e3,Z=class extends Error{constructor(r,n){super(`WechatApiError[${r}]: ${n}`);this.errcode=r;this.name="WechatApiError"}};function ya(){let t=Fn(4).readUInt32BE(0);return Buffer.from(String(t),"utf-8").toString("base64")}function Je(t,e){let r={"Content-Type":"application/json","Content-Length":String(Buffer.byteLength(e,"utf-8")),AuthorizationType:"ilink_bot_token","X-WECHAT-UIN":ya()};return t&&(r.Authorization=`Bearer ${t}`),r}async function Dn(t,e=fetch){let n=`${t.endsWith("/")?t:`${t}/`}ilink/bot/get_bot_qrcode?bot_type=3`,i=await e(n,{method:"GET"});if(!i.ok)throw new Error(`HTTP ${i.status} from getQrCode`);let s=await i.json();return{qrcode:s.qrcode,qrcodeImgUrl:s.qrcode_img_content}}async function qn(t,e,r=fetch){let i=`${t.endsWith("/")?t:`${t}/`}ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(e)}`,s;try{s=await r(i,{method:"GET",headers:{"iLink-App-ClientVersion":"1"},signal:AbortSignal.timeout(35e3)})}catch(a){if(a instanceof Error&&a.name==="AbortError")return{status:"wait"};throw a}if(!s.ok)throw new Error(`HTTP ${s.status} from pollQrStatus`);let o=await s.json();return{status:o.status,token:o.bot_token,botId:o.ilink_bot_id,userId:o.ilink_user_id,resolvedBaseUrl:o.baseurl,redirectHost:o.redirect_host}}async function Wn(t,e,r,n=fetch){let i=t.endsWith("/")?t:`${t}/`,s=JSON.stringify({get_updates_buf:r,base_info:{channel_version:"claude-code-1.0"}}),o;try{let c=await n(`${i}ilink/bot/getupdates`,{method:"POST",headers:Je(e,s),body:s,signal:AbortSignal.timeout(4e4)});if(o=await c.text(),!c.ok)throw new Error(`getUpdates HTTP ${c.status}: ${o}`)}catch(c){if(c instanceof Error&&c.name==="AbortError")return{msgs:[],syncBuf:r};throw c}let a=JSON.parse(o),u=a.ret??a.errcode??0;if(u!==0)throw new Z(u,a.errmsg??"unknown");return{msgs:a.msgs??[],syncBuf:a.get_updates_buf??r}}function $n(){return`cc-wx-${Date.now()}-${Fn(4).toString("hex")}`}async function le(t,e,r,n,i,s=fetch,o){let a=t.endsWith("/")?t:`${t}/`;if(o){let u;if("kind"in o&&o.kind==="file"){let g=o.item;u=[{type:4,file_item:{media:{encrypt_query_param:g.encryptQueryParam,aes_key:g.aesKeyBase64,encrypt_type:1},file_name:g.fileName,md5:"",len:String(g.fileSize)}}]}else if("kind"in o&&o.kind==="voice"){let g=o.item;u=[{type:3,voice_item:{media:{encrypt_query_param:g.encryptQueryParam,aes_key:g.aesKeyBase64,encrypt_type:1},encode_type:g.encodeType??6,sample_rate:g.sampleRate??16e3,bits_per_sample:g.bitsPerSample??16,playtime:g.playtimeMs??0}}]}else if("kind"in o&&o.kind==="video"){let g=o.item;u=[{type:5,video_item:{media:{encrypt_query_param:g.encryptQueryParam,aes_key:g.aesKeyBase64,encrypt_type:1},video_size:g.videoSize}}]}else{let g=o;u=[{type:2,image_item:{media:{encrypt_query_param:g.encryptQueryParam,aes_key:g.aesKeyBase64,encrypt_type:1},mid_size:g.midSize}}]}let c={from_user_id:"",to_user_id:r,client_id:$n(),message_type:2,message_state:2,item_list:u};i&&(c.context_token=i);let h=JSON.stringify({msg:c,base_info:{channel_version:"claude-code-1.0"}}),y=await s(`${a}ilink/bot/sendmessage`,{method:"POST",headers:Je(e,h),body:h});if(!y.ok)throw new Error(`sendMessage HTTP ${y.status}`);let _=await y.json(),b=_.ret??_.errcode??0;if(b!==0)throw new Z(b,_.errmsg??"unknown");n&&await le(t,e,r,n,i,s);return}for(let u of _a(n)){let c={from_user_id:"",to_user_id:r,client_id:$n(),message_type:2,message_state:2,item_list:[{type:1,text_item:{text:u}}]};i&&(c.context_token=i);let h=JSON.stringify({msg:c,base_info:{channel_version:"claude-code-1.0"}}),y=await s(`${a}ilink/bot/sendmessage`,{method:"POST",headers:Je(e,h),body:h});if(!y.ok)throw new Error(`sendMessage HTTP ${y.status}`);let _=await y.json(),b=_.ret??_.errcode??0;if(b!==0)throw new Z(b,_.errmsg??"unknown")}}function _a(t,e=ma){if(t.length<=e)return[t];let r=[],n=0;for(;n<t.length;)r.push(t.slice(n,n+e)),n+=e;return r}async function Hn(t,e,r,n,i=fetch){let s=t.endsWith("/")?t:`${t}/`,o=JSON.stringify({ilink_user_id:r,context_token:n,base_info:{}}),a=await i(`${s}ilink/bot/getconfig`,{method:"POST",headers:Je(e,o),body:o});if(!a.ok)throw new Error(`getConfig HTTP ${a.status}`);return await a.json()}async function zn(t,e,r,n,i,s=fetch){let o=t.endsWith("/")?t:`${t}/`,a=JSON.stringify({ilink_user_id:r,typing_ticket:n,status:i,base_info:{}});try{await s(`${o}ilink/bot/sendtyping`,{method:"POST",headers:Je(e,a),body:a})}catch{}}import{mkdir as Lu,readFile as Mu,unlink as Xs,writeFile as Nu}from"node:fs/promises";import{existsSync as Uu}from"node:fs";import{resolve as $u}from"node:path";var Fu="qrcode.png",Du="qrcode.txt";function eo(t,e){return $u(t,e)}function Qr(t){return eo(t,Fu)}function Gr(t){return eo(t,Du)}async function to(t,e){Uu(t)||await Lu(t,{recursive:!0}),await Nu(Gr(t),e,"utf8")}async function ro(t){await Promise.all([Xs(Qr(t)).catch(()=>{}),Xs(Gr(t)).catch(()=>{})])}async function no(t,e=r=>process.stdout.write(r)){let r=(await Mu(Gr(t),"utf8")).trim();if(!r)throw new Error(`No pending QR code found in ${t}`);let i=await(await Promise.resolve().then(()=>Xt(jr(),1))).default.toString(r,{type:"terminal",small:!0});e(i.endsWith(`
|
|
33
|
-
`)?
|
|
34
|
-
`)}var
|
|
32
|
+
`)(...B),p=`methodCaller<(${f.map(D=>D.name).join(", ")}) => ${d.name}>`,ta(Object.defineProperty(l,"name",{value:p}))},q:l=>{9<l&&(ce[l+1]+=1)},g:l=>{var f=Gt(l);Cn(f),Qt(l)},j:(l,f)=>(l=Rn(l,"_emval_take_value"),l=l.readValueFromPointer(f),Yt(l)),t:(l,f)=>{if(Ye[l]&&(clearTimeout(Ye[l].id),delete Ye[l]),!f)return 0;var p=setTimeout(()=>{delete Ye[l],ia(()=>aa(l,performance.now()))},f);return Ye[l]={id:p,M:f},0},w:l=>{var f=L.length;if(l>>>=0,2147483648<l)return!1;for(var p=1;4>=p;p*=2){var d=f*(1+.2/p);d=Math.min(d,l+100663296);e:{d=(Math.min(2147483648,65536*Math.ceil(Math.max(l,d)/65536))-I.buffer.byteLength+65535)/65536|0;try{I.grow(d),hn();var m=1;break e}catch{}m=void 0}if(m)return!0}return!1},r:An},he=await(async function(){function l(d){return he=d.exports,I=he.x,hn(),Pn=he.D,xe--,r.monitorRunDependencies?.(xe),xe==0&&Ge&&(d=Ge,Ge=null,d()),he}xe++,r.monitorRunDependencies?.(xe);var f={a:sa};if(r.instantiateWasm)return new Promise(d=>{r.instantiateWasm(f,(m,T)=>{d(l(m,T))})});Ht??=r.locateFile?r.locateFile?r.locateFile("silk.wasm",_):_+"silk.wasm":new URL("silk.wasm",en).href;try{var p=await Oo(f);return l(p.instance)}catch(d){return i(d),Promise.reject(d)}})(),oa=he.z,vn=he.A,Re=he.B,aa=he.C;function Zt(){function l(){if(r.calledRun=!0,!O){if(he.y(),n(r),r.onRuntimeInitialized?.(),r.postRun)for(typeof r.postRun=="function"&&(r.postRun=[r.postRun]);r.postRun.length;){var f=r.postRun.shift();gn.push(f)}pn(gn)}}if(0<xe)Ge=Zt;else{if(r.preRun)for(typeof r.preRun=="function"&&(r.preRun=[r.preRun]);r.preRun.length;)Lo();pn(mn),0<xe?Ge=Zt:r.setStatus?(r.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>r.setStatus(""),1),l()},1)):l()}}if(r.preInit)for(typeof r.preInit=="function"&&(r.preInit=[r.preInit]);0<r.preInit.length;)r.preInit.shift()();return Zt(),e=s,e},po=uf;function go(t){try{let e=nn(t),r=sn(e.get("fmt")),n=e.get("data");return mo(r),yo(n,r),!0}catch{return!1}}var ff=["int","float"],cf=[0,0,0,1];function hf(t){let e=nn(t),r=sn(e.get("fmt")),n=e.get("data"),i=mo(r),s=cf[i],o=ff[s]+r.bitsPerSample;return yo(n,r),{channelData:pf(n,r,i),sampleRate:r.sampleRate,numberOfChannels:r.numberOfChannels,audioEncoding:s,bitsPerSample:r.bitsPerSample,wavFileTypeName:o}}function nn(t){let e;t instanceof ArrayBuffer?e=new DataView(t):e=new DataView(t.buffer,t.byteOffset,t.byteLength);let r=e.byteLength;if(r<20)throw new Error("WAV file is too short.");if(tn(e,0,4)!="RIFF")throw new Error("Not a valid WAV file (no RIFF header).");let n=e.getUint32(4,!0);if(8+n!=r)throw new Error(`Main chunk length of WAV file (${8+n}) does not match file size (${r}).`);if(tn(e,8,4)!="WAVE")throw new Error("RIFF file is not a WAV file.");let i=new Map,s=12;for(;s<r;){if(s+8>r)throw new Error(`Incomplete chunk prefix in WAV file at offset ${s}.`);let o=tn(e,s,4).trim(),a=e.getUint32(s+4,!0);if(s+8+a>r)throw new Error(`Incomplete chunk data in WAV file at offset ${s}.`);let u=new DataView(e.buffer,e.byteOffset+s+8,a);i.set(o,u);let c=a%2;s+=8+a+c}return i}function tn(t,e,r){let n=new Uint8Array(t.buffer,t.byteOffset+e,r);return String.fromCharCode.apply(null,n)}function df(t,e){let r=t.getInt8(e+2)*65536,n=t.getUint16(e,!0);return r+n}function sn(t){if(!t)throw new Error("No format chunk found in WAV file.");if(t.byteLength<16)throw new Error("Format chunk of WAV file is too short.");let e={};return e.formatCode=t.getUint16(0,!0),e.numberOfChannels=t.getUint16(2,!0),e.sampleRate=t.getUint32(4,!0),e.bytesPerSec=t.getUint32(8,!0),e.bytesPerFrame=t.getUint16(12,!0),e.bitsPerSample=t.getUint16(14,!0),e}function mo(t){if(t.numberOfChannels<1||t.numberOfChannels>999)throw new Error("Invalid number of channels in WAV file.");let e=Math.ceil(t.bitsPerSample/8),r=t.numberOfChannels*e;if(t.formatCode==1&&t.bitsPerSample>=1&&t.bitsPerSample<=8&&t.bytesPerFrame==r)return 0;if(t.formatCode==1&&t.bitsPerSample>=9&&t.bitsPerSample<=16&&t.bytesPerFrame==r)return 1;if(t.formatCode==1&&t.bitsPerSample>=17&&t.bitsPerSample<=24&&t.bytesPerFrame==r)return 2;if(t.formatCode==3&&t.bitsPerSample==32&&t.bytesPerFrame==r)return 3;throw new Error(`Unsupported WAV file type, formatCode=${t.formatCode}, bitsPerSample=${t.bitsPerSample}, bytesPerFrame=${t.bytesPerFrame}, numberOfChannels=${t.numberOfChannels}.`)}function pf(t,e,r){switch(r){case 0:return mf(t,e);case 1:return gf(t,e);case 2:return yf(t,e);case 3:return _f(t,e);default:throw new Error("No decoder.")}}function gf(t,e){let r=Lt(t.byteLength,e),n=e.numberOfChannels,i=r[0].length,s=0;for(let o=0;o<i;o++)for(let a=0;a<n;a++){let u=t.getInt16(s,!0)/32768;r[a][o]=u,s+=2}return r}function mf(t,e){let r=Lt(t.byteLength,e),n=e.numberOfChannels,i=r[0].length,s=0;for(let o=0;o<i;o++)for(let a=0;a<n;a++){let u=(t.getUint8(s)-128)/128;r[a][o]=u,s+=1}return r}function yf(t,e){let r=Lt(t.byteLength,e),n=e.numberOfChannels,i=r[0].length,s=0;for(let o=0;o<i;o++)for(let a=0;a<n;a++){let u=df(t,s)/8388608;r[a][o]=u,s+=3}return r}function _f(t,e){let r=Lt(t.byteLength,e),n=e.numberOfChannels,i=r[0].length,s=0;for(let o=0;o<i;o++)for(let a=0;a<n;a++){let u=t.getFloat32(s,!0);r[a][o]=u,s+=4}return r}function Lt(t,e){let r=Math.floor(t/e.bytesPerFrame),n=new Array(e.numberOfChannels);for(let i=0;i<e.numberOfChannels;i++)n[i]=new Float32Array(r);return n}function yo(t,e){if(!t)throw new Error("No data chunk found in WAV file.");if(t.byteLength%e.bytesPerFrame!=0)throw new Error("WAV file data chunk length is not a multiple of frame size.")}function wf(t){let e=nn(t),r=bf(e),n=sn(e.get("fmt"));return{chunkInfo:r,fmt:n}}function bf(t){let e=[];for(let r of t){let n={};n.chunkId=r[0],n.dataOffset=r[1].byteOffset,n.dataLength=r[1].byteLength,e.push(n)}return e.sort((r,n)=>r.dataOffset-n.dataOffset),e}function Cf(t){let{length:e}=t;if(e===1)return t[0];let r=new Float32Array(t[0].length);for(let n=0;n<r.length;n++){let i=0;for(let s=0;s<e;s++)i+=t[s][n];r[n]=i/e}return r}function Ef(t){let e=new Int16Array(t.length);for(let r=0;r<t.length;r++){let n=~~(t[r]*32768);e[r]=n>32767?32767:n}return e.buffer}function Tf(t,e=0,r=t.byteLength){return new TextDecoder().decode(t.slice(e,r))}function Mt(t){return ArrayBuffer.isView(t)?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength):t}async function kf(t,e){let r=await po(),n=Mt(t);if(!n?.byteLength)throw new Error("input data length is 0");if(go(t)){let{channelData:o,sampleRate:a}=hf(t);e||=a,n=Ef(Cf(o))}let i=new Uint8Array,s=r.silk_encode(n,e,o=>{i=o.slice()});if(s===0)throw new Error("silk encoding failure");return{data:i,duration:s}}async function Pf(t,e){let r=await po(),n=Mt(t);if(!n?.byteLength)throw new Error("input data length is 0");let i=new Uint8Array,s=r.silk_decode(n,e,o=>{o.length>0&&(i=o.slice())});if(s===0)throw new Error("silk decoding failure");return{data:i,duration:s}}function Sf(t,e=20){let r=Mt(t),n=new DataView(r),i=n.byteLength,s=n.getUint8(0)===2?10:9,o=0;for(;s<i;){let a=n.getUint16(s,!0);o+=1,s+=a+2}return o*e}function xf(t){return go(t)}function Bf(t){return wf(t)}function Rf(t){let e=Mt(t);return e.byteLength<7?!1:Tf(e,0,7).includes("#!SILK")}});import{writeFileSync as tc,readFileSync as rc,unlinkSync as nc,existsSync as ic}from"node:fs";import{join as sc}from"node:path";import{pathToFileURL as oc}from"node:url";import{homedir as ma}from"node:os";import{resolve as Nn}from"node:path";function tr(t=process.env){let e=t.WECHAT_STATE_DIR??"~/.aladuo/channel-wechat";return e.startsWith("~")?Nn(ma(),e.slice(2)):Nn(e)}function $n(){let t=process.env.WECHAT_DM_POLICY??"open";if(t!=="open"&&t!=="allowlist")throw new Error(`WECHAT_DM_POLICY must be 'open' or 'allowlist', got: ${t}`);let r=(process.env.WECHAT_ALLOW_FROM??"").split(",").map(s=>s.trim()).filter(Boolean);if(t==="allowlist"&&r.length===0)throw new Error("WECHAT_DM_POLICY=allowlist requires WECHAT_ALLOW_FROM to be set");let n=tr(),i=process.env.WECHAT_LOG_LEVEL??"info";if(!["error","warn","info","debug"].includes(i))throw new Error(`WECHAT_LOG_LEVEL must be one of error|warn|info|debug, got: ${i}`);return{daemonUrl:process.env.ALADUO_DAEMON_URL??"http://127.0.0.1:20233",apiBase:process.env.WECHAT_API_BASE??"https://ilinkai.weixin.qq.com",cdnBase:process.env.WECHAT_CDN_BASE??"https://novac2c.cdn.weixin.qq.com/c2c",dmPolicy:t,allowFrom:r,stateDir:n,logLevel:i}}import{mkdir as Du,readFile as so,writeFile as oo,chmod as Wu,unlink as Hu}from"node:fs/promises";import{existsSync as zu}from"node:fs";import{resolve as ao}from"node:path";import{randomBytes as Fn}from"node:crypto";var ya=4e3,Z=class extends Error{constructor(r,n){super(`WechatApiError[${r}]: ${n}`);this.errcode=r;this.name="WechatApiError"}};function _a(){let t=Fn(4).readUInt32BE(0);return Buffer.from(String(t),"utf-8").toString("base64")}function Ke(t,e){let r={"Content-Type":"application/json","Content-Length":String(Buffer.byteLength(e,"utf-8")),AuthorizationType:"ilink_bot_token","X-WECHAT-UIN":_a()};return t&&(r.Authorization=`Bearer ${t}`),r}async function qn(t,e=fetch){let n=`${t.endsWith("/")?t:`${t}/`}ilink/bot/get_bot_qrcode?bot_type=3`,i=await e(n,{method:"GET"});if(!i.ok)throw new Error(`HTTP ${i.status} from getQrCode`);let s=await i.json();return{qrcode:s.qrcode,qrcodeImgUrl:s.qrcode_img_content}}async function Dn(t,e,r=fetch){let i=`${t.endsWith("/")?t:`${t}/`}ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(e)}`,s;try{s=await r(i,{method:"GET",headers:{"iLink-App-ClientVersion":"1"},signal:AbortSignal.timeout(35e3)})}catch(a){if(a instanceof Error&&a.name==="AbortError")return{status:"wait"};throw a}if(!s.ok)throw new Error(`HTTP ${s.status} from pollQrStatus`);let o=await s.json();return{status:o.status,token:o.bot_token,botId:o.ilink_bot_id,userId:o.ilink_user_id,resolvedBaseUrl:o.baseurl,redirectHost:o.redirect_host}}async function Wn(t,e,r,n=fetch){let i=t.endsWith("/")?t:`${t}/`,s=JSON.stringify({get_updates_buf:r,base_info:{channel_version:"claude-code-1.0"}}),o;try{let c=await n(`${i}ilink/bot/getupdates`,{method:"POST",headers:Ke(e,s),body:s,signal:AbortSignal.timeout(4e4)});if(o=await c.text(),!c.ok)throw new Error(`getUpdates HTTP ${c.status}: ${o}`)}catch(c){if(c instanceof Error&&c.name==="AbortError")return{msgs:[],syncBuf:r};throw c}let a=JSON.parse(o),u=a.ret??a.errcode??0;if(u!==0)throw new Z(u,a.errmsg??"unknown");return{msgs:a.msgs??[],syncBuf:a.get_updates_buf??r}}function Un(){return`cc-wx-${Date.now()}-${Fn(4).toString("hex")}`}async function le(t,e,r,n,i,s=fetch,o){let a=t.endsWith("/")?t:`${t}/`;if(o){let u;if("kind"in o&&o.kind==="file"){let g=o.item;u=[{type:4,file_item:{media:{encrypt_query_param:g.encryptQueryParam,aes_key:g.aesKeyBase64,encrypt_type:1},file_name:g.fileName,md5:"",len:String(g.fileSize)}}]}else if("kind"in o&&o.kind==="voice"){let g=o.item;u=[{type:3,voice_item:{media:{encrypt_query_param:g.encryptQueryParam,aes_key:g.aesKeyBase64,encrypt_type:1},encode_type:g.encodeType??6,sample_rate:g.sampleRate??16e3,bits_per_sample:g.bitsPerSample??16,playtime:g.playtimeMs??0}}]}else if("kind"in o&&o.kind==="video"){let g=o.item;u=[{type:5,video_item:{media:{encrypt_query_param:g.encryptQueryParam,aes_key:g.aesKeyBase64,encrypt_type:1},video_size:g.videoSize}}]}else{let g=o;u=[{type:2,image_item:{media:{encrypt_query_param:g.encryptQueryParam,aes_key:g.aesKeyBase64,encrypt_type:1},mid_size:g.midSize}}]}let c={from_user_id:"",to_user_id:r,client_id:Un(),message_type:2,message_state:2,item_list:u};i&&(c.context_token=i);let h=JSON.stringify({msg:c,base_info:{channel_version:"claude-code-1.0"}}),y=await s(`${a}ilink/bot/sendmessage`,{method:"POST",headers:Ke(e,h),body:h});if(!y.ok)throw new Error(`sendMessage HTTP ${y.status}`);let _=await y.json(),b=_.ret??_.errcode??0;if(b!==0)throw new Z(b,_.errmsg??"unknown");n&&await le(t,e,r,n,i,s);return}for(let u of wa(n)){let c={from_user_id:"",to_user_id:r,client_id:Un(),message_type:2,message_state:2,item_list:[{type:1,text_item:{text:u}}]};i&&(c.context_token=i);let h=JSON.stringify({msg:c,base_info:{channel_version:"claude-code-1.0"}}),y=await s(`${a}ilink/bot/sendmessage`,{method:"POST",headers:Ke(e,h),body:h});if(!y.ok)throw new Error(`sendMessage HTTP ${y.status}`);let _=await y.json(),b=_.ret??_.errcode??0;if(b!==0)throw new Z(b,_.errmsg??"unknown")}}function wa(t,e=ya){if(t.length<=e)return[t];let r=[],n=0;for(;n<t.length;)r.push(t.slice(n,n+e)),n+=e;return r}async function Hn(t,e,r,n,i=fetch){let s=t.endsWith("/")?t:`${t}/`,o=JSON.stringify({ilink_user_id:r,context_token:n,base_info:{}}),a=await i(`${s}ilink/bot/getconfig`,{method:"POST",headers:Ke(e,o),body:o});if(!a.ok)throw new Error(`getConfig HTTP ${a.status}`);return await a.json()}async function zn(t,e,r,n,i,s=fetch){let o=t.endsWith("/")?t:`${t}/`,a=JSON.stringify({ilink_user_id:r,typing_ticket:n,status:i,base_info:{}});try{await s(`${o}ilink/bot/sendtyping`,{method:"POST",headers:Ke(e,a),body:a})}catch{}}import{mkdir as Mu,readFile as Nu,unlink as Xs,writeFile as $u}from"node:fs/promises";import{existsSync as eo}from"node:fs";import{resolve as Uu}from"node:path";var Fu="qrcode.png",qu="qrcode.txt";function to(t,e){return Uu(t,e)}function At(t){return to(t,Fu)}function Gr(t){return to(t,qu)}async function ro(t,e){eo(t)||await Mu(t,{recursive:!0}),await $u(Gr(t),e,"utf8")}async function no(t){await Promise.all([Xs(At(t)).catch(()=>{}),Xs(Gr(t)).catch(()=>{})])}async function io(t,e=r=>process.stdout.write(r)){let r=Gr(t),n;try{n=(await Nu(r,"utf8")).trim()}catch(o){if(o.code==="ENOENT"){let a=At(t);throw eo(a)?new Error(`No current pending QR code found in ${t}. Existing ${a} is likely stale; trigger a fresh QR login before using qrcode-terminal.`):new Error(`No current pending QR code found in ${t}. Start a fresh QR login before using qrcode-terminal.`)}throw o}if(!n)throw new Error(`No current pending QR code found in ${t}. Start a fresh QR login before using qrcode-terminal.`);let s=await(await Promise.resolve().then(()=>er(Qr(),1))).default.toString(n,{type:"terminal",small:!0});e(s.endsWith(`
|
|
33
|
+
`)?s:`${s}
|
|
34
|
+
`)}var It=class t{constructor(e,r,n=fetch,i=2e3){this.stateDir=e;this.fetchFn=n;this.pollIntervalMs=i;this.apiBase=r,this.credFile=ao(e,"credentials.json"),this.syncBufFile=ao(e,"sync-buf.txt"),this.qrcodePng=At(e)}credFile;syncBufFile;qrcodePng;cached=null;apiBase;tokenObtainedAt=0;static PROACTIVE_REFRESH_MS=720*60*1e3;silentRefreshInProgress=!1;async getToken(){if(this.cached)return await this.cleanupQrPng(),this.tokenObtainedAt>0&&Date.now()-this.tokenObtainedAt>t.PROACTIVE_REFRESH_MS&&!this.silentRefreshInProgress&&this.silentRefresh(),this.cached.token;let e=await this.loadCredentials();return e?(await this.cleanupQrPng(),this.cached=e,e.apiBase&&(this.apiBase=e.apiBase),this.tokenObtainedAt===0&&(this.tokenObtainedAt=Date.now()),e.token):this.startQrLogin()}getApiBase(){return this.apiBase}async startQrLogin(){let{qrcode:e,qrcodeImgUrl:r}=await qn(this.apiBase,this.fetchFn);await this.ensureStateDir(),await ro(this.stateDir,r);let n=(await Promise.resolve().then(()=>er(Qr(),1))).default;await n.toFile(this.qrcodePng,r,{type:"png",width:300});let i=await n.toString(r,{type:"terminal",small:!0});process.stdout.write(`QRCODE_READY:${this.qrcodePng}
|
|
35
35
|
`),process.stdout.write(`QRCODE_TERMINAL_BEGIN
|
|
36
36
|
`),process.stdout.write(i.endsWith(`
|
|
37
37
|
`)?i:`${i}
|
|
38
38
|
`),process.stdout.write(`QRCODE_TERMINAL_END
|
|
39
|
-
`);let s=Date.now()+480*1e3;for(;Date.now()<s;){await ju(this.pollIntervalMs);let o;try{o=await
|
|
40
|
-
`),await this.cleanupQrPng(),a.token}if(o.status==="scaned_but_redirect"&&o.redirectHost){this.apiBase=Qu(o.redirectHost);continue}if(o.status==="expired")return await this.cleanupQrPng(),this.startQrLogin()}throw await this.cleanupQrPng(),new Error("QR login timed out after 8 minutes")}async getSyncBuf(){try{return(await
|
|
39
|
+
`);let s=Date.now()+480*1e3;for(;Date.now()<s;){await ju(this.pollIntervalMs);let o;try{o=await Dn(this.apiBase,e,this.fetchFn)}catch(a){if(a instanceof Z&&a.errcode===-14)return await this.cleanupQrPng(),this.startQrLogin();throw a}if(o.status==="confirmed"&&o.token){o.resolvedBaseUrl&&(this.apiBase=o.resolvedBaseUrl);let a={token:o.token,botId:o.botId,apiBase:this.apiBase};await this.saveCredentials(a),this.cached=a,this.tokenObtainedAt=Date.now();let u=o.botId??"unknown";return process.stdout.write(`WECHAT_CONNECTED:${u}
|
|
40
|
+
`),await this.cleanupQrPng(),a.token}if(o.status==="scaned_but_redirect"&&o.redirectHost){this.apiBase=Qu(o.redirectHost);continue}if(o.status==="expired")return await this.cleanupQrPng(),this.startQrLogin()}throw await this.cleanupQrPng(),new Error("QR login timed out after 8 minutes")}async getSyncBuf(){try{return(await so(this.syncBufFile,"utf-8")).trim()}catch{return""}}async saveSyncBuf(e){await this.ensureStateDir(),await oo(this.syncBufFile,e,"utf-8")}invalidateToken(){this.cached=null,this.tokenObtainedAt=0,Hu(this.credFile).catch(()=>{})}async silentRefresh(){this.silentRefreshInProgress=!0;try{this.tokenObtainedAt=Date.now()}finally{this.silentRefreshInProgress=!1}}async relogin(){return this.cached=null,this.startQrLogin()}async loadCredentials(){try{let e=await so(this.credFile,"utf-8");return JSON.parse(e)}catch{return null}}async saveCredentials(e){await this.ensureStateDir(),await oo(this.credFile,JSON.stringify(e),"utf-8"),await Wu(this.credFile,384)}async cleanupQrPng(){await no(this.stateDir)}async ensureStateDir(){zu(this.stateDir)||await Du(this.stateDir,{recursive:!0})}};function ju(t){return new Promise(e=>setTimeout(e,t))}function Qu(t){return t.includes("://")?t:`https://${t}`}import{mkdir as $f,readFile as Uf,writeFile as ke}from"node:fs/promises";import{randomBytes as Pe}from"node:crypto";import{extname as fn,basename as Ft,resolve as Ff}from"node:path";import{createCipheriv as Gu,createDecipheriv as Yu,createHash as Vu,randomBytes as Yr}from"node:crypto";import{readFile as Ju}from"node:fs/promises";function Ku(t,e){let r=Gu("aes-128-ecb",e,null);return Buffer.concat([r.update(t),r.final()])}function Zu(t,e){let r=Yu("aes-128-ecb",e,null);return Buffer.concat([r.update(t),r.final()])}function Xu(t){return Math.ceil((t+1)/16)*16}function ef(t){let e=Buffer.from(t,"base64");if(e.length===16)return e;if(e.length===32&&/^[0-9a-fA-F]{32}$/.test(e.toString("ascii")))return Buffer.from(e.toString("ascii"),"hex");throw new Error(`aes_key must decode to 16 raw bytes or 32-char hex string, got ${e.length} bytes`)}async function pe(t){let{cdnBaseUrl:e,encryptQueryParam:r,fullUrl:n,aesKeyBase64:i,fetchFn:s=fetch}=t,o=e.endsWith("/")?e.slice(0,-1):e,a=n||(r?`${o}/download?encrypted_query_param=${encodeURIComponent(r)}`:void 0);if(!a)throw new Error("downloadMedia requires fullUrl or encryptQueryParam");let u=await s(a);if(!u.ok){let y=await u.text().catch(()=>"(unreadable)");throw new Error(`CDN download failed: ${u.status} ${u.statusText} body=${y}`)}let c=Buffer.from(await u.arrayBuffer());if(!i)return c;let h=ef(i);return Zu(c,h)}var vt=1,Vr=2,Jr=3,Kr=4;async function ft(t){let{apiBase:e,cdnBase:r,token:n,filePath:i,toUserId:s,mediaType:o=vt,fetchFn:a=fetch}=t,u=Buffer.isBuffer(i)?i:await Ju(i),c=u.length,h=Vu("md5").update(u).digest("hex"),y=Xu(c),_=Yr(16).toString("hex"),b=Yr(16),g=e.endsWith("/")?e:`${e}/`,w=JSON.stringify({filekey:_,media_type:o,to_user_id:s,rawsize:c,rawfilemd5:h,filesize:y,no_need_thumb:!0,aeskey:b.toString("hex"),base_info:{channel_version:"claude-code-1.0"}}),C=Buffer.from(String(Yr(4).readUInt32BE(0))).toString("base64"),E=await a(`${g}ilink/bot/getuploadurl`,{method:"POST",headers:{"Content-Type":"application/json","Content-Length":String(Buffer.byteLength(w,"utf-8")),AuthorizationType:"ilink_bot_token",Authorization:`Bearer ${n}`,"X-WECHAT-UIN":C},body:w});if(!E.ok)throw new Error(`getuploadurl HTTP ${E.status}`);let x=await E.json(),I=x.ret??x.errcode??0;if(I!==0)throw new Error(`getuploadurl error ${I}: ${x.errmsg??"unknown"}`);let O=x.upload_param,N=x.upload_full_url?.trim();if(!O&&!N)throw new Error("getuploadurl returned no upload destination");let v=r.endsWith("/")?r.slice(0,-1):r,L=N||`${v}/upload?encrypted_query_param=${encodeURIComponent(O)}&filekey=${encodeURIComponent(_)}`,G=Ku(u,b),z=await a(L,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:new Uint8Array(G)});if(!z.ok){let X=z.headers.get("x-error-message")??`status ${z.status}`;throw new Error(`CDN upload failed: ${X}`)}let U=z.headers.get("x-encrypted-param");if(!U)throw new Error("CDN upload response missing x-encrypted-param header");let F=Buffer.from(b.toString("hex")).toString("base64");return{encryptQueryParam:U,aesKeyBase64:F,fileSizeCiphertext:y,rawSize:c}}function Zr(t){return{sessionKey:t.session_key,text:t.payload.text??"",attachments:t.payload.attachments,raw:t}}function Xr(t){let e=t.daemonUrl.replace(/^http/,"ws")+"/ws",r=new WebSocket(e),n=1;return r.addEventListener("open",()=>{let i={jsonrpc:"2.0",id:`pull_${n++}`,method:"channel.pull",params:{session_key:t.sessionKey,consumer_id:t.consumerId,cursor:t.cursor||void 0,return_mask:["final"],source_kind:t.sourceKind??"wechat",channel_id:t.sessionKey,channel_capabilities:{outbound:{accept_mime:["*/*"]}}}};r.send(JSON.stringify(i))}),r.addEventListener("message",async i=>{let s;try{s=JSON.parse(i.data)}catch{return}if(s.method==="session.output"){let o=s.params;if(o?.record){let a=Zr(o.record);try{await t.onOutput(a)}finally{if(o.record.id){let u={jsonrpc:"2.0",id:`ack_${n++}`,method:"channel.ack",params:{session_key:t.sessionKey,consumer_id:t.consumerId,cursor:o.record.id}};r.send(JSON.stringify(u)),t.onAck(o.record.id)}}}return}s.error&&t.onError(new Ot(s.error.code,s.error.message))}),r.addEventListener("error",()=>{t.onError(new Error("WebSocket error"))}),r.addEventListener("close",()=>{t.onClose()}),()=>{try{r.close()}catch{}}}var tf=1,Ot=class extends Error{constructor(r,n){super(`DaemonError[${r}]: ${n}`);this.code=r;this.name="DaemonError"}};async function uo(t,e,r,n=fetch){let s={jsonrpc:"2.0",id:tf++,method:e,params:r},o=await n(`${t}/rpc`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!o.ok)throw new Error(`Daemon HTTP ${o.status} for method ${e}`);let a=await o.json();if(a.error)throw new Ot(a.error.code,a.error.message);return a.result}async function fo(t,e,r=fetch){await uo(t,"channel.ingress",e,r)}async function co(t,e,r=fetch){let n=await uo(t,"channel.file.download",{path:e},r);return Buffer.from(n.content_base64,"base64")}import{spawn as an}from"node:child_process";import{writeFile as Af,unlink as bo}from"node:fs/promises";import{tmpdir as on}from"node:os";import{join as Co}from"node:path";import{randomBytes as If}from"node:crypto";var Nt=16e3;async function ln(t,e){if(e==="audio/silk"||Mf(t)){let a=Nf(t);return{silk:t,playtimeMs:a}}let r=await vf(t),{encode:n}=await Promise.resolve().then(()=>er(wo(),1)),i=await n(r,Nt),s=Buffer.from(i.data),o=Math.round(r.length/(Nt*2)*1e3);return{silk:s,playtimeMs:o}}function vf(t){return new Promise((e,r)=>{let n=an("ffmpeg",["-v","quiet","-i","pipe:0","-f","s16le","-acodec","pcm_s16le","-ar",String(Nt),"-ac","1","pipe:1"]),i=[],s=[];n.stdout.on("data",o=>i.push(o)),n.stderr.on("data",o=>s.push(o)),n.on("close",o=>{if(o!==0){let a=Buffer.concat(s).toString("utf-8").slice(-500);return r(new Error(`ffmpeg exited ${o}: ${a}`))}e(Buffer.concat(i))}),n.on("error",o=>r(new Error(`ffmpeg spawn failed: ${o.message}`))),n.stdin.write(t),n.stdin.end()})}async function Eo(t){let e=Co(on(),`wechat-voice-${If(4).toString("hex")}.wav`);try{let r=await Of(t);return await Af(e,r),await Lf(e)||null}finally{bo(e).catch(()=>{})}}function Of(t){return new Promise((e,r)=>{let n=an("ffmpeg",["-v","quiet","-i","pipe:0","-f","wav","-acodec","pcm_s16le","-ar",String(Nt),"-ac","1","pipe:1"]),i=[],s=[];n.stdout.on("data",o=>i.push(o)),n.stderr.on("data",o=>s.push(o)),n.on("close",o=>{if(o!==0){let a=Buffer.concat(s).toString("utf-8").slice(-500);return r(new Error(`ffmpeg (toWav) exited ${o}: ${a}`))}e(Buffer.concat(i))}),n.on("error",o=>r(new Error(`ffmpeg spawn failed: ${o.message}`))),n.stdin.write(t),n.stdin.end()})}function Lf(t){return new Promise((e,r)=>{let n=an("whisper",[t,"--model","base","--language","zh","--output_format","txt","--output_dir",on(),"--fp16","False"]),i=[];n.stderr.on("data",s=>i.push(s)),n.on("close",async s=>{if(s!==0){let a=Buffer.concat(i).toString("utf-8").slice(-500);return r(new Error(`whisper exited ${s}: ${a}`))}let o=Co(on(),t.replace(/\\/g,"/").split("/").pop().replace(/\.wav$/,".txt"));try{let{readFile:a}=await import("node:fs/promises"),u=await a(o,"utf-8");bo(o).catch(()=>{}),e(u.trim())}catch{e("")}}),n.on("error",s=>r(new Error(`whisper spawn failed: ${s.message}`)))})}function Mf(t){if(t.length<9)return!1;let e=t.subarray(0,9).toString("ascii");return e.startsWith("#!SILK_V3")||e.startsWith("#!SILK")}function Nf(t){return Math.round(t.length/3)}var $t=class t{buffer="";inFence=!1;atLineStart=!0;inline=null;feed(e){return this.buffer+=e,this.pump(!1)}flush(){return this.pump(!0)}pump(e){let r="";for(;this.buffer;){let n=this.buffer,i=this.atLineStart,s=this.inFence,o=this.inline;if(this.inFence?r+=this.pumpFence(e):this.inline?r+=this.pumpInline(e):this.atLineStart?r+=this.pumpLineStart(e):r+=this.pumpBody(e),this.buffer===n&&this.atLineStart===i&&this.inFence===s&&this.inline===o)break}return e&&this.inline&&(r+=`${{image:"![",bold3:"***",italic:"*",ubold3:"___",uitalic:"_"}[this.inline.type]??""}${this.inline.acc}`,this.inline=null),r}pumpFence(e){if(this.atLineStart){if(this.buffer.length<3&&!e)return"";if(this.buffer.startsWith("```")){let i=this.buffer.indexOf(`
|
|
41
41
|
`,3);if(i!==-1){let s=this.buffer.slice(0,i+1);return this.buffer=this.buffer.slice(i+1),this.atLineStart=!0,this.inFence=!1,s}if(e){let s=this.buffer;return this.buffer="",this.atLineStart=!1,this.inFence=!1,s}return""}this.atLineStart=!1}let r=this.buffer.indexOf(`
|
|
42
42
|
`);if(r!==-1){let i=this.buffer.slice(0,r+1);return this.buffer=this.buffer.slice(r+1),this.atLineStart=!0,i}let n=this.buffer;return this.buffer="",n}pumpLineStart(e){let r=this.buffer;if(r[0]===`
|
|
43
43
|
`)return this.buffer=r.slice(1),`
|
|
@@ -48,19 +48,19 @@ return ret;
|
|
|
48
48
|
`)return r+=this.buffer.slice(0,n),this.buffer=this.buffer.slice(n+1),this.inline={type:"italic",acc:""},r;n++;continue}if(s==="_"){if(n+2<this.buffer.length&&this.buffer[n+1]==="_"&&this.buffer[n+2]==="_")return r+=this.buffer.slice(0,n),this.buffer=this.buffer.slice(n+3),this.inline={type:"ubold3",acc:""},r;if(n+1<this.buffer.length&&this.buffer[n+1]==="_"){n+=2;continue}if(n+1<this.buffer.length&&this.buffer[n+1]!==" "&&this.buffer[n+1]!==`
|
|
49
49
|
`)return r+=this.buffer.slice(0,n),this.buffer=this.buffer.slice(n+1),this.inline={type:"uitalic",acc:""},r;n++;continue}n++}let i=0;return e||(this.buffer.endsWith("**")||this.buffer.endsWith("__")?i=2:(this.buffer.endsWith("*")||this.buffer.endsWith("_")||this.buffer.endsWith("!"))&&(i=1)),r+=this.buffer.slice(0,this.buffer.length-i),this.buffer=i>0?this.buffer.slice(-i):"",r}pumpInline(e){if(!this.inline)return"";switch(this.inline.acc+=this.buffer,this.buffer="",this.inline.type){case"bold3":{let r=this.inline.acc.indexOf("***");if(r===-1)return"";let n=this.inline.acc.slice(0,r);return this.buffer=this.inline.acc.slice(r+3),this.inline=null,t.containsCjk(n)?n:`***${n}***`}case"ubold3":{let r=this.inline.acc.indexOf("___");if(r===-1)return"";let n=this.inline.acc.slice(0,r);return this.buffer=this.inline.acc.slice(r+3),this.inline=null,t.containsCjk(n)?n:`___${n}___`}case"italic":{for(let r=0;r<this.inline.acc.length;r++){let n=this.inline.acc[r];if(n===`
|
|
50
50
|
`){let i=`*${this.inline.acc.slice(0,r+1)}`;return this.buffer=this.inline.acc.slice(r+1),this.inline=null,this.atLineStart=!0,i}if(n==="*"){if(r+1<this.inline.acc.length&&this.inline.acc[r+1]==="*"){r++;continue}let i=this.inline.acc.slice(0,r);return this.buffer=this.inline.acc.slice(r+1),this.inline=null,t.containsCjk(i)?i:`*${i}*`}}return""}case"uitalic":{for(let r=0;r<this.inline.acc.length;r++){let n=this.inline.acc[r];if(n===`
|
|
51
|
-
`){let i=`_${this.inline.acc.slice(0,r+1)}`;return this.buffer=this.inline.acc.slice(r+1),this.inline=null,this.atLineStart=!0,i}if(n==="_"){if(r+1<this.inline.acc.length&&this.inline.acc[r+1]==="_"){r++;continue}let i=this.inline.acc.slice(0,r);return this.buffer=this.inline.acc.slice(r+1),this.inline=null,t.containsCjk(i)?i:`_${i}_`}}return""}case"image":{let r=this.inline.acc.indexOf("]");if(r===-1||r+1>=this.inline.acc.length)return"";if(this.inline.acc[r+1]!=="("){let i=`![${this.inline.acc.slice(0,r+1)}`;return this.buffer=this.inline.acc.slice(r+1),this.inline=null,i}let n=this.inline.acc.indexOf(")",r+2);return n===-1||(this.buffer=this.inline.acc.slice(n+1),this.inline=null),""}}return""}static containsCjk(e){return/[\u2E80-\u9FFF\uAC00-\uD7AF\uF900-\uFAFF]/.test(e)}};var ge="/tmp/channel-wechat-media",
|
|
51
|
+
`){let i=`_${this.inline.acc.slice(0,r+1)}`;return this.buffer=this.inline.acc.slice(r+1),this.inline=null,this.atLineStart=!0,i}if(n==="_"){if(r+1<this.inline.acc.length&&this.inline.acc[r+1]==="_"){r++;continue}let i=this.inline.acc.slice(0,r);return this.buffer=this.inline.acc.slice(r+1),this.inline=null,t.containsCjk(i)?i:`_${i}_`}}return""}case"image":{let r=this.inline.acc.indexOf("]");if(r===-1||r+1>=this.inline.acc.length)return"";if(this.inline.acc[r+1]!=="("){let i=`![${this.inline.acc.slice(0,r+1)}`;return this.buffer=this.inline.acc.slice(r+1),this.inline=null,i}let n=this.inline.acc.indexOf(")",r+2);return n===-1||(this.buffer=this.inline.acc.slice(n+1),this.inline=null),""}}return""}static containsCjk(e){return/[\u2E80-\u9FFF\uAC00-\uD7AF\uF900-\uFAFF]/.test(e)}};var ge="/tmp/channel-wechat-media",To="channel-wechat",ko=3e3,qf=3e4,un=5,Po=3e4;function A(t,e,r){let n=["error","warn","info","debug"],i=r?.logLevel??"info";n.indexOf(t)<=n.indexOf(i)&&console.log(`[${t.toUpperCase()}] [wechat-channel] ${e}`)}function Df(t){return t?t.text_item?.text?t.text_item.text:t.voice_item?.text?t.voice_item.text:t.file_item?.file_name?t.file_item.file_name:"":""}function So(t){return!!(t&&(t.image_item?.media?.encrypt_query_param||t.image_item?.media?.full_url||t.voice_item?.media?.encrypt_query_param||t.voice_item?.media?.full_url||t.file_item?.media?.encrypt_query_param||t.file_item?.media?.full_url||t.video_item?.media?.encrypt_query_param||t.video_item?.media?.full_url))}function Wf(t){for(let e of t??[])if(So(e))return;for(let e of t??[])if(e.ref_msg?.message_item&&So(e.ref_msg.message_item))return e.ref_msg.message_item}function Hf(t){let r=t.raw?.payload?.data;if(!r)return[];let n=[];if(typeof r.mediaUrl=="string"&&r.mediaUrl.trim()&&n.push(r.mediaUrl.trim()),Array.isArray(r.mediaUrls))for(let i of r.mediaUrls)typeof i=="string"&&i.trim()&&n.push(i.trim());return n}function zf(t){if(t){if(t.startsWith("file://"))return new URL(t).pathname;if(!t.includes("://"))return Ff(t)}}var qt=class{constructor(e,r,n=fetch,i){this.config=e;this.auth=r;this.fetchFn=n;this.outbox=i}running=!1;abortController=new AbortController;sessions=new Map;typingTickets=new Map;TYPING_TICKET_TTL_MS=1200*60*1e3;start(){this.running=!0,this.abortController=new AbortController;let e=this.abortController.signal,r=this.fetchFn,n=(i,s)=>r(i,{...s,signal:e});this.ingressLoop(n),this.pullLoop(n),this.outbox&&this.replayOutbox(n)}stop(){this.running=!1,this.abortController.abort()}async ingressLoop(e){let r=0;for(A("info","ingressLoop started",this.config);this.running;){A("debug","ingressLoop tick",this.config);try{let n=await this.auth.getToken(),i=await this.auth.getSyncBuf(),s=this.auth.getApiBase(),{msgs:o,syncBuf:a}=await Wn(s,n,i,e);await this.auth.saveSyncBuf(a),r=0,o.length>0&&A("debug",`getUpdates: ${o.length} msgs, types=${o.map(u=>`msg_type=${u.message_type} items=[${u.item_list?.map(c=>c.type).join(",")}]`).join(" | ")}`,this.config);for(let u of o){if(u.message_type===2)continue;if(!this.isAllowed(u.from_user_id)){A("debug",`Blocked message from ${u.from_user_id}`,this.config);continue}A("debug",`raw item_list from ${u.from_user_id}: ${JSON.stringify(u.item_list)}`,this.config);let c=u.item_list?.filter(g=>g.type===1&&g.text_item?.text).map(g=>g.text_item.text).join("")??"";for(let g of u.item_list??[])if(g.ref_msg){let w=g.ref_msg,C=[];w.title&&C.push(w.title);let E=Df(w.message_item);if(E&&C.push(E),C.length>0){let x=`<quoted_message>
|
|
52
52
|
${C.join(`
|
|
53
53
|
`)}
|
|
54
54
|
</quoted_message>`;c=c?`${x}
|
|
55
|
-
${c}`:x,
|
|
55
|
+
${c}`:x,A("info",`Quoted message context: "${C.join(" | ")}"`,this.config)}break}await $f(ge,{recursive:!0});let h=[];for(let g of u.item_list??[])try{if(g.type===2&&(g.image_item?.media?.encrypt_query_param||g.image_item?.media?.full_url)){let w=g.image_item,C=w.media.aes_key??(w.aeskey?Buffer.from(w.aeskey,"hex").toString("base64"):void 0),E=await pe({cdnBaseUrl:this.config.cdnBase,encryptQueryParam:w.media.encrypt_query_param,fullUrl:w.media.full_url,aesKeyBase64:C,fetchFn:e}),x=`${ge}/${Date.now()}-${Pe(4).toString("hex")}.jpg`;await ke(x,E),h.push({path:x,mime:"image/jpeg"}),A("info",`Downloaded image \u2192 ${x} (${E.length}B)`,this.config)}else if(g.type===3&&(g.voice_item?.media?.encrypt_query_param||g.voice_item?.media?.full_url)&&g.voice_item.media.aes_key){let w=g.voice_item,C=await pe({cdnBaseUrl:this.config.cdnBase,encryptQueryParam:w.media.encrypt_query_param,fullUrl:w.media.full_url,aesKeyBase64:w.media.aes_key,fetchFn:e}),E=`${ge}/${Date.now()}-${Pe(4).toString("hex")}.silk`;if(await ke(E,C),h.push({path:E,mime:"audio/silk"}),A("info",`Downloaded voice \u2192 ${E} (${C.length}B)`,this.config),w.text){let x=`<voice_transcript>
|
|
56
56
|
${w.text}
|
|
57
57
|
</voice_transcript>`;c=c?`${c}
|
|
58
|
-
${x}`:x,
|
|
58
|
+
${x}`:x,A("info",`Voice transcription from WeChat: "${w.text}"`,this.config)}else try{let x=await Eo(C);if(x){let I=`<voice_transcript>
|
|
59
59
|
${x}
|
|
60
60
|
</voice_transcript>`;c=c?`${c}
|
|
61
|
-
${I}`:I,R("info",`Whisper transcript: "${x}"`,this.config)}}catch(x){R("warn",`Whisper failed, no transcript injected: ${x}`,this.config)}}else if(g.type===4&&(g.file_item?.media?.encrypt_query_param||g.file_item?.media?.full_url)&&g.file_item.media.aes_key){let w=g.file_item,C=await pe({cdnBaseUrl:this.config.cdnBase,encryptQueryParam:w.media.encrypt_query_param,fullUrl:w.media.full_url,aesKeyBase64:w.media.aes_key,fetchFn:e}),E=w.file_name??"file.bin",x=fn(E)||".bin",I=ht(E),O=`${ge}/${Date.now()}-${Pe(4).toString("hex")}${x}`;await ke(O,C),h.push({path:O,mime:I}),R("info",`Downloaded file "${E}" \u2192 ${O} (${C.length}B)`,this.config)}else if(g.type===5&&(g.video_item?.media?.encrypt_query_param||g.video_item?.media?.full_url)&&g.video_item.media.aes_key){let w=g.video_item,C=await pe({cdnBaseUrl:this.config.cdnBase,encryptQueryParam:w.media.encrypt_query_param,fullUrl:w.media.full_url,aesKeyBase64:w.media.aes_key,fetchFn:e}),E=`${ge}/${Date.now()}-${Pe(4).toString("hex")}.mp4`;await ke(E,C),h.push({path:E,mime:"video/mp4"}),R("info",`Downloaded video \u2192 ${E} (${C.length}B)`,this.config)}}catch(w){R("warn",`Failed to download media item type=${g.type}: ${String(w)}`,this.config)}let y=h.length===0?Wf(u.item_list):void 0;if(y)try{if(y.type===2&&y.image_item?.media){let g=y.image_item,w=g.media;if(!w)continue;let C=w.aes_key??(g.aeskey?Buffer.from(g.aeskey,"hex").toString("base64"):void 0),E=await pe({cdnBaseUrl:this.config.cdnBase,encryptQueryParam:w.encrypt_query_param,fullUrl:w.full_url,aesKeyBase64:C,fetchFn:e}),x=`${ge}/${Date.now()}-${Pe(4).toString("hex")}.jpg`;await ke(x,E),h.push({path:x,mime:"image/jpeg"})}else if(y.type===3&&y.voice_item?.media?.aes_key){let g=y.voice_item,w=await pe({cdnBaseUrl:this.config.cdnBase,encryptQueryParam:g.media.encrypt_query_param,fullUrl:g.media.full_url,aesKeyBase64:g.media.aes_key,fetchFn:e}),C=`${ge}/${Date.now()}-${Pe(4).toString("hex")}.silk`;await ke(C,w),h.push({path:C,mime:"audio/silk"})}else if(y.type===4&&y.file_item?.media?.aes_key){let g=y.file_item,w=await pe({cdnBaseUrl:this.config.cdnBase,encryptQueryParam:g.media.encrypt_query_param,fullUrl:g.media.full_url,aesKeyBase64:g.media.aes_key,fetchFn:e}),C=g.file_name??"file.bin",E=fn(C)||".bin",x=ht(C),I=`${ge}/${Date.now()}-${Pe(4).toString("hex")}${E}`;await ke(I,w),h.push({path:I,mime:x})}else if(y.type===5&&y.video_item?.media?.aes_key){let g=y.video_item,w=await pe({cdnBaseUrl:this.config.cdnBase,encryptQueryParam:g.media.encrypt_query_param,fullUrl:g.media.full_url,aesKeyBase64:g.media.aes_key,fetchFn:e}),C=`${ge}/${Date.now()}-${Pe(4).toString("hex")}.mp4`;await ke(C,w),h.push({path:C,mime:"video/mp4"})}}catch(g){R("warn",`Failed to download quoted media type=${y.type}: ${String(g)}`,this.config)}if(!c&&h.length===0){R("debug",`Non-text/media message from ${u.from_user_id}, skipping`,this.config);continue}let _=`wechat:${u.from_user_id}`,b=this.sessions.get(_);b?u.context_token&&(b.contextToken=u.context_token):this.sessions.set(_,{toUser:u.from_user_id,contextToken:u.context_token,cursor:""}),R("info",`Ingress from ${u.from_user_id} text=${JSON.stringify(c.slice(0,80))} attachments=${h.length}`,this.config),this.getTypingTicket(u.from_user_id,u.context_token,e).then(g=>{if(!g)return;let w=this.sessions.get(_);w&&(w.stopTyping?.(),w.stopTyping=this.startTyping(u.from_user_id,g,e))});try{await uo(this.config.daemonUrl,{session_key:_,text:c||void 0,attachments:h,idempotency_key:String(u.message_id),source_kind:"wechat",channel_id:`wechat-${u.from_user_id.replace(/[^A-Za-z0-9_-]/g,"_")}`},e)}catch(g){R("error",`ingress failed for ${_}: ${String(g)}`,this.config)}}}catch(n){if(n?.name==="AbortError")return;if(r++,n instanceof Z&&n.errcode===-14){R("warn","Token invalid (-14), triggering re-login",this.config),this.auth.invalidateToken(),r=0;continue}R("error",`ingressLoop error (${r}): ${String(n)}`,this.config),r>=un&&(R("warn",`Backing off ${ko}ms after ${un} errors`,this.config),await Ut(ko),r=0)}}}async pullLoop(e){R("info","pullLoop started (WebSocket mode)",this.config);let r="wechat:__cap_heartbeat__",n;n=null;let i=()=>{n||(R("debug","Registering capability heartbeat WS",this.config),n=Xr({daemonUrl:this.config.daemonUrl,sessionKey:r,consumerId:Eo,sourceKind:"wechat",onOutput:async()=>{},onAck:()=>{},onError:()=>{},onClose:()=>{n=null,this.running&&setTimeout(i,To)}}))};i();let s=new Map,o=new Map,a=(c,h)=>{if(s.has(c))return;R("info",`WS subscribing for ${c}`,this.config);let y=Xr({daemonUrl:this.config.daemonUrl,sessionKey:c,consumerId:Eo,cursor:h.cursor||void 0,sourceKind:"wechat",onOutput:async _=>{let b=await this.auth.getToken(),g=this.auth.getApiBase(),w=this.filterOutboundText(_.text??""),C=_.attachments??[],E=C.length===0?Hf(_):[];if(C.length>0)for(let x=0;x<C.length;x++){let I=C[x],O=x===C.length-1,N=O?w:"";R("info",`Sending attachment to ${h.toUser}: ${I.path} (${I.mime})`,this.config);try{let v=await fo(this.config.daemonUrl,I.path,e),L=I.mime.startsWith("image/"),G=I.mime.startsWith("audio/"),z=I.mime.startsWith("video/");if(G){let{silk:$,playtimeMs:F}=await ln(v,I.mime),X=await this.withRetry(()=>ft({apiBase:g,cdnBase:this.config.cdnBase,token:b,filePath:$,toUserId:h.toUser,mediaType:Jr,fetchFn:e}),"uploadMedia(voice)");await this.withRetry(()=>le(g,b,h.toUser,N,h.contextToken,e,{kind:"voice",item:{encryptQueryParam:X.encryptQueryParam,aesKeyBase64:X.aesKeyBase64,playtimeMs:F}}),"sendMessage(voice)")}else{let $=await this.withRetry(()=>ft({apiBase:g,cdnBase:this.config.cdnBase,token:b,filePath:v,toUserId:h.toUser,mediaType:L?It:z?Vr:Kr,fetchFn:e}),L?"uploadMedia(image)":z?"uploadMedia(video)":"uploadMedia(file)"),F=$t(I.path)||"file";await this.withRetry(()=>le(g,b,h.toUser,N,h.contextToken,e,L?{encryptQueryParam:$.encryptQueryParam,aesKeyBase64:$.aesKeyBase64,midSize:$.fileSizeCiphertext}:z?{kind:"video",item:{encryptQueryParam:$.encryptQueryParam,aesKeyBase64:$.aesKeyBase64,videoSize:$.fileSizeCiphertext}}:{kind:"file",item:{encryptQueryParam:$.encryptQueryParam,aesKeyBase64:$.aesKeyBase64,fileName:F,fileSize:$.rawSize}}),L?"sendMessage(image)":z?"sendMessage(video)":"sendMessage(file)")}}catch(v){v instanceof Z&&v.errcode===-14&&this.auth.invalidateToken(),R("error",`sendAttachment failed to ${h.toUser}: ${String(v)}`,this.config),O&&_.text&&await this.withRetry(()=>le(g,b,h.toUser,w,h.contextToken,e),"sendMessage(fallback)").catch(L=>R("error",`sendMessage fallback failed: ${String(L)}`,this.config))}}else if(E.length>0)for(let x=0;x<E.length;x++){let I=E[x],O=x===E.length-1,N=O?w:"";try{let v=zf(I),L=v?void 0:await this.downloadRemoteMedia(I,e),G=L?.buffer,z=v?ht(v):L?.mime??"application/octet-stream",$=z.startsWith("image/"),F=z.startsWith("audio/"),X=z.startsWith("video/");if(F){let Ne=G??await this.readLocalMedia(v),{silk:K,playtimeMs:Ue}=await ln(Ne,z),Se=await this.withRetry(()=>ft({apiBase:g,cdnBase:this.config.cdnBase,token:b,filePath:K,toUserId:h.toUser,mediaType:Jr,fetchFn:e}),"uploadMedia(voice-url)");await this.withRetry(()=>le(g,b,h.toUser,N,h.contextToken,e,{kind:"voice",item:{encryptQueryParam:Se.encryptQueryParam,aesKeyBase64:Se.aesKeyBase64,playtimeMs:Ue}}),"sendMessage(voice-url)")}else{let Ne=G??v,K=await this.withRetry(()=>ft({apiBase:g,cdnBase:this.config.cdnBase,token:b,filePath:Ne,toUserId:h.toUser,mediaType:$?It:X?Vr:Kr,fetchFn:e}),$?"uploadMedia(image-url)":X?"uploadMedia(video-url)":"uploadMedia(file-url)"),Ue=v?$t(v):L?.fileName??$t(I.split("?")[0]??"file");await this.withRetry(()=>le(g,b,h.toUser,N,h.contextToken,e,$?{encryptQueryParam:K.encryptQueryParam,aesKeyBase64:K.aesKeyBase64,midSize:K.fileSizeCiphertext}:X?{kind:"video",item:{encryptQueryParam:K.encryptQueryParam,aesKeyBase64:K.aesKeyBase64,videoSize:K.fileSizeCiphertext}}:{kind:"file",item:{encryptQueryParam:K.encryptQueryParam,aesKeyBase64:K.aesKeyBase64,fileName:Ue,fileSize:K.rawSize}}),$?"sendMessage(image-url)":X?"sendMessage(video-url)":"sendMessage(file-url)")}}catch(v){v instanceof Z&&v.errcode===-14&&this.auth.invalidateToken(),R("error",`sendMediaUrl failed to ${h.toUser}: ${String(v)}`,this.config),O&&_.text&&await this.withRetry(()=>le(g,b,h.toUser,w,h.contextToken,e),"sendMessage(mediaUrl-fallback)").catch(L=>R("error",`sendMessage mediaUrl fallback failed: ${String(L)}`,this.config))}}else if(w){R("info",`Sending reply to ${h.toUser}: ${w.slice(0,60)}`,this.config);try{await this.withRetry(()=>le(g,b,h.toUser,w,h.contextToken,e),"sendMessage(text)")}catch(x){x instanceof Z&&x.errcode===-14&&this.auth.invalidateToken(),R("error",`sendMessage failed to ${h.toUser}: ${String(x)}`,this.config),this.outbox&&await this.outbox.enqueue({sessionKey:c,toUser:h.toUser,contextToken:h.contextToken,text:w,attachments:[]}).catch(I=>R("warn",`outbox.enqueue failed: ${String(I)}`,this.config))}}h.stopTyping&&(h.stopTyping(),h.stopTyping=void 0)},onAck:_=>{h.cursor=_,o.set(c,0)},onError:_=>{let b=(o.get(c)??0)+1;o.set(c,b),R("error",`WS error for ${c} (${b}): ${String(_)}`,this.config)},onClose:()=>{if(s.delete(c),!this.running)return;let b=(o.get(c)??0)>=un?Df:To;R("info",`WS closed for ${c}, reconnecting in ${b}ms`,this.config),setTimeout(()=>{if(this.running&&this.sessions.has(c)){let g=this.sessions.get(c);a(c,g)}},b)}});s.set(c,y)};for(;this.running;){for(let[c,h]of this.sessions)a(c,h);for(let[c,h]of s)this.sessions.has(c)||(h(),s.delete(c));await Ut(1e3,this.abortController.signal)}let u=n;n=null,u?.();for(let c of s.values())c();s.clear()}async getTypingTicket(e,r,n){let i=this.typingTickets.get(e);if(i&&Date.now()-i.fetchedAt<this.TYPING_TICKET_TTL_MS)return i.ticket;try{let s=await this.auth.getToken(),o=await Hn(this.auth.getApiBase(),s,e,r,n);if(o.typing_ticket)return this.typingTickets.set(e,{ticket:o.typing_ticket,fetchedAt:Date.now()}),o.typing_ticket}catch(s){R("debug",`getTypingTicket failed for ${e}: ${String(s)}`,this.config)}}startTyping(e,r,n){let i=async o=>{try{let a=await this.auth.getToken();await zn(this.auth.getApiBase(),a,e,r,o,n)}catch{}};i(1);let s=setInterval(()=>{i(1)},5e3);return()=>{clearInterval(s),i(2)}}async readLocalMedia(e){return $f(e)}async downloadRemoteMedia(e,r){let n=await r(e);if(!n.ok){let a=await n.text().catch(()=>"(unreadable)");throw new Error(`Remote media download failed: ${n.status} ${n.statusText} body=${a}`)}let s=n.headers?.get("content-type")?.split(";")[0]?.trim().toLowerCase()||ht(new URL(e).pathname),o=Qf(e,s);return{buffer:Buffer.from(await n.arrayBuffer()),mime:s,fileName:o}}filterOutboundText(e){let r=new Nt;return r.feed(e)+r.flush()}async withRetry(e,r,n={}){let i=n.maxAttempts??3,s=n.baseMs??500,o;for(let a=1;a<=i;a++)try{return await e()}catch(u){if(o=u,u instanceof Z&&[-14,400,403].includes(u.errcode))throw u;if(a<i){let c=s*Math.pow(2,a-1);R("warn",`${r} attempt ${a}/${i} failed, retry in ${c}ms: ${String(u)}`,this.config),await Ut(c)}}throw o}async replayOutbox(e){if(!this.outbox)return;await Ut(5e3);let r=await this.outbox.getPending();if(r.length!==0){R("info",`Replaying ${r.length} outbox pending records`,this.config);for(let n of r){if(!this.running)break;try{let i=await this.auth.getToken(),s=this.auth.getApiBase();await this.withRetry(()=>le(s,i,n.toUser,n.text,n.contextToken,e),"outbox.replay"),await this.outbox.markSent(n.id),R("info",`Outbox replayed ${n.id} to ${n.toUser}`,this.config)}catch(i){await this.outbox.markFailed(n.id,String(i)),R("warn",`Outbox replay failed for ${n.id}: ${String(i)}`,this.config)}}}}isAllowed(e){return this.config.dmPolicy==="open"?!0:this.config.allowFrom.includes(e)}};function ht(t){let e=fn(t).toLowerCase();return{".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".zip":"application/zip",".txt":"text/plain",".csv":"text/csv",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".mp4":"video/mp4",".mov":"video/quicktime",".mp3":"audio/mpeg",".m4a":"audio/mp4",".wav":"audio/wav"}[e]??"application/octet-stream"}function jf(t){return{"application/pdf":".pdf","application/msword":".doc","application/vnd.openxmlformats-officedocument.wordprocessingml.document":".docx","application/vnd.ms-excel":".xls","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":".xlsx","application/vnd.ms-powerpoint":".ppt","application/vnd.openxmlformats-officedocument.presentationml.presentation":".pptx","application/zip":".zip","text/plain":".txt","text/csv":".csv","application/json":".json","image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp","video/mp4":".mp4","video/quicktime":".mov","audio/mpeg":".mp3","audio/mp4":".m4a","audio/wav":".wav"}[t]}function Qf(t,e){let r=new URL(t).pathname,n=$t(r)||"file";if(ht(n)!=="application/octet-stream")return n;let i=jf(e);return i?`${n}${i}`:n}function Ut(t,e){return new Promise(r=>{let n=setTimeout(r,t);e?.addEventListener("abort",()=>{clearTimeout(n),r()},{once:!0})})}import Gf from"node:http";function So(t,e){let r=Gf.createServer((n,i)=>{if(n.method!=="GET"||n.url!=="/health"){i.writeHead(404),i.end("Not Found");return}if(!t.running){i.writeHead(503,{"Content-Type":"application/json"}),i.end(JSON.stringify({status:"unavailable",reason:"gateway_stopped"}));return}let s=t.tokenObtainedAt>0?Date.now()-t.tokenObtainedAt:1/0;if(s>72e6){i.writeHead(503,{"Content-Type":"application/json"}),i.end(JSON.stringify({status:"token_stale",token_age_hours:Math.floor(s/36e5)}));return}i.writeHead(200,{"Content-Type":"application/json"}),i.end(JSON.stringify({status:"ok",uptime_seconds:Math.floor(process.uptime()),token_age_hours:Math.floor(s/36e5)}))});return r.listen(e,()=>{console.log(`[INFO] [wechat-channel] Health check listening on :${e}/health`)}),r}import{appendFile as Yf,readFile as Vf,writeFile as Kf,mkdir as xo,rename as Jf}from"node:fs/promises";import{existsSync as Zf}from"node:fs";import{dirname as Bo}from"node:path";import{randomBytes as Xf}from"node:crypto";var ec=3,Dt=class{constructor(e){this.filePath=e}writeChain=Promise.resolve();async enqueue(e){let r=Xf(8).toString("hex"),n={...e,id:r,createdAt:Date.now(),attempts:0},i=JSON.stringify(n)+`
|
|
62
|
-
`;return this.writeChain=this.writeChain.then(async()=>{await
|
|
63
|
-
`)){let i=n.trim();if(i)try{r.push(JSON.parse(i))}catch{}}return r}async rewrite(e){this.writeChain=this.writeChain.then(async()=>{await
|
|
61
|
+
${I}`:I,A("info",`Whisper transcript: "${x}"`,this.config)}}catch(x){A("warn",`Whisper failed, no transcript injected: ${x}`,this.config)}}else if(g.type===4&&(g.file_item?.media?.encrypt_query_param||g.file_item?.media?.full_url)&&g.file_item.media.aes_key){let w=g.file_item,C=await pe({cdnBaseUrl:this.config.cdnBase,encryptQueryParam:w.media.encrypt_query_param,fullUrl:w.media.full_url,aesKeyBase64:w.media.aes_key,fetchFn:e}),E=w.file_name??"file.bin",x=fn(E)||".bin",I=ht(E),O=`${ge}/${Date.now()}-${Pe(4).toString("hex")}${x}`;await ke(O,C),h.push({path:O,mime:I}),A("info",`Downloaded file "${E}" \u2192 ${O} (${C.length}B)`,this.config)}else if(g.type===5&&(g.video_item?.media?.encrypt_query_param||g.video_item?.media?.full_url)&&g.video_item.media.aes_key){let w=g.video_item,C=await pe({cdnBaseUrl:this.config.cdnBase,encryptQueryParam:w.media.encrypt_query_param,fullUrl:w.media.full_url,aesKeyBase64:w.media.aes_key,fetchFn:e}),E=`${ge}/${Date.now()}-${Pe(4).toString("hex")}.mp4`;await ke(E,C),h.push({path:E,mime:"video/mp4"}),A("info",`Downloaded video \u2192 ${E} (${C.length}B)`,this.config)}}catch(w){A("warn",`Failed to download media item type=${g.type}: ${String(w)}`,this.config)}let y=h.length===0?Wf(u.item_list):void 0;if(y)try{if(y.type===2&&y.image_item?.media){let g=y.image_item,w=g.media;if(!w)continue;let C=w.aes_key??(g.aeskey?Buffer.from(g.aeskey,"hex").toString("base64"):void 0),E=await pe({cdnBaseUrl:this.config.cdnBase,encryptQueryParam:w.encrypt_query_param,fullUrl:w.full_url,aesKeyBase64:C,fetchFn:e}),x=`${ge}/${Date.now()}-${Pe(4).toString("hex")}.jpg`;await ke(x,E),h.push({path:x,mime:"image/jpeg"})}else if(y.type===3&&y.voice_item?.media?.aes_key){let g=y.voice_item,w=await pe({cdnBaseUrl:this.config.cdnBase,encryptQueryParam:g.media.encrypt_query_param,fullUrl:g.media.full_url,aesKeyBase64:g.media.aes_key,fetchFn:e}),C=`${ge}/${Date.now()}-${Pe(4).toString("hex")}.silk`;await ke(C,w),h.push({path:C,mime:"audio/silk"})}else if(y.type===4&&y.file_item?.media?.aes_key){let g=y.file_item,w=await pe({cdnBaseUrl:this.config.cdnBase,encryptQueryParam:g.media.encrypt_query_param,fullUrl:g.media.full_url,aesKeyBase64:g.media.aes_key,fetchFn:e}),C=g.file_name??"file.bin",E=fn(C)||".bin",x=ht(C),I=`${ge}/${Date.now()}-${Pe(4).toString("hex")}${E}`;await ke(I,w),h.push({path:I,mime:x})}else if(y.type===5&&y.video_item?.media?.aes_key){let g=y.video_item,w=await pe({cdnBaseUrl:this.config.cdnBase,encryptQueryParam:g.media.encrypt_query_param,fullUrl:g.media.full_url,aesKeyBase64:g.media.aes_key,fetchFn:e}),C=`${ge}/${Date.now()}-${Pe(4).toString("hex")}.mp4`;await ke(C,w),h.push({path:C,mime:"video/mp4"})}}catch(g){A("warn",`Failed to download quoted media type=${y.type}: ${String(g)}`,this.config)}if(!c&&h.length===0){A("debug",`Non-text/media message from ${u.from_user_id}, skipping`,this.config);continue}let _=`wechat:${u.from_user_id}`,b=this.sessions.get(_);b?u.context_token&&(b.contextToken=u.context_token):this.sessions.set(_,{toUser:u.from_user_id,contextToken:u.context_token,cursor:""}),A("info",`Ingress from ${u.from_user_id} text=${JSON.stringify(c.slice(0,80))} attachments=${h.length}`,this.config),this.getTypingTicket(u.from_user_id,u.context_token,e).then(g=>{if(!g)return;let w=this.sessions.get(_);w&&(w.stopTyping?.(),w.stopTyping=this.startTyping(u.from_user_id,g,e))});try{await fo(this.config.daemonUrl,{session_key:_,text:c||void 0,attachments:h,idempotency_key:String(u.message_id),source_kind:"wechat",channel_id:`wechat-${u.from_user_id.replace(/[^A-Za-z0-9_-]/g,"_")}`},e)}catch(g){A("error",`ingress failed for ${_}: ${String(g)}`,this.config)}}}catch(n){if(n?.name==="AbortError")return;if(r++,n instanceof Z&&n.errcode===-14){A("warn","Token invalid (-14), triggering re-login",this.config),this.auth.invalidateToken(),r=0;continue}A("error",`ingressLoop error (${r}): ${String(n)}`,this.config),r>=un&&(A("warn",`Backing off ${Po}ms after ${un} errors`,this.config),await Ut(Po),r=0)}}}async pullLoop(e){A("info","pullLoop started (WebSocket mode)",this.config);let r="wechat:__cap_heartbeat__",n;n=null;let i=()=>{n||(A("debug","Registering capability heartbeat WS",this.config),n=Xr({daemonUrl:this.config.daemonUrl,sessionKey:r,consumerId:To,sourceKind:"wechat",onOutput:async()=>{},onAck:()=>{},onError:()=>{},onClose:()=>{n=null,this.running&&setTimeout(i,ko)}}))};i();let s=new Map,o=new Map,a=(c,h)=>{if(s.has(c))return;A("info",`WS subscribing for ${c}`,this.config);let y=Xr({daemonUrl:this.config.daemonUrl,sessionKey:c,consumerId:To,cursor:h.cursor||void 0,sourceKind:"wechat",onOutput:async _=>{let b=await this.auth.getToken(),g=this.auth.getApiBase(),w=this.filterOutboundText(_.text??""),C=_.attachments??[],E=C.length===0?Hf(_):[];if(C.length>0)for(let x=0;x<C.length;x++){let I=C[x],O=x===C.length-1,N=O?w:"";A("info",`Sending attachment to ${h.toUser}: ${I.path} (${I.mime})`,this.config);try{let v=await co(this.config.daemonUrl,I.path,e),L=I.mime.startsWith("image/"),G=I.mime.startsWith("audio/"),z=I.mime.startsWith("video/");if(G){let{silk:U,playtimeMs:F}=await ln(v,I.mime),X=await this.withRetry(()=>ft({apiBase:g,cdnBase:this.config.cdnBase,token:b,filePath:U,toUserId:h.toUser,mediaType:Kr,fetchFn:e}),"uploadMedia(voice)");await this.withRetry(()=>le(g,b,h.toUser,N,h.contextToken,e,{kind:"voice",item:{encryptQueryParam:X.encryptQueryParam,aesKeyBase64:X.aesKeyBase64,playtimeMs:F}}),"sendMessage(voice)")}else{let U=await this.withRetry(()=>ft({apiBase:g,cdnBase:this.config.cdnBase,token:b,filePath:v,toUserId:h.toUser,mediaType:L?vt:z?Vr:Jr,fetchFn:e}),L?"uploadMedia(image)":z?"uploadMedia(video)":"uploadMedia(file)"),F=Ft(I.path)||"file";await this.withRetry(()=>le(g,b,h.toUser,N,h.contextToken,e,L?{encryptQueryParam:U.encryptQueryParam,aesKeyBase64:U.aesKeyBase64,midSize:U.fileSizeCiphertext}:z?{kind:"video",item:{encryptQueryParam:U.encryptQueryParam,aesKeyBase64:U.aesKeyBase64,videoSize:U.fileSizeCiphertext}}:{kind:"file",item:{encryptQueryParam:U.encryptQueryParam,aesKeyBase64:U.aesKeyBase64,fileName:F,fileSize:U.rawSize}}),L?"sendMessage(image)":z?"sendMessage(video)":"sendMessage(file)")}}catch(v){v instanceof Z&&v.errcode===-14&&this.auth.invalidateToken(),A("error",`sendAttachment failed to ${h.toUser}: ${String(v)}`,this.config),O&&_.text&&await this.withRetry(()=>le(g,b,h.toUser,w,h.contextToken,e),"sendMessage(fallback)").catch(L=>A("error",`sendMessage fallback failed: ${String(L)}`,this.config))}}else if(E.length>0)for(let x=0;x<E.length;x++){let I=E[x],O=x===E.length-1,N=O?w:"";try{let v=zf(I),L=v?void 0:await this.downloadRemoteMedia(I,e),G=L?.buffer,z=v?ht(v):L?.mime??"application/octet-stream",U=z.startsWith("image/"),F=z.startsWith("audio/"),X=z.startsWith("video/");if(F){let Ne=G??await this.readLocalMedia(v),{silk:J,playtimeMs:$e}=await ln(Ne,z),Se=await this.withRetry(()=>ft({apiBase:g,cdnBase:this.config.cdnBase,token:b,filePath:J,toUserId:h.toUser,mediaType:Kr,fetchFn:e}),"uploadMedia(voice-url)");await this.withRetry(()=>le(g,b,h.toUser,N,h.contextToken,e,{kind:"voice",item:{encryptQueryParam:Se.encryptQueryParam,aesKeyBase64:Se.aesKeyBase64,playtimeMs:$e}}),"sendMessage(voice-url)")}else{let Ne=G??v,J=await this.withRetry(()=>ft({apiBase:g,cdnBase:this.config.cdnBase,token:b,filePath:Ne,toUserId:h.toUser,mediaType:U?vt:X?Vr:Jr,fetchFn:e}),U?"uploadMedia(image-url)":X?"uploadMedia(video-url)":"uploadMedia(file-url)"),$e=v?Ft(v):L?.fileName??Ft(I.split("?")[0]??"file");await this.withRetry(()=>le(g,b,h.toUser,N,h.contextToken,e,U?{encryptQueryParam:J.encryptQueryParam,aesKeyBase64:J.aesKeyBase64,midSize:J.fileSizeCiphertext}:X?{kind:"video",item:{encryptQueryParam:J.encryptQueryParam,aesKeyBase64:J.aesKeyBase64,videoSize:J.fileSizeCiphertext}}:{kind:"file",item:{encryptQueryParam:J.encryptQueryParam,aesKeyBase64:J.aesKeyBase64,fileName:$e,fileSize:J.rawSize}}),U?"sendMessage(image-url)":X?"sendMessage(video-url)":"sendMessage(file-url)")}}catch(v){v instanceof Z&&v.errcode===-14&&this.auth.invalidateToken(),A("error",`sendMediaUrl failed to ${h.toUser}: ${String(v)}`,this.config),O&&_.text&&await this.withRetry(()=>le(g,b,h.toUser,w,h.contextToken,e),"sendMessage(mediaUrl-fallback)").catch(L=>A("error",`sendMessage mediaUrl fallback failed: ${String(L)}`,this.config))}}else if(w){A("info",`Sending reply to ${h.toUser}: ${w.slice(0,60)}`,this.config);try{await this.withRetry(()=>le(g,b,h.toUser,w,h.contextToken,e),"sendMessage(text)")}catch(x){x instanceof Z&&x.errcode===-14&&this.auth.invalidateToken(),A("error",`sendMessage failed to ${h.toUser}: ${String(x)}`,this.config),this.outbox&&await this.outbox.enqueue({sessionKey:c,toUser:h.toUser,contextToken:h.contextToken,text:w,attachments:[]}).catch(I=>A("warn",`outbox.enqueue failed: ${String(I)}`,this.config))}}h.stopTyping&&(h.stopTyping(),h.stopTyping=void 0)},onAck:_=>{h.cursor=_,o.set(c,0)},onError:_=>{let b=(o.get(c)??0)+1;o.set(c,b),A("error",`WS error for ${c} (${b}): ${String(_)}`,this.config)},onClose:()=>{if(s.delete(c),!this.running)return;let b=(o.get(c)??0)>=un?qf:ko;A("info",`WS closed for ${c}, reconnecting in ${b}ms`,this.config),setTimeout(()=>{if(this.running&&this.sessions.has(c)){let g=this.sessions.get(c);a(c,g)}},b)}});s.set(c,y)};for(;this.running;){for(let[c,h]of this.sessions)a(c,h);for(let[c,h]of s)this.sessions.has(c)||(h(),s.delete(c));await Ut(1e3,this.abortController.signal)}let u=n;n=null,u?.();for(let c of s.values())c();s.clear()}async getTypingTicket(e,r,n){let i=this.typingTickets.get(e);if(i&&Date.now()-i.fetchedAt<this.TYPING_TICKET_TTL_MS)return i.ticket;try{let s=await this.auth.getToken(),o=await Hn(this.auth.getApiBase(),s,e,r,n);if(o.typing_ticket)return this.typingTickets.set(e,{ticket:o.typing_ticket,fetchedAt:Date.now()}),o.typing_ticket}catch(s){A("debug",`getTypingTicket failed for ${e}: ${String(s)}`,this.config)}}startTyping(e,r,n){let i=async o=>{try{let a=await this.auth.getToken();await zn(this.auth.getApiBase(),a,e,r,o,n)}catch{}};i(1);let s=setInterval(()=>{i(1)},5e3);return()=>{clearInterval(s),i(2)}}async readLocalMedia(e){return Uf(e)}async downloadRemoteMedia(e,r){let n=await r(e);if(!n.ok){let a=await n.text().catch(()=>"(unreadable)");throw new Error(`Remote media download failed: ${n.status} ${n.statusText} body=${a}`)}let s=n.headers?.get("content-type")?.split(";")[0]?.trim().toLowerCase()||ht(new URL(e).pathname),o=Qf(e,s);return{buffer:Buffer.from(await n.arrayBuffer()),mime:s,fileName:o}}filterOutboundText(e){let r=new $t;return r.feed(e)+r.flush()}async withRetry(e,r,n={}){let i=n.maxAttempts??3,s=n.baseMs??500,o;for(let a=1;a<=i;a++)try{return await e()}catch(u){if(o=u,u instanceof Z&&[-14,400,403].includes(u.errcode))throw u;if(a<i){let c=s*Math.pow(2,a-1);A("warn",`${r} attempt ${a}/${i} failed, retry in ${c}ms: ${String(u)}`,this.config),await Ut(c)}}throw o}async replayOutbox(e){if(!this.outbox)return;await Ut(5e3);let r=await this.outbox.getPending();if(r.length!==0){A("info",`Replaying ${r.length} outbox pending records`,this.config);for(let n of r){if(!this.running)break;try{let i=await this.auth.getToken(),s=this.auth.getApiBase();await this.withRetry(()=>le(s,i,n.toUser,n.text,n.contextToken,e),"outbox.replay"),await this.outbox.markSent(n.id),A("info",`Outbox replayed ${n.id} to ${n.toUser}`,this.config)}catch(i){await this.outbox.markFailed(n.id,String(i)),A("warn",`Outbox replay failed for ${n.id}: ${String(i)}`,this.config)}}}}isAllowed(e){return this.config.dmPolicy==="open"?!0:this.config.allowFrom.includes(e)}};function ht(t){let e=fn(t).toLowerCase();return{".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".zip":"application/zip",".txt":"text/plain",".csv":"text/csv",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".mp4":"video/mp4",".mov":"video/quicktime",".mp3":"audio/mpeg",".m4a":"audio/mp4",".wav":"audio/wav"}[e]??"application/octet-stream"}function jf(t){return{"application/pdf":".pdf","application/msword":".doc","application/vnd.openxmlformats-officedocument.wordprocessingml.document":".docx","application/vnd.ms-excel":".xls","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":".xlsx","application/vnd.ms-powerpoint":".ppt","application/vnd.openxmlformats-officedocument.presentationml.presentation":".pptx","application/zip":".zip","text/plain":".txt","text/csv":".csv","application/json":".json","image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp","video/mp4":".mp4","video/quicktime":".mov","audio/mpeg":".mp3","audio/mp4":".m4a","audio/wav":".wav"}[t]}function Qf(t,e){let r=new URL(t).pathname,n=Ft(r)||"file";if(ht(n)!=="application/octet-stream")return n;let i=jf(e);return i?`${n}${i}`:n}function Ut(t,e){return new Promise(r=>{let n=setTimeout(r,t);e?.addEventListener("abort",()=>{clearTimeout(n),r()},{once:!0})})}import Gf from"node:http";function xo(t,e){let r=Gf.createServer((n,i)=>{if(n.method!=="GET"||n.url!=="/health"){i.writeHead(404),i.end("Not Found");return}if(!t.running){i.writeHead(503,{"Content-Type":"application/json"}),i.end(JSON.stringify({status:"unavailable",reason:"gateway_stopped"}));return}let s=t.tokenObtainedAt>0?Date.now()-t.tokenObtainedAt:1/0;if(s>72e6){i.writeHead(503,{"Content-Type":"application/json"}),i.end(JSON.stringify({status:"token_stale",token_age_hours:Math.floor(s/36e5)}));return}i.writeHead(200,{"Content-Type":"application/json"}),i.end(JSON.stringify({status:"ok",uptime_seconds:Math.floor(process.uptime()),token_age_hours:Math.floor(s/36e5)}))});return r.listen(e,()=>{console.log(`[INFO] [wechat-channel] Health check listening on :${e}/health`)}),r}import{appendFile as Yf,readFile as Vf,writeFile as Jf,mkdir as Bo,rename as Kf}from"node:fs/promises";import{existsSync as Zf}from"node:fs";import{dirname as Ro}from"node:path";import{randomBytes as Xf}from"node:crypto";var ec=3,Dt=class{constructor(e){this.filePath=e}writeChain=Promise.resolve();async enqueue(e){let r=Xf(8).toString("hex"),n={...e,id:r,createdAt:Date.now(),attempts:0},i=JSON.stringify(n)+`
|
|
62
|
+
`;return this.writeChain=this.writeChain.then(async()=>{await Bo(Ro(this.filePath),{recursive:!0}),await Yf(this.filePath,i,"utf8")}),await this.writeChain,r}async getPending(e=ec){return(await this.readAll()).filter(n=>n.attempts<e).sort((n,i)=>n.createdAt-i.createdAt)}async markSent(e){await this.rewrite(r=>r.filter(n=>n.id!==e))}async markFailed(e,r){await this.rewrite(n=>n.map(i=>i.id===e?{...i,attempts:i.attempts+1,lastError:r}:i))}async readAll(){if(!Zf(this.filePath))return[];let e=await Vf(this.filePath,"utf8"),r=[];for(let n of e.split(`
|
|
63
|
+
`)){let i=n.trim();if(i)try{r.push(JSON.parse(i))}catch{}}return r}async rewrite(e){this.writeChain=this.writeChain.then(async()=>{await Bo(Ro(this.filePath),{recursive:!0});let r=await this.readAll(),n=e(r),i=n.map(o=>JSON.stringify(o)).join(`
|
|
64
64
|
`)+(n.length>0?`
|
|
65
|
-
`:""),s=this.filePath+".tmp";await
|
|
65
|
+
`:""),s=this.filePath+".tmp";await Jf(s,i,"utf8"),await Kf(s,this.filePath)}),await this.writeChain}};var Wt="/tmp/channel-wechat.pid";function ac(){if(ic(Wt)){let t=parseInt(rc(Wt,"utf-8").trim(),10);try{process.kill(t,0),console.error(`[ERROR] Another channel-wechat process is already running (PID ${t}). Exiting.`),process.exit(1)}catch{console.warn(`[WARN] Stale pidfile found (PID ${t} is dead), overwriting.`)}}tc(Wt,String(process.pid),"utf-8")}function cn(){try{nc(Wt)}catch{}}function lc(t){for(let e=0;e<t.length;e+=1){let r=t[e];if(r==="--state-dir")return t[e+1];if(r.startsWith("--state-dir="))return r.slice(12)}}async function uc(t){let e=lc(t)??tr();await io(e)}async function fc(){ac();let t;try{t=$n()}catch(u){cn(),console.error(`[ERROR] Configuration error: ${String(u)}`),process.exit(1)}console.log("[INFO] [wechat-channel] Starting openduo WeChat channel adapter"),console.log(`[INFO] [wechat-channel] Daemon: ${t.daemonUrl}`),console.log(`[INFO] [wechat-channel] DM policy: ${t.dmPolicy}`),console.log(`[INFO] [wechat-channel] State dir: ${t.stateDir}`);let e=new It(t.stateDir,t.apiBase);try{await e.getToken()}catch(u){console.error(`[ERROR] Authentication failed: ${String(u)}`),process.exit(1)}let r=new Dt(sc(t.stateDir,"outbox.jsonl")),n=new qt(t,e,fetch,r);n.start();let i=parseInt(process.env.WECHAT_HEALTH_PORT??"8765",10),s={running:!0,tokenObtainedAt:e.tokenObtainedAt},o=xo(s,i),a=setInterval(()=>{s.tokenObtainedAt=e.tokenObtainedAt},6e4);for(let u of["SIGINT","SIGTERM"])process.on(u,()=>{console.log(`
|
|
66
66
|
[INFO] [wechat-channel] Received ${u}, shutting down\u2026`),s.running=!1,clearInterval(a),o.close(),n.stop(),cn(),process.exit(0)});process.on("exit",cn)}async function cc(t=process.argv.slice(2)){let[e,...r]=t;if(e==="qrcode-terminal"){await uc(r);return}await fc()}var Ao=process.argv[1],hc=!!Ao&&import.meta.url===oc(Ao).href;hc&&cc().catch(t=>{console.error("[FATAL]",t),process.exit(1)});export{cc as runCli};
|