imapkit 5.1.0 → 5.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +41 -23
- package/bin/help.txt +29 -3
- package/bin/imapkit.js +43 -0
- package/dist/browser/imapkit.js +99 -35
- package/dist/cjs/control.d.ts +16 -5
- package/dist/cjs/control.js +36 -5
- package/dist/cjs/oauth/http.d.ts +28 -0
- package/dist/cjs/oauth/http.js +216 -0
- package/dist/cjs/oauth/jwt.d.ts +33 -0
- package/dist/cjs/oauth/jwt.js +58 -0
- package/dist/cjs/oauth/pages.d.ts +47 -0
- package/dist/cjs/oauth/pages.js +310 -0
- package/dist/cjs/oauth/policy.d.ts +48 -0
- package/dist/cjs/oauth/policy.js +66 -0
- package/dist/cjs/oauth/provider.d.ts +455 -0
- package/dist/cjs/oauth/provider.js +1422 -0
- package/dist/cjs/plugins/oauthbearer.js +10 -15
- package/dist/cjs/plugins/xoauth2.js +4 -3
- package/dist/cjs/rest.d.ts +18 -1
- package/dist/cjs/rest.js +63 -35
- package/dist/cjs/server.d.ts +49 -1
- package/dist/cjs/server.js +126 -12
- package/dist/cjs/smtp-listener.d.ts +3 -2
- package/dist/cjs/smtp-listener.js +15 -3
- package/dist/cjs/types.d.ts +16 -0
- package/dist/esm/control.d.ts +16 -5
- package/dist/esm/control.js +36 -6
- package/dist/esm/oauth/http.d.ts +28 -0
- package/dist/esm/oauth/http.js +211 -0
- package/dist/esm/oauth/jwt.d.ts +33 -0
- package/dist/esm/oauth/jwt.js +50 -0
- package/dist/esm/oauth/pages.d.ts +47 -0
- package/dist/esm/oauth/pages.js +305 -0
- package/dist/esm/oauth/policy.d.ts +48 -0
- package/dist/esm/oauth/policy.js +59 -0
- package/dist/esm/oauth/provider.d.ts +455 -0
- package/dist/esm/oauth/provider.js +1415 -0
- package/dist/esm/plugins/oauthbearer.js +10 -15
- package/dist/esm/plugins/xoauth2.js +4 -3
- package/dist/esm/rest.d.ts +18 -1
- package/dist/esm/rest.js +62 -36
- package/dist/esm/server.d.ts +49 -1
- package/dist/esm/server.js +127 -13
- package/dist/esm/smtp-listener.d.ts +3 -2
- package/dist/esm/smtp-listener.js +15 -3
- package/dist/esm/types.d.ts +16 -0
- package/dist/plugin-help.json +2 -2
- package/package.json +7 -7
package/dist/browser/imapkit.js
CHANGED
|
@@ -1,42 +1,106 @@
|
|
|
1
|
-
var Ju=Object.create;var Es=Object.defineProperty;var Zu=Object.getOwnPropertyDescriptor;var tl=Object.getOwnPropertyNames;var el=Object.getPrototypeOf,rl=Object.prototype.hasOwnProperty;var gs=(r,t,e)=>()=>{if(e)throw e[0];try{return r&&(t=r(r=0)),t}catch(s){throw e=[s],s}};var Ze=(r,t)=>()=>{try{return t||r((t={exports:{}}).exports,t),t.exports}catch(e){throw t=0,e}},sl=(r,t)=>{for(var e in t)Es(r,e,{get:t[e],enumerable:!0})},nl=(r,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of tl(t))!rl.call(r,n)&&n!==e&&Es(r,n,{get:()=>t[n],enumerable:!(s=Zu(t,n))||s.enumerable});return r};var Ce=(r,t,e)=>(e=r!=null?Ju(el(r)):{},nl(t||!r||!r.__esModule?Es(e,"default",{value:r,enumerable:!0}):e,r));var ha=Ze(tr=>{"use strict";E();tr.byteLength=al;tr.toByteArray=ul;tr.fromByteArray=fl;var Dt=[],St=[],il=typeof Uint8Array<"u"?Uint8Array:Array,As="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Qt=0,ca=As.length;Qt<ca;++Qt)Dt[Qt]=As[Qt],St[As.charCodeAt(Qt)]=Qt;var Qt,ca;St[45]=62;St[95]=63;function fa(r){var t=r.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var e=r.indexOf("=");e===-1&&(e=t);var s=e===t?0:4-e%4;return[e,s]}function al(r){var t=fa(r),e=t[0],s=t[1];return(e+s)*3/4-s}function ol(r,t,e){return(t+e)*3/4-e}function ul(r){var t,e=fa(r),s=e[0],n=e[1],i=new il(ol(r,s,n)),a=0,o=n>0?s-4:s,u;for(u=0;u<o;u+=4)t=St[r.charCodeAt(u)]<<18|St[r.charCodeAt(u+1)]<<12|St[r.charCodeAt(u+2)]<<6|St[r.charCodeAt(u+3)],i[a++]=t>>16&255,i[a++]=t>>8&255,i[a++]=t&255;return n===2&&(t=St[r.charCodeAt(u)]<<2|St[r.charCodeAt(u+1)]>>4,i[a++]=t&255),n===1&&(t=St[r.charCodeAt(u)]<<10|St[r.charCodeAt(u+1)]<<4|St[r.charCodeAt(u+2)]>>2,i[a++]=t>>8&255,i[a++]=t&255),i}function ll(r){return Dt[r>>18&63]+Dt[r>>12&63]+Dt[r>>6&63]+Dt[r&63]}function cl(r,t,e){for(var s,n=[],i=t;i<e;i+=3)s=(r[i]<<16&16711680)+(r[i+1]<<8&65280)+(r[i+2]&255),n.push(ll(s));return n.join("")}function fl(r){for(var t,e=r.length,s=e%3,n=[],i=16383,a=0,o=e-s;a<o;a+=i)n.push(cl(r,a,a+i>o?o:a+i));return s===1?(t=r[e-1],n.push(Dt[t>>2]+Dt[t<<4&63]+"==")):s===2&&(t=(r[e-2]<<8)+r[e-1],n.push(Dt[t>>10]+Dt[t>>4&63]+Dt[t<<2&63]+"=")),n.join("")}});var da=Ze(Ts=>{E();Ts.read=function(r,t,e,s,n){var i,a,o=n*8-s-1,u=(1<<o)-1,l=u>>1,c=-7,h=e?n-1:0,m=e?-1:1,T=r[t+h];for(h+=m,i=T&(1<<-c)-1,T>>=-c,c+=o;c>0;i=i*256+r[t+h],h+=m,c-=8);for(a=i&(1<<-c)-1,i>>=-c,c+=s;c>0;a=a*256+r[t+h],h+=m,c-=8);if(i===0)i=1-l;else{if(i===u)return a?NaN:(T?-1:1)*(1/0);a=a+Math.pow(2,s),i=i-l}return(T?-1:1)*a*Math.pow(2,i-s)};Ts.write=function(r,t,e,s,n,i){var a,o,u,l=i*8-n-1,c=(1<<l)-1,h=c>>1,m=n===23?Math.pow(2,-24)-Math.pow(2,-77):0,T=s?0:i-1,A=s?1:-1,p=t<0||t===0&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(o=isNaN(t)?1:0,a=c):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),a+h>=1?t+=m/u:t+=m*Math.pow(2,1-h),t*u>=2&&(a++,u/=2),a+h>=c?(o=0,a=c):a+h>=1?(o=(t*u-1)*Math.pow(2,n),a=a+h):(o=t*Math.pow(2,h-1)*Math.pow(2,n),a=0));n>=8;r[e+T]=o&255,T+=A,o/=256,n-=8);for(a=a<<n|o,l+=n;l>0;r[e+T]=a&255,T+=A,a/=256,l-=8);r[e+T-A]|=p*128}});var Ms=Ze(le=>{"use strict";E();var ys=ha(),oe=da(),pa=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;le.Buffer=H;le.SlowBuffer=gl;le.INSPECT_MAX_BYTES=50;var er=2147483647;le.kMaxLength=er;H.TYPED_ARRAY_SUPPORT=hl();!H.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function hl(){try{let r=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(r,t),r.foo()===42}catch{return!1}}Object.defineProperty(H.prototype,"parent",{enumerable:!0,get:function(){if(H.isBuffer(this))return this.buffer}});Object.defineProperty(H.prototype,"offset",{enumerable:!0,get:function(){if(H.isBuffer(this))return this.byteOffset}});function Bt(r){if(r>er)throw new RangeError('The value "'+r+'" is invalid for option "size"');let t=new Uint8Array(r);return Object.setPrototypeOf(t,H.prototype),t}function H(r,t,e){if(typeof r=="number"){if(typeof t=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return Os(r)}return Aa(r,t,e)}H.poolSize=8192;function Aa(r,t,e){if(typeof r=="string")return pl(r,t);if(ArrayBuffer.isView(r))return ml(r);if(r==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof r);if(Lt(r,ArrayBuffer)||r&&Lt(r.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Lt(r,SharedArrayBuffer)||r&&Lt(r.buffer,SharedArrayBuffer)))return bs(r,t,e);if(typeof r=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let s=r.valueOf&&r.valueOf();if(s!=null&&s!==r)return H.from(s,t,e);let n=El(r);if(n)return n;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof r[Symbol.toPrimitive]=="function")return H.from(r[Symbol.toPrimitive]("string"),t,e);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof r)}H.from=function(r,t,e){return Aa(r,t,e)};Object.setPrototypeOf(H.prototype,Uint8Array.prototype);Object.setPrototypeOf(H,Uint8Array);function Ta(r){if(typeof r!="number")throw new TypeError('"size" argument must be of type number');if(r<0)throw new RangeError('The value "'+r+'" is invalid for option "size"')}function dl(r,t,e){return Ta(r),r<=0?Bt(r):t!==void 0?typeof e=="string"?Bt(r).fill(t,e):Bt(r).fill(t):Bt(r)}H.alloc=function(r,t,e){return dl(r,t,e)};function Os(r){return Ta(r),Bt(r<0?0:Ns(r)|0)}H.allocUnsafe=function(r){return Os(r)};H.allocUnsafeSlow=function(r){return Os(r)};function pl(r,t){if((typeof t!="string"||t==="")&&(t="utf8"),!H.isEncoding(t))throw new TypeError("Unknown encoding: "+t);let e=ya(r,t)|0,s=Bt(e),n=s.write(r,t);return n!==e&&(s=s.slice(0,n)),s}function Ss(r){let t=r.length<0?0:Ns(r.length)|0,e=Bt(t);for(let s=0;s<t;s+=1)e[s]=r[s]&255;return e}function ml(r){if(Lt(r,Uint8Array)){let t=new Uint8Array(r);return bs(t.buffer,t.byteOffset,t.byteLength)}return Ss(r)}function bs(r,t,e){if(t<0||r.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(r.byteLength<t+(e||0))throw new RangeError('"length" is outside of buffer bounds');let s;return t===void 0&&e===void 0?s=new Uint8Array(r):e===void 0?s=new Uint8Array(r,t):s=new Uint8Array(r,t,e),Object.setPrototypeOf(s,H.prototype),s}function El(r){if(H.isBuffer(r)){let t=Ns(r.length)|0,e=Bt(t);return e.length===0||r.copy(e,0,0,t),e}if(r.length!==void 0)return typeof r.length!="number"||xs(r.length)?Bt(0):Ss(r);if(r.type==="Buffer"&&Array.isArray(r.data))return Ss(r.data)}function Ns(r){if(r>=er)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+er.toString(16)+" bytes");return r|0}function gl(r){return+r!=r&&(r=0),H.alloc(+r)}H.isBuffer=function(t){return t!=null&&t._isBuffer===!0&&t!==H.prototype};H.compare=function(t,e){if(Lt(t,Uint8Array)&&(t=H.from(t,t.offset,t.byteLength)),Lt(e,Uint8Array)&&(e=H.from(e,e.offset,e.byteLength)),!H.isBuffer(t)||!H.isBuffer(e))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(t===e)return 0;let s=t.length,n=e.length;for(let i=0,a=Math.min(s,n);i<a;++i)if(t[i]!==e[i]){s=t[i],n=e[i];break}return s<n?-1:n<s?1:0};H.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}};H.concat=function(t,e){if(!Array.isArray(t))throw new TypeError('"list" argument must be an Array of Buffers');if(t.length===0)return H.alloc(0);let s;if(e===void 0)for(e=0,s=0;s<t.length;++s)e+=t[s].length;let n=H.allocUnsafe(e),i=0;for(s=0;s<t.length;++s){let a=t[s];if(Lt(a,Uint8Array))i+a.length>n.length?(H.isBuffer(a)||(a=H.from(a)),a.copy(n,i)):Uint8Array.prototype.set.call(n,a,i);else if(H.isBuffer(a))a.copy(n,i);else throw new TypeError('"list" argument must be an Array of Buffers');i+=a.length}return n};function ya(r,t){if(H.isBuffer(r))return r.length;if(ArrayBuffer.isView(r)||Lt(r,ArrayBuffer))return r.byteLength;if(typeof r!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof r);let e=r.length,s=arguments.length>2&&arguments[2]===!0;if(!s&&e===0)return 0;let n=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return e;case"utf8":case"utf-8":return Is(r).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return e*2;case"hex":return e>>>1;case"base64":return wa(r).length;default:if(n)return s?-1:Is(r).length;t=(""+t).toLowerCase(),n=!0}}H.byteLength=ya;function Al(r,t,e){let s=!1;if((t===void 0||t<0)&&(t=0),t>this.length||((e===void 0||e>this.length)&&(e=this.length),e<=0)||(e>>>=0,t>>>=0,e<=t))return"";for(r||(r="utf8");;)switch(r){case"hex":return Ml(this,t,e);case"utf8":case"utf-8":return ba(this,t,e);case"ascii":return Cl(this,t,e);case"latin1":case"binary":return xl(this,t,e);case"base64":return Ol(this,t,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return wl(this,t,e);default:if(s)throw new TypeError("Unknown encoding: "+r);r=(r+"").toLowerCase(),s=!0}}H.prototype._isBuffer=!0;function Yt(r,t,e){let s=r[t];r[t]=r[e],r[e]=s}H.prototype.swap16=function(){let t=this.length;if(t%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let e=0;e<t;e+=2)Yt(this,e,e+1);return this};H.prototype.swap32=function(){let t=this.length;if(t%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let e=0;e<t;e+=4)Yt(this,e,e+3),Yt(this,e+1,e+2);return this};H.prototype.swap64=function(){let t=this.length;if(t%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let e=0;e<t;e+=8)Yt(this,e,e+7),Yt(this,e+1,e+6),Yt(this,e+2,e+5),Yt(this,e+3,e+4);return this};H.prototype.toString=function(){let t=this.length;return t===0?"":arguments.length===0?ba(this,0,t):Al.apply(this,arguments)};H.prototype.toLocaleString=H.prototype.toString;H.prototype.equals=function(t){if(!H.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t?!0:H.compare(this,t)===0};H.prototype.inspect=function(){let t="",e=le.INSPECT_MAX_BYTES;return t=this.toString("hex",0,e).replace(/(.{2})/g,"$1 ").trim(),this.length>e&&(t+=" ... "),"<Buffer "+t+">"};pa&&(H.prototype[pa]=H.prototype.inspect);H.prototype.compare=function(t,e,s,n,i){if(Lt(t,Uint8Array)&&(t=H.from(t,t.offset,t.byteLength)),!H.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(e===void 0&&(e=0),s===void 0&&(s=t?t.length:0),n===void 0&&(n=0),i===void 0&&(i=this.length),e<0||s>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=s)return 0;if(n>=i)return-1;if(e>=s)return 1;if(e>>>=0,s>>>=0,n>>>=0,i>>>=0,this===t)return 0;let a=i-n,o=s-e,u=Math.min(a,o),l=this.slice(n,i),c=t.slice(e,s);for(let h=0;h<u;++h)if(l[h]!==c[h]){a=l[h],o=c[h];break}return a<o?-1:o<a?1:0};function Sa(r,t,e,s,n){if(r.length===0)return-1;if(typeof e=="string"?(s=e,e=0):e>2147483647?e=2147483647:e<-2147483648&&(e=-2147483648),e=+e,xs(e)&&(e=n?0:r.length-1),e<0&&(e=r.length+e),e>=r.length){if(n)return-1;e=r.length-1}else if(e<0)if(n)e=0;else return-1;if(typeof t=="string"&&(t=H.from(t,s)),H.isBuffer(t))return t.length===0?-1:ma(r,t,e,s,n);if(typeof t=="number")return t=t&255,typeof Uint8Array.prototype.indexOf=="function"?n?Uint8Array.prototype.indexOf.call(r,t,e):Uint8Array.prototype.lastIndexOf.call(r,t,e):ma(r,[t],e,s,n);throw new TypeError("val must be string, number or Buffer")}function ma(r,t,e,s,n){let i=1,a=r.length,o=t.length;if(s!==void 0&&(s=String(s).toLowerCase(),s==="ucs2"||s==="ucs-2"||s==="utf16le"||s==="utf-16le")){if(r.length<2||t.length<2)return-1;i=2,a/=2,o/=2,e/=2}function u(c,h){return i===1?c[h]:c.readUInt16BE(h*i)}let l;if(n){let c=-1;for(l=e;l<a;l++)if(u(r,l)===u(t,c===-1?0:l-c)){if(c===-1&&(c=l),l-c+1===o)return c*i}else c!==-1&&(l-=l-c),c=-1}else for(e+o>a&&(e=a-o),l=e;l>=0;l--){let c=!0;for(let h=0;h<o;h++)if(u(r,l+h)!==u(t,h)){c=!1;break}if(c)return l}return-1}H.prototype.includes=function(t,e,s){return this.indexOf(t,e,s)!==-1};H.prototype.indexOf=function(t,e,s){return Sa(this,t,e,s,!0)};H.prototype.lastIndexOf=function(t,e,s){return Sa(this,t,e,s,!1)};function Tl(r,t,e,s){e=Number(e)||0;let n=r.length-e;s?(s=Number(s),s>n&&(s=n)):s=n;let i=t.length;s>i/2&&(s=i/2);let a;for(a=0;a<s;++a){let o=parseInt(t.substr(a*2,2),16);if(xs(o))return a;r[e+a]=o}return a}function yl(r,t,e,s){return rr(Is(t,r.length-e),r,e,s)}function Sl(r,t,e,s){return rr(Ul(t),r,e,s)}function bl(r,t,e,s){return rr(wa(t),r,e,s)}function Il(r,t,e,s){return rr(Bl(t,r.length-e),r,e,s)}H.prototype.write=function(t,e,s,n){if(e===void 0)n="utf8",s=this.length,e=0;else if(s===void 0&&typeof e=="string")n=e,s=this.length,e=0;else if(isFinite(e))e=e>>>0,isFinite(s)?(s=s>>>0,n===void 0&&(n="utf8")):(n=s,s=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let i=this.length-e;if((s===void 0||s>i)&&(s=i),t.length>0&&(s<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let a=!1;for(;;)switch(n){case"hex":return Tl(this,t,e,s);case"utf8":case"utf-8":return yl(this,t,e,s);case"ascii":case"latin1":case"binary":return Sl(this,t,e,s);case"base64":return bl(this,t,e,s);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Il(this,t,e,s);default:if(a)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),a=!0}};H.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Ol(r,t,e){return t===0&&e===r.length?ys.fromByteArray(r):ys.fromByteArray(r.slice(t,e))}function ba(r,t,e){e=Math.min(r.length,e);let s=[],n=t;for(;n<e;){let i=r[n],a=null,o=i>239?4:i>223?3:i>191?2:1;if(n+o<=e){let u,l,c,h;switch(o){case 1:i<128&&(a=i);break;case 2:u=r[n+1],(u&192)===128&&(h=(i&31)<<6|u&63,h>127&&(a=h));break;case 3:u=r[n+1],l=r[n+2],(u&192)===128&&(l&192)===128&&(h=(i&15)<<12|(u&63)<<6|l&63,h>2047&&(h<55296||h>57343)&&(a=h));break;case 4:u=r[n+1],l=r[n+2],c=r[n+3],(u&192)===128&&(l&192)===128&&(c&192)===128&&(h=(i&15)<<18|(u&63)<<12|(l&63)<<6|c&63,h>65535&&h<1114112&&(a=h))}}a===null?(a=65533,o=1):a>65535&&(a-=65536,s.push(a>>>10&1023|55296),a=56320|a&1023),s.push(a),n+=o}return Nl(s)}var Ea=4096;function Nl(r){let t=r.length;if(t<=Ea)return String.fromCharCode.apply(String,r);let e="",s=0;for(;s<t;)e+=String.fromCharCode.apply(String,r.slice(s,s+=Ea));return e}function Cl(r,t,e){let s="";e=Math.min(r.length,e);for(let n=t;n<e;++n)s+=String.fromCharCode(r[n]&127);return s}function xl(r,t,e){let s="";e=Math.min(r.length,e);for(let n=t;n<e;++n)s+=String.fromCharCode(r[n]);return s}function Ml(r,t,e){let s=r.length;(!t||t<0)&&(t=0),(!e||e<0||e>s)&&(e=s);let n="";for(let i=t;i<e;++i)n+=Hl[r[i]];return n}function wl(r,t,e){let s=r.slice(t,e),n="";for(let i=0;i<s.length-1;i+=2)n+=String.fromCharCode(s[i]+s[i+1]*256);return n}H.prototype.slice=function(t,e){let s=this.length;t=~~t,e=e===void 0?s:~~e,t<0?(t+=s,t<0&&(t=0)):t>s&&(t=s),e<0?(e+=s,e<0&&(e=0)):e>s&&(e=s),e<t&&(e=t);let n=this.subarray(t,e);return Object.setPrototypeOf(n,H.prototype),n};function ot(r,t,e){if(r%1!==0||r<0)throw new RangeError("offset is not uint");if(r+t>e)throw new RangeError("Trying to access beyond buffer length")}H.prototype.readUintLE=H.prototype.readUIntLE=function(t,e,s){t=t>>>0,e=e>>>0,s||ot(t,e,this.length);let n=this[t],i=1,a=0;for(;++a<e&&(i*=256);)n+=this[t+a]*i;return n};H.prototype.readUintBE=H.prototype.readUIntBE=function(t,e,s){t=t>>>0,e=e>>>0,s||ot(t,e,this.length);let n=this[t+--e],i=1;for(;e>0&&(i*=256);)n+=this[t+--e]*i;return n};H.prototype.readUint8=H.prototype.readUInt8=function(t,e){return t=t>>>0,e||ot(t,1,this.length),this[t]};H.prototype.readUint16LE=H.prototype.readUInt16LE=function(t,e){return t=t>>>0,e||ot(t,2,this.length),this[t]|this[t+1]<<8};H.prototype.readUint16BE=H.prototype.readUInt16BE=function(t,e){return t=t>>>0,e||ot(t,2,this.length),this[t]<<8|this[t+1]};H.prototype.readUint32LE=H.prototype.readUInt32LE=function(t,e){return t=t>>>0,e||ot(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+this[t+3]*16777216};H.prototype.readUint32BE=H.prototype.readUInt32BE=function(t,e){return t=t>>>0,e||ot(t,4,this.length),this[t]*16777216+(this[t+1]<<16|this[t+2]<<8|this[t+3])};H.prototype.readBigUInt64LE=_t(function(t){t=t>>>0,ue(t,"offset");let e=this[t],s=this[t+7];(e===void 0||s===void 0)&&xe(t,this.length-8);let n=e+this[++t]*2**8+this[++t]*2**16+this[++t]*2**24,i=this[++t]+this[++t]*2**8+this[++t]*2**16+s*2**24;return BigInt(n)+(BigInt(i)<<BigInt(32))});H.prototype.readBigUInt64BE=_t(function(t){t=t>>>0,ue(t,"offset");let e=this[t],s=this[t+7];(e===void 0||s===void 0)&&xe(t,this.length-8);let n=e*2**24+this[++t]*2**16+this[++t]*2**8+this[++t],i=this[++t]*2**24+this[++t]*2**16+this[++t]*2**8+s;return(BigInt(n)<<BigInt(32))+BigInt(i)});H.prototype.readIntLE=function(t,e,s){t=t>>>0,e=e>>>0,s||ot(t,e,this.length);let n=this[t],i=1,a=0;for(;++a<e&&(i*=256);)n+=this[t+a]*i;return i*=128,n>=i&&(n-=Math.pow(2,8*e)),n};H.prototype.readIntBE=function(t,e,s){t=t>>>0,e=e>>>0,s||ot(t,e,this.length);let n=e,i=1,a=this[t+--n];for(;n>0&&(i*=256);)a+=this[t+--n]*i;return i*=128,a>=i&&(a-=Math.pow(2,8*e)),a};H.prototype.readInt8=function(t,e){return t=t>>>0,e||ot(t,1,this.length),this[t]&128?(255-this[t]+1)*-1:this[t]};H.prototype.readInt16LE=function(t,e){t=t>>>0,e||ot(t,2,this.length);let s=this[t]|this[t+1]<<8;return s&32768?s|4294901760:s};H.prototype.readInt16BE=function(t,e){t=t>>>0,e||ot(t,2,this.length);let s=this[t+1]|this[t]<<8;return s&32768?s|4294901760:s};H.prototype.readInt32LE=function(t,e){return t=t>>>0,e||ot(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24};H.prototype.readInt32BE=function(t,e){return t=t>>>0,e||ot(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]};H.prototype.readBigInt64LE=_t(function(t){t=t>>>0,ue(t,"offset");let e=this[t],s=this[t+7];(e===void 0||s===void 0)&&xe(t,this.length-8);let n=this[t+4]+this[t+5]*2**8+this[t+6]*2**16+(s<<24);return(BigInt(n)<<BigInt(32))+BigInt(e+this[++t]*2**8+this[++t]*2**16+this[++t]*2**24)});H.prototype.readBigInt64BE=_t(function(t){t=t>>>0,ue(t,"offset");let e=this[t],s=this[t+7];(e===void 0||s===void 0)&&xe(t,this.length-8);let n=(e<<24)+this[++t]*2**16+this[++t]*2**8+this[++t];return(BigInt(n)<<BigInt(32))+BigInt(this[++t]*2**24+this[++t]*2**16+this[++t]*2**8+s)});H.prototype.readFloatLE=function(t,e){return t=t>>>0,e||ot(t,4,this.length),oe.read(this,t,!0,23,4)};H.prototype.readFloatBE=function(t,e){return t=t>>>0,e||ot(t,4,this.length),oe.read(this,t,!1,23,4)};H.prototype.readDoubleLE=function(t,e){return t=t>>>0,e||ot(t,8,this.length),oe.read(this,t,!0,52,8)};H.prototype.readDoubleBE=function(t,e){return t=t>>>0,e||ot(t,8,this.length),oe.read(this,t,!1,52,8)};function pt(r,t,e,s,n,i){if(!H.isBuffer(r))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>n||t<i)throw new RangeError('"value" argument is out of bounds');if(e+s>r.length)throw new RangeError("Index out of range")}H.prototype.writeUintLE=H.prototype.writeUIntLE=function(t,e,s,n){if(t=+t,e=e>>>0,s=s>>>0,!n){let o=Math.pow(2,8*s)-1;pt(this,t,e,s,o,0)}let i=1,a=0;for(this[e]=t&255;++a<s&&(i*=256);)this[e+a]=t/i&255;return e+s};H.prototype.writeUintBE=H.prototype.writeUIntBE=function(t,e,s,n){if(t=+t,e=e>>>0,s=s>>>0,!n){let o=Math.pow(2,8*s)-1;pt(this,t,e,s,o,0)}let i=s-1,a=1;for(this[e+i]=t&255;--i>=0&&(a*=256);)this[e+i]=t/a&255;return e+s};H.prototype.writeUint8=H.prototype.writeUInt8=function(t,e,s){return t=+t,e=e>>>0,s||pt(this,t,e,1,255,0),this[e]=t&255,e+1};H.prototype.writeUint16LE=H.prototype.writeUInt16LE=function(t,e,s){return t=+t,e=e>>>0,s||pt(this,t,e,2,65535,0),this[e]=t&255,this[e+1]=t>>>8,e+2};H.prototype.writeUint16BE=H.prototype.writeUInt16BE=function(t,e,s){return t=+t,e=e>>>0,s||pt(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=t&255,e+2};H.prototype.writeUint32LE=H.prototype.writeUInt32LE=function(t,e,s){return t=+t,e=e>>>0,s||pt(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=t&255,e+4};H.prototype.writeUint32BE=H.prototype.writeUInt32BE=function(t,e,s){return t=+t,e=e>>>0,s||pt(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=t&255,e+4};function Ia(r,t,e,s,n){Ma(t,s,n,r,e,7);let i=Number(t&BigInt(4294967295));r[e++]=i,i=i>>8,r[e++]=i,i=i>>8,r[e++]=i,i=i>>8,r[e++]=i;let a=Number(t>>BigInt(32)&BigInt(4294967295));return r[e++]=a,a=a>>8,r[e++]=a,a=a>>8,r[e++]=a,a=a>>8,r[e++]=a,e}function Oa(r,t,e,s,n){Ma(t,s,n,r,e,7);let i=Number(t&BigInt(4294967295));r[e+7]=i,i=i>>8,r[e+6]=i,i=i>>8,r[e+5]=i,i=i>>8,r[e+4]=i;let a=Number(t>>BigInt(32)&BigInt(4294967295));return r[e+3]=a,a=a>>8,r[e+2]=a,a=a>>8,r[e+1]=a,a=a>>8,r[e]=a,e+8}H.prototype.writeBigUInt64LE=_t(function(t,e=0){return Ia(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))});H.prototype.writeBigUInt64BE=_t(function(t,e=0){return Oa(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))});H.prototype.writeIntLE=function(t,e,s,n){if(t=+t,e=e>>>0,!n){let u=Math.pow(2,8*s-1);pt(this,t,e,s,u-1,-u)}let i=0,a=1,o=0;for(this[e]=t&255;++i<s&&(a*=256);)t<0&&o===0&&this[e+i-1]!==0&&(o=1),this[e+i]=(t/a>>0)-o&255;return e+s};H.prototype.writeIntBE=function(t,e,s,n){if(t=+t,e=e>>>0,!n){let u=Math.pow(2,8*s-1);pt(this,t,e,s,u-1,-u)}let i=s-1,a=1,o=0;for(this[e+i]=t&255;--i>=0&&(a*=256);)t<0&&o===0&&this[e+i+1]!==0&&(o=1),this[e+i]=(t/a>>0)-o&255;return e+s};H.prototype.writeInt8=function(t,e,s){return t=+t,e=e>>>0,s||pt(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=t&255,e+1};H.prototype.writeInt16LE=function(t,e,s){return t=+t,e=e>>>0,s||pt(this,t,e,2,32767,-32768),this[e]=t&255,this[e+1]=t>>>8,e+2};H.prototype.writeInt16BE=function(t,e,s){return t=+t,e=e>>>0,s||pt(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=t&255,e+2};H.prototype.writeInt32LE=function(t,e,s){return t=+t,e=e>>>0,s||pt(this,t,e,4,2147483647,-2147483648),this[e]=t&255,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4};H.prototype.writeInt32BE=function(t,e,s){return t=+t,e=e>>>0,s||pt(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=t&255,e+4};H.prototype.writeBigInt64LE=_t(function(t,e=0){return Ia(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});H.prototype.writeBigInt64BE=_t(function(t,e=0){return Oa(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function Na(r,t,e,s,n,i){if(e+s>r.length)throw new RangeError("Index out of range");if(e<0)throw new RangeError("Index out of range")}function Ca(r,t,e,s,n){return t=+t,e=e>>>0,n||Na(r,t,e,4,34028234663852886e22,-34028234663852886e22),oe.write(r,t,e,s,23,4),e+4}H.prototype.writeFloatLE=function(t,e,s){return Ca(this,t,e,!0,s)};H.prototype.writeFloatBE=function(t,e,s){return Ca(this,t,e,!1,s)};function xa(r,t,e,s,n){return t=+t,e=e>>>0,n||Na(r,t,e,8,17976931348623157e292,-17976931348623157e292),oe.write(r,t,e,s,52,8),e+8}H.prototype.writeDoubleLE=function(t,e,s){return xa(this,t,e,!0,s)};H.prototype.writeDoubleBE=function(t,e,s){return xa(this,t,e,!1,s)};H.prototype.copy=function(t,e,s,n){if(!H.isBuffer(t))throw new TypeError("argument should be a Buffer");if(s||(s=0),!n&&n!==0&&(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n<s&&(n=s),n===s||t.length===0||this.length===0)return 0;if(e<0)throw new RangeError("targetStart out of bounds");if(s<0||s>=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e<n-s&&(n=t.length-e+s);let i=n-s;return this===t&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(e,s,n):Uint8Array.prototype.set.call(t,this.subarray(s,n),e),i};H.prototype.fill=function(t,e,s,n){if(typeof t=="string"){if(typeof e=="string"?(n=e,e=0,s=this.length):typeof s=="string"&&(n=s,s=this.length),n!==void 0&&typeof n!="string")throw new TypeError("encoding must be a string");if(typeof n=="string"&&!H.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(t.length===1){let a=t.charCodeAt(0);(n==="utf8"&&a<128||n==="latin1")&&(t=a)}}else typeof t=="number"?t=t&255:typeof t=="boolean"&&(t=Number(t));if(e<0||this.length<e||this.length<s)throw new RangeError("Out of range index");if(s<=e)return this;e=e>>>0,s=s===void 0?this.length:s>>>0,t||(t=0);let i;if(typeof t=="number")for(i=e;i<s;++i)this[i]=t;else{let a=H.isBuffer(t)?t:H.from(t,n),o=a.length;if(o===0)throw new TypeError('The value "'+t+'" is invalid for argument "value"');for(i=0;i<s-e;++i)this[i+e]=a[i%o]}return this};var ae={};function Cs(r,t,e){ae[r]=class extends e{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${r}]`,this.stack,delete this.name}get code(){return r}set code(n){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:n,writable:!0})}toString(){return`${this.name} [${r}]: ${this.message}`}}}Cs("ERR_BUFFER_OUT_OF_BOUNDS",function(r){return r?`${r} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError);Cs("ERR_INVALID_ARG_TYPE",function(r,t){return`The "${r}" argument must be of type number. Received type ${typeof t}`},TypeError);Cs("ERR_OUT_OF_RANGE",function(r,t,e){let s=`The value of "${r}" is out of range.`,n=e;return Number.isInteger(e)&&Math.abs(e)>2**32?n=ga(String(e)):typeof e=="bigint"&&(n=String(e),(e>BigInt(2)**BigInt(32)||e<-(BigInt(2)**BigInt(32)))&&(n=ga(n)),n+="n"),s+=` It must be ${t}. Received ${n}`,s},RangeError);function ga(r){let t="",e=r.length,s=r[0]==="-"?1:0;for(;e>=s+4;e-=3)t=`_${r.slice(e-3,e)}${t}`;return`${r.slice(0,e)}${t}`}function Dl(r,t,e){ue(t,"offset"),(r[t]===void 0||r[t+e]===void 0)&&xe(t,r.length-(e+1))}function Ma(r,t,e,s,n,i){if(r>e||r<t){let a=typeof t=="bigint"?"n":"",o;throw i>3?t===0||t===BigInt(0)?o=`>= 0${a} and < 2${a} ** ${(i+1)*8}${a}`:o=`>= -(2${a} ** ${(i+1)*8-1}${a}) and < 2 ** ${(i+1)*8-1}${a}`:o=`>= ${t}${a} and <= ${e}${a}`,new ae.ERR_OUT_OF_RANGE("value",o,r)}Dl(s,n,i)}function ue(r,t){if(typeof r!="number")throw new ae.ERR_INVALID_ARG_TYPE(t,"number",r)}function xe(r,t,e){throw Math.floor(r)!==r?(ue(r,e),new ae.ERR_OUT_OF_RANGE(e||"offset","an integer",r)):t<0?new ae.ERR_BUFFER_OUT_OF_BOUNDS:new ae.ERR_OUT_OF_RANGE(e||"offset",`>= ${e?1:0} and <= ${t}`,r)}var Ll=/[^+/0-9A-Za-z-_]/g;function Rl(r){if(r=r.split("=")[0],r=r.trim().replace(Ll,""),r.length<2)return"";for(;r.length%4!==0;)r=r+"=";return r}function Is(r,t){t=t||1/0;let e,s=r.length,n=null,i=[];for(let a=0;a<s;++a){if(e=r.charCodeAt(a),e>55295&&e<57344){if(!n){if(e>56319){(t-=3)>-1&&i.push(239,191,189);continue}else if(a+1===s){(t-=3)>-1&&i.push(239,191,189);continue}n=e;continue}if(e<56320){(t-=3)>-1&&i.push(239,191,189),n=e;continue}e=(n-55296<<10|e-56320)+65536}else n&&(t-=3)>-1&&i.push(239,191,189);if(n=null,e<128){if((t-=1)<0)break;i.push(e)}else if(e<2048){if((t-=2)<0)break;i.push(e>>6|192,e&63|128)}else if(e<65536){if((t-=3)<0)break;i.push(e>>12|224,e>>6&63|128,e&63|128)}else if(e<1114112){if((t-=4)<0)break;i.push(e>>18|240,e>>12&63|128,e>>6&63|128,e&63|128)}else throw new Error("Invalid code point")}return i}function Ul(r){let t=[];for(let e=0;e<r.length;++e)t.push(r.charCodeAt(e)&255);return t}function Bl(r,t){let e,s,n,i=[];for(let a=0;a<r.length&&!((t-=2)<0);++a)e=r.charCodeAt(a),s=e>>8,n=e%256,i.push(n),i.push(s);return i}function wa(r){return ys.toByteArray(Rl(r))}function rr(r,t,e,s){let n;for(n=0;n<s&&!(n+e>=t.length||n>=r.length);++n)t[n+e]=r[n];return n}function Lt(r,t){return r instanceof t||r!=null&&r.constructor!=null&&r.constructor.name!=null&&r.constructor.name===t.name}function xs(r){return r!==r}var Hl=(function(){let r="0123456789abcdef",t=new Array(256);for(let e=0;e<16;++e){let s=e*16;for(let n=0;n<16;++n)t[s+n]=r[e]+r[n]}return t})();function _t(r){return typeof BigInt>"u"?vl:r}function vl(){throw new Error("BigInt not supported")}});function Da(){let r=ws.shift();ws.length||ce?.port1.unref?.(),r&&!r.cleared&&r.fn(...r.args)}function L(r,...t){if(typeof globalThis.setImmediate=="function")return globalThis.setImmediate(r,...t);let e={fn:r,args:t,cleared:!1};return ws.push(e),typeof MessageChannel=="function"?(ce||(ce=new MessageChannel,ce.port1.onmessage=Da),ce.port1.ref?.(),ce.port2.postMessage(null)):setTimeout(Da,0),e}function R(r){if(typeof globalThis.clearImmediate=="function")return globalThis.clearImmediate(r);r&&typeof r=="object"&&(r.cleared=!0)}var I,ws,ce,U,E=gs(()=>{"use strict";I=Ce(Ms(),1),ws=[],ce=null;U=globalThis.process||{env:{},nextTick:(r,...t)=>queueMicrotask(()=>r(...t))}});var ir=Ze((md,Ds)=>{"use strict";E();var fe=typeof Reflect=="object"?Reflect:null,La=fe&&typeof fe.apply=="function"?fe.apply:function(t,e,s){return Function.prototype.apply.call(t,e,s)},sr;fe&&typeof fe.ownKeys=="function"?sr=fe.ownKeys:Object.getOwnPropertySymbols?sr=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:sr=function(t){return Object.getOwnPropertyNames(t)};function Fl(r){console&&console.warn&&console.warn(r)}var Ua=Number.isNaN||function(t){return t!==t};function st(){st.init.call(this)}Ds.exports=st;Ds.exports.once=_l;st.EventEmitter=st;st.prototype._events=void 0;st.prototype._eventsCount=0;st.prototype._maxListeners=void 0;var Ra=10;function nr(r){if(typeof r!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof r)}Object.defineProperty(st,"defaultMaxListeners",{enumerable:!0,get:function(){return Ra},set:function(r){if(typeof r!="number"||r<0||Ua(r))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+r+".");Ra=r}});st.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};st.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Ua(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function Ba(r){return r._maxListeners===void 0?st.defaultMaxListeners:r._maxListeners}st.prototype.getMaxListeners=function(){return Ba(this)};st.prototype.emit=function(t){for(var e=[],s=1;s<arguments.length;s++)e.push(arguments[s]);var n=t==="error",i=this._events;if(i!==void 0)n=n&&i.error===void 0;else if(!n)return!1;if(n){var a;if(e.length>0&&(a=e[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var u=i[t];if(u===void 0)return!1;if(typeof u=="function")La(u,this,e);else for(var l=u.length,c=Xa(u,l),s=0;s<l;++s)La(c[s],this,e);return!0};function Ha(r,t,e,s){var n,i,a;if(nr(e),i=r._events,i===void 0?(i=r._events=Object.create(null),r._eventsCount=0):(i.newListener!==void 0&&(r.emit("newListener",t,e.listener?e.listener:e),i=r._events),a=i[t]),a===void 0)a=i[t]=e,++r._eventsCount;else if(typeof a=="function"?a=i[t]=s?[e,a]:[a,e]:s?a.unshift(e):a.push(e),n=Ba(r),n>0&&a.length>n&&!a.warned){a.warned=!0;var o=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");o.name="MaxListenersExceededWarning",o.emitter=r,o.type=t,o.count=a.length,Fl(o)}return r}st.prototype.addListener=function(t,e){return Ha(this,t,e,!1)};st.prototype.on=st.prototype.addListener;st.prototype.prependListener=function(t,e){return Ha(this,t,e,!0)};function Pl(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function va(r,t,e){var s={fired:!1,wrapFn:void 0,target:r,type:t,listener:e},n=Pl.bind(s);return n.listener=e,s.wrapFn=n,n}st.prototype.once=function(t,e){return nr(e),this.on(t,va(this,t,e)),this};st.prototype.prependOnceListener=function(t,e){return nr(e),this.prependListener(t,va(this,t,e)),this};st.prototype.removeListener=function(t,e){var s,n,i,a,o;if(nr(e),n=this._events,n===void 0)return this;if(s=n[t],s===void 0)return this;if(s===e||s.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete n[t],n.removeListener&&this.emit("removeListener",t,s.listener||e));else if(typeof s!="function"){for(i=-1,a=s.length-1;a>=0;a--)if(s[a]===e||s[a].listener===e){o=s[a].listener,i=a;break}if(i<0)return this;i===0?s.shift():Xl(s,i),s.length===1&&(n[t]=s[0]),n.removeListener!==void 0&&this.emit("removeListener",t,o||e)}return this};st.prototype.off=st.prototype.removeListener;st.prototype.removeAllListeners=function(t){var e,s,n;if(s=this._events,s===void 0)return this;if(s.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):s[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete s[t]),this;if(arguments.length===0){var i=Object.keys(s),a;for(n=0;n<i.length;++n)a=i[n],a!=="removeListener"&&this.removeAllListeners(a);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=s[t],typeof e=="function")this.removeListener(t,e);else if(e!==void 0)for(n=e.length-1;n>=0;n--)this.removeListener(t,e[n]);return this};function Fa(r,t,e){var s=r._events;if(s===void 0)return[];var n=s[t];return n===void 0?[]:typeof n=="function"?e?[n.listener||n]:[n]:e?Gl(n):Xa(n,n.length)}st.prototype.listeners=function(t){return Fa(this,t,!0)};st.prototype.rawListeners=function(t){return Fa(this,t,!1)};st.listenerCount=function(r,t){return typeof r.listenerCount=="function"?r.listenerCount(t):Pa.call(r,t)};st.prototype.listenerCount=Pa;function Pa(r){var t=this._events;if(t!==void 0){var e=t[r];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}st.prototype.eventNames=function(){return this._eventsCount>0?sr(this._events):[]};function Xa(r,t){for(var e=new Array(t),s=0;s<t;++s)e[s]=r[s];return e}function Xl(r,t){for(;t+1<r.length;t++)r[t]=r[t+1];r.pop()}function Gl(r){for(var t=new Array(r.length),e=0;e<t.length;++e)t[e]=r[e].listener||r[e];return t}function _l(r,t){return new Promise(function(e,s){function n(a){r.removeListener(t,i),s(a)}function i(){typeof r.removeListener=="function"&&r.removeListener("error",n),e([].slice.call(arguments))}Ga(r,t,i,{once:!0}),t!=="error"&&kl(r,n,{once:!0})})}function kl(r,t,e){typeof r.on=="function"&&Ga(r,"error",t,e)}function Ga(r,t,e,s){if(typeof r.on=="function")s.once?r.once(t,e):r.on(t,e);else if(typeof r.addEventListener=="function")r.addEventListener(t,function n(i){s.once&&r.removeEventListener(t,n),e(i)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof r)}});var ds,Pu=gs(()=>{E();ds=class{constructor(){throw new Error("SMTP is not available in the browser")}}});var Xu={};sl(Xu,{startSMTPServer:()=>qh});function qh(r,t,e,s){let n=t.getCredentials(),i=new ds({banner:"ImapKit",key:n.key,cert:n.cert,authOptional:!0,logger:!1,onAuth(o,u,l){l(null,{user:o.username})},onData(o,u,l){let c=[];o.on("data",h=>c.push(h)),o.on("error",l),o.on("end",()=>{t.appendMessage("INBOX",[],!1,I.Buffer.concat(c).toString("binary")),l()})}});i.on("error",o=>{t.options.debug&&console.error("SMTP server error: %s",o.message)});let a=()=>e?.(i.server.address().port);return s?i.listen(r,s,a):i.listen(r,a),i}var Gu=gs(()=>{"use strict";E();Pu()});E();E();E();var _a=Ce(ir()),ar=class extends _a.default{};E();var Rs=Ce(ir()),Us=r=>()=>{throw new Error(r+" is not available in the browser, open connections with server.connect()")},or=class extends Rs.default{},Ls=class extends or{constructor(){super(),Us("TLS")()}},ur=class extends Rs.default{listen(){Us("listen()")()}close(t){return t&&queueMicrotask(()=>t()),this}address(){return null}},jl=()=>new ur,Vl=Us("TLS"),Kt={Socket:or,TLSSocket:Ls,Server:ur,createServer:jl,createSecureContext:Vl};E();E();E();var ql=Ce(Ms());function kt(r){try{return new TextDecoder("utf-8",{fatal:!0}).decode(r),!0}catch{return!1}}E();var bt=r=>{let t;return()=>(t===void 0&&(t=r()),t)},zt=(r,t)=>{let e=[];for(let s=r;s<=t;s++)e.push(s);return String.fromCharCode(...e)},lr=(r,t)=>Array.from(r).filter(e=>!t.includes(e)).join(""),Ql=bt(()=>new Set(ht["ATOM-CHAR"]())),ht={CHAR:bt(()=>zt(1,127)),CHAR8:bt(()=>zt(1,255)),SP:()=>" ",CTL:bt(()=>zt(0,31)+"\x7F"),DQUOTE:()=>'"',ALPHA:bt(()=>zt(65,90)+zt(97,122)),DIGIT:bt(()=>zt(48,57)),"ATOM-CHAR":bt(()=>lr(ht.CHAR(),ht["atom-specials"]())),"ASTRING-CHAR":bt(()=>ht["ATOM-CHAR"]()+ht["resp-specials"]()),"TEXT-CHAR":bt(()=>lr(ht.CHAR(),`\r
|
|
2
|
-
`)),"atom-specials":
|
|
3
|
-
`)
|
|
4
|
-
`)
|
|
5
|
-
`+r,qa=r=>'"'+r.replace(/["\\]/g,"\\$&")+'"',ec=r=>"~"+cr(r),rc=r=>ja.test(r)?cr(r):qa(r),sc=r=>!ja.test(r)||!Va.test(r)&&kt(I.Buffer.from(r,"binary"))?qa(r):cr(r),Gs=(r,t)=>{let e=new Error(r);return e.code=t,e},Xs=(r,t)=>{if(Va.test(r))throw Gs("Line break or NUL in "+t,"InvalidTextValue");return r},ka=r=>[].concat(r||[]);function _s(r,t){let e=t&&t.utf8?sc:rc,s=Xs(Ht(r.tag),"tag")+(r.command?" "+Xs(Ht(r.command),"command"):""),n=!1,i=a=>{if(n||(s+=" "),n=!1,Array.isArray(a)){let u=a;s+="(",n=!0;let l=0;if(u.adjacentLists)for(;l<u.length&&Array.isArray(u[l]);)l++;u.forEach((c,h)=>{h&&h<l&&(n=!0),i(c)}),s+=")",n=!1;return}if(I.Buffer.isBuffer(a)){s+=e(Ht(a));return}if(!a&&typeof a!="string"&&typeof a!="number"){s+="NIL";return}if(typeof a=="string"){s+=e(a);return}if(typeof a=="number"){s+=Ps(a);return}let o;switch(typeof a.type=="string"?a.type.toUpperCase():""){case"LITERAL":s+=cr(Ht(a.value));break;case"LITERAL8":s+=ec(Ht(a.value));break;case"STRING":s+=e(Ht(a.value));break;case"TEXT":s+=Xs(Ht(a.value),"TEXT value");break;case"SEQUENCE":if(o=Ht(a.value),!tc(o))throw Gs("Invalid sequence set","InvalidSequenceSet");s+=o;break;case"NUMBER":s+=Ps(a.value);break;case"ATOM":case"SECTION":o=Ht(a.value),(o||!a.section)&&(s+=Zl(o)?o:e(o)),a.section&&(s+="[",n=!0,a.section.forEach(i),s+="]",n=!1),a.partial&&(s+="<"+ka(a.partial).map(Ps).join(".")+">");break;default:throw Gs("Unknown node type "+JSON.stringify(a.type),"InvalidNodeType")}};return ka(r.attributes).forEach(i),s}var Wt={parser:Fs,compiler:_s};E();E();E();E();var fr=["Not Authenticated","Authenticated","Selected"],hr=["Not Authenticated"],It=["Authenticated","Selected"],xt=["Selected"];function et(r){let t=(Array.isArray(r)?{states:r}:r)||{};return{states:t.states?[].concat(t.states):!1,noArguments:!!t.noArguments,mailboxArguments:[].concat(t.mailboxArguments||[]),astringArguments:[].concat(t.astringArguments||[]),searchCriteria:typeof t.searchCriteria=="number"?t.searchCriteria:!1,sequenceSet:typeof t.sequenceSet=="number"?t.sequenceSet:!1,noExpunge:!!t.noExpunge,literal8:t.literal8===!0||typeof t.literal8=="string"?t.literal8:!1,noPipelining:!!t.noPipelining,appendMessage:!!t.appendMessage}}var Qa={CAPABILITY:et({states:fr,noArguments:!0}),NOOP:et({states:fr,noArguments:!0}),LOGOUT:et({states:fr,noArguments:!0}),STARTTLS:et({states:hr,noArguments:!0,noPipelining:!0}),LOGIN:et({states:hr,astringArguments:[0,1]}),SELECT:et({states:It,mailboxArguments:[0]}),EXAMINE:et({states:It,mailboxArguments:[0]}),CREATE:et({states:It,mailboxArguments:[0]}),DELETE:et({states:It,mailboxArguments:[0]}),RENAME:et({states:It,mailboxArguments:[0,1]}),SUBSCRIBE:et({states:It,mailboxArguments:[0]}),UNSUBSCRIBE:et({states:It,mailboxArguments:[0]}),LIST:et({states:It,astringArguments:[0,1]}),LSUB:et({states:It,astringArguments:[0,1]}),STATUS:et({states:It,mailboxArguments:[0]}),APPEND:et({states:It,mailboxArguments:[0],literal8:"BINARY",appendMessage:!0}),CHECK:et({states:xt,noArguments:!0}),CLOSE:et({states:xt,noArguments:!0}),EXPUNGE:et({states:xt,noArguments:!0}),SEARCH:et({states:xt,searchCriteria:0,noExpunge:!0}),FETCH:et({states:xt,sequenceSet:0,noExpunge:!0}),STORE:et({states:xt,sequenceSet:0,noExpunge:!0}),COPY:et({states:xt,sequenceSet:0,mailboxArguments:[1]}),"UID COPY":et({states:xt,mailboxArguments:[1]}),"UID SEARCH":et({states:xt,searchCriteria:0})},nc=et({states:xt}),ic=et({states:hr});function Ya(r){return Object.hasOwn(Qa,r)?Qa[r]:/^UID /.test(r)?nc:/^AUTHENTICATE /.test(r)?ic:!1}var J={ANY:fr,NOT_AUTHENTICATED:hr,AUTHENTICATED:It,SELECTED:xt};E();var ks=/[\x00-\x1f\x7f (){%*"\\\]]/;function gt(r){return r.charAt(0)==="\\"&&(r=r.charAt(0)+r.charAt(1).toUpperCase()+r.substr(2).toLowerCase()),r}function Ot(r,t){if(t.charAt(0)==="\\"){if(r.systemFlags.indexOf(t)<0)throw new Error("Invalid system flag "+t)}else if(!t||ks.test(t))throw new Error("Invalid flag keyword "+JSON.stringify(t))}E();var $t={},dr=$t;function Ka(r,t,e){let s=r.selectedMailbox,n=[];[].concat(e).forEach(i=>{i=gt(typeof i=="string"?i:String(i.value||"")),Ot(r.server,i),r.server.isPermanentFlag(s,i)&&n.indexOf(i)<0&&n.push(i)}),t.flags=n,r.server.rememberFlags(s,n)}function za(r,t,e){let s=r.selectedMailbox;[].concat(e).forEach(n=>{n=gt(typeof n=="string"?n:String(n.value||"")),Ot(r.server,n),r.server.isPermanentFlag(s,n)&&t.flags.indexOf(n)<0&&t.flags.push(n)}),r.server.rememberFlags(s,t.flags)}function Wa(r,t,e){[].concat(e).forEach(s=>{if(s=gt(typeof s=="string"?s:String(s.value||"")),Ot(r.server,s),t.flags.indexOf(s)>=0){for(let n=0;n<t.flags.length;n++)if(t.flags[n]===s){t.flags.splice(n,1);break}}})}function js(r,t,e,s,n){let i=[{type:"ATOM",value:"FLAGS"},r.getFlags(n).map(a=>({type:"ATOM",value:a}))];(t.command||"").toUpperCase()==="UID STORE"&&(i.push({type:"ATOM",value:"UID"}),i.push(n.uid)),r.send({tag:"*",attributes:[s,{type:"ATOM",value:"FETCH"},i]},"FLAG UPDATE",t,e,n)}$t.FLAGS=function(r,t,e,s,n,i){Ka(r,t,e),js(r,n,i,s,t)};$t["+FLAGS"]=function(r,t,e,s,n,i){za(r,t,e),js(r,n,i,s,t)};$t["-FLAGS"]=function(r,t,e,s,n,i){Wa(r,t,e),js(r,n,i,s,t)};$t["FLAGS.SILENT"]=function(r,t,e){Ka(r,t,e)};$t["+FLAGS.SILENT"]=function(r,t,e){za(r,t,e)};$t["-FLAGS.SILENT"]=function(r,t,e){Wa(r,t,e)};E();function jt(r){return r.listExtensions||(r.listExtensions={enabled:!1,selectionOptions:Object.create(null),returnOptions:Object.create(null)}),r.listExtensions}E();function Vs(r,t,e,s){return Qs(r,t,e,s,!1)}function qs(r,t,e){r.everSelected=!0,r.state==="Selected"&&r.server.closedChecks.some(s=>s(r))&&r.send({tag:"*",command:"OK",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"CLOSED"}]},{type:"TEXT",value:"Previous mailbox closed"}]},"CLOSED",t,e)}function Qs(r,t,e,s,n){let i=n?"EXAMINE":"SELECT";if(!t.attributes||t.attributes.length!==1||!t.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(t.attributes[0].type)<0)return r.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:i+" expects 1 mailbox argument"}]},"INVALID COMMAND",t,e),s();let a=t.attributes[0].value;qs(r,t,e);let o=r.server.getMailbox(a);if(!o||o.flags.indexOf("\\Noselect")>=0)return r.closeMailbox(),r.sendStatus(t,e,"NO","Mailbox does not exist","NONEXISTENT",i+" FAILED"),s();r.state="Selected",r.selectedMailbox=o,r.readOnly=n,r.emitSession("select"),r.notificationQueue=[];let u=new Set;r.recent=u,o.messages.forEach(m=>{m.recent&&(u.add(m),n||delete m.recent)});let c=r.server.getStatus(o).permanentFlags.map(m=>({type:"ATOM",value:m}));r.send({tag:"*",command:"FLAGS",attributes:[c]},i+" FLAGS",t,e),o.allowPermanentFlags&&c.push({type:"TEXT",value:"\\*"}),r.send({tag:"*",command:"OK",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"PERMANENTFLAGS"},n?[]:c]},{type:"TEXT",value:n?"No permanent flags permitted":"Flags permitted"}]},i+" PERMANENTFLAGS",t,e),r.send({tag:"*",attributes:[o.messages.length,{type:"ATOM",value:"EXISTS"}]},i+" EXISTS",t,e),r.send({tag:"*",attributes:[r.recent.size,{type:"ATOM",value:"RECENT"}]},i+" RECENT",t,e);let h=o.messages.findIndex(m=>m.flags.indexOf("\\Seen")<0);return h>=0&&r.send({tag:"*",command:"OK",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"UNSEEN"},h+1]},{type:"TEXT",value:"First unseen message"}]},i+" UNSEEN",t,e),r.send({tag:"*",command:"OK",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"UIDVALIDITY"},o.uidvalidity]},{type:"TEXT",value:"UIDs valid"}]},i+" UIDVALIDITY",t,e),r.send({tag:"*",command:"OK",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"UIDNEXT"},o.uidnext]},{type:"TEXT",value:"Predicted next UID"}]},i+" UIDNEXT",t,e),r.send({tag:t.tag,command:"OK",attributes:[{type:"SECTION",section:[{type:"ATOM",value:n?"READ-ONLY":"READ-WRITE"}]},{type:"TEXT",value:"Completed"}]},i,t,e),s()}E();E();function $(r,t){return!!r&&!Array.isArray(r)&&r.type==="ATOM"&&(t===void 0||String(r.value).toUpperCase()===t)}function at(r){return!!r&&!Array.isArray(r)&&["ATOM","STRING","LITERAL"].indexOf(r.type)>=0&&!r.section&&!r.partial}var $a=/[\s()[\]{"%*\\<]/;function ac(r){let t=[],e=0;for(;e<r.length;){let s=r.charAt(e);if(s==='"'){for(e++;e<r.length&&r.charAt(e)!=='"';e++)r.charAt(e)==="\\"&&e++;e++;continue}let n=(s==="{"||s==="~")&&r.substr(e,32).match(/^~?\{(\d+)\+?\}\r\n/);if(n){e+=n[0].length+Number(n[1]);continue}if($a.test(s)){e++;continue}let i=e;for(;i<r.length&&!$a.test(r.charAt(i));)i++;let a=r.substring(e,i);/^nil$/i.test(a)&&t.push(a),e=i}return t}function he(r,t,e){if(!r.attributes||!/nil/i.test(t||""))return;let s=[],n=(a,o)=>{a.forEach((u,l)=>{u===null?s.push({list:a,index:l,path:o.concat(l)}):Array.isArray(u)?n(u,o.concat(l)):u&&Array.isArray(u.section)&&n(u.section,o.concat(l,"section"))})};if(n(r.attributes,[]),!s.length)return;let i=ac(t).slice(-s.length);s.forEach((a,o)=>{e(a.path)&&(a.list[a.index]={type:"ATOM",value:i.length===s.length?i[o]:"NIL"})})}function Jt(r,t,e,s){let n=new Error(r);return n.imapResponse=s||"NO",n.responseCode=t||!1,n.responseCodeArgs=e||[],n}var vt=r=>Jt(r,!1,!1,"BAD");function oc(r,t){try{return t.map(e=>{if(!e||e.type!=="ATOM")throw new Error("Invalid flags argument");let s=gt(e.value);return Ot(r.server,s),s})}catch{throw vt("Invalid flags argument")}}function uc(r,t,e){let s=r.server,n=[];for(let i=0;i<t.length;){let a={flags:[],internaldate:!1,raw:!1};if(Array.isArray(t[i])&&(a.flags=oc(r,t[i++])),t[i]&&t[i].type==="STRING"){if(!s.validateInternalDate(t[i].value))throw vt("Invalid internaldate argument");a.internaldate=t[i++].value}let o=t[i++],u=o&&o.type==="ATOM"?String(o.value).toUpperCase():"";if(o&&o.type==="LITERAL")a.raw=o.value;else if(o&&o.type==="LITERAL8"&&s.appendLiteral8)a.raw=o.value,a.literal8=!0;else if(u&&Object.hasOwn(s.appendDataHandlers,u)&&i<t.length)a.resolve=s.appendDataHandlers[u](r,t[i++]);else throw vt("Invalid message source argument");n.push(a)}if(!n.length)throw vt("Missing message argument");if(n.length>e)throw vt("Only a single message can be appended");return n}function lc(r,t,e,s,n){let i=[];s.responseCode&&i.push({type:"SECTION",section:[{type:"ATOM",value:s.responseCode}].concat(s.responseCodeArgs)}),i.push({type:"TEXT",value:s.message}),r.send({tag:t.tag,command:s.imapResponse,attributes:i},s.imapResponse==="BAD"?"INVALID COMMAND":n,t,e)}function Me(r,t,e){let s=r.server.getCommandOptions(t);if(!s.appendMessage)return!1;let n=s.mailboxArguments[0];if(/[ (]URL $/i.test(e.slice(-5)))return!1;let i=l=>{l=l.replace(/ $/,"");for(let c of["",")"])try{let h=Wt.parser(l+c);return he(h,l,m=>m.length===1&&m[0]===n),h.attributes||[]}catch{}return[]},a=e.match(/(~?)\{(\d+)\+?\}\r\n/),o=i(a?e.substr(0,a.index):e);o.length<=n&&a&&!a[1]&&(o=i(e.substr(0,a.index+a[0].length+Number(a[2]))));let u=o[n];if(!at(u))return!1;try{return r.importMailboxName(u.value)}catch{return!1}}function Ja(r,t,e){let s=!r.isBusy()&&Me(r,t,e);return s!==!1&&r.server.targetRefusal(s)}function Ys(r,t,e,s,n,i){let a=i.command+" FAILED",o=i.maxMessages||(r.server.multiAppend?1/0:1);try{if(!s||["STRING","ATOM","LITERAL"].indexOf(s.type)<0)throw vt("Invalid mailbox argument");let u=uc(r,n,o),l=r.getTargetMailbox(s.value,t,e,a);if(!l)return!1;u.forEach(h=>{h.resolve?h.raw=h.resolve():h.literal8&&(h.raw=r.server.appendLiteral8(h.raw))});let c=u;return r.checkAppend(l,c,t,e,a,{command:i.command,replaced:i.replaced})?{mailbox:l,messages:c}:!1}catch(u){let l=u;if(!l.imapResponse)throw l;return lc(r,t,e,l,a),!1}}function Ks(r,t){let e=t.messages.map(s=>r.server.appendMessage(t.mailbox,s.flags,s.internaldate,s.raw).message);return{mailbox:t.mailbox,message:e[e.length-1],messages:e}}function zs(r,t,e,s){let n=[].concat(t.attributes||[]),i=Ys(r,t,e,n.shift(),n,{command:"APPEND"});if(!i)return s();let a=Ks(r,i);r.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"APPEND Completed"}]},"APPEND",t,e,a),s()}E();E();function pr(r){let t=r>>>0;return()=>{t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}}E();var Ft=2n**63n-1n;function mt(r,t){let e=String(t===void 0?4294967295:t);return typeof r!="string"||!/^\d+$/.test(r)||r.replace(/^0+(?=\d)/,"").length>e.length?!1:BigInt(r)<=BigInt(e)}function Mt(r,t){return mt(r,t)&&/^[1-9]/.test(r)}function mr(r,t){return typeof r!="string"||!/^[\d*]+(:[\d*]+)?(,[\d*]+(:[\d*]+)?)*$/.test(r)?!1:r.split(/[,:]/).every(e=>e==="*"?!t:Mt(e))}var Er=3600*1e3,nt=class extends Error{constructor(t,e){super(t),this.name="ImapKitError",this.code=e}};function K(r,t){return new nt(r,t)}function Zt(r,t,e,s={}){let n;if(Array.isArray(e)){let c=new Set(e);n=h=>c.has(h)}else n=e;let i=[],a=[];if(t.messages.forEach((c,h)=>{n(c)?(c.ghost=!0,i.push({seq:s.highestFirst?h+1:a.length+1,message:c})):a.push(c)}),!i.length)return[];let o=t.messages.slice();a.forEach((c,h)=>{t.messages[h]=c}),t.messages.length=a.length;let u=i.map(c=>c.message),l=s.origin!==void 0?s.origin:r.activeConnection;return r.emit("expunge",t,u,l),(s.highestFirst?i.slice().reverse():i).forEach(c=>{r.notify({tag:"*",attributes:[c.seq,{type:"ATOM",value:"EXPUNGE"}],message:c.message},t,s.skip)}),r.notify({tag:"*",attributes:[t.messages.length,{type:"ATOM",value:"EXISTS"}],mailboxCopy:o},t,s.skip||s.skipExists),u}function Ws(r,t,e,s){e.length&&r.notify({tag:"*",flagUpdate:e},t,s)}function $s(r,t,e,s){if(!Array.isArray(e))throw K("Flags must be an array","INVALID");let n=[];return e.forEach(i=>{if(typeof i!="string")throw K("Flags must be strings","INVALID");let a=gt(i);try{Ot(r,a)}catch(o){throw K(o.message,"INVALID")}if(s&&!r.isPermanentFlag(t,a))throw K("Flag "+a+" is not a permanent flag of "+t.path,"INVALID");n.indexOf(a)<0&&n.push(a)}),n}function Za(r,t,e,s,n){if(["set","add","remove"].indexOf(n)<0)throw K("Invalid flag mode "+JSON.stringify(n)+", expected set, add or remove","INVALID");let i=$s(r,t,s,n!=="remove"),a=[];return e.forEach(o=>{let u=o.flags.join(" ");n==="set"?o.flags=i.slice():n==="add"?i.forEach(l=>r.ensureFlag(o.flags,l)):i.forEach(l=>r.removeFlag(o.flags,l)),r.rememberFlags(t,o.flags),o.flags.join(" ")!==u&&a.push(o)}),a.length&&(r.emit("flags",t,a,r.activeConnection),Ws(r,t,a,null)),a}function gr(r,t){let e=new Set(Object.keys(r.folderCache)),s=r.createMailbox(t),n=Object.keys(r.folderCache).filter(i=>!e.has(i)).sort((i,a)=>i.length-a.length);return r.mailboxChanged("create",s.path,{created:n}),s}function Ar(r,t){let e=r.getMailbox(t);if(!e)throw K("Mailbox does not exist","NONEXISTENT");r.deleteMailbox(t),r.mailboxChanged("delete",e.path,{mailbox:e}),to(r,e,"Selected mailbox was deleted","MAILBOX DELETED")}function to(r,t,e,s){let n=r.activeConnection;r.connections.forEach(i=>{i!==n&&i.selectedMailbox===t&&i.bye(e,s)})}function Tr(r,t,e){let s=r.getMailbox(t),n=r.getMailbox(e);if(!s||s.flags.indexOf("\\Noselect")>=0)throw K("Mailbox does not exist","NONEXISTENT");if(n&&n.flags.indexOf("\\Noselect")<0)throw K("Mailbox already exists","ALREADYEXISTS");let i=r.getSeparator(s);if(e.substr(0,s.path.length+i.length)===s.path+i)throw K("Can not move a mailbox into itself","CANNOT");let a=s.path,o;if(t.toUpperCase()==="INBOX"){let u=r.createMailbox(e);o=u.path,s.messages.forEach(l=>{r.copyMessage(u,l)}),Zt(r,s,()=>!0)}else{r.deleteMailbox(t,!0);try{r.createMailbox(e,s)}catch(u){throw r.createMailbox(t,s),r.indexFolders(),u}r.indexFolders(),o=s.path}return r.mailboxChanged("rename",o,{oldPath:a}),{path:o,mailbox:s}}function eo(r,t,e={}){let s=e.uids||"keep";if(["keep","renumber","shuffle","offset"].indexOf(s)<0)throw K("Invalid UID mode "+JSON.stringify(s)+", expected keep, renumber, shuffle or offset","INVALID");let n=e.offset===void 0?0:e.offset;if(!Number.isSafeInteger(n)||n<0)throw K("Offset must be a non-negative integer","INVALID");let i=e.uidvalidity;if(i===void 0)i=Math.max(t.uidvalidity,r.uidvalidityCounter)+1;else if(!Number.isSafeInteger(i)||i<=t.uidvalidity||i>4294967295)throw K("UIDVALIDITY must be an integer above "+t.uidvalidity+" and below 2^32","INVALID");if(e.seed!==void 0&&!Number.isSafeInteger(e.seed))throw K("Seed must be an integer","INVALID");to(r,t,"UIDVALIDITY of the selected mailbox changed","UIDVALIDITY CHANGED");let a=t.messages,o=a.map(l=>l.uid),u=o;if(s==="renumber"||s==="shuffle"){if(u=a.map((l,c)=>c+1),s==="shuffle"){let l=pr(e.seed===void 0?Math.floor(Math.random()*4294967295):e.seed);for(let c=u.length-1;c>0;c--){let h=Math.floor(l()*(c+1));[u[c],u[h]]=[u[h],u[c]]}}t.uidnext=a.length+1}else if(s==="offset"){let l=t.uidnext-1+n;u=o.map(c=>c+l),t.uidnext+=l}return a.forEach((l,c)=>{l.uid=u[c]}),s==="shuffle"&&a.sort((l,c)=>l.uid-c.uid),t.uidvalidity=i,r.uidvalidityCounter=Math.max(r.uidvalidityCounter,i),{uidvalidity:i,uidnext:t.uidnext,uids:o.map((l,c)=>({uid:l,newUid:u[c]}))}}function we(r,t){let e=r.getMailbox(t);if(!e||e.flags.indexOf("\\Noselect")>=0)throw K("Mailbox does not exist","NONEXISTENT");return e.subscribed?!1:(e.subscribed=!0,r.mailboxChanged("subscribe",e.path),!0)}function yr(r,t){return t.toUpperCase()==="INBOX"&&(t="INBOX"),r.subscriptions.delete(t)?(r.mailboxChanged("unsubscribe",t),!0):!1}var tn="lrswipkxtea",Le=new Set(tn),Re={c:"kx",d:"et"},cc=["i","e","s","w","t"],ro=["s","w","t"],fc=["l","r","i","k","x","a"],so=["FLAGS","+FLAGS","-FLAGS","FLAGS.SILENT","+FLAGS.SILENT","-FLAGS.SILENT"];function hc(r){return r=I.Buffer.from(r,"utf-8").toString("binary"),r&&r.charAt(0)!=="\\"&&!/^NIL$/i.test(r)?{type:"ATOM",value:r}:r}function no(r){let t=new Error(r);return t.imapResponse="BAD",t}function Js(r){let t=new Set;for(let e of r)if(Le.has(e))t.add(e);else if(Object.hasOwn(Re,e))Re[e].split("").forEach(s=>t.add(s));else throw/^[A-Z]$/.test(e)?no("Uppercase rights are not allowed"):no("The "+(/^[\x21-\x7e]$/.test(e)?e+" ":"")+"right is not supported");return t}function Zs(r,t){return[{type:"MAILBOX",value:r.path}].concat(t.map(e=>hc(e)))}function De(r){let t=tn.split("").filter(e=>r.has(e)).join("");return Object.keys(Re).forEach(e=>{Re[e].split("").some(s=>r.has(s))&&(t+=e)}),t}function dc(r){if(!r||r==="-")return"Empty identifier";if(/[\x00-\x1f\x7f]/.test(r))return"Identifier contains control characters";let t=I.Buffer.from(r,"binary").toString("utf-8");return I.Buffer.from(t,"utf-8").toString("binary")!==r?"Identifier is not valid UTF-8":!1}function en(r){r.registerCapability("ACL"),r.registerCapability("RIGHTS=texk");let t=typeof r.options.aclOwner=="string"?r.options.aclOwner:"testuser",e=S=>S.username===t,s=S=>{if(!(S.acl instanceof Map)){let y=new Map,O=S.acl&&typeof S.acl=="object"?S.acl:{};Object.keys(O).forEach(w=>{try{y.set(w,Js(String(O[w])))}catch(F){throw new Error("Invalid ACL in storage for "+S.path+": "+F.message,{cause:F})}}),S.acl=y}return S.acl},n=(S,y,O)=>{let w=S.username;if(w===t)return Le;O=O||s(y);let F=["anyone"].concat(typeof w=="string"&&w?w:[]),P=new Set;return F.forEach(j=>(O.get(j)||[]).forEach(Y=>P.add(Y))),F.forEach(j=>(O.get("-"+j)||[]).forEach(Y=>P.delete(Y))),P};r.acl={getRights:n,isOwner:e};let i=(S,y)=>{let O=s(S),w=new Map(O);y(O),r.emit("acl",S,w)},a=(S,y,O,w)=>{i(S,F=>{let P=new Set(F.get(y)||[]);O==="+"?w.forEach(Y=>P.add(Y)):O==="-"&&w.forEach(Y=>P.delete(Y));let j=O?P:w;j.size?F.set(y,j):F.delete(y)})};r.urlAccessChecks.push((S,y)=>{let O=n(S,y);return O.has("r")?!1:{text:O.has("l")?"Permission denied":"Mailbox does not exist"}}),r.searchAccessChecks.push((S,y,O)=>{let w=n(S,y);return w.has("r")&&(O||w.has("l"))});let o=S=>S.aclRights||Le,u=S=>(S=gt(S),S==="\\Deleted"?"t":S==="\\Seen"?"s":"w"),l=S=>typeof S=="string"?S:String(S&&S.value||""),c=(S,y)=>S.has(u(l(y))),h=(S,y)=>{let O=(S.attributes||[])[y];return at(O)?O.value:!1},m=(S,y)=>{let O=h(S,y);return O!==!1&&r.getMailbox(O)||!1},T=(S,y,O,w)=>S.sendStatus(y,O,"NO","Permission denied","NOPERM",w),A=(S,y,O,w,F,P)=>{w.has("l")?T(S,y,O,F):P==="TRYCREATE"?S.sendStatus(y,O,"NO","Target mailbox does not exist","TRYCREATE",F):S.sendStatus(y,O,"NO","Mailbox does not exist","NONEXISTENT",F)},p=S=>{for(let y=r.getParentPath(S);y;y=r.getParentPath(y)){let O=r.getMailbox(y);if(O)return O}return!1},f=(S,y,O,w,F)=>{if(!w)return S.sendStatus(y,O,"NO","Mailbox does not exist","NONEXISTENT"),!1;let P=n(S,w);return F(P)?!0:(A(S,y,O,P),!1)},d=S=>S.has("a"),g=(S,y,O,w)=>{let F=y.attributes||[],P=y.command.toUpperCase();if(F.length!==w||F.some(Y=>!at(Y)))return S.sendStatus(y,O,"BAD",P+" expects "+(w===1?"a mailbox name":w+" string arguments")),!1;let j=w>1&&dc(F[1].value);return j?(S.sendStatus(y,O,"BAD",j),!1):(w>1&&(F[1].value=I.Buffer.from(F[1].value,"binary").toString("utf-8")),!0)},b=(S,y,O)=>{let w=y.attributes[1].value;return w!==t&&w!=="-"+t?!1:(S.sendStatus(y,O,"NO","Rights of the mailbox owner can not be changed","CANNOT"),!0)},C=(S,y)=>(O,w,F,P)=>{g(O,w,F,S)&&y(O,w,F,r.getMailbox(w.attributes[0].value)),P()},v={states:J.AUTHENTICATED,mailboxArguments:[0]},M=Object.assign({astringArguments:[1]},v),x=(S,y,O,w)=>S.send({tag:"*",command:"MYRIGHTS",attributes:Zs(y,[De(n(S,y))])},"MYRIGHTS",O,w,y),_=jt(r);r.registerCapability("LIST-MYRIGHTS",()=>_.enabled),_.returnOptions.MYRIGHTS={onItem:(S,y,O,w,F,P)=>{w.matched&&w.exists&&x(S,y,F,P)}},r.setCommandHandler("SETACL",C(3,(S,y,O,w)=>{let F=y.attributes[1].value,P=y.attributes[2].value,j=/^[+-]/.test(P)?P.charAt(0):"",Y=Js(P.substr(j.length));!f(S,y,O,w,d)||b(S,y,O)||(a(w,F,j,Y),S.sendStatus(y,O,"OK","Setacl complete"))}),Object.assign({astringArguments:[1,2]},v)),r.setCommandHandler("DELETEACL",C(2,(S,y,O,w)=>{!f(S,y,O,w,d)||b(S,y,O)||(i(w,F=>F.delete(y.attributes[1].value)),S.sendStatus(y,O,"OK","Deleteacl complete"))}),M),r.setCommandHandler("GETACL",C(1,(S,y,O,w)=>{if(!f(S,y,O,w,d))return;let F=[t,De(Le)];s(w).forEach((P,j)=>{F.push(j,De(P))}),S.send({tag:"*",command:"ACL",attributes:Zs(w,F)},"ACL",y,O,w),S.sendStatus(y,O,"OK","Getacl complete")}),v),r.setCommandHandler("LISTRIGHTS",C(2,(S,y,O,w)=>{if(!f(S,y,O,w,d))return;let F=y.attributes[1].value,P;F===t?P=[F,De(Le)]:P=[F,""].concat(tn.split(""),Object.keys(Re)),S.send({tag:"*",command:"LISTRIGHTS",attributes:Zs(w,P)},"LISTRIGHTS",y,O,w),S.sendStatus(y,O,"OK","Listrights complete")}),M),r.setCommandHandler("MYRIGHTS",C(1,(S,y,O,w)=>{f(S,y,O,w,F=>fc.some(P=>F.has(P)))&&(x(S,w,y,O),S.sendStatus(y,O,"OK","Myrights complete"))}),v);let X={},z={},N=()=>{Object.keys(X).forEach(S=>{let y=r.getCommandHandler(S);y&&(z[S]=y,r.setCommandHandler(S,(O,w,F,P)=>e(O)?y(O,w,F,P):X[S](y,O,w,F,P)))}),Object.keys(_.returnOptions).forEach(S=>{let y=_.returnOptions[S];if(typeof y.onItem!="function")return;let O=y.onItem,w=S==="STATUS"?"r":"l";y.onItem=(F,P,...j)=>{if(e(F))return O(F,P,...j);let Y=n(F,P);if(Y.has("l")&&Y.has(w))return O(F,P,...j)}}),so.forEach(S=>{let y=r.storeHandlers[S]||dr[S];r.storeHandlers[S]=(O,w,F,...P)=>{let j=o(O);if(ro.every(W=>j.has(W)))return y(O,w,F,...P);F=[].concat(F),F.forEach(W=>Ot(O.server,gt(l(W))));let Y=F.filter(W=>c(j,W));return S.charAt(0)!=="+"&&S.charAt(0)!=="-"&&(Y=w.flags.filter(W=>!c(j,W)).concat(Y)),y(O,w,Y,...P)}})};r.once("pluginsLoaded",N);let D=(S,y,O,w,F)=>{let P=m(O,0);if(!P)return S(y,O,w,F);let j=O.command.toUpperCase(),Y=n(y,P);return Y.has("r")?(y.aclRights=Y,j==="SELECT"&&!cc.some(W=>Y.has(W))?z.EXAMINE(y,O,w,F):S(y,O,w,F)):(qs(y,O,w),y.closeMailbox(),A(y,O,w,Y,j+" FAILED"),F())};X.SELECT=D,X.EXAMINE=D;let B=(S,y,O)=>(w,F,P)=>{let j=m(F,y),Y=j&&n(w,j);return Y&&!Y.has(S)?(A(w,F,P,Y,void 0,O),!1):!0},V=(S,y,O)=>{let w=B(S,y,O);return(F,P,j,Y,W)=>w(P,j,Y)?F(P,j,Y,W):W()};X.STATUS=V("r",0),X.SUBSCRIBE=V("l",0),X.DELETE=V("x",0);let G=(S,y,O,w)=>{let F=p(w);return!F||!n(S,F).has("k")?(T(S,y,O),!1):!0};X.CREATE=(S,y,O,w,F)=>{let P=h(O,0);return P!==!1&&!G(y,O,w,P)?F():S(y,O,w,F)};let k=B("x",0);X.RENAME=(S,y,O,w,F)=>{if(!k(y,O,w))return F();let P=h(O,1);return P!==!1&&m(O,0)&&!G(y,O,w,P)?F():S(y,O,w,F)},X.APPEND=(S,y,O,w,F)=>{let P=m(O,0);if(!P)return S(y,O,w,F);let j=n(y,P);if(!j.has("i"))return A(y,O,w,j,"APPEND FAILED","TRYCREATE"),F();let Y=O.attributes[1];if(Array.isArray(Y)&&Y.every(W=>W&&W.type==="ATOM"))try{Y.forEach(W=>Ot(y.server,gt(W.value))),O.attributes[1]=Y.filter(W=>c(j,W))}catch{}return S(y,O,w,F)};let q=(S,y)=>{let O=y?n(S,y):!1;return!O||O.has("i")?!1:O.has("l")?{command:"NO",code:"NOPERM",text:"Permission denied"}:{command:"NO",code:"TRYCREATE",text:"Target mailbox does not exist"}},tt=V("i",1,"TRYCREATE"),Z=S=>(y,O,w,F,P)=>{let j=w.command.toUpperCase();if(S&&!O.readOnly){let Y=o(O);if(!Y.has("t")||!Y.has("e"))return T(O,w,F,j+" FAIL"),P()}return tt(y,O,w,F,P)};X.COPY=Z(!1),X["UID COPY"]=Z(!1),X.MOVE=Z(!0),X["UID MOVE"]=Z(!0);let ut=(S,y)=>{let O=o(S);return!S.readOnly&&(!O.has("t")||!O.has("e"))?{command:"NO",code:"NOPERM",text:"Permission denied"}:q(S,y)},$e=(S,y,O,w,F)=>{let P=ut(y,m(O,1));return P?(y.sendStatus(O,w,P.command,P.text,P.code,O.command.toUpperCase()+" FAILED"),F()):S(y,O,w,F)};X.REPLACE=$e,X["UID REPLACE"]=$e,r.literalFilters.unshift((S,y,O)=>{if(e(S)||S.isBusy())return!1;let w=Me(S,y,O),F=w!==!1&&r.getMailbox(w);return F?y==="APPEND"?q(S,F):ut(S,F):!1});let ps=["r","s","w","i","p"],Oe=S=>S.has("l")&&ps.some(y=>S.has(y)),oa=(S,y,O,w,F)=>{let P=O.attributes||[],j=O.command.toUpperCase()==="GETMETADATA"&&Array.isArray(P[0])?1:0,Y=m(O,j);if(Y&&h(O,j)!==""){let W=n(y,Y);if(!Oe(W))return A(y,O,w,W),F()}return S(y,O,w,F)};X.GETMETADATA=oa,X.SETMETADATA=oa,r.notifyFilters.push((S,y)=>{let O=y.command||{};if(O.command!=="METADATA"||e(S))return!0;let w=O.attributes&&O.attributes[0],F=w&&typeof w=="object"?w.value:w,P=typeof F=="string"&&F!==""&&r.getMailbox(F);return!P||Oe(n(S,P))}),X.GETQUOTAROOT=(S,y,O,w,F)=>{let P=m(O,0);return(!P||!n(y,P).has("r"))&&(O.aclQuotaMailboxOnly=!0),S(y,O,w,F)},X.SETQUOTA=(S,y,O,w,F)=>{let P=O.attributes||[];return P.length===2&&Array.isArray(P[1])&&!Object.keys(r.folderCache).every(Y=>{let W=r.folderCache[Y];return!r.isPersonal(W)||n(y,W).has("a")})?(T(y,O,w),F()):S(y,O,w,F)};let ua=(S,y,O,w,F)=>!y.readOnly&&!o(y).has("e")?(T(y,O,w),F()):S(y,O,w,F);X.EXPUNGE=ua,X["UID EXPUNGE"]=ua,r.resetHandlers.push(S=>{S.aclRights=null}),r.connectionHandlers.push(S=>{let y=S.canSetSeen,O=S.canExpunge;S.canSetSeen=()=>y.call(S)&&o(S).has("s"),S.canExpunge=()=>O.call(S)&&o(S).has("e")});let la=(S,y,O,w,F)=>{let P=o(y),j=O.attributes||[],Y=j.length>=3&&j[j.length-2]&&j[j.length-2].type==="ATOM"&&j[j.length-2].value.toUpperCase();if(y.readOnly||!Y)return S(y,O,w,F);if(so.indexOf(Y)<0)return Object.hasOwn(r.storeHandlers,Y)&&!P.has("w")?(T(y,O,w),F()):S(y,O,w,F);let W=[].concat(j[j.length-1]||[]);try{W.forEach(Ne=>Ot(y.server,gt(l(Ne))))}catch{return S(y,O,w,F)}let Ct;return Y.charAt(0)==="+"||Y.charAt(0)==="-"?Ct=!W.length||W.some(Ne=>c(P,Ne)):Ct=ro.some(Ne=>P.has(Ne)),Ct?S(y,O,w,F):(T(y,O,w),F())};X.STORE=la,X["UID STORE"]=la;let Yu=S=>{let y=S&&S.attributes||[];return y.some((O,w)=>O&&O.type==="ATOM"&&/^RETURN$/i.test(O.value)&&Array.isArray(y[w+1])&&y[w+1].some(F=>F&&F.type==="ATOM"&&/^STATUS$/i.test(F.value)))},Ku=(S,y)=>r.hasDescendant(y.path,O=>n(S,O).has("l"));r.outputHandlers.push((S,y,O,w,F,P)=>{if(!e(S)){if((O==="LIST ITEM"||O==="LSUB ITEM")&&P&&P.path){if(!n(S,P).has("l")){y.skipResponse=!0;return}let j=y.attributes[0];if(!Array.isArray(j))return;y.attributes[0]=j.slice();let Y=j.findIndex(Ct=>Ct&&Ct.value==="\\HasChildren");Y>=0&&!Ku(S,P)&&(y.attributes[0][Y]={type:"ATOM",value:"\\HasNoChildren"}),!j.some(Ct=>Ct&&/^\\(Noselect|NonExistent)$/i.test(Ct.value))&&Yu(w)&&!n(S,P).has("r")&&y.attributes[0].push({type:"ATOM",value:"\\Noselect"});return}if(O==="QUOTA"&&w&&w.aclQuotaMailboxOnly&&Array.isArray(y.attributes[1])){let j=y.attributes[1],Y=[];for(let W=0;W<j.length;W+=3)j[W]&&String(j[W].value).toUpperCase()==="MAILBOX"&&Y.push(j[W],j[W+1],j[W+2]);Y.length?y.attributes[1]=Y:y.skipResponse=!0;return}if(O==="SELECT PERMANENTFLAGS"){let j=y.attributes[0]&&y.attributes[0].section,Y=o(S);j&&Array.isArray(j[1])&&(j[1]=j[1].filter(W=>W.value==="\\*"?Y.has("w"):c(Y,W)));return}if(P&&P.targetUids&&P.mailbox&&/^(UID )?(COPY|MOVE COPYUID)$/.test(O)){let j=n(S,P.mailbox),Y=new Set(P.targetUids);P.mailbox.messages.forEach(W=>{Y.has(W.uid)&&(W.flags=W.flags.filter(Ct=>c(j,Ct)))})}}}),r.on("mailbox",S=>{if(S.type==="delete"){let y=r.getMailbox(S.path);y&&y!==S.mailbox&&delete y.acl}else S.type==="create"&&(S.created||[]).forEach(y=>{let O=p(y),w=r.folderCache[y];if(O&&w&&O!==w){let F=new Map;s(O).forEach((P,j)=>F.set(j,new Set(P))),w.acl=F}})});let Je=S=>{let y={};return s(S).forEach((O,w)=>{y[w]=De(O)}),y},ms=S=>r.control.requireMailbox(S);r.control.snapshotHandlers.push((S,y)=>{S.acl instanceof Map&&(y.acl=Je(S))});let zu=S=>Je(ms(S)),Wu=(S,y,O)=>{let w=ms(S);if(typeof y!="string"||!y||typeof O!="string")throw K("setAcl expects an identifier and a rights string","INVALID");let F=/^[+-]/.test(O)?O.charAt(0):"",P;try{P=Js(O.substr(F.length))}catch(j){throw K(j.message,"INVALID")}return a(w,y,F,P),Je(w)},$u=(S,y)=>{let O=ms(S);if(typeof y!="string"||!s(O).has(y))throw K("No ACL entry for "+JSON.stringify(y),"NONEXISTENT");return i(O,w=>w.delete(y)),Je(O)};r.control.register("getAcl",zu,[{method:"GET",path:"/v1/mailboxes/{path}/acl",summary:"The ACL of a mailbox (ACL plugin)",handler:({params:S})=>r.control.getAcl(S.path)}]),r.control.register("setAcl",Wu,[{method:"PUT",path:"/v1/mailboxes/{path}/acl/{identifier}",summary:'Sets the rights of an identifier ({ rights }, "+" or "-" in front adds or removes, ACL plugin)',handler:({params:S,body:y})=>r.control.setAcl(S.path,S.identifier,y.rights)}]),r.control.register("deleteAcl",$u,[{method:"DELETE",path:"/v1/mailboxes/{path}/acl/{identifier}",summary:"Removes an identifier from the ACL (ACL plugin)",handler:({params:S})=>r.control.deleteAcl(S.path,S.identifier)}])}E();function rn(r){let t="appendLimit"in r.options?r.options.appendLimit:null;if(t!==null&&!io(t))throw new TypeError("Invalid appendLimit option, expecting a non-negative integer");let e=a=>Object.hasOwn(a,"appendLimit"),s=()=>Object.values(r.folderCache).some(e),n=a=>e(a)?io(a.appendLimit)?a.appendLimit:null:t,i=(a,o)=>{let u=n(a);return u!==null&&(o>u||u===0)};t!==null&&r.registerCapability("APPENDLIMIT="+t,()=>!s()),r.registerCapability("APPENDLIMIT",()=>t===null||s()),r.appendChecks.push((a,o,u,l)=>l.command&&u.some(c=>i(o,c.raw.length))?{code:"TOOBIG",text:"Message exceeds the APPENDLIMIT of the mailbox"}:!1),r.literalFilters.push((a,o,u,l)=>{let c=Me(a,o,u),h=c!==!1&&r.getMailbox(c);return h&&i(h,l)?{command:"NO",code:"TOOBIG",text:"Message exceeds the APPENDLIMIT of the mailbox"}:!1}),r.allowedStatus.push("APPENDLIMIT"),r.statusHandlers.APPENDLIMIT=(a,o)=>n(o)}function io(r){return Number.isSafeInteger(r)&&r>=0}E();var pc=new TextDecoder("utf-8",{fatal:!0});function sn(r){r.registerCapability("AUTH=PLAIN",e=>e.state==="Not Authenticated");let t=(e,s,n,i)=>{let a=e.decodeSaslResponse(i);if(!a)return e.sendStatus(s,n,"BAD","Invalid base64 in SASL response",!1,"AUTHENTICATE PLAIN FAILED");let o;try{o=pc.decode(a)}catch{return e.sendStatus(s,n,"BAD","Invalid UTF-8 in SASL PLAIN message",!1,"AUTHENTICATE PLAIN FAILED")}let u=o.split("\0"),l=u[0]||"",c=u[1]||"",h=u[2]||"",m=e.server.getUser(c);if(u.length!==3||!m||m.password!==h)return e.sendStatus(s,n,"NO","Login failed: authentication failure","AUTHENTICATIONFAILED","AUTHENTICATE PLAIN FAILED");if(l&&l!==c)return e.sendStatus(s,n,"NO","Can not act as "+l,"AUTHORIZATIONFAILED","AUTHENTICATE PLAIN FAILED");e.state="Authenticated",e.username=c,e.sendStatus(s,n,"OK","User logged in",!1,"AUTHENTICATE PLAIN SUCCESS")};r.setCommandHandler("AUTHENTICATE PLAIN",(e,s,n,i)=>{if(!s.attributes)e.inputHandler=function(a){if(e.inputHandler=!1,a==="*")return e.sendStatus(s,n,"BAD","Authentication cancelled",!1,"AUTHENTICATE PLAIN FAILED");t(e,s,n,a)},e.sendContinuation("","AUTHENTICATE PLAIN");else if(s.attributes.length===1&&s.attributes[0].type==="ATOM"){if(!r.capabilities["SASL-IR"]||!r.capabilities["SASL-IR"](e))return e.sendStatus(s,n,"BAD","SASL-IR must be enabled to send Initial Response with the request",!1,"AUTHENTICATE PLAIN FAILED"),i();t(e,s,n,s.attributes[0].value)}else e.sendStatus(s,n,"BAD","Invalid attributes for AUTHENTICATE PLAIN",!1,"AUTHENTICATE PLAIN FAILED");return i()})}E();E();E();function br(r,t){let s=new Sr(r).tokenize(),n=[],i=[],a=[];return s.forEach(o=>{o.type==="operator"&&(o.value===","||o.value===";")?(i.length&&n.push(i),i=[]):i.push(o)}),i.length&&n.push(i),n.forEach(o=>{let u=mc(o,t);u.length&&(a=a.concat(u))}),a}function mc(r,t){let e,s=!1,n="text",i=[],a={address:[],comment:[],group:[],text:[]},o,u;for(o=0,u=r.length;o<u;o++)if(e=r[o],e.type==="operator")switch(e.value){case"<":n="address";break;case"(":n="comment";break;case":":if(t){n="text";break}n="group",s=!0;break;default:n="text"}else e.value&&a[n].push(e.value);if(!a.text.length&&a.comment.length&&(a.text=a.comment,a.comment=[]),s){let l=a.text.join(" ");i.push({name:l,group:a.group.length?br(a.group.join(","),!0):[]})}else{if(!a.address.length&&a.text.length){for(o=a.text.length-1;o>=0;o--)if(a.text[o].match(/^[^@\s]+@[^@\s]+$/)){a.address=a.text.splice(o,1);break}let m=function(T){return a.address.length?T:(a.address=[T.trim()]," ")};if(!a.address.length)for(o=a.text.length-1;o>=0&&(a.text[o]=a.text[o].replace(/\s*\b[^@\s]+@[^@\s]+\b\s*/,m).trim(),!a.address.length);o--);}!a.text.length&&a.comment.length&&(a.text=a.comment,a.comment=[]),a.address.length>1&&(a.text=a.text.concat(a.address.splice(1)));let l=a.text.join(" "),c=a.address.join(" "),h={address:c||l||"",name:l||c||""};h.address===h.name&&((h.address||"").match(/@/)?h.name="":h.address=""),i.push(h)}return i}var Sr=class{constructor(t){this.str=(t||"").toString(),this.operatorCurrent="",this.operatorExpecting="",this.node=null,this.escaped=!1,this.list=[]}tokenize(){let t,e=[];for(let s=0,n=this.str.length;s<n;s++)t=this.str.charAt(s),this.checkChar(t);return this.list.forEach(s=>{s.value=(s.value||"").toString().trim(),s.value&&e.push(s)}),e}checkChar(t){if((t in this.operators||t==="\\")&&this.escaped)this.escaped=!1;else if(this.operatorExpecting&&t===this.operatorExpecting){this.node={type:"operator",value:t},this.list.push(this.node),this.node=null,this.operatorExpecting="",this.escaped=!1;return}else if(!this.operatorExpecting&&t in this.operators){this.node={type:"operator",value:t},this.list.push(this.node),this.node=null,this.operatorExpecting=this.operators[t],this.escaped=!1;return}if(!this.escaped&&t==="\\"){this.escaped=!0;return}this.node||(this.node={type:"text",value:""},this.list.push(this.node)),this.escaped&&t!=="\\"&&(this.node.value+="\\"),this.node.value+=t,this.escaped=!1}};Sr.prototype.operators={'"':'"',"(":")","<":">",",":"",":":";"};var ao=/^[a-zA-Z0-9\-*]{1,99}$/,Ir=["7bit","8bit","binary"],Ec=32;function Ue(r){let t=I.Buffer.isBuffer(r)?r.toString("binary"):r||"";return/(?:^|[^\r])\n/.test(t)?t.replace(/\r?\n/g,`\r
|
|
6
|
-
`):
|
|
7
|
-
`,this._pos);if(
|
|
8
|
-
`)&&(this._node.headerUnterminated=!0));let
|
|
9
|
-
`+n:
|
|
1
|
+
var jl=Object.create;var Rr=Object.defineProperty;var Vl=Object.getOwnPropertyDescriptor;var ql=Object.getOwnPropertyNames;var Ql=Object.getPrototypeOf,Yl=Object.prototype.hasOwnProperty;var Lr=(s,e,t)=>()=>{if(t)throw t[0];try{return s&&(e=s(s=0)),e}catch(r){throw t=[r],r}};var as=(s,e)=>()=>{try{return e||s((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},Kl=(s,e)=>{for(var t in e)Rr(s,t,{get:e[t],enumerable:!0})},zl=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ql(e))!Yl.call(s,n)&&n!==t&&Rr(s,n,{get:()=>e[n],enumerable:!(r=Vl(e,n))||r.enumerable});return s};var Ut=(s,e,t)=>(t=s!=null?jl(Ql(s)):{},zl(e||!s||!s.__esModule?Rr(t,"default",{value:s,enumerable:!0}):t,s));var Xo=as(us=>{"use strict";g();us.byteLength=$l;us.toByteArray=Zl;us.fromByteArray=sc;var Ue=[],Oe=[],Wl=typeof Uint8Array<"u"?Uint8Array:Array,Dr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Ze=0,_o=Dr.length;Ze<_o;++Ze)Ue[Ze]=Dr[Ze],Oe[Dr.charCodeAt(Ze)]=Ze;var Ze,_o;Oe[45]=62;Oe[95]=63;function Go(s){var e=s.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var t=s.indexOf("=");t===-1&&(t=e);var r=t===e?0:4-t%4;return[t,r]}function $l(s){var e=Go(s),t=e[0],r=e[1];return(t+r)*3/4-r}function Jl(s,e,t){return(e+t)*3/4-t}function Zl(s){var e,t=Go(s),r=t[0],n=t[1],i=new Wl(Jl(s,r,n)),o=0,a=n>0?r-4:r,u;for(u=0;u<a;u+=4)e=Oe[s.charCodeAt(u)]<<18|Oe[s.charCodeAt(u+1)]<<12|Oe[s.charCodeAt(u+2)]<<6|Oe[s.charCodeAt(u+3)],i[o++]=e>>16&255,i[o++]=e>>8&255,i[o++]=e&255;return n===2&&(e=Oe[s.charCodeAt(u)]<<2|Oe[s.charCodeAt(u+1)]>>4,i[o++]=e&255),n===1&&(e=Oe[s.charCodeAt(u)]<<10|Oe[s.charCodeAt(u+1)]<<4|Oe[s.charCodeAt(u+2)]>>2,i[o++]=e>>8&255,i[o++]=e&255),i}function ec(s){return Ue[s>>18&63]+Ue[s>>12&63]+Ue[s>>6&63]+Ue[s&63]}function tc(s,e,t){for(var r,n=[],i=e;i<t;i+=3)r=(s[i]<<16&16711680)+(s[i+1]<<8&65280)+(s[i+2]&255),n.push(ec(r));return n.join("")}function sc(s){for(var e,t=s.length,r=t%3,n=[],i=16383,o=0,a=t-r;o<a;o+=i)n.push(tc(s,o,o+i>a?a:o+i));return r===1?(e=s[t-1],n.push(Ue[e>>2]+Ue[e<<4&63]+"==")):r===2&&(e=(s[t-2]<<8)+s[t-1],n.push(Ue[e>>10]+Ue[e>>4&63]+Ue[e<<2&63]+"=")),n.join("")}});var jo=as(Ur=>{g();Ur.read=function(s,e,t,r,n){var i,o,a=n*8-r-1,u=(1<<a)-1,l=u>>1,c=-7,f=t?n-1:0,p=t?-1:1,y=s[e+f];for(f+=p,i=y&(1<<-c)-1,y>>=-c,c+=a;c>0;i=i*256+s[e+f],f+=p,c-=8);for(o=i&(1<<-c)-1,i>>=-c,c+=r;c>0;o=o*256+s[e+f],f+=p,c-=8);if(i===0)i=1-l;else{if(i===u)return o?NaN:(y?-1:1)*(1/0);o=o+Math.pow(2,r),i=i-l}return(y?-1:1)*o*Math.pow(2,i-r)};Ur.write=function(s,e,t,r,n,i){var o,a,u,l=i*8-n-1,c=(1<<l)-1,f=c>>1,p=n===23?Math.pow(2,-24)-Math.pow(2,-77):0,y=r?0:i-1,A=r?1:-1,m=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=c):(o=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-o))<1&&(o--,u*=2),o+f>=1?e+=p/u:e+=p*Math.pow(2,1-f),e*u>=2&&(o++,u/=2),o+f>=c?(a=0,o=c):o+f>=1?(a=(e*u-1)*Math.pow(2,n),o=o+f):(a=e*Math.pow(2,f-1)*Math.pow(2,n),o=0));n>=8;s[t+y]=a&255,y+=A,a/=256,n-=8);for(o=o<<n|a,l+=n;l>0;s[t+y]=o&255,y+=A,o/=256,l-=8);s[t+y-A]|=m*128}});var Xr=as(gt=>{"use strict";g();var vr=Xo(),pt=jo(),Vo=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;gt.Buffer=B;gt.SlowBuffer=uc;gt.INSPECT_MAX_BYTES=50;var ls=2147483647;gt.kMaxLength=ls;B.TYPED_ARRAY_SUPPORT=rc();!B.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function rc(){try{let s=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(s,e),s.foo()===42}catch{return!1}}Object.defineProperty(B.prototype,"parent",{enumerable:!0,get:function(){if(B.isBuffer(this))return this.buffer}});Object.defineProperty(B.prototype,"offset",{enumerable:!0,get:function(){if(B.isBuffer(this))return this.byteOffset}});function Pe(s){if(s>ls)throw new RangeError('The value "'+s+'" is invalid for option "size"');let e=new Uint8Array(s);return Object.setPrototypeOf(e,B.prototype),e}function B(s,e,t){if(typeof s=="number"){if(typeof e=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return Pr(s)}return Ko(s,e,t)}B.poolSize=8192;function Ko(s,e,t){if(typeof s=="string")return ic(s,e);if(ArrayBuffer.isView(s))return oc(s);if(s==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof s);if(ve(s,ArrayBuffer)||s&&ve(s.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(ve(s,SharedArrayBuffer)||s&&ve(s.buffer,SharedArrayBuffer)))return Hr(s,e,t);if(typeof s=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let r=s.valueOf&&s.valueOf();if(r!=null&&r!==s)return B.from(r,e,t);let n=ac(s);if(n)return n;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof s[Symbol.toPrimitive]=="function")return B.from(s[Symbol.toPrimitive]("string"),e,t);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof s)}B.from=function(s,e,t){return Ko(s,e,t)};Object.setPrototypeOf(B.prototype,Uint8Array.prototype);Object.setPrototypeOf(B,Uint8Array);function zo(s){if(typeof s!="number")throw new TypeError('"size" argument must be of type number');if(s<0)throw new RangeError('The value "'+s+'" is invalid for option "size"')}function nc(s,e,t){return zo(s),s<=0?Pe(s):e!==void 0?typeof t=="string"?Pe(s).fill(e,t):Pe(s).fill(e):Pe(s)}B.alloc=function(s,e,t){return nc(s,e,t)};function Pr(s){return zo(s),Pe(s<0?0:Fr(s)|0)}B.allocUnsafe=function(s){return Pr(s)};B.allocUnsafeSlow=function(s){return Pr(s)};function ic(s,e){if((typeof e!="string"||e==="")&&(e="utf8"),!B.isEncoding(e))throw new TypeError("Unknown encoding: "+e);let t=Wo(s,e)|0,r=Pe(t),n=r.write(s,e);return n!==t&&(r=r.slice(0,n)),r}function Br(s){let e=s.length<0?0:Fr(s.length)|0,t=Pe(e);for(let r=0;r<e;r+=1)t[r]=s[r]&255;return t}function oc(s){if(ve(s,Uint8Array)){let e=new Uint8Array(s);return Hr(e.buffer,e.byteOffset,e.byteLength)}return Br(s)}function Hr(s,e,t){if(e<0||s.byteLength<e)throw new RangeError('"offset" is outside of buffer bounds');if(s.byteLength<e+(t||0))throw new RangeError('"length" is outside of buffer bounds');let r;return e===void 0&&t===void 0?r=new Uint8Array(s):t===void 0?r=new Uint8Array(s,e):r=new Uint8Array(s,e,t),Object.setPrototypeOf(r,B.prototype),r}function ac(s){if(B.isBuffer(s)){let e=Fr(s.length)|0,t=Pe(e);return t.length===0||s.copy(t,0,0,e),t}if(s.length!==void 0)return typeof s.length!="number"||Gr(s.length)?Pe(0):Br(s);if(s.type==="Buffer"&&Array.isArray(s.data))return Br(s.data)}function Fr(s){if(s>=ls)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+ls.toString(16)+" bytes");return s|0}function uc(s){return+s!=s&&(s=0),B.alloc(+s)}B.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==B.prototype};B.compare=function(e,t){if(ve(e,Uint8Array)&&(e=B.from(e,e.offset,e.byteLength)),ve(t,Uint8Array)&&(t=B.from(t,t.offset,t.byteLength)),!B.isBuffer(e)||!B.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let r=e.length,n=t.length;for(let i=0,o=Math.min(r,n);i<o;++i)if(e[i]!==t[i]){r=e[i],n=t[i];break}return r<n?-1:n<r?1:0};B.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}};B.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(e.length===0)return B.alloc(0);let r;if(t===void 0)for(t=0,r=0;r<e.length;++r)t+=e[r].length;let n=B.allocUnsafe(t),i=0;for(r=0;r<e.length;++r){let o=e[r];if(ve(o,Uint8Array))i+o.length>n.length?(B.isBuffer(o)||(o=B.from(o)),o.copy(n,i)):Uint8Array.prototype.set.call(n,o,i);else if(B.isBuffer(o))o.copy(n,i);else throw new TypeError('"list" argument must be an Array of Buffers');i+=o.length}return n};function Wo(s,e){if(B.isBuffer(s))return s.length;if(ArrayBuffer.isView(s)||ve(s,ArrayBuffer))return s.byteLength;if(typeof s!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof s);let t=s.length,r=arguments.length>2&&arguments[2]===!0;if(!r&&t===0)return 0;let n=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return t;case"utf8":case"utf-8":return kr(s).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return t*2;case"hex":return t>>>1;case"base64":return ia(s).length;default:if(n)return r?-1:kr(s).length;e=(""+e).toLowerCase(),n=!0}}B.byteLength=Wo;function lc(s,e,t){let r=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((t===void 0||t>this.length)&&(t=this.length),t<=0)||(t>>>=0,e>>>=0,t<=e))return"";for(s||(s="utf8");;)switch(s){case"hex":return yc(this,e,t);case"utf8":case"utf-8":return Jo(this,e,t);case"ascii":return Ec(this,e,t);case"latin1":case"binary":return Ac(this,e,t);case"base64":return mc(this,e,t);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return bc(this,e,t);default:if(r)throw new TypeError("Unknown encoding: "+s);s=(s+"").toLowerCase(),r=!0}}B.prototype._isBuffer=!0;function et(s,e,t){let r=s[e];s[e]=s[t],s[t]=r}B.prototype.swap16=function(){let e=this.length;if(e%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)et(this,t,t+1);return this};B.prototype.swap32=function(){let e=this.length;if(e%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)et(this,t,t+3),et(this,t+1,t+2);return this};B.prototype.swap64=function(){let e=this.length;if(e%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)et(this,t,t+7),et(this,t+1,t+6),et(this,t+2,t+5),et(this,t+3,t+4);return this};B.prototype.toString=function(){let e=this.length;return e===0?"":arguments.length===0?Jo(this,0,e):lc.apply(this,arguments)};B.prototype.toLocaleString=B.prototype.toString;B.prototype.equals=function(e){if(!B.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e?!0:B.compare(this,e)===0};B.prototype.inspect=function(){let e="",t=gt.INSPECT_MAX_BYTES;return e=this.toString("hex",0,t).replace(/(.{2})/g,"$1 ").trim(),this.length>t&&(e+=" ... "),"<Buffer "+e+">"};Vo&&(B.prototype[Vo]=B.prototype.inspect);B.prototype.compare=function(e,t,r,n,i){if(ve(e,Uint8Array)&&(e=B.from(e,e.offset,e.byteLength)),!B.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(t===void 0&&(t=0),r===void 0&&(r=e?e.length:0),n===void 0&&(n=0),i===void 0&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return-1;if(t>=r)return 1;if(t>>>=0,r>>>=0,n>>>=0,i>>>=0,this===e)return 0;let o=i-n,a=r-t,u=Math.min(o,a),l=this.slice(n,i),c=e.slice(t,r);for(let f=0;f<u;++f)if(l[f]!==c[f]){o=l[f],a=c[f];break}return o<a?-1:a<o?1:0};function $o(s,e,t,r,n){if(s.length===0)return-1;if(typeof t=="string"?(r=t,t=0):t>2147483647?t=2147483647:t<-2147483648&&(t=-2147483648),t=+t,Gr(t)&&(t=n?0:s.length-1),t<0&&(t=s.length+t),t>=s.length){if(n)return-1;t=s.length-1}else if(t<0)if(n)t=0;else return-1;if(typeof e=="string"&&(e=B.from(e,r)),B.isBuffer(e))return e.length===0?-1:qo(s,e,t,r,n);if(typeof e=="number")return e=e&255,typeof Uint8Array.prototype.indexOf=="function"?n?Uint8Array.prototype.indexOf.call(s,e,t):Uint8Array.prototype.lastIndexOf.call(s,e,t):qo(s,[e],t,r,n);throw new TypeError("val must be string, number or Buffer")}function qo(s,e,t,r,n){let i=1,o=s.length,a=e.length;if(r!==void 0&&(r=String(r).toLowerCase(),r==="ucs2"||r==="ucs-2"||r==="utf16le"||r==="utf-16le")){if(s.length<2||e.length<2)return-1;i=2,o/=2,a/=2,t/=2}function u(c,f){return i===1?c[f]:c.readUInt16BE(f*i)}let l;if(n){let c=-1;for(l=t;l<o;l++)if(u(s,l)===u(e,c===-1?0:l-c)){if(c===-1&&(c=l),l-c+1===a)return c*i}else c!==-1&&(l-=l-c),c=-1}else for(t+a>o&&(t=o-a),l=t;l>=0;l--){let c=!0;for(let f=0;f<a;f++)if(u(s,l+f)!==u(e,f)){c=!1;break}if(c)return l}return-1}B.prototype.includes=function(e,t,r){return this.indexOf(e,t,r)!==-1};B.prototype.indexOf=function(e,t,r){return $o(this,e,t,r,!0)};B.prototype.lastIndexOf=function(e,t,r){return $o(this,e,t,r,!1)};function cc(s,e,t,r){t=Number(t)||0;let n=s.length-t;r?(r=Number(r),r>n&&(r=n)):r=n;let i=e.length;r>i/2&&(r=i/2);let o;for(o=0;o<r;++o){let a=parseInt(e.substr(o*2,2),16);if(Gr(a))return o;s[t+o]=a}return o}function fc(s,e,t,r){return cs(kr(e,s.length-t),s,t,r)}function hc(s,e,t,r){return cs(Oc(e),s,t,r)}function dc(s,e,t,r){return cs(ia(e),s,t,r)}function pc(s,e,t,r){return cs(xc(e,s.length-t),s,t,r)}B.prototype.write=function(e,t,r,n){if(t===void 0)n="utf8",r=this.length,t=0;else if(r===void 0&&typeof t=="string")n=t,r=this.length,t=0;else if(isFinite(t))t=t>>>0,isFinite(r)?(r=r>>>0,n===void 0&&(n="utf8")):(n=r,r=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let i=this.length-t;if((r===void 0||r>i)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let o=!1;for(;;)switch(n){case"hex":return cc(this,e,t,r);case"utf8":case"utf-8":return fc(this,e,t,r);case"ascii":case"latin1":case"binary":return hc(this,e,t,r);case"base64":return dc(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return pc(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}};B.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function mc(s,e,t){return e===0&&t===s.length?vr.fromByteArray(s):vr.fromByteArray(s.slice(e,t))}function Jo(s,e,t){t=Math.min(s.length,t);let r=[],n=e;for(;n<t;){let i=s[n],o=null,a=i>239?4:i>223?3:i>191?2:1;if(n+a<=t){let u,l,c,f;switch(a){case 1:i<128&&(o=i);break;case 2:u=s[n+1],(u&192)===128&&(f=(i&31)<<6|u&63,f>127&&(o=f));break;case 3:u=s[n+1],l=s[n+2],(u&192)===128&&(l&192)===128&&(f=(i&15)<<12|(u&63)<<6|l&63,f>2047&&(f<55296||f>57343)&&(o=f));break;case 4:u=s[n+1],l=s[n+2],c=s[n+3],(u&192)===128&&(l&192)===128&&(c&192)===128&&(f=(i&15)<<18|(u&63)<<12|(l&63)<<6|c&63,f>65535&&f<1114112&&(o=f))}}o===null?(o=65533,a=1):o>65535&&(o-=65536,r.push(o>>>10&1023|55296),o=56320|o&1023),r.push(o),n+=a}return gc(r)}var Qo=4096;function gc(s){let e=s.length;if(e<=Qo)return String.fromCharCode.apply(String,s);let t="",r=0;for(;r<e;)t+=String.fromCharCode.apply(String,s.slice(r,r+=Qo));return t}function Ec(s,e,t){let r="";t=Math.min(s.length,t);for(let n=e;n<t;++n)r+=String.fromCharCode(s[n]&127);return r}function Ac(s,e,t){let r="";t=Math.min(s.length,t);for(let n=e;n<t;++n)r+=String.fromCharCode(s[n]);return r}function yc(s,e,t){let r=s.length;(!e||e<0)&&(e=0),(!t||t<0||t>r)&&(t=r);let n="";for(let i=e;i<t;++i)n+=Cc[s[i]];return n}function bc(s,e,t){let r=s.slice(e,t),n="";for(let i=0;i<r.length-1;i+=2)n+=String.fromCharCode(r[i]+r[i+1]*256);return n}B.prototype.slice=function(e,t){let r=this.length;e=~~e,t=t===void 0?r:~~t,e<0?(e+=r,e<0&&(e=0)):e>r&&(e=r),t<0?(t+=r,t<0&&(t=0)):t>r&&(t=r),t<e&&(t=e);let n=this.subarray(e,t);return Object.setPrototypeOf(n,B.prototype),n};function le(s,e,t){if(s%1!==0||s<0)throw new RangeError("offset is not uint");if(s+e>t)throw new RangeError("Trying to access beyond buffer length")}B.prototype.readUintLE=B.prototype.readUIntLE=function(e,t,r){e=e>>>0,t=t>>>0,r||le(e,t,this.length);let n=this[e],i=1,o=0;for(;++o<t&&(i*=256);)n+=this[e+o]*i;return n};B.prototype.readUintBE=B.prototype.readUIntBE=function(e,t,r){e=e>>>0,t=t>>>0,r||le(e,t,this.length);let n=this[e+--t],i=1;for(;t>0&&(i*=256);)n+=this[e+--t]*i;return n};B.prototype.readUint8=B.prototype.readUInt8=function(e,t){return e=e>>>0,t||le(e,1,this.length),this[e]};B.prototype.readUint16LE=B.prototype.readUInt16LE=function(e,t){return e=e>>>0,t||le(e,2,this.length),this[e]|this[e+1]<<8};B.prototype.readUint16BE=B.prototype.readUInt16BE=function(e,t){return e=e>>>0,t||le(e,2,this.length),this[e]<<8|this[e+1]};B.prototype.readUint32LE=B.prototype.readUInt32LE=function(e,t){return e=e>>>0,t||le(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};B.prototype.readUint32BE=B.prototype.readUInt32BE=function(e,t){return e=e>>>0,t||le(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};B.prototype.readBigUInt64LE=qe(function(e){e=e>>>0,mt(e,"offset");let t=this[e],r=this[e+7];(t===void 0||r===void 0)&&vt(e,this.length-8);let n=t+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24,i=this[++e]+this[++e]*2**8+this[++e]*2**16+r*2**24;return BigInt(n)+(BigInt(i)<<BigInt(32))});B.prototype.readBigUInt64BE=qe(function(e){e=e>>>0,mt(e,"offset");let t=this[e],r=this[e+7];(t===void 0||r===void 0)&&vt(e,this.length-8);let n=t*2**24+this[++e]*2**16+this[++e]*2**8+this[++e],i=this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+r;return(BigInt(n)<<BigInt(32))+BigInt(i)});B.prototype.readIntLE=function(e,t,r){e=e>>>0,t=t>>>0,r||le(e,t,this.length);let n=this[e],i=1,o=0;for(;++o<t&&(i*=256);)n+=this[e+o]*i;return i*=128,n>=i&&(n-=Math.pow(2,8*t)),n};B.prototype.readIntBE=function(e,t,r){e=e>>>0,t=t>>>0,r||le(e,t,this.length);let n=t,i=1,o=this[e+--n];for(;n>0&&(i*=256);)o+=this[e+--n]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*t)),o};B.prototype.readInt8=function(e,t){return e=e>>>0,t||le(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};B.prototype.readInt16LE=function(e,t){e=e>>>0,t||le(e,2,this.length);let r=this[e]|this[e+1]<<8;return r&32768?r|4294901760:r};B.prototype.readInt16BE=function(e,t){e=e>>>0,t||le(e,2,this.length);let r=this[e+1]|this[e]<<8;return r&32768?r|4294901760:r};B.prototype.readInt32LE=function(e,t){return e=e>>>0,t||le(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};B.prototype.readInt32BE=function(e,t){return e=e>>>0,t||le(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};B.prototype.readBigInt64LE=qe(function(e){e=e>>>0,mt(e,"offset");let t=this[e],r=this[e+7];(t===void 0||r===void 0)&&vt(e,this.length-8);let n=this[e+4]+this[e+5]*2**8+this[e+6]*2**16+(r<<24);return(BigInt(n)<<BigInt(32))+BigInt(t+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24)});B.prototype.readBigInt64BE=qe(function(e){e=e>>>0,mt(e,"offset");let t=this[e],r=this[e+7];(t===void 0||r===void 0)&&vt(e,this.length-8);let n=(t<<24)+this[++e]*2**16+this[++e]*2**8+this[++e];return(BigInt(n)<<BigInt(32))+BigInt(this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+r)});B.prototype.readFloatLE=function(e,t){return e=e>>>0,t||le(e,4,this.length),pt.read(this,e,!0,23,4)};B.prototype.readFloatBE=function(e,t){return e=e>>>0,t||le(e,4,this.length),pt.read(this,e,!1,23,4)};B.prototype.readDoubleLE=function(e,t){return e=e>>>0,t||le(e,8,this.length),pt.read(this,e,!0,52,8)};B.prototype.readDoubleBE=function(e,t){return e=e>>>0,t||le(e,8,this.length),pt.read(this,e,!1,52,8)};function Ee(s,e,t,r,n,i){if(!B.isBuffer(s))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>n||e<i)throw new RangeError('"value" argument is out of bounds');if(t+r>s.length)throw new RangeError("Index out of range")}B.prototype.writeUintLE=B.prototype.writeUIntLE=function(e,t,r,n){if(e=+e,t=t>>>0,r=r>>>0,!n){let a=Math.pow(2,8*r)-1;Ee(this,e,t,r,a,0)}let i=1,o=0;for(this[t]=e&255;++o<r&&(i*=256);)this[t+o]=e/i&255;return t+r};B.prototype.writeUintBE=B.prototype.writeUIntBE=function(e,t,r,n){if(e=+e,t=t>>>0,r=r>>>0,!n){let a=Math.pow(2,8*r)-1;Ee(this,e,t,r,a,0)}let i=r-1,o=1;for(this[t+i]=e&255;--i>=0&&(o*=256);)this[t+i]=e/o&255;return t+r};B.prototype.writeUint8=B.prototype.writeUInt8=function(e,t,r){return e=+e,t=t>>>0,r||Ee(this,e,t,1,255,0),this[t]=e&255,t+1};B.prototype.writeUint16LE=B.prototype.writeUInt16LE=function(e,t,r){return e=+e,t=t>>>0,r||Ee(this,e,t,2,65535,0),this[t]=e&255,this[t+1]=e>>>8,t+2};B.prototype.writeUint16BE=B.prototype.writeUInt16BE=function(e,t,r){return e=+e,t=t>>>0,r||Ee(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=e&255,t+2};B.prototype.writeUint32LE=B.prototype.writeUInt32LE=function(e,t,r){return e=+e,t=t>>>0,r||Ee(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=e&255,t+4};B.prototype.writeUint32BE=B.prototype.writeUInt32BE=function(e,t,r){return e=+e,t=t>>>0,r||Ee(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4};function Zo(s,e,t,r,n){na(e,r,n,s,t,7);let i=Number(e&BigInt(4294967295));s[t++]=i,i=i>>8,s[t++]=i,i=i>>8,s[t++]=i,i=i>>8,s[t++]=i;let o=Number(e>>BigInt(32)&BigInt(4294967295));return s[t++]=o,o=o>>8,s[t++]=o,o=o>>8,s[t++]=o,o=o>>8,s[t++]=o,t}function ea(s,e,t,r,n){na(e,r,n,s,t,7);let i=Number(e&BigInt(4294967295));s[t+7]=i,i=i>>8,s[t+6]=i,i=i>>8,s[t+5]=i,i=i>>8,s[t+4]=i;let o=Number(e>>BigInt(32)&BigInt(4294967295));return s[t+3]=o,o=o>>8,s[t+2]=o,o=o>>8,s[t+1]=o,o=o>>8,s[t]=o,t+8}B.prototype.writeBigUInt64LE=qe(function(e,t=0){return Zo(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))});B.prototype.writeBigUInt64BE=qe(function(e,t=0){return ea(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))});B.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t=t>>>0,!n){let u=Math.pow(2,8*r-1);Ee(this,e,t,r,u-1,-u)}let i=0,o=1,a=0;for(this[t]=e&255;++i<r&&(o*=256);)e<0&&a===0&&this[t+i-1]!==0&&(a=1),this[t+i]=(e/o>>0)-a&255;return t+r};B.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t=t>>>0,!n){let u=Math.pow(2,8*r-1);Ee(this,e,t,r,u-1,-u)}let i=r-1,o=1,a=0;for(this[t+i]=e&255;--i>=0&&(o*=256);)e<0&&a===0&&this[t+i+1]!==0&&(a=1),this[t+i]=(e/o>>0)-a&255;return t+r};B.prototype.writeInt8=function(e,t,r){return e=+e,t=t>>>0,r||Ee(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=e&255,t+1};B.prototype.writeInt16LE=function(e,t,r){return e=+e,t=t>>>0,r||Ee(this,e,t,2,32767,-32768),this[t]=e&255,this[t+1]=e>>>8,t+2};B.prototype.writeInt16BE=function(e,t,r){return e=+e,t=t>>>0,r||Ee(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=e&255,t+2};B.prototype.writeInt32LE=function(e,t,r){return e=+e,t=t>>>0,r||Ee(this,e,t,4,2147483647,-2147483648),this[t]=e&255,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4};B.prototype.writeInt32BE=function(e,t,r){return e=+e,t=t>>>0,r||Ee(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4};B.prototype.writeBigInt64LE=qe(function(e,t=0){return Zo(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});B.prototype.writeBigInt64BE=qe(function(e,t=0){return ea(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function ta(s,e,t,r,n,i){if(t+r>s.length)throw new RangeError("Index out of range");if(t<0)throw new RangeError("Index out of range")}function sa(s,e,t,r,n){return e=+e,t=t>>>0,n||ta(s,e,t,4,34028234663852886e22,-34028234663852886e22),pt.write(s,e,t,r,23,4),t+4}B.prototype.writeFloatLE=function(e,t,r){return sa(this,e,t,!0,r)};B.prototype.writeFloatBE=function(e,t,r){return sa(this,e,t,!1,r)};function ra(s,e,t,r,n){return e=+e,t=t>>>0,n||ta(s,e,t,8,17976931348623157e292,-17976931348623157e292),pt.write(s,e,t,r,52,8),t+8}B.prototype.writeDoubleLE=function(e,t,r){return ra(this,e,t,!0,r)};B.prototype.writeDoubleBE=function(e,t,r){return ra(this,e,t,!1,r)};B.prototype.copy=function(e,t,r,n){if(!B.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),!n&&n!==0&&(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n<r&&(n=r),n===r||e.length===0||this.length===0)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t<n-r&&(n=e.length-t+r);let i=n-r;return this===e&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(t,r,n):Uint8Array.prototype.set.call(e,this.subarray(r,n),t),i};B.prototype.fill=function(e,t,r,n){if(typeof e=="string"){if(typeof t=="string"?(n=t,t=0,r=this.length):typeof r=="string"&&(n=r,r=this.length),n!==void 0&&typeof n!="string")throw new TypeError("encoding must be a string");if(typeof n=="string"&&!B.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(e.length===1){let o=e.charCodeAt(0);(n==="utf8"&&o<128||n==="latin1")&&(e=o)}}else typeof e=="number"?e=e&255:typeof e=="boolean"&&(e=Number(e));if(t<0||this.length<t||this.length<r)throw new RangeError("Out of range index");if(r<=t)return this;t=t>>>0,r=r===void 0?this.length:r>>>0,e||(e=0);let i;if(typeof e=="number")for(i=t;i<r;++i)this[i]=e;else{let o=B.isBuffer(e)?e:B.from(e,n),a=o.length;if(a===0)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(i=0;i<r-t;++i)this[i+t]=o[i%a]}return this};var dt={};function _r(s,e,t){dt[s]=class extends t{constructor(){super(),Object.defineProperty(this,"message",{value:e.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${s}]`,this.stack,delete this.name}get code(){return s}set code(n){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:n,writable:!0})}toString(){return`${this.name} [${s}]: ${this.message}`}}}_r("ERR_BUFFER_OUT_OF_BOUNDS",function(s){return s?`${s} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError);_r("ERR_INVALID_ARG_TYPE",function(s,e){return`The "${s}" argument must be of type number. Received type ${typeof e}`},TypeError);_r("ERR_OUT_OF_RANGE",function(s,e,t){let r=`The value of "${s}" is out of range.`,n=t;return Number.isInteger(t)&&Math.abs(t)>2**32?n=Yo(String(t)):typeof t=="bigint"&&(n=String(t),(t>BigInt(2)**BigInt(32)||t<-(BigInt(2)**BigInt(32)))&&(n=Yo(n)),n+="n"),r+=` It must be ${e}. Received ${n}`,r},RangeError);function Yo(s){let e="",t=s.length,r=s[0]==="-"?1:0;for(;t>=r+4;t-=3)e=`_${s.slice(t-3,t)}${e}`;return`${s.slice(0,t)}${e}`}function Tc(s,e,t){mt(e,"offset"),(s[e]===void 0||s[e+t]===void 0)&&vt(e,s.length-(t+1))}function na(s,e,t,r,n,i){if(s>t||s<e){let o=typeof e=="bigint"?"n":"",a;throw i>3?e===0||e===BigInt(0)?a=`>= 0${o} and < 2${o} ** ${(i+1)*8}${o}`:a=`>= -(2${o} ** ${(i+1)*8-1}${o}) and < 2 ** ${(i+1)*8-1}${o}`:a=`>= ${e}${o} and <= ${t}${o}`,new dt.ERR_OUT_OF_RANGE("value",a,s)}Tc(r,n,i)}function mt(s,e){if(typeof s!="number")throw new dt.ERR_INVALID_ARG_TYPE(e,"number",s)}function vt(s,e,t){throw Math.floor(s)!==s?(mt(s,t),new dt.ERR_OUT_OF_RANGE(t||"offset","an integer",s)):e<0?new dt.ERR_BUFFER_OUT_OF_BOUNDS:new dt.ERR_OUT_OF_RANGE(t||"offset",`>= ${t?1:0} and <= ${e}`,s)}var Sc=/[^+/0-9A-Za-z-_]/g;function Ic(s){if(s=s.split("=")[0],s=s.trim().replace(Sc,""),s.length<2)return"";for(;s.length%4!==0;)s=s+"=";return s}function kr(s,e){e=e||1/0;let t,r=s.length,n=null,i=[];for(let o=0;o<r;++o){if(t=s.charCodeAt(o),t>55295&&t<57344){if(!n){if(t>56319){(e-=3)>-1&&i.push(239,191,189);continue}else if(o+1===r){(e-=3)>-1&&i.push(239,191,189);continue}n=t;continue}if(t<56320){(e-=3)>-1&&i.push(239,191,189),n=t;continue}t=(n-55296<<10|t-56320)+65536}else n&&(e-=3)>-1&&i.push(239,191,189);if(n=null,t<128){if((e-=1)<0)break;i.push(t)}else if(t<2048){if((e-=2)<0)break;i.push(t>>6|192,t&63|128)}else if(t<65536){if((e-=3)<0)break;i.push(t>>12|224,t>>6&63|128,t&63|128)}else if(t<1114112){if((e-=4)<0)break;i.push(t>>18|240,t>>12&63|128,t>>6&63|128,t&63|128)}else throw new Error("Invalid code point")}return i}function Oc(s){let e=[];for(let t=0;t<s.length;++t)e.push(s.charCodeAt(t)&255);return e}function xc(s,e){let t,r,n,i=[];for(let o=0;o<s.length&&!((e-=2)<0);++o)t=s.charCodeAt(o),r=t>>8,n=t%256,i.push(n),i.push(r);return i}function ia(s){return vr.toByteArray(Ic(s))}function cs(s,e,t,r){let n;for(n=0;n<r&&!(n+t>=e.length||n>=s.length);++n)e[n+t]=s[n];return n}function ve(s,e){return s instanceof e||s!=null&&s.constructor!=null&&s.constructor.name!=null&&s.constructor.name===e.name}function Gr(s){return s!==s}var Cc=(function(){let s="0123456789abcdef",e=new Array(256);for(let t=0;t<16;++t){let r=t*16;for(let n=0;n<16;++n)e[r+n]=s[t]+s[n]}return e})();function qe(s){return typeof BigInt>"u"?wc:s}function wc(){throw new Error("BigInt not supported")}});function oa(){let s=jr.shift();jr.length||Et?.port1.unref?.(),s&&!s.cleared&&s.fn(...s.args)}function R(s,...e){if(typeof globalThis.setImmediate=="function")return globalThis.setImmediate(s,...e);let t={fn:s,args:e,cleared:!1};return jr.push(t),typeof MessageChannel=="function"?(Et||(Et=new MessageChannel,Et.port1.onmessage=oa),Et.port1.ref?.(),Et.port2.postMessage(null)):setTimeout(oa,0),t}function D(s){if(typeof globalThis.clearImmediate=="function")return globalThis.clearImmediate(s);s&&typeof s=="object"&&(s.cleared=!0)}var b,jr,Et,U,g=Lr(()=>{"use strict";b=Ut(Xr(),1),jr=[],Et=null;U=globalThis.process||{env:{},nextTick:(s,...e)=>queueMicrotask(()=>s(...e))}});var ds=as((yp,Vr)=>{"use strict";g();var At=typeof Reflect=="object"?Reflect:null,aa=At&&typeof At.apply=="function"?At.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)},fs;At&&typeof At.ownKeys=="function"?fs=At.ownKeys:Object.getOwnPropertySymbols?fs=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:fs=function(e){return Object.getOwnPropertyNames(e)};function Nc(s){console&&console.warn&&console.warn(s)}var la=Number.isNaN||function(e){return e!==e};function oe(){oe.init.call(this)}Vr.exports=oe;Vr.exports.once=Dc;oe.EventEmitter=oe;oe.prototype._events=void 0;oe.prototype._eventsCount=0;oe.prototype._maxListeners=void 0;var ua=10;function hs(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(oe,"defaultMaxListeners",{enumerable:!0,get:function(){return ua},set:function(s){if(typeof s!="number"||s<0||la(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");ua=s}});oe.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};oe.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||la(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function ca(s){return s._maxListeners===void 0?oe.defaultMaxListeners:s._maxListeners}oe.prototype.getMaxListeners=function(){return ca(this)};oe.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var n=e==="error",i=this._events;if(i!==void 0)n=n&&i.error===void 0;else if(!n)return!1;if(n){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var u=i[e];if(u===void 0)return!1;if(typeof u=="function")aa(u,this,t);else for(var l=u.length,c=ma(u,l),r=0;r<l;++r)aa(c[r],this,t);return!0};function fa(s,e,t,r){var n,i,o;if(hs(t),i=s._events,i===void 0?(i=s._events=Object.create(null),s._eventsCount=0):(i.newListener!==void 0&&(s.emit("newListener",e,t.listener?t.listener:t),i=s._events),o=i[e]),o===void 0)o=i[e]=t,++s._eventsCount;else if(typeof o=="function"?o=i[e]=r?[t,o]:[o,t]:r?o.unshift(t):o.push(t),n=ca(s),n>0&&o.length>n&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=s,a.type=e,a.count=o.length,Nc(a)}return s}oe.prototype.addListener=function(e,t){return fa(this,e,t,!1)};oe.prototype.on=oe.prototype.addListener;oe.prototype.prependListener=function(e,t){return fa(this,e,t,!0)};function Mc(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function ha(s,e,t){var r={fired:!1,wrapFn:void 0,target:s,type:e,listener:t},n=Mc.bind(r);return n.listener=t,r.wrapFn=n,n}oe.prototype.once=function(e,t){return hs(t),this.on(e,ha(this,e,t)),this};oe.prototype.prependOnceListener=function(e,t){return hs(t),this.prependListener(e,ha(this,e,t)),this};oe.prototype.removeListener=function(e,t){var r,n,i,o,a;if(hs(t),n=this._events,n===void 0)return this;if(r=n[e],r===void 0)return this;if(r===t||r.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,r.listener||t));else if(typeof r!="function"){for(i=-1,o=r.length-1;o>=0;o--)if(r[o]===t||r[o].listener===t){a=r[o].listener,i=o;break}if(i<0)return this;i===0?r.shift():Rc(r,i),r.length===1&&(n[e]=r[0]),n.removeListener!==void 0&&this.emit("removeListener",e,a||t)}return this};oe.prototype.off=oe.prototype.removeListener;oe.prototype.removeAllListeners=function(e){var t,r,n;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[e]),this;if(arguments.length===0){var i=Object.keys(r),o;for(n=0;n<i.length;++n)o=i[n],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=r[e],typeof t=="function")this.removeListener(e,t);else if(t!==void 0)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this};function da(s,e,t){var r=s._events;if(r===void 0)return[];var n=r[e];return n===void 0?[]:typeof n=="function"?t?[n.listener||n]:[n]:t?Lc(n):ma(n,n.length)}oe.prototype.listeners=function(e){return da(this,e,!0)};oe.prototype.rawListeners=function(e){return da(this,e,!1)};oe.listenerCount=function(s,e){return typeof s.listenerCount=="function"?s.listenerCount(e):pa.call(s,e)};oe.prototype.listenerCount=pa;function pa(s){var e=this._events;if(e!==void 0){var t=e[s];if(typeof t=="function")return 1;if(t!==void 0)return t.length}return 0}oe.prototype.eventNames=function(){return this._eventsCount>0?fs(this._events):[]};function ma(s,e){for(var t=new Array(e),r=0;r<e;++r)t[r]=s[r];return t}function Rc(s,e){for(;e+1<s.length;e++)s[e]=s[e+1];s.pop()}function Lc(s){for(var e=new Array(s.length),t=0;t<e.length;++t)e[t]=s[t].listener||s[t];return e}function Dc(s,e){return new Promise(function(t,r){function n(o){s.removeListener(e,i),r(o)}function i(){typeof s.removeListener=="function"&&s.removeListener("error",n),t([].slice.call(arguments))}ga(s,e,i,{once:!0}),e!=="error"&&Uc(s,n,{once:!0})})}function Uc(s,e,t){typeof s.on=="function"&&ga(s,"error",e,t)}function ga(s,e,t,r){if(typeof s.on=="function")r.once?s.once(e,t):s.on(e,t);else if(typeof s.addEventListener=="function")s.addEventListener(e,function n(i){r.once&&s.removeEventListener(e,n),t(i)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}});var Cr,Ml=Lr(()=>{g();Cr=class{constructor(){throw new Error("SMTP is not available in the browser")}}});var Rl={};Kl(Rl,{startSMTPServer:()=>zd});function zd(s,e,t,r){let n=e.getCredentials(),i=new Cr({banner:"ImapKit",key:n.key,cert:n.cert,authOptional:!0,authMethods:e.oauth?["PLAIN","LOGIN","XOAUTH2"]:["PLAIN","LOGIN"],logger:!1,onAuth(a,u,l){if(a.method!=="XOAUTH2")return l(null,{user:a.username});let c=e.checkAccessToken(a.accessToken||"",a.username,"smtp");if("error"in c)return l(null,{data:{status:"401",schemes:"bearer",scope:e.oauth.mailScope}});l(null,{user:c.user})},onData(a,u,l){let c=[];a.on("data",f=>c.push(f)),a.on("error",l),a.on("end",()=>{e.appendMessage("INBOX",[],!1,b.Buffer.concat(c).toString("binary")),l()})}});i.on("error",a=>{e.options.debug&&console.error("SMTP server error: %s",a.message)});let o=()=>t?.(i.server.address().port);return r?i.listen(s,r,o):i.listen(s,o),i}var Ll=Lr(()=>{"use strict";g();Ml()});g();g();g();var Ea=Ut(ds()),ps=class extends Ea.default{};g();var Qr=Ut(ds()),Yr=s=>()=>{throw new Error(s+" is not available in the browser, open connections with server.connect()")},ms=class extends Qr.default{},qr=class extends ms{constructor(){super(),Yr("TLS")()}},gs=class extends Qr.default{listen(){Yr("listen()")()}close(e){return e&&queueMicrotask(()=>e()),this}address(){return null}},vc=()=>new gs,Bc=Yr("TLS"),Qe={Socket:ms,TLSSocket:qr,Server:gs,createServer:vc,createSecureContext:Bc};g();g();g();var Hc=Ut(Xr());function Ye(s){try{return new TextDecoder("utf-8",{fatal:!0}).decode(s),!0}catch{return!1}}g();var xe=s=>{let e;return()=>(e===void 0&&(e=s()),e)},tt=(s,e)=>{let t=[];for(let r=s;r<=e;r++)t.push(r);return String.fromCharCode(...t)},Es=(s,e)=>Array.from(s).filter(t=>!e.includes(t)).join(""),kc=xe(()=>new Set(me["ATOM-CHAR"]())),me={CHAR:xe(()=>tt(1,127)),CHAR8:xe(()=>tt(1,255)),SP:()=>" ",CTL:xe(()=>tt(0,31)+"\x7F"),DQUOTE:()=>'"',ALPHA:xe(()=>tt(65,90)+tt(97,122)),DIGIT:xe(()=>tt(48,57)),"ATOM-CHAR":xe(()=>Es(me.CHAR(),me["atom-specials"]())),"ASTRING-CHAR":xe(()=>me["ATOM-CHAR"]()+me["resp-specials"]()),"TEXT-CHAR":xe(()=>Es(me.CHAR(),`\r
|
|
2
|
+
`)),"atom-specials":xe(()=>"(){"+me.SP()+me.CTL()+me["list-wildcards"]()+me["quoted-specials"]()+me["resp-specials"]()),"list-wildcards":()=>"%*","quoted-specials":()=>me.DQUOTE()+"\\","resp-specials":()=>"]",tag:xe(()=>Es(me["ASTRING-CHAR"](),"+")),command:xe(()=>me["ATOM-CHAR"]()),_expandRange:tt,_excludeChars:Es,isAtomChar(s){return kc().has(s)},isSequenceSet(s){return!!s&&s.split(",").every(e=>/^(?:\d+|\*)(?::(?:\d+|\*))?$/.test(e))},verify(s,e){for(let t=0,r=s.length;t<r;t++)if(e.indexOf(s.charAt(t))<0)return t;return-1}},he=me;var Pc=4294967295,Fc=Number.MAX_SAFE_INTEGER,_c=25,Gc=s=>he.isAtomChar(s),Kr=s=>s>=48&&s<=57,Xc=s=>he.isSequenceSet(s),ae=(s,e,t)=>{let r=new Error(s+" at position "+e);return r.code=t||"ParserError",r.pos=e,r};function $r(s,e){let t={...e,allowSection:e?.allowSection||["BODY","BODY.PEEK"],multiWords:e?.multiWords||["UID","AUTHENTICATE"],allowUntagged:!!e?.allowUntagged},r=new zr(s,t),n=r.getTag();r.getSpace();let i={tag:n,command:r.getCommand()};return t.multiWords.indexOf((i.command||"").toUpperCase())>=0&&(r.getSpace(),i.command+=" "+r.getElement(he.command())),r.remainder.length&&(r.getSpace(),i.attributes=r.getAttributes()),i}var zr=class{constructor(e,t){this.input=(e||"").toString(),this.options=t,this.remainder=this.input,this.pos=0}getTag(){return this.tag||(this.tag=this.getElement(he.tag()+(this.options.allowUntagged?"*":""))),this.tag}getCommand(){return this.command||(this.command=this.getElement(he.command())),this.command}getElement(e){let t;if(this.remainder.match(/^\s/))throw ae("Unexpected whitespace",this.pos);let r=this.remainder.match(/^[^\s]+(?=\s|$)/);if(!r)throw ae("Unexpected end of input",this.pos);let n=r[0];if((t=he.verify(n,e))>=0)throw ae("Unexpected char",this.pos+t);return this.pos+=n.length,this.remainder=this.remainder.substring(n.length),n}getSpace(){if(!this.remainder.length)throw ae("Unexpected end of input",this.pos);if(he.verify(this.remainder.charAt(0),he.SP())>=0)throw ae("Unexpected char",this.pos);this.pos++,this.remainder=this.remainder.substring(1)}getAttributes(){if(!this.remainder.length)throw ae("Unexpected end of input",this.pos);if(this.remainder.match(/^\s/))throw ae("Unexpected whitespace",this.pos);return new Wr(this.pos,this.remainder,this.options).getAttributes()}},Wr=class{constructor(e,t,r){this.str=(t||"").toString(),this.options=r,this.pos=e||0,this.maxSectionName=Math.max(0,...this.options.allowSection.map(n=>n.length)),this.maxNumber=this.options.number64?Fc:Pc,this.tree=this.currentNode=this.createNode(),this.currentNode.type="TREE",this.processString()}getAttributes(){let e=[],t=e,r=()=>t[t.length-1],n=i=>{let o,a=t;if(!i.closed)throw ae("Unexpected end of input",this.pos+this.str.length);switch(i.type){case"LITERAL":case"LITERAL8":case"ATOM":case"STRING":case"SEQUENCE":if(i.type==="ATOM"&&i.value.toUpperCase()==="NIL"){t.push(null);break}o={type:i.type,value:i.value},t.push(o);break;case"SECTION":t=r().section=[];break;case"LIST":o=[],t.push(o),t=o;break;case"PARTIAL":r().partial=i.value.split(".").map(Number);break}i.childNodes.forEach(n),t=a};return n(this.tree),e}createNode(e,t){let r={childNodes:[],type:!1,value:"",closed:!0,depth:e?e.depth+1:0};if(r.depth>_c)throw ae("Too much nesting",t,"MaxNestingReached");return e&&(r.parentNode=e,e.childNodes.push(r)),typeof t=="number"&&(r.startPos=t),r}addValue(e,t,r,n){let i=this.createNode(this.currentNode,this.pos+r);return i.type=e,i.value=t,i.endPos=this.pos+n-1,i}closeNode(e){this.currentNode.closed=!0,this.currentNode.endPos=this.pos+e,this.currentNode=this.currentNode.parentNode}unexpected(e){return ae(e>=this.str.length?"Unexpected end of input":"Unexpected char",this.pos+e)}afterValue(e){let t=this.str;if(e>=t.length)return e;let r=t.charAt(e);if(r===" "){let n=t.charAt(e+1);if(e+1>=t.length||n===" "||n===")"||n==="]"&&this.currentNode.type==="SECTION")throw ae("Unexpected whitespace",this.pos+e);return e+1}if(r===")"&&this.currentNode.type==="LIST"||r==="]"&&this.currentNode.type==="SECTION")return e;throw ae("Unexpected char",this.pos+e)}processString(){let e=this.str,t=e.length,r=0;for(;r<t;)switch(e.charAt(r)){case" ":throw ae("Unexpected whitespace",this.pos+r);case'"':r=this.readString(r);break;case"(":this.currentNode=this.createNode(this.currentNode,this.pos+r),this.currentNode.type="LIST",this.currentNode.closed=!1,r++;break;case")":if(this.currentNode.type!=="LIST")throw ae("Unexpected list terminator )",this.pos+r);this.closeNode(r),r=this.afterValue(r+1);break;case"]":if(this.currentNode.type!=="SECTION"){r=this.readAtom(r);break}this.closeNode(r),r=this.str.charAt(r+1)==="<"?this.readPartial(r+1):this.afterValue(r+1);break;case"{":r=this.readLiteral(r,!1);break;case"~":r=this.options.literal8&&e.charAt(r+1)==="{"?this.readLiteral(r,!0):this.readAtom(r);break;default:r=this.readAtom(r);break}}readAtom(e){let t=this.str,r=t.length,n=this.currentNode.type,i=!0,o=!0,a;for(a=e;a<r;a++){let c=t.charAt(a),f=t.charCodeAt(a);if(c===" "||c===")"&&n==="LIST"||c==="]"&&n==="SECTION")break;if(c==="["&&a>e&&a-e<=this.maxSectionName&&this.options.allowSection.indexOf(t.slice(e,a).toUpperCase())>=0)return this.addValue("ATOM",t.slice(e,a),e,a),this.currentNode=this.createNode(this.currentNode,this.pos+a),this.currentNode.type="SECTION",this.currentNode.closed=!1,a+1;if(!Gc(c)&&c!=="%"&&c!=="*"&&c!=="]"&&!(c==="\\"&&a===e))throw ae("Unexpected char",this.pos+a);Kr(f)||(o=!1,c!==":"&&c!==","&&c!=="*"&&(i=!1))}if(a===e)throw ae("Unexpected char",this.pos+a);let u=t.slice(e,a),l="ATOM";return i&&!o&&u!=="*"&&Xc(u)&&(l="SEQUENCE"),this.addValue(l,u,e,a),this.afterValue(a)}readString(e){let t=this.str,r=t.length,n=!!this.options.utf8,i=!1,o="",a=e+1;for(let u=e+1;u<r;u++){let l=t.charCodeAt(u);if(l===34){if(i&&!Ye(b.Buffer.from(t.slice(e+1,u),"binary")))throw ae("Invalid UTF-8",this.pos+e+1);return o+=t.slice(a,u),this.addValue("STRING",o,e,u+1),this.afterValue(u+1)}if(l===92){if(u+1>=r)throw ae("Unexpected end of input",this.pos+u+1);let c=t.charAt(u+1);if(c!=='"'&&c!=="\\")throw ae("Unexpected escaped char",this.pos+u+1);o+=t.slice(a,u)+c,u++,a=u+1;continue}if(n&&l>127&&l<=255){i=!0;continue}if(l===0||l===10||l===13||l>127)throw ae("Unexpected char",this.pos+u)}throw ae("Unexpected end of input",this.pos+r)}readLiteral(e,t){let r=this.str,n=r.length,i=e+(t?2:1),o=i;for(;o<n&&Kr(r.charCodeAt(o));)o++;if(o===i)throw this.unexpected(o);let a=Number(r.slice(i,o));if(r.charAt(o)==="+"&&this.options.literalPlus&&o++,r.charAt(o)!=="}")throw this.unexpected(o);if(o++,r.charAt(o)===`
|
|
3
|
+
`)o++;else if(r.charAt(o)==="\r"&&r.charAt(o+1)===`
|
|
4
|
+
`)o+=2;else throw this.unexpected(o);if(a>this.maxNumber||o+a>n)throw ae("Unexpected end of input",this.pos+n);let u=r.substring(o,o+a);if(!t){let l=u.indexOf("\0");if(l>=0)throw ae("Unexpected \\x00",this.pos+o+l)}return this.addValue(t?"LITERAL8":"LITERAL",u,e,o+a),this.afterValue(o+a)}readPartial(e){let t=this.str,r=t.length,n=e+1,i=o=>{let a=n;for(;n<r&&Kr(t.charCodeAt(n));)n++;if(n===a)throw this.unexpected(n);if(o&&t.charAt(a)==="0")throw ae("Invalid partial",this.pos+a);if(Number(t.slice(a,n))>this.maxNumber)throw ae("Invalid partial",this.pos+a)};if(i(!1),t.charAt(n)==="."&&(n++,i(!0)),t.charAt(n)!==">")throw this.unexpected(n);return this.addValue("PARTIAL",t.slice(e+1,n),e,n+1),this.afterValue(n+1)}};g();var ya=/[\x00\r\n\x80-\uffff]/,ba=/[\x00\r\n\u0100-\uffff]/,jc=s=>{for(let e=0,t=s.length;e<t;e++)if(!he.isAtomChar(s.charAt(e)))return!1;return!!s.length},Vc=s=>s==="\\*"||jc(s.charAt(0)==="\\"?s.slice(1):s),qc=s=>s==="$"||he.isSequenceSet(s),Jr=s=>{let e=Math.round(Number(s));return Number.isSafeInteger(e)&&e>=0?e:0},Fe=s=>b.Buffer.isBuffer(s)?s.toString("binary"):s==null?"":String(s),As=s=>"{"+s.length+`}\r
|
|
5
|
+
`+s,Ta=s=>'"'+s.replace(/["\\]/g,"\\$&")+'"',Qc=s=>"~"+As(s),Yc=s=>ya.test(s)?As(s):Ta(s),Kc=s=>!ya.test(s)||!ba.test(s)&&Ye(b.Buffer.from(s,"binary"))?Ta(s):As(s),en=(s,e)=>{let t=new Error(s);return t.code=e,t},Zr=(s,e)=>{if(ba.test(s))throw en("Line break or NUL in "+e,"InvalidTextValue");return s},Aa=s=>[].concat(s||[]);function tn(s,e){let t=e&&e.utf8?Kc:Yc,r=Zr(Fe(s.tag),"tag")+(s.command?" "+Zr(Fe(s.command),"command"):""),n=!1,i=o=>{if(n||(r+=" "),n=!1,Array.isArray(o)){let u=o;r+="(",n=!0;let l=0;if(u.adjacentLists)for(;l<u.length&&Array.isArray(u[l]);)l++;u.forEach((c,f)=>{f&&f<l&&(n=!0),i(c)}),r+=")",n=!1;return}if(b.Buffer.isBuffer(o)){r+=t(Fe(o));return}if(!o&&typeof o!="string"&&typeof o!="number"){r+="NIL";return}if(typeof o=="string"){r+=t(o);return}if(typeof o=="number"){r+=Jr(o);return}let a;switch(typeof o.type=="string"?o.type.toUpperCase():""){case"LITERAL":r+=As(Fe(o.value));break;case"LITERAL8":r+=Qc(Fe(o.value));break;case"STRING":r+=t(Fe(o.value));break;case"TEXT":r+=Zr(Fe(o.value),"TEXT value");break;case"SEQUENCE":if(a=Fe(o.value),!qc(a))throw en("Invalid sequence set","InvalidSequenceSet");r+=a;break;case"NUMBER":r+=Jr(o.value);break;case"ATOM":case"SECTION":a=Fe(o.value),(a||!o.section)&&(r+=Vc(a)?a:t(a)),o.section&&(r+="[",n=!0,o.section.forEach(i),r+="]",n=!1),o.partial&&(r+="<"+Aa(o.partial).map(Jr).join(".")+">");break;default:throw en("Unknown node type "+JSON.stringify(o.type),"InvalidNodeType")}};return Aa(s.attributes).forEach(i),r}var st={parser:$r,compiler:tn};g();g();g();g();var ys=["Not Authenticated","Authenticated","Selected"],bs=["Not Authenticated"],Ce=["Authenticated","Selected"],Re=["Selected"];function re(s){let e=(Array.isArray(s)?{states:s}:s)||{};return{states:e.states?[].concat(e.states):!1,noArguments:!!e.noArguments,mailboxArguments:[].concat(e.mailboxArguments||[]),astringArguments:[].concat(e.astringArguments||[]),searchCriteria:typeof e.searchCriteria=="number"?e.searchCriteria:!1,sequenceSet:typeof e.sequenceSet=="number"?e.sequenceSet:!1,noExpunge:!!e.noExpunge,literal8:e.literal8===!0||typeof e.literal8=="string"?e.literal8:!1,noPipelining:!!e.noPipelining,appendMessage:!!e.appendMessage}}var Sa={CAPABILITY:re({states:ys,noArguments:!0}),NOOP:re({states:ys,noArguments:!0}),LOGOUT:re({states:ys,noArguments:!0}),STARTTLS:re({states:bs,noArguments:!0,noPipelining:!0}),LOGIN:re({states:bs,astringArguments:[0,1]}),SELECT:re({states:Ce,mailboxArguments:[0]}),EXAMINE:re({states:Ce,mailboxArguments:[0]}),CREATE:re({states:Ce,mailboxArguments:[0]}),DELETE:re({states:Ce,mailboxArguments:[0]}),RENAME:re({states:Ce,mailboxArguments:[0,1]}),SUBSCRIBE:re({states:Ce,mailboxArguments:[0]}),UNSUBSCRIBE:re({states:Ce,mailboxArguments:[0]}),LIST:re({states:Ce,astringArguments:[0,1]}),LSUB:re({states:Ce,astringArguments:[0,1]}),STATUS:re({states:Ce,mailboxArguments:[0]}),APPEND:re({states:Ce,mailboxArguments:[0],literal8:"BINARY",appendMessage:!0}),CHECK:re({states:Re,noArguments:!0}),CLOSE:re({states:Re,noArguments:!0}),EXPUNGE:re({states:Re,noArguments:!0}),SEARCH:re({states:Re,searchCriteria:0,noExpunge:!0}),FETCH:re({states:Re,sequenceSet:0,noExpunge:!0}),STORE:re({states:Re,sequenceSet:0,noExpunge:!0}),COPY:re({states:Re,sequenceSet:0,mailboxArguments:[1]}),"UID COPY":re({states:Re,mailboxArguments:[1]}),"UID SEARCH":re({states:Re,searchCriteria:0})},zc=re({states:Re}),Wc=re({states:bs});function Ia(s){return Object.hasOwn(Sa,s)?Sa[s]:/^UID /.test(s)?zc:/^AUTHENTICATE /.test(s)?Wc:!1}var Z={ANY:ys,NOT_AUTHENTICATED:bs,AUTHENTICATED:Ce,SELECTED:Re};g();var sn=/[\x00-\x1f\x7f (){%*"\\\]]/;function be(s){return s.charAt(0)==="\\"&&(s=s.charAt(0)+s.charAt(1).toUpperCase()+s.substr(2).toLowerCase()),s}function we(s,e){if(e.charAt(0)==="\\"){if(s.systemFlags.indexOf(e)<0)throw new Error("Invalid system flag "+e)}else if(!e||sn.test(e))throw new Error("Invalid flag keyword "+JSON.stringify(e))}g();var rt={},Ts=rt;function Oa(s,e,t){let r=s.selectedMailbox,n=[];[].concat(t).forEach(i=>{i=be(typeof i=="string"?i:String(i.value||"")),we(s.server,i),s.server.isPermanentFlag(r,i)&&n.indexOf(i)<0&&n.push(i)}),e.flags=n,s.server.rememberFlags(r,n)}function xa(s,e,t){let r=s.selectedMailbox;[].concat(t).forEach(n=>{n=be(typeof n=="string"?n:String(n.value||"")),we(s.server,n),s.server.isPermanentFlag(r,n)&&e.flags.indexOf(n)<0&&e.flags.push(n)}),s.server.rememberFlags(r,e.flags)}function Ca(s,e,t){[].concat(t).forEach(r=>{if(r=be(typeof r=="string"?r:String(r.value||"")),we(s.server,r),e.flags.indexOf(r)>=0){for(let n=0;n<e.flags.length;n++)if(e.flags[n]===r){e.flags.splice(n,1);break}}})}function rn(s,e,t,r,n){let i=[{type:"ATOM",value:"FLAGS"},s.getFlags(n).map(o=>({type:"ATOM",value:o}))];(e.command||"").toUpperCase()==="UID STORE"&&(i.push({type:"ATOM",value:"UID"}),i.push(n.uid)),s.send({tag:"*",attributes:[r,{type:"ATOM",value:"FETCH"},i]},"FLAG UPDATE",e,t,n)}rt.FLAGS=function(s,e,t,r,n,i){Oa(s,e,t),rn(s,n,i,r,e)};rt["+FLAGS"]=function(s,e,t,r,n,i){xa(s,e,t),rn(s,n,i,r,e)};rt["-FLAGS"]=function(s,e,t,r,n,i){Ca(s,e,t),rn(s,n,i,r,e)};rt["FLAGS.SILENT"]=function(s,e,t){Oa(s,e,t)};rt["+FLAGS.SILENT"]=function(s,e,t){xa(s,e,t)};rt["-FLAGS.SILENT"]=function(s,e,t){Ca(s,e,t)};g();function Ke(s){return s.listExtensions||(s.listExtensions={enabled:!1,selectionOptions:Object.create(null),returnOptions:Object.create(null)}),s.listExtensions}g();function nn(s,e,t,r){return an(s,e,t,r,!1)}function on(s,e,t){s.everSelected=!0,s.state==="Selected"&&s.server.closedChecks.some(r=>r(s))&&s.send({tag:"*",command:"OK",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"CLOSED"}]},{type:"TEXT",value:"Previous mailbox closed"}]},"CLOSED",e,t)}function an(s,e,t,r,n){let i=n?"EXAMINE":"SELECT";if(!e.attributes||e.attributes.length!==1||!e.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[0].type)<0)return s.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:i+" expects 1 mailbox argument"}]},"INVALID COMMAND",e,t),r();let o=e.attributes[0].value;on(s,e,t);let a=s.server.getMailbox(o);if(!a||a.flags.indexOf("\\Noselect")>=0)return s.closeMailbox(),s.sendStatus(e,t,"NO","Mailbox does not exist","NONEXISTENT",i+" FAILED"),r();s.state="Selected",s.selectedMailbox=a,s.readOnly=n,s.emitSession("select"),s.notificationQueue=[];let u=new Set;s.recent=u,a.messages.forEach(p=>{p.recent&&(u.add(p),n||delete p.recent)});let c=s.server.getStatus(a).permanentFlags.map(p=>({type:"ATOM",value:p}));s.send({tag:"*",command:"FLAGS",attributes:[c]},i+" FLAGS",e,t),a.allowPermanentFlags&&c.push({type:"TEXT",value:"\\*"}),s.send({tag:"*",command:"OK",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"PERMANENTFLAGS"},n?[]:c]},{type:"TEXT",value:n?"No permanent flags permitted":"Flags permitted"}]},i+" PERMANENTFLAGS",e,t),s.send({tag:"*",attributes:[a.messages.length,{type:"ATOM",value:"EXISTS"}]},i+" EXISTS",e,t),s.send({tag:"*",attributes:[s.recent.size,{type:"ATOM",value:"RECENT"}]},i+" RECENT",e,t);let f=a.messages.findIndex(p=>p.flags.indexOf("\\Seen")<0);return f>=0&&s.send({tag:"*",command:"OK",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"UNSEEN"},f+1]},{type:"TEXT",value:"First unseen message"}]},i+" UNSEEN",e,t),s.send({tag:"*",command:"OK",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"UIDVALIDITY"},a.uidvalidity]},{type:"TEXT",value:"UIDs valid"}]},i+" UIDVALIDITY",e,t),s.send({tag:"*",command:"OK",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"UIDNEXT"},a.uidnext]},{type:"TEXT",value:"Predicted next UID"}]},i+" UIDNEXT",e,t),s.send({tag:e.tag,command:"OK",attributes:[{type:"SECTION",section:[{type:"ATOM",value:n?"READ-ONLY":"READ-WRITE"}]},{type:"TEXT",value:"Completed"}]},i,e,t),r()}g();g();function J(s,e){return!!s&&!Array.isArray(s)&&s.type==="ATOM"&&(e===void 0||String(s.value).toUpperCase()===e)}function ue(s){return!!s&&!Array.isArray(s)&&["ATOM","STRING","LITERAL"].indexOf(s.type)>=0&&!s.section&&!s.partial}var wa=/[\s()[\]{"%*\\<]/;function $c(s){let e=[],t=0;for(;t<s.length;){let r=s.charAt(t);if(r==='"'){for(t++;t<s.length&&s.charAt(t)!=='"';t++)s.charAt(t)==="\\"&&t++;t++;continue}let n=(r==="{"||r==="~")&&s.substr(t,32).match(/^~?\{(\d+)\+?\}\r\n/);if(n){t+=n[0].length+Number(n[1]);continue}if(wa.test(r)){t++;continue}let i=t;for(;i<s.length&&!wa.test(s.charAt(i));)i++;let o=s.substring(t,i);/^nil$/i.test(o)&&e.push(o),t=i}return e}function yt(s,e,t){if(!s.attributes||!/nil/i.test(e||""))return;let r=[],n=(o,a)=>{o.forEach((u,l)=>{u===null?r.push({list:o,index:l,path:a.concat(l)}):Array.isArray(u)?n(u,a.concat(l)):u&&Array.isArray(u.section)&&n(u.section,a.concat(l,"section"))})};if(n(s.attributes,[]),!r.length)return;let i=$c(e).slice(-r.length);r.forEach((o,a)=>{t(o.path)&&(o.list[o.index]={type:"ATOM",value:i.length===r.length?i[a]:"NIL"})})}function nt(s,e,t,r){let n=new Error(s);return n.imapResponse=r||"NO",n.responseCode=e||!1,n.responseCodeArgs=t||[],n}var _e=s=>nt(s,!1,!1,"BAD");function Jc(s,e){try{return e.map(t=>{if(!t||t.type!=="ATOM")throw new Error("Invalid flags argument");let r=be(t.value);return we(s.server,r),r})}catch{throw _e("Invalid flags argument")}}function Zc(s,e,t){let r=s.server,n=[];for(let i=0;i<e.length;){let o={flags:[],internaldate:!1,raw:!1};if(Array.isArray(e[i])&&(o.flags=Jc(s,e[i++])),e[i]&&e[i].type==="STRING"){if(!r.validateInternalDate(e[i].value))throw _e("Invalid internaldate argument");o.internaldate=e[i++].value}let a=e[i++],u=a&&a.type==="ATOM"?String(a.value).toUpperCase():"";if(a&&a.type==="LITERAL")o.raw=a.value;else if(a&&a.type==="LITERAL8"&&r.appendLiteral8)o.raw=a.value,o.literal8=!0;else if(u&&Object.hasOwn(r.appendDataHandlers,u)&&i<e.length)o.resolve=r.appendDataHandlers[u](s,e[i++]);else throw _e("Invalid message source argument");n.push(o)}if(!n.length)throw _e("Missing message argument");if(n.length>t)throw _e("Only a single message can be appended");return n}function ef(s,e,t,r,n){let i=[];r.responseCode&&i.push({type:"SECTION",section:[{type:"ATOM",value:r.responseCode}].concat(r.responseCodeArgs)}),i.push({type:"TEXT",value:r.message}),s.send({tag:e.tag,command:r.imapResponse,attributes:i},r.imapResponse==="BAD"?"INVALID COMMAND":n,e,t)}function Bt(s,e,t){let r=s.server.getCommandOptions(e);if(!r.appendMessage)return!1;let n=r.mailboxArguments[0];if(/[ (]URL $/i.test(t.slice(-5)))return!1;let i=l=>{l=l.replace(/ $/,"");for(let c of["",")"])try{let f=st.parser(l+c);return yt(f,l,p=>p.length===1&&p[0]===n),f.attributes||[]}catch{}return[]},o=t.match(/(~?)\{(\d+)\+?\}\r\n/),a=i(o?t.substr(0,o.index):t);a.length<=n&&o&&!o[1]&&(a=i(t.substr(0,o.index+o[0].length+Number(o[2]))));let u=a[n];if(!ue(u))return!1;try{return s.importMailboxName(u.value)}catch{return!1}}function Na(s,e,t){let r=!s.isBusy()&&Bt(s,e,t);return r!==!1&&s.server.targetRefusal(r)}function un(s,e,t,r,n,i){let o=i.command+" FAILED",a=i.maxMessages||(s.server.multiAppend?1/0:1);try{if(!r||["STRING","ATOM","LITERAL"].indexOf(r.type)<0)throw _e("Invalid mailbox argument");let u=Zc(s,n,a),l=s.getTargetMailbox(r.value,e,t,o);if(!l)return!1;u.forEach(f=>{f.resolve?f.raw=f.resolve():f.literal8&&(f.raw=s.server.appendLiteral8(f.raw))});let c=u;return s.checkAppend(l,c,e,t,o,{command:i.command,replaced:i.replaced})?{mailbox:l,messages:c}:!1}catch(u){let l=u;if(!l.imapResponse)throw l;return ef(s,e,t,l,o),!1}}function ln(s,e){let t=e.messages.map(r=>s.server.appendMessage(e.mailbox,r.flags,r.internaldate,r.raw).message);return{mailbox:e.mailbox,message:t[t.length-1],messages:t}}function cn(s,e,t,r){let n=[].concat(e.attributes||[]),i=un(s,e,t,n.shift(),n,{command:"APPEND"});if(!i)return r();let o=ln(s,i);s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"APPEND Completed"}]},"APPEND",e,t,o),r()}g();g();function Ss(s){let e=s>>>0;return()=>{e=e+1831565813>>>0;let t=e;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}}g();var Ge=2n**63n-1n;function Ae(s,e){let t=String(e===void 0?4294967295:e);return typeof s!="string"||!/^\d+$/.test(s)||s.replace(/^0+(?=\d)/,"").length>t.length?!1:BigInt(s)<=BigInt(t)}function Le(s,e){return Ae(s,e)&&/^[1-9]/.test(s)}function Is(s,e){return typeof s!="string"||!/^[\d*]+(:[\d*]+)?(,[\d*]+(:[\d*]+)?)*$/.test(s)?!1:s.split(/[,:]/).every(t=>t==="*"?!e:Le(t))}var Os=3600*1e3,z=class extends Error{constructor(e,t){super(e),this.name="ImapKitError",this.code=t}};function K(s,e){return new z(s,e)}function it(s,e,t,r={}){let n;if(Array.isArray(t)){let c=new Set(t);n=f=>c.has(f)}else n=t;let i=[],o=[];if(e.messages.forEach((c,f)=>{n(c)?(c.ghost=!0,i.push({seq:r.highestFirst?f+1:o.length+1,message:c})):o.push(c)}),!i.length)return[];let a=e.messages.slice();o.forEach((c,f)=>{e.messages[f]=c}),e.messages.length=o.length;let u=i.map(c=>c.message),l=r.origin!==void 0?r.origin:s.activeConnection;return s.emit("expunge",e,u,l),(r.highestFirst?i.slice().reverse():i).forEach(c=>{s.notify({tag:"*",attributes:[c.seq,{type:"ATOM",value:"EXPUNGE"}],message:c.message},e,r.skip)}),s.notify({tag:"*",attributes:[e.messages.length,{type:"ATOM",value:"EXISTS"}],mailboxCopy:a},e,r.skip||r.skipExists),u}function fn(s,e,t,r){t.length&&s.notify({tag:"*",flagUpdate:t},e,r)}function hn(s,e,t,r){if(!Array.isArray(t))throw K("Flags must be an array","INVALID");let n=[];return t.forEach(i=>{if(typeof i!="string")throw K("Flags must be strings","INVALID");let o=be(i);try{we(s,o)}catch(a){throw K(a.message,"INVALID")}if(r&&!s.isPermanentFlag(e,o))throw K("Flag "+o+" is not a permanent flag of "+e.path,"INVALID");n.indexOf(o)<0&&n.push(o)}),n}function Ma(s,e,t,r,n){if(["set","add","remove"].indexOf(n)<0)throw K("Invalid flag mode "+JSON.stringify(n)+", expected set, add or remove","INVALID");let i=hn(s,e,r,n!=="remove"),o=[];return t.forEach(a=>{let u=a.flags.join(" ");n==="set"?a.flags=i.slice():n==="add"?i.forEach(l=>s.ensureFlag(a.flags,l)):i.forEach(l=>s.removeFlag(a.flags,l)),s.rememberFlags(e,a.flags),a.flags.join(" ")!==u&&o.push(a)}),o.length&&(s.emit("flags",e,o,s.activeConnection),fn(s,e,o,null)),o}function xs(s,e){let t=new Set(Object.keys(s.folderCache)),r=s.createMailbox(e),n=Object.keys(s.folderCache).filter(i=>!t.has(i)).sort((i,o)=>i.length-o.length);return s.mailboxChanged("create",r.path,{created:n}),r}function Cs(s,e){let t=s.getMailbox(e);if(!t)throw K("Mailbox does not exist","NONEXISTENT");s.deleteMailbox(e),s.mailboxChanged("delete",t.path,{mailbox:t}),Ra(s,t,"Selected mailbox was deleted","MAILBOX DELETED")}function Ra(s,e,t,r){let n=s.activeConnection;s.connections.forEach(i=>{i!==n&&i.selectedMailbox===e&&i.bye(t,r)})}function ws(s,e,t){let r=s.getMailbox(e),n=s.getMailbox(t);if(!r||r.flags.indexOf("\\Noselect")>=0)throw K("Mailbox does not exist","NONEXISTENT");if(n&&n.flags.indexOf("\\Noselect")<0)throw K("Mailbox already exists","ALREADYEXISTS");let i=s.getSeparator(r);if(t.substr(0,r.path.length+i.length)===r.path+i)throw K("Can not move a mailbox into itself","CANNOT");let o=r.path,a;if(e.toUpperCase()==="INBOX"){let u=s.createMailbox(t);a=u.path,r.messages.forEach(l=>{s.copyMessage(u,l)}),it(s,r,()=>!0)}else{s.deleteMailbox(e,!0);try{s.createMailbox(t,r)}catch(u){throw s.createMailbox(e,r),s.indexFolders(),u}s.indexFolders(),a=r.path}return s.mailboxChanged("rename",a,{oldPath:o}),{path:a,mailbox:r}}function La(s,e,t={}){let r=t.uids||"keep";if(["keep","renumber","shuffle","offset"].indexOf(r)<0)throw K("Invalid UID mode "+JSON.stringify(r)+", expected keep, renumber, shuffle or offset","INVALID");let n=t.offset===void 0?0:t.offset;if(!Number.isSafeInteger(n)||n<0)throw K("Offset must be a non-negative integer","INVALID");let i=t.uidvalidity;if(i===void 0)i=Math.max(e.uidvalidity,s.uidvalidityCounter)+1;else if(!Number.isSafeInteger(i)||i<=e.uidvalidity||i>4294967295)throw K("UIDVALIDITY must be an integer above "+e.uidvalidity+" and below 2^32","INVALID");if(t.seed!==void 0&&!Number.isSafeInteger(t.seed))throw K("Seed must be an integer","INVALID");Ra(s,e,"UIDVALIDITY of the selected mailbox changed","UIDVALIDITY CHANGED");let o=e.messages,a=o.map(l=>l.uid),u=a;if(r==="renumber"||r==="shuffle"){if(u=o.map((l,c)=>c+1),r==="shuffle"){let l=Ss(t.seed===void 0?Math.floor(Math.random()*4294967295):t.seed);for(let c=u.length-1;c>0;c--){let f=Math.floor(l()*(c+1));[u[c],u[f]]=[u[f],u[c]]}}e.uidnext=o.length+1}else if(r==="offset"){let l=e.uidnext-1+n;u=a.map(c=>c+l),e.uidnext+=l}return o.forEach((l,c)=>{l.uid=u[c]}),r==="shuffle"&&o.sort((l,c)=>l.uid-c.uid),e.uidvalidity=i,s.uidvalidityCounter=Math.max(s.uidvalidityCounter,i),{uidvalidity:i,uidnext:e.uidnext,uids:a.map((l,c)=>({uid:l,newUid:u[c]}))}}function Ht(s,e){let t=s.getMailbox(e);if(!t||t.flags.indexOf("\\Noselect")>=0)throw K("Mailbox does not exist","NONEXISTENT");return t.subscribed?!1:(t.subscribed=!0,s.mailboxChanged("subscribe",t.path),!0)}function Ns(s,e){return e.toUpperCase()==="INBOX"&&(e="INBOX"),s.subscriptions.delete(e)?(s.mailboxChanged("unsubscribe",e),!0):!1}var mn="lrswipkxtea",Pt=new Set(mn),Ft={c:"kx",d:"et"},tf=["i","e","s","w","t"],Da=["s","w","t"],sf=["l","r","i","k","x","a"],Ua=["FLAGS","+FLAGS","-FLAGS","FLAGS.SILENT","+FLAGS.SILENT","-FLAGS.SILENT"];function rf(s){return s=b.Buffer.from(s,"utf-8").toString("binary"),s&&s.charAt(0)!=="\\"&&!/^NIL$/i.test(s)?{type:"ATOM",value:s}:s}function va(s){let e=new Error(s);return e.imapResponse="BAD",e}function dn(s){let e=new Set;for(let t of s)if(Pt.has(t))e.add(t);else if(Object.hasOwn(Ft,t))Ft[t].split("").forEach(r=>e.add(r));else throw/^[A-Z]$/.test(t)?va("Uppercase rights are not allowed"):va("The "+(/^[\x21-\x7e]$/.test(t)?t+" ":"")+"right is not supported");return e}function pn(s,e){return[{type:"MAILBOX",value:s.path}].concat(e.map(t=>rf(t)))}function kt(s){let e=mn.split("").filter(t=>s.has(t)).join("");return Object.keys(Ft).forEach(t=>{Ft[t].split("").some(r=>s.has(r))&&(e+=t)}),e}function nf(s){if(!s||s==="-")return"Empty identifier";if(/[\x00-\x1f\x7f]/.test(s))return"Identifier contains control characters";let e=b.Buffer.from(s,"binary").toString("utf-8");return b.Buffer.from(e,"utf-8").toString("binary")!==s?"Identifier is not valid UTF-8":!1}function gn(s){s.registerCapability("ACL"),s.registerCapability("RIGHTS=texk");let e=typeof s.options.aclOwner=="string"?s.options.aclOwner:"testuser",t=S=>S.username===e,r=S=>{if(!(S.acl instanceof Map)){let T=new Map,O=S.acl&&typeof S.acl=="object"?S.acl:{};Object.keys(O).forEach(M=>{try{T.set(M,dn(String(O[M])))}catch(k){throw new Error("Invalid ACL in storage for "+S.path+": "+k.message,{cause:k})}}),S.acl=T}return S.acl},n=(S,T,O)=>{let M=S.username;if(M===e)return Pt;O=O||r(T);let k=["anyone"].concat(typeof M=="string"&&M?M:[]),P=new Set;return k.forEach(j=>(O.get(j)||[]).forEach(Y=>P.add(Y))),k.forEach(j=>(O.get("-"+j)||[]).forEach(Y=>P.delete(Y))),P};s.acl={getRights:n,isOwner:t};let i=(S,T)=>{let O=r(S),M=new Map(O);T(O),s.emit("acl",S,M)},o=(S,T,O,M)=>{i(S,k=>{let P=new Set(k.get(T)||[]);O==="+"?M.forEach(Y=>P.add(Y)):O==="-"&&M.forEach(Y=>P.delete(Y));let j=O?P:M;j.size?k.set(T,j):k.delete(T)})};s.urlAccessChecks.push((S,T)=>{let O=n(S,T);return O.has("r")?!1:{text:O.has("l")?"Permission denied":"Mailbox does not exist"}}),s.searchAccessChecks.push((S,T,O)=>{let M=n(S,T);return M.has("r")&&(O||M.has("l"))});let a=S=>S.aclRights||Pt,u=S=>(S=be(S),S==="\\Deleted"?"t":S==="\\Seen"?"s":"w"),l=S=>typeof S=="string"?S:String(S&&S.value||""),c=(S,T)=>S.has(u(l(T))),f=(S,T)=>{let O=(S.attributes||[])[T];return ue(O)?O.value:!1},p=(S,T)=>{let O=f(S,T);return O!==!1&&s.getMailbox(O)||!1},y=(S,T,O,M)=>S.sendStatus(T,O,"NO","Permission denied","NOPERM",M),A=(S,T,O,M,k,P)=>{M.has("l")?y(S,T,O,k):P==="TRYCREATE"?S.sendStatus(T,O,"NO","Target mailbox does not exist","TRYCREATE",k):S.sendStatus(T,O,"NO","Mailbox does not exist","NONEXISTENT",k)},m=S=>{for(let T=s.getParentPath(S);T;T=s.getParentPath(T)){let O=s.getMailbox(T);if(O)return O}return!1},h=(S,T,O,M,k)=>{if(!M)return S.sendStatus(T,O,"NO","Mailbox does not exist","NONEXISTENT"),!1;let P=n(S,M);return k(P)?!0:(A(S,T,O,P),!1)},d=S=>S.has("a"),E=(S,T,O,M)=>{let k=T.attributes||[],P=T.command.toUpperCase();if(k.length!==M||k.some(Y=>!ue(Y)))return S.sendStatus(T,O,"BAD",P+" expects "+(M===1?"a mailbox name":M+" string arguments")),!1;let j=M>1&&nf(k[1].value);return j?(S.sendStatus(T,O,"BAD",j),!1):(M>1&&(k[1].value=b.Buffer.from(k[1].value,"binary").toString("utf-8")),!0)},I=(S,T,O)=>{let M=T.attributes[1].value;return M!==e&&M!=="-"+e?!1:(S.sendStatus(T,O,"NO","Rights of the mailbox owner can not be changed","CANNOT"),!0)},C=(S,T)=>(O,M,k,P)=>{E(O,M,k,S)&&T(O,M,k,s.getMailbox(M.attributes[0].value)),P()},H={states:Z.AUTHENTICATED,mailboxArguments:[0]},N=Object.assign({astringArguments:[1]},H),w=(S,T,O,M)=>S.send({tag:"*",command:"MYRIGHTS",attributes:pn(T,[kt(n(S,T))])},"MYRIGHTS",O,M,T),G=Ke(s);s.registerCapability("LIST-MYRIGHTS",()=>G.enabled),G.returnOptions.MYRIGHTS={onItem:(S,T,O,M,k,P)=>{M.matched&&M.exists&&w(S,T,k,P)}},s.setCommandHandler("SETACL",C(3,(S,T,O,M)=>{let k=T.attributes[1].value,P=T.attributes[2].value,j=/^[+-]/.test(P)?P.charAt(0):"",Y=dn(P.substr(j.length));!h(S,T,O,M,d)||I(S,T,O)||(o(M,k,j,Y),S.sendStatus(T,O,"OK","Setacl complete"))}),Object.assign({astringArguments:[1,2]},H)),s.setCommandHandler("DELETEACL",C(2,(S,T,O,M)=>{!h(S,T,O,M,d)||I(S,T,O)||(i(M,k=>k.delete(T.attributes[1].value)),S.sendStatus(T,O,"OK","Deleteacl complete"))}),N),s.setCommandHandler("GETACL",C(1,(S,T,O,M)=>{if(!h(S,T,O,M,d))return;let k=[e,kt(Pt)];r(M).forEach((P,j)=>{k.push(j,kt(P))}),S.send({tag:"*",command:"ACL",attributes:pn(M,k)},"ACL",T,O,M),S.sendStatus(T,O,"OK","Getacl complete")}),H),s.setCommandHandler("LISTRIGHTS",C(2,(S,T,O,M)=>{if(!h(S,T,O,M,d))return;let k=T.attributes[1].value,P;k===e?P=[k,kt(Pt)]:P=[k,""].concat(mn.split(""),Object.keys(Ft)),S.send({tag:"*",command:"LISTRIGHTS",attributes:pn(M,P)},"LISTRIGHTS",T,O,M),S.sendStatus(T,O,"OK","Listrights complete")}),N),s.setCommandHandler("MYRIGHTS",C(1,(S,T,O,M)=>{h(S,T,O,M,k=>sf.some(P=>k.has(P)))&&(w(S,M,T,O),S.sendStatus(T,O,"OK","Myrights complete"))}),H);let F={},W={},x=()=>{Object.keys(F).forEach(S=>{let T=s.getCommandHandler(S);T&&(W[S]=T,s.setCommandHandler(S,(O,M,k,P)=>t(O)?T(O,M,k,P):F[S](T,O,M,k,P)))}),Object.keys(G.returnOptions).forEach(S=>{let T=G.returnOptions[S];if(typeof T.onItem!="function")return;let O=T.onItem,M=S==="STATUS"?"r":"l";T.onItem=(k,P,...j)=>{if(t(k))return O(k,P,...j);let Y=n(k,P);if(Y.has("l")&&Y.has(M))return O(k,P,...j)}}),Ua.forEach(S=>{let T=s.storeHandlers[S]||Ts[S];s.storeHandlers[S]=(O,M,k,...P)=>{let j=a(O);if(Da.every($=>j.has($)))return T(O,M,k,...P);k=[].concat(k),k.forEach($=>we(O.server,be(l($))));let Y=k.filter($=>c(j,$));return S.charAt(0)!=="+"&&S.charAt(0)!=="-"&&(Y=M.flags.filter($=>!c(j,$)).concat(Y)),T(O,M,Y,...P)}})};s.once("pluginsLoaded",x);let L=(S,T,O,M,k)=>{let P=p(O,0);if(!P)return S(T,O,M,k);let j=O.command.toUpperCase(),Y=n(T,P);return Y.has("r")?(T.aclRights=Y,j==="SELECT"&&!tf.some($=>Y.has($))?W.EXAMINE(T,O,M,k):S(T,O,M,k)):(on(T,O,M),T.closeMailbox(),A(T,O,M,Y,j+" FAILED"),k())};F.SELECT=L,F.EXAMINE=L;let v=(S,T,O)=>(M,k,P)=>{let j=p(k,T),Y=j&&n(M,j);return Y&&!Y.has(S)?(A(M,k,P,Y,void 0,O),!1):!0},V=(S,T,O)=>{let M=v(S,T,O);return(k,P,j,Y,$)=>M(P,j,Y)?k(P,j,Y,$):$()};F.STATUS=V("r",0),F.SUBSCRIBE=V("l",0),F.DELETE=V("x",0);let _=(S,T,O,M)=>{let k=m(M);return!k||!n(S,k).has("k")?(y(S,T,O),!1):!0};F.CREATE=(S,T,O,M,k)=>{let P=f(O,0);return P!==!1&&!_(T,O,M,P)?k():S(T,O,M,k)};let X=v("x",0);F.RENAME=(S,T,O,M,k)=>{if(!X(T,O,M))return k();let P=f(O,1);return P!==!1&&p(O,0)&&!_(T,O,M,P)?k():S(T,O,M,k)},F.APPEND=(S,T,O,M,k)=>{let P=p(O,0);if(!P)return S(T,O,M,k);let j=n(T,P);if(!j.has("i"))return A(T,O,M,j,"APPEND FAILED","TRYCREATE"),k();let Y=O.attributes[1];if(Array.isArray(Y)&&Y.every($=>$&&$.type==="ATOM"))try{Y.forEach($=>we(T.server,be($.value))),O.attributes[1]=Y.filter($=>c(j,$))}catch{}return S(T,O,M,k)};let q=(S,T)=>{let O=T?n(S,T):!1;return!O||O.has("i")?!1:O.has("l")?{command:"NO",code:"NOPERM",text:"Permission denied"}:{command:"NO",code:"TRYCREATE",text:"Target mailbox does not exist"}},se=V("i",1,"TRYCREATE"),ee=S=>(T,O,M,k,P)=>{let j=M.command.toUpperCase();if(S&&!O.readOnly){let Y=a(O);if(!Y.has("t")||!Y.has("e"))return y(O,M,k,j+" FAIL"),P()}return se(T,O,M,k,P)};F.COPY=ee(!1),F["UID COPY"]=ee(!1),F.MOVE=ee(!0),F["UID MOVE"]=ee(!0);let fe=(S,T)=>{let O=a(S);return!S.readOnly&&(!O.has("t")||!O.has("e"))?{command:"NO",code:"NOPERM",text:"Permission denied"}:q(S,T)},is=(S,T,O,M,k)=>{let P=fe(T,p(O,1));return P?(T.sendStatus(O,M,P.command,P.text,P.code,O.command.toUpperCase()+" FAILED"),k()):S(T,O,M,k)};F.REPLACE=is,F["UID REPLACE"]=is,s.literalFilters.unshift((S,T,O)=>{if(t(S)||S.isBusy())return!1;let M=Bt(S,T,O),k=M!==!1&&s.getMailbox(M);return k?T==="APPEND"?q(S,k):fe(S,k):!1});let Nr=["r","s","w","i","p"],Lt=S=>S.has("l")&&Nr.some(T=>S.has(T)),ko=(S,T,O,M,k)=>{let P=O.attributes||[],j=O.command.toUpperCase()==="GETMETADATA"&&Array.isArray(P[0])?1:0,Y=p(O,j);if(Y&&f(O,j)!==""){let $=n(T,Y);if(!Lt($))return A(T,O,M,$),k()}return S(T,O,M,k)};F.GETMETADATA=ko,F.SETMETADATA=ko,s.notifyFilters.push((S,T)=>{let O=T.command||{};if(O.command!=="METADATA"||t(S))return!0;let M=O.attributes&&O.attributes[0],k=M&&typeof M=="object"?M.value:M,P=typeof k=="string"&&k!==""&&s.getMailbox(k);return!P||Lt(n(S,P))}),F.GETQUOTAROOT=(S,T,O,M,k)=>{let P=p(O,0);return(!P||!n(T,P).has("r"))&&(O.aclQuotaMailboxOnly=!0),S(T,O,M,k)},F.SETQUOTA=(S,T,O,M,k)=>{let P=O.attributes||[];return P.length===2&&Array.isArray(P[1])&&!Object.keys(s.folderCache).every(Y=>{let $=s.folderCache[Y];return!s.isPersonal($)||n(T,$).has("a")})?(y(T,O,M),k()):S(T,O,M,k)};let Po=(S,T,O,M,k)=>!T.readOnly&&!a(T).has("e")?(y(T,O,M),k()):S(T,O,M,k);F.EXPUNGE=Po,F["UID EXPUNGE"]=Po,s.resetHandlers.push(S=>{S.aclRights=null}),s.connectionHandlers.push(S=>{let T=S.canSetSeen,O=S.canExpunge;S.canSetSeen=()=>T.call(S)&&a(S).has("s"),S.canExpunge=()=>O.call(S)&&a(S).has("e")});let Fo=(S,T,O,M,k)=>{let P=a(T),j=O.attributes||[],Y=j.length>=3&&j[j.length-2]&&j[j.length-2].type==="ATOM"&&j[j.length-2].value.toUpperCase();if(T.readOnly||!Y)return S(T,O,M,k);if(Ua.indexOf(Y)<0)return Object.hasOwn(s.storeHandlers,Y)&&!P.has("w")?(y(T,O,M),k()):S(T,O,M,k);let $=[].concat(j[j.length-1]||[]);try{$.forEach(Dt=>we(T.server,be(l(Dt))))}catch{return S(T,O,M,k)}let Me;return Y.charAt(0)==="+"||Y.charAt(0)==="-"?Me=!$.length||$.some(Dt=>c(P,Dt)):Me=Da.some(Dt=>P.has(Dt)),Me?S(T,O,M,k):(y(T,O,M),k())};F.STORE=Fo,F["UID STORE"]=Fo;let Pl=S=>{let T=S&&S.attributes||[];return T.some((O,M)=>O&&O.type==="ATOM"&&/^RETURN$/i.test(O.value)&&Array.isArray(T[M+1])&&T[M+1].some(k=>k&&k.type==="ATOM"&&/^STATUS$/i.test(k.value)))},Fl=(S,T)=>s.hasDescendant(T.path,O=>n(S,O).has("l"));s.outputHandlers.push((S,T,O,M,k,P)=>{if(!t(S)){if((O==="LIST ITEM"||O==="LSUB ITEM")&&P&&P.path){if(!n(S,P).has("l")){T.skipResponse=!0;return}let j=T.attributes[0];if(!Array.isArray(j))return;T.attributes[0]=j.slice();let Y=j.findIndex(Me=>Me&&Me.value==="\\HasChildren");Y>=0&&!Fl(S,P)&&(T.attributes[0][Y]={type:"ATOM",value:"\\HasNoChildren"}),!j.some(Me=>Me&&/^\\(Noselect|NonExistent)$/i.test(Me.value))&&Pl(M)&&!n(S,P).has("r")&&T.attributes[0].push({type:"ATOM",value:"\\Noselect"});return}if(O==="QUOTA"&&M&&M.aclQuotaMailboxOnly&&Array.isArray(T.attributes[1])){let j=T.attributes[1],Y=[];for(let $=0;$<j.length;$+=3)j[$]&&String(j[$].value).toUpperCase()==="MAILBOX"&&Y.push(j[$],j[$+1],j[$+2]);Y.length?T.attributes[1]=Y:T.skipResponse=!0;return}if(O==="SELECT PERMANENTFLAGS"){let j=T.attributes[0]&&T.attributes[0].section,Y=a(S);j&&Array.isArray(j[1])&&(j[1]=j[1].filter($=>$.value==="\\*"?Y.has("w"):c(Y,$)));return}if(P&&P.targetUids&&P.mailbox&&/^(UID )?(COPY|MOVE COPYUID)$/.test(O)){let j=n(S,P.mailbox),Y=new Set(P.targetUids);P.mailbox.messages.forEach($=>{Y.has($.uid)&&($.flags=$.flags.filter(Me=>c(j,Me)))})}}}),s.on("mailbox",S=>{if(S.type==="delete"){let T=s.getMailbox(S.path);T&&T!==S.mailbox&&delete T.acl}else S.type==="create"&&(S.created||[]).forEach(T=>{let O=m(T),M=s.folderCache[T];if(O&&M&&O!==M){let k=new Map;r(O).forEach((P,j)=>k.set(j,new Set(P))),M.acl=k}})});let os=S=>{let T={};return r(S).forEach((O,M)=>{T[M]=kt(O)}),T},Mr=S=>s.control.requireMailbox(S);s.control.snapshotHandlers.push((S,T)=>{S.acl instanceof Map&&(T.acl=os(S))});let _l=S=>os(Mr(S)),Gl=(S,T,O)=>{let M=Mr(S);if(typeof T!="string"||!T||typeof O!="string")throw K("setAcl expects an identifier and a rights string","INVALID");let k=/^[+-]/.test(O)?O.charAt(0):"",P;try{P=dn(O.substr(k.length))}catch(j){throw K(j.message,"INVALID")}return o(M,T,k,P),os(M)},Xl=(S,T)=>{let O=Mr(S);if(typeof T!="string"||!r(O).has(T))throw K("No ACL entry for "+JSON.stringify(T),"NONEXISTENT");return i(O,M=>M.delete(T)),os(O)};s.control.register("getAcl",_l,[{method:"GET",path:"/v1/mailboxes/{path}/acl",summary:"The ACL of a mailbox (ACL plugin)",handler:({params:S})=>s.control.getAcl(S.path)}]),s.control.register("setAcl",Gl,[{method:"PUT",path:"/v1/mailboxes/{path}/acl/{identifier}",summary:'Sets the rights of an identifier ({ rights }, "+" or "-" in front adds or removes, ACL plugin)',handler:({params:S,body:T})=>s.control.setAcl(S.path,S.identifier,T.rights)}]),s.control.register("deleteAcl",Xl,[{method:"DELETE",path:"/v1/mailboxes/{path}/acl/{identifier}",summary:"Removes an identifier from the ACL (ACL plugin)",handler:({params:S})=>s.control.deleteAcl(S.path,S.identifier)}])}g();function En(s){let e="appendLimit"in s.options?s.options.appendLimit:null;if(e!==null&&!Ba(e))throw new TypeError("Invalid appendLimit option, expecting a non-negative integer");let t=o=>Object.hasOwn(o,"appendLimit"),r=()=>Object.values(s.folderCache).some(t),n=o=>t(o)?Ba(o.appendLimit)?o.appendLimit:null:e,i=(o,a)=>{let u=n(o);return u!==null&&(a>u||u===0)};e!==null&&s.registerCapability("APPENDLIMIT="+e,()=>!r()),s.registerCapability("APPENDLIMIT",()=>e===null||r()),s.appendChecks.push((o,a,u,l)=>l.command&&u.some(c=>i(a,c.raw.length))?{code:"TOOBIG",text:"Message exceeds the APPENDLIMIT of the mailbox"}:!1),s.literalFilters.push((o,a,u,l)=>{let c=Bt(o,a,u),f=c!==!1&&s.getMailbox(c);return f&&i(f,l)?{command:"NO",code:"TOOBIG",text:"Message exceeds the APPENDLIMIT of the mailbox"}:!1}),s.allowedStatus.push("APPENDLIMIT"),s.statusHandlers.APPENDLIMIT=(o,a)=>n(a)}function Ba(s){return Number.isSafeInteger(s)&&s>=0}g();var of=new TextDecoder("utf-8",{fatal:!0});function An(s){s.registerCapability("AUTH=PLAIN",t=>t.state==="Not Authenticated");let e=(t,r,n,i)=>{let o=t.decodeSaslResponse(i);if(!o)return t.sendStatus(r,n,"BAD","Invalid base64 in SASL response",!1,"AUTHENTICATE PLAIN FAILED");let a;try{a=of.decode(o)}catch{return t.sendStatus(r,n,"BAD","Invalid UTF-8 in SASL PLAIN message",!1,"AUTHENTICATE PLAIN FAILED")}let u=a.split("\0"),l=u[0]||"",c=u[1]||"",f=u[2]||"",p=t.server.getUser(c);if(u.length!==3||!p||p.password!==f)return t.sendStatus(r,n,"NO","Login failed: authentication failure","AUTHENTICATIONFAILED","AUTHENTICATE PLAIN FAILED");if(l&&l!==c)return t.sendStatus(r,n,"NO","Can not act as "+l,"AUTHORIZATIONFAILED","AUTHENTICATE PLAIN FAILED");t.state="Authenticated",t.username=c,t.sendStatus(r,n,"OK","User logged in",!1,"AUTHENTICATE PLAIN SUCCESS")};s.setCommandHandler("AUTHENTICATE PLAIN",(t,r,n,i)=>{if(!r.attributes)t.inputHandler=function(o){if(t.inputHandler=!1,o==="*")return t.sendStatus(r,n,"BAD","Authentication cancelled",!1,"AUTHENTICATE PLAIN FAILED");e(t,r,n,o)},t.sendContinuation("","AUTHENTICATE PLAIN");else if(r.attributes.length===1&&r.attributes[0].type==="ATOM"){if(!s.capabilities["SASL-IR"]||!s.capabilities["SASL-IR"](t))return t.sendStatus(r,n,"BAD","SASL-IR must be enabled to send Initial Response with the request",!1,"AUTHENTICATE PLAIN FAILED"),i();e(t,r,n,r.attributes[0].value)}else t.sendStatus(r,n,"BAD","Invalid attributes for AUTHENTICATE PLAIN",!1,"AUTHENTICATE PLAIN FAILED");return i()})}g();g();g();function Rs(s,e){let r=new Ms(s).tokenize(),n=[],i=[],o=[];return r.forEach(a=>{a.type==="operator"&&(a.value===","||a.value===";")?(i.length&&n.push(i),i=[]):i.push(a)}),i.length&&n.push(i),n.forEach(a=>{let u=af(a,e);u.length&&(o=o.concat(u))}),o}function af(s,e){let t,r=!1,n="text",i=[],o={address:[],comment:[],group:[],text:[]},a,u;for(a=0,u=s.length;a<u;a++)if(t=s[a],t.type==="operator")switch(t.value){case"<":n="address";break;case"(":n="comment";break;case":":if(e){n="text";break}n="group",r=!0;break;default:n="text"}else t.value&&o[n].push(t.value);if(!o.text.length&&o.comment.length&&(o.text=o.comment,o.comment=[]),r){let l=o.text.join(" ");i.push({name:l,group:o.group.length?Rs(o.group.join(","),!0):[]})}else{if(!o.address.length&&o.text.length){for(a=o.text.length-1;a>=0;a--)if(o.text[a].match(/^[^@\s]+@[^@\s]+$/)){o.address=o.text.splice(a,1);break}let p=function(y){return o.address.length?y:(o.address=[y.trim()]," ")};if(!o.address.length)for(a=o.text.length-1;a>=0&&(o.text[a]=o.text[a].replace(/\s*\b[^@\s]+@[^@\s]+\b\s*/,p).trim(),!o.address.length);a--);}!o.text.length&&o.comment.length&&(o.text=o.comment,o.comment=[]),o.address.length>1&&(o.text=o.text.concat(o.address.splice(1)));let l=o.text.join(" "),c=o.address.join(" "),f={address:c||l||"",name:l||c||""};f.address===f.name&&((f.address||"").match(/@/)?f.name="":f.address=""),i.push(f)}return i}var Ms=class{constructor(e){this.str=(e||"").toString(),this.operatorCurrent="",this.operatorExpecting="",this.node=null,this.escaped=!1,this.list=[]}tokenize(){let e,t=[];for(let r=0,n=this.str.length;r<n;r++)e=this.str.charAt(r),this.checkChar(e);return this.list.forEach(r=>{r.value=(r.value||"").toString().trim(),r.value&&t.push(r)}),t}checkChar(e){if((e in this.operators||e==="\\")&&this.escaped)this.escaped=!1;else if(this.operatorExpecting&&e===this.operatorExpecting){this.node={type:"operator",value:e},this.list.push(this.node),this.node=null,this.operatorExpecting="",this.escaped=!1;return}else if(!this.operatorExpecting&&e in this.operators){this.node={type:"operator",value:e},this.list.push(this.node),this.node=null,this.operatorExpecting=this.operators[e],this.escaped=!1;return}if(!this.escaped&&e==="\\"){this.escaped=!0;return}this.node||(this.node={type:"text",value:""},this.list.push(this.node)),this.escaped&&e!=="\\"&&(this.node.value+="\\"),this.node.value+=e,this.escaped=!1}};Ms.prototype.operators={'"':'"',"(":")","<":">",",":"",":":";"};var Ha=/^[a-zA-Z0-9\-*]{1,99}$/,Ls=["7bit","8bit","binary"],uf=32;function _t(s){let e=b.Buffer.isBuffer(s)?s.toString("binary"):s||"";return/(?:^|[^\r])\n/.test(e)?e.replace(/\r?\n/g,`\r
|
|
6
|
+
`):e}function ka(s,e){let t=[],r="",n=!1,i=0;for(let o=0;o<s.length;o++){let a=s.charAt(o);if(n){r+=a,a==="\\"&&o+1<s.length?r+=s.charAt(++o):a==='"'&&(n=!1);continue}if(i){a==="\\"?o++:a==="("?i++:a===")"&&i--;continue}a==='"'?(n=!0,r+=a):a==="("?i=1:e&&a===e?(t.push(r),r=""):r+=a}return t.push(r),t}function Pa(s,e){let t=e.replace(/%([0-9a-fA-F]{2})/g,(r,n)=>String.fromCharCode(parseInt(n,16)));switch((s||"").trim().toLowerCase()){case"":case"utf-8":case"utf8":case"us-ascii":case"ascii":return t;case"iso-8859-1":case"latin1":return b.Buffer.from(t,"utf-8").toString("binary");default:return"=?"+s.toUpperCase()+"?Q?"+e.replace(/%/g,"=")+"?="}}var yn=class{constructor(e,t){this.rfc822=e||"",this.depth=t||0,this._br="",this._pos=0,this.tree={childNodes:[]},this._node=this.createNode(this.tree)}parse(){let e,t="";for(;typeof this._br=="string";){e=this.readLine();let r=this.matchDelimiter(e);if(r)this.endPart(r,t);else switch(this._node.state){case"header":e?this._node.header.push(e):this.endHeader();break;case"body":this._node.body.push((this._node.body.length?t:"")+e);break;case"epilogue":this._node.epilogue||(this._node.epilogue=[]),this._node.epilogue.push(t+e);break;default:throw new Error("Unexpected state")}t=this._br}}readLine(){let e=this.rfc822.indexOf(`
|
|
7
|
+
`,this._pos);if(e<0){let n=this.rfc822.slice(this._pos);return this._pos=this.rfc822.length,this._br=!1,n}let t=e;t>this._pos&&this.rfc822.charCodeAt(t-1)===13&&t--;let r=this.rfc822.slice(this._pos,t);return this._br=this.rfc822.slice(t,e+1),this._pos=e+1,r}endHeader(){this.processNodeHeader(),this.processContentType(),this._node.state="body"}matchDelimiter(e){if(!e.startsWith("--"))return!1;let t=this._node,r=t.boundary?t:t.parentNode;for(let n=r;n.boundary;n=n.parentNode){let i="--"+n.boundary;if(!e.startsWith(i))continue;let o=e.slice(i.length),a=o.startsWith("--");if(a&&(o=o.slice(2)),!/[^ \t]/.test(o))return n.state==="epilogue"?!1:{multipart:n,close:a,pad:o}}return!1}endPart(e,t){let r=this._node,n=e.multipart;if(r!==n){if(r.state==="header"){this.endHeader();for(let i=r;i!==n;i=i.parentNode)i.bare=!0}}else r.body.length&&(r.body[r.body.length-1]+=t);if(e.close)e.pad&&(n.closePad=e.pad),delete n.unterminated,n.state="epilogue",this._node=n;else{let i=this.createNode(n);e.pad&&(i.pad=e.pad),this._node=i}}parseEmbeddedMessage(e){let t=e.parsedHeader["content-type"],r=(t&&t.value||"").toLowerCase();if(r!=="message/rfc822"&&r!=="message/global"||this.depth>=uf)return;let n=(e.parsedHeader["content-transfer-encoding"]||"").toString().trim().toLowerCase();n&&!Ls.includes(n)||(e[r==="message/rfc822"?"message":"globalMessage"]=Gt(e.body,this.depth+1))}finalizeTree(){this._node.state==="header"&&(this.endHeader(),this._node.header.length&&!this.rfc822.endsWith(`
|
|
8
|
+
`)&&(this._node.headerUnterminated=!0));let e=[...this.tree.childNodes];for(;e.length;){let t=e.pop(),r=t,n=t.body,i=r.boundary&&!r.unterminated;n.length||t.childNodes.length||i||(r.hasBody=!1),r.lineCount=n.length?n.length-1:0,r.body=n.join(""),r.size=r.body.length,this.parseEmbeddedMessage(r),t.epilogue&&(r.epilogue=t.epilogue.join("")),t.childNodes.forEach(o=>e.push(o)),delete t.parentNode,delete t.state,r.childNodes.length||delete r.childNodes}}createNode(e){let t={state:"header",childNodes:[],header:[],parsedHeader:Object.create(null),body:[],multipart:!1,boundary:!1,parentNode:e};return e.childNodes.push(t),t}processNodeHeader(){let e=this._node,t=e.parsedHeader,r=[];for(let n of e.header)r.length&&/^\s/.test(n)?r[r.length-1]+=`\r
|
|
9
|
+
`+n:r.push(n);e.header=r;for(let n of r){let i=n.split(":"),o=(i.shift()||"").trim().toLowerCase(),a=i.join(":").trim();Ha.test(o)&&(o in t?Array.isArray(t[o])?t[o].push(a):t[o]=[t[o],a]:t[o]=a.replace(/\s*\r?\n\s*/g," "))}if(!t["content-type"]){let n=(e.parentNode&&e.parentNode.multipart||"").toString().toLowerCase();t["content-type"]=n==="digest"?"message/rfc822":"text/plain"}["content-type","content-disposition"].forEach(n=>{t[n]&&(t[n]=this.parseValueParams([].concat(t[n]).pop()))}),["subject","date","in-reply-to","message-id","content-transfer-encoding","content-id","content-description","content-language","content-md5","content-location"].forEach(n=>{Array.isArray(t[n])&&(t[n]=t[n].pop().replace(/\s*\r?\n\s*/g," "))}),t["content-transfer-encoding"]&&(t["content-transfer-encoding"]=ka(t["content-transfer-encoding"])[0].trim()),["from","sender","reply-to","to","cc","bcc"].forEach(n=>{t[n]&&(t[n]=[].concat(t[n]).flatMap(i=>i&&Rs(i.replace(/\s*\r?\n\s*/g," "))||[]))})}parseValueParams(e){let t={value:"",type:"",subtype:"",params:Object.create(null)},r=Object.create(null);return ka(e||"",";").forEach((n,i)=>{if(!i){t.value=n.trim();let c=t.value.split("/");t.type=(c.shift()||"").toLowerCase(),t.subtype=c.join("/");return}let o=n.split("="),a=(o.shift()||"").trim().toLowerCase(),u=o.join("=").trim();if(u.length>=2&&u.startsWith('"')&&u.endsWith('"')?u=u.slice(1,-1).replace(/\\([\s\S])/g,"$1"):u=u.replace(/^['"\s]*|['"\s]*$/g,""),!Ha.test(a))return;let l=a.match(/^([^*]+)(?:\*(\d{1,3}))?(\*)?$/);if(l&&(l[2]!==void 0||l[3])){let c=l[1];r[c]||(r[c]=[]),r[c][Number(l[2])||0]={value:u,extended:!!l[3]}}else t.params[a]=u;t.hasParams=!0}),Object.keys(r).forEach(n=>{let i="",o="",a=!1;r[n].forEach((u,l)=>{if(!u)return;let c=u.value;if(u.extended&&!l){let f=c.split("'");f.length>=3&&(i=f.shift(),f.shift(),c=f.join("'"))}u.extended?(a=!0,o+=c):o+=c.replace(/[^\x21-\x24\x26-\x7e]/g,f=>"%"+("0"+f.charCodeAt(0).toString(16)).substr(-2))}),t.params[n]=Pa(a?i:"",o)}),t}processContentType(){let e=this._node,t=e.parsedHeader["content-type"];t.type==="multipart"&&t.params.boundary&&(e.multipart=t.subtype,e.boundary=t.params.boundary,e.unterminated=!0)}};function Gt(s,e){let t=new yn(s,e);return t.parse(),t.finalizeTree(),t.tree.childNodes[0]}var lf=Gt(`Content-Type: text/plain\r
|
|
10
10
|
\r
|
|
11
|
-
`);function
|
|
12
|
-
`)+(
|
|
13
|
-
`):"":
|
|
11
|
+
`);function ot(s){return s.childNodes?s.childNodes:s.boundary?[lf]:void 0}function at(s,e){return s.message||(e?s.globalMessage:void 0)}function bt(s,e,t){let r=s,n=s;for(let i of(e||"").toString().split(".")){let o=Number(i)-1;if(!r||!(o>=0))return!1;let a=ot(r);if(n=a?a[o]:o===0?r:void 0,!n)return!1;r=at(n,t)||(ot(n)?n:!1)}return n}function Ds(s){let e=s.header||[];return s.hasBody===!1?e.length?e.join(`\r
|
|
12
|
+
`)+(s.headerUnterminated?"":`\r
|
|
13
|
+
`):"":e.length?e.join(`\r
|
|
14
14
|
`)+`\r
|
|
15
15
|
\r
|
|
16
16
|
`:`\r
|
|
17
|
-
`}function
|
|
17
|
+
`}function Be(s,e){let t=[],r=(n,i)=>{if(i){let a=n.header||[];a.length&&t.push(a.join(`\r
|
|
18
18
|
`)+(n.headerUnterminated?"":`\r
|
|
19
|
-
`))}if(n.hasBody===!1||(i&&
|
|
20
|
-
`),
|
|
21
|
-
`),
|
|
22
|
-
`)}n.unterminated||(
|
|
19
|
+
`))}if(n.hasBody===!1||(i&&t.push(`\r
|
|
20
|
+
`),t.push(n.body||""),!n.boundary))return;let o=n.childNodes||[];for(let a=0;a<o.length;a++){let u=o[a];t.push("--"+n.boundary+(u.pad||"")+`\r
|
|
21
|
+
`),r(u,!0),(!n.unterminated||a<o.length-1)&&!u.bare&&t.push(`\r
|
|
22
|
+
`)}n.unterminated||(t.push("--"+n.boundary+"--"+(n.closePad||"")),t.push(n.epilogue||""))};return r(s,!e),t.join("")}var Fa=new WeakMap;function ne(s){let e=Fa.get(s);if(!e||e.source!==s.raw){let t=_t(s.raw);e={source:s.raw,raw:t,tree:Gt(t)},Fa.set(s,e)}return e}g();g();g();var cf=/^[\s,]*(@(?:[^:[]|\[[^\]]*\])*):/;function ff(s){let e=s.match(cf);return e?[e[1].split(",").map(r=>r.trim()).filter(r=>r).join(","),s.substr(e[0].length).trim()]:[null,s]}function Xt(s){let e=s.subject;return[s.date||null,typeof e=="string"?e:null,Xe(s.from),Xe(s.sender,s.from),Xe(s["reply-to"],s.from),Xe(s.to),Xe(s.cc),Xe(s.bcc),s["in-reply-to"]||null,s["message-id"]||null]}function Xe(s,e){let t=[].concat(s||[]);if(t.length||(t=[].concat(e||[])),!t.length)return null;let r=[];return t.forEach(n=>{if(n.group){r.push([null,null,n.name||"",null]),r=r.concat(Xe(n.group)||[]),r.push([null,null,null,null]);return}let i=n.name||null,o=n.address||"";if(!o&&i&&(o=i,i=null),!o)return;let[a,u]=ff(o);o=u;let l=o.lastIndexOf("@"),c=l>=0?o.substr(0,l):o,f=(l>=0?o.substr(l+1):"")||"MISSING_DOMAIN";r.push([i,a,c||null,f])}),Object.defineProperty(r,"adjacentLists",{value:!0}),r.length?r:null}var bn=hf;function hf(s,e){e=e||{};let t=l=>e.upperCaseKeys&&typeof l=="string"?l.toUpperCase():l,r=l=>{if(!l||!l.hasParams)return null;let c=[],f=l.params;return Object.keys(f).forEach(p=>{c.push(t(p),f[p])}),c.length?c:null},n=l=>{let c=l.parsedHeader["content-type"]||{},f=c.type||null,p=c.subtype||null;return(!f||!p)&&(f==="text"||p==="plain"?(f="text",p="plain"):(f="application",p="octet-stream")),[t(f),t(p),r(c),l.parsedHeader["content-id"]||null,l.parsedHeader["content-description"]||null,t(l.parsedHeader["content-transfer-encoding"]||"7bit"),l.size]},i=l=>{let c=l.parsedHeader["content-language"]&&l.parsedHeader["content-language"].replace(/[ ,]+/g,",").replace(/^,+|,+$/g,""),f=c&&c.split(",")||null,p=l.parsedHeader["content-disposition"],y=[p&&[t(p.value),r(p)]||null,f];return e.skipContentLocation||y.push(l.parsedHeader["content-location"]||null),y},o=(l,c)=>{let f=n(l).concat(c);return e.body||(f=f.concat([l.parsedHeader["content-md5"]||null],i(l))),f},a=l=>{let c=ot(l).map(u).concat([t(l.multipart)]);return e.body||(c=c.concat([r(l.parsedHeader["content-type"])],i(l))),Object.defineProperty(c,"adjacentLists",{value:!0}),c},u=l=>{switch((l.parsedHeader["content-type"]||{}).type){case"multipart":return ot(l)?a(l):o(l,[]);case"text":return o(l,[l.lineCount]);case"message":{let f=at(l,e.messageGlobal);return f?o(l,[Xt(f.parsedHeader),u(f),l.lineCount]):o(l,[])}default:return o(l,[])}};return u(s)}var pe={},Te=pe;Object.defineProperty(pe,"applyPartial",{value:Us});pe.UID=function(s,e){return e.uid};pe.FLAGS=function(s,e){return s.getFlags(e).map(t=>({type:"ATOM",value:t}))};pe.BODYSTRUCTURE=function(s,e){return bn(ne(e).tree,{upperCaseKeys:!0,skipContentLocation:!0,messageGlobal:s.messageGlobal})};pe.ENVELOPE=function(s,e){return Xt(ne(e).tree.parsedHeader)};pe["BODY.PEEK"]=function(s,e,t){if(!t.section)throw new Error("BODY.PEEK requires ans argument list");return pe.BODY(s,e,t)};function df(s,e){if(s.section.length!==2||!Array.isArray(s.section[1])||!s.section[1].length)throw new Error(e+" expects a list of header fields");return s.section[1].map(t=>{if(["ATOM","STRING","LITERAL"].indexOf(t.type)<0)throw new Error("Invalid header field name in list");return t.type="ATOM",t.value.toUpperCase()})}function pf(s,e,t){if(!e.section.length)return s.raw;if(e.section[0].type!=="ATOM")throw new Error("Invalid BODY[<section>] identifier"+(e.section[0].value?" "+e.section[0].type:""));let r=(e.section[0].value||"").toUpperCase().match(/^((?:[1-9]\d*)(?:\.[1-9]\d*)*)?(?:(?:^|\.)(HEADER|HEADER\.FIELDS|HEADER\.FIELDS\.NOT|TEXT|MIME))?$/);if(!r||r[2]==="MIME"&&!r[1])throw new Error("Invalid BODY[<section>] identifier "+e.section[0].value);let n=r[1]||"",i=r[2]||"",o=[];if(["HEADER.FIELDS","HEADER.FIELDS.NOT"].indexOf(i)>=0)o=df(e,i);else if(e.section.length>1)throw new Error((i||"Part number")+" does not take any arguments");let a=n?bt(s.tree,n,t):s.tree;if(!a)return"";let u=n?at(a,t):a;switch(i){case"":return Be(a,!0);case"MIME":return Ds(a);case"TEXT":return u?Be(u,!0):"";case"HEADER":return u?Ds(u):"";default:{if(!u)return"";let l=i==="HEADER.FIELDS",c="";return(u.header||[]).forEach(f=>{let p=f.split(":")[0].toUpperCase().trim();o.indexOf(p)>=0===l&&(c+=f+`\r
|
|
23
23
|
`)}),c+`\r
|
|
24
|
-
`}}}function
|
|
25
|
-
`),n.header=n.header.filter(o=>!/^content-transfer-encoding\s*:/i.test(o)).concat("Content-Transfer-Encoding: base64"),!0)},s=e(t)?Rt(t):r;if(s.indexOf("\0")>=0)throw co("NUL octets are only allowed in the body of a part with the binary, 7bit or 8bit encoding");return s}function ln(r){r.registerCapability("BINARY"),r.parserOptions.literal8=!0,r.parserOptions.allowSection.push("BINARY","BINARY.PEEK","BINARY.SIZE"),r.fetchHandlers.BINARY=un,r.fetchHandlers["BINARY.PEEK"]=(t,e,s)=>un(t,e,s),r.fetchHandlers["BINARY.SIZE"]=xc,r.appendLiteral8=t=>{try{return Mc(t)}catch(e){throw Jt(e.message,e.code)}}}E();E();var wc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+,";function Eo(r){if(typeof r!="string")return"Invalid mailbox name";let t=0;for(;t<r.length;){let e=r.charCodeAt(t);if(e<32||e>126)return"Mailbox name must use modified UTF-7 for non-ASCII characters (RFC 3501 section 5.1.3)";if(r.charAt(t)!=="&"){t++;continue}if(r.charAt(t+1)==="-"){t+=2;continue}let s=r.indexOf("-",t+1);if(s<0)return'Modified BASE64 in mailbox name must end with "-" (RFC 3501 section 5.1.3)';let n=Dc(r.slice(t+1,s));if(n)return n;if(r.charAt(s+1)==="&"&&r.charAt(s+2)!=="-")return"Mailbox name contains a superfluous shift (RFC 3501 section 5.1.3)";t=s+1}return!1}function Dc(r){let t=0,e=0,s=[];for(let n=0;n<r.length;n++){let i=wc.indexOf(r.charAt(n));if(i<0)return"Invalid modified BASE64 in mailbox name (RFC 3501 section 5.1.3)";t=t<<6|i,e+=6,e>=16&&(e-=16,s.push(t>>e&65535),t&=(1<<e)-1)}if(!s.length||e>=6||t!==0)return"Invalid modified BASE64 in mailbox name (RFC 3501 section 5.1.3)";for(let n=0;n<s.length;n++){let i=s[n];if(i>=32&&i<=126)return"Modified BASE64 must not encode printable US-ASCII (RFC 3501 section 5.1.3)";if(i>=55296&&i<=56319){if(!(s[n+1]>=56320&&s[n+1]<=57343))return"Invalid UTF-16 in mailbox name";n++}else if(i>=56320&&i<=57343)return"Invalid UTF-16 in mailbox name"}return!1}function Cr(r){return r.replace(/&|[^\x20-\x7e]+/g,t=>t==="&"?"&-":"&"+I.Buffer.from(t,"utf16le").swap16().toString("base64").replace(/=+$/,"").replace(/\//g,",")+"-")}function cn(r){return Eo(r)?!1:r.replace(/&([^-]*)-/g,(t,e)=>e?I.Buffer.from(e.replace(/,/g,"/"),"base64").swap16().toString("utf16le"):"&")}var pe=Eo;function fn(r){r.registerCapability("CATENATE"),r.registerCapability("URL-PARTIAL"),r.appendDataHandlers.CATENATE=(t,e)=>{if(!Array.isArray(e)||!e.length||e.length%2)throw vt("CATENATE expects a list of TEXT literals and URLs");let s=[];for(let n=0;n<e.length;n+=2){let i=e[n]&&e[n].type==="ATOM"?String(e[n].value).toUpperCase():"",a=e[n+1];if(i==="TEXT"&&a&&a.type==="LITERAL")s.push({text:a.value});else if(i==="URL"&&a&&["ATOM","STRING","LITERAL"].indexOf(a.type)>=0)s.push({url:a.value});else throw vt("Invalid CATENATE part "+(n/2+1))}return()=>{let n=t.getMaxLiteralSize(),i="";for(let a of s)if(i+="text"in a?a.text:Hc(t,a.url),i.length>n)throw Jt("Catenated message is too large","TOOBIG");return i}}}var Lc=/^[A-Za-z0-9\-._~!$'()*+,&=:@/;%]*$/,Rc=/^\/([^;]+?)(?:;UIDVALIDITY=([^/;]*))?\/;UID=([^/;]*)(?:\/;SECTION=([^/;]*))?(?:\/;PARTIAL=([^/;]*))?$/i;function Tt(r,t){if(!r)return Jt(t);let e=r.replace(/[^\x20-\x5c\x5e-\x7e]/g,s=>"%"+s.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0"));return Jt(t,"BADURL",[{type:"TEXT",value:e}])}function Uc(r){let t=r.split("/").slice(1),e=[];return t.forEach((s,n)=>{let i=n===t.length-1;if(s==="."||s===".."){s===".."&&e.pop(),i&&e.push("");return}e.push(s)}),"/"+e.join("/")}function go(r){return r.replace(/%([0-9a-f]{2})/gi,(t,e)=>String.fromCharCode(parseInt(e,16)))}function Bc(r,t,e){if(!e||!/^[\x20-\x7e]+$/.test(e))return!1;let s;try{let a=Wt.parser("X FETCH 1 BODY.PEEK["+e+"]");s=a.attributes.length===2&&!a.attributes[1].partial&&a.attributes[1]}catch{return!1}if(!s||!s.section||!s.section.length||s.section[0].type!=="ATOM")return!1;let n=String(s.section[0].value).toUpperCase(),i=(n.match(/^[1-9]\d*(?:\.[1-9]\d*)*/)||[""])[0];if(i){let a=de(rt(t).tree,i),o=n.substr(i.length+1);if(!a||o&&o!=="MIME"&&!a.message)return!1}try{return At.BODY(r,t,{section:s.section}).value}catch{return!1}}function Hc(r,t){if(!t)throw Tt(t,"Empty URL does not refer to a message");if(/^[a-z][a-z0-9+.-]*:/i.test(t)||t.substr(0,2)==="//")throw Tt(t,"Only absolute-path URLs of this server are supported, e.g. /INBOX/;UID=1");if(t.charAt(0)!=="/")throw Tt(t,"Relative-path URLs are not allowed (RFC 5092 section 7.2)");if(!Lc.test(t)||/%(?![0-9a-f]{2})/i.test(t))throw Tt(t,"Invalid characters in URL");let e=Uc(t).match(Rc);if(!e)throw Tt(t,"URL does not refer to a message or a message part");let[,s,n,i,a,o]=e;if(n!==void 0&&!Mt(n)||!Mt(i))throw Tt(t,"Invalid UIDVALIDITY or UID in URL");let u;try{u=new TextDecoder("utf-8",{fatal:!0}).decode(I.Buffer.from(go(s),"binary"))}catch{throw Tt(t,"Mailbox name in URL is not valid UTF-8")}let l=r.server.getMailbox(Cr(u));if(!l||l.flags.indexOf("\\Noselect")>=0)throw Tt(t,"Mailbox does not exist");for(let m of r.server.urlAccessChecks){let T=m(r,l,t);if(T)throw Tt(t,T.text||"Permission denied")}if(n!==void 0&&Number(n)!==l.uidvalidity)throw Tt(t,"UIDVALIDITY does not match");let c=l.messages.find(m=>m.uid===Number(i));if(!c)throw Tt(t,"Message does not exist");let h=c.raw;if(a!==void 0&&(h=Bc(r,c,go(a)),h===!1))throw Tt(t,"Invalid section or the message part does not exist");if(o!==void 0){let m=o.match(/^(\d+)(?:\.(\d+))?$/);if(!m||!mt(m[1])||m[2]!==void 0&&!Mt(m[2]))throw Tt(t,"Invalid partial range");h=h.substr(Number(m[1]),m[2]?Number(m[2]):void 0)}return h}E();function hn(){throw new Error("The COMPRESS plugin is not available in the browser")}E();E();var ve={ALL:["FLAGS","INTERNALDATE","RFC822.SIZE","ENVELOPE"],FAST:["FLAGS","INTERNALDATE","RFC822.SIZE"],FULL:["FLAGS","INTERNALDATE","RFC822.SIZE","ENVELOPE","BODY"]};function Ao(r){return r.map(t=>{let e=Object.assign({},t,{value:t.value.replace(/\.PEEK\b/i,"")});return e.partial&&(e.partial=e.partial.slice(0,1)),e})}function To(r,t){return t.map((e,s)=>{let n=(e.value||"").toUpperCase(),i=r.server.fetchHandlers[n]||At[n];if(!i)throw new Error("Invalid FETCH argument "+(n||"#"+(s+1)));return i})}function xr(r,t,e,s,n){let i=s||To(r,e),a=n||Ao(e),o=[];return e.forEach((u,l)=>o.push(a[l],i[l](r,t,u))),o}function dn(r,t,e,s,n){let i=r?"UID FETCH":"FETCH";if(!e.attributes||e.attributes.length!==2||!e.attributes[0]||["ATOM","SEQUENCE"].indexOf(e.attributes[0].type)<0||!e.attributes[1]||["ATOM"].indexOf(e.attributes[1].type)<0&&!Array.isArray(e.attributes[1]))return t.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:i+" expects sequence set and message item names"}]},"INVALID COMMAND",e,s),n();let a=t.limitRange(e,t.getCommandRange(e.attributes[0].value,r)),o=[].concat(e.attributes[1]||[]);e.attributes[1].type==="ATOM"&&Object.prototype.hasOwnProperty.call(ve,e.attributes[1].value.toUpperCase())&&(o=ve[e.attributes[1].value.toUpperCase()].slice());let u=[],l=[],c=[];try{let h=!1,m=!1,T=!1;o.forEach((f,d)=>{if(!f||typeof f!="string"&&f.type!=="ATOM")throw new Error("Invalid FETCH argument #"+(d+1));typeof f=="string"&&(f=o[d]={type:"ATOM",value:f});let g=f.value.toUpperCase();g==="FLAGS"&&(m=!0),g==="UID"&&(h=!0);let b=t.server.fetchHandlers[g]||At[g];t.canSetSeen()&&(g==="BODY"&&f.section||b&&b.setsSeen)&&(T=!0)}),T&&!m&&o.push({type:"ATOM",value:"FLAGS"}),r&&!h&&o.push({type:"ATOM",value:"UID"});let A=To(t,o),p=Ao(o);a.forEach(f=>{for(let g=0,b=t.server.fetchFilters.length;g<b;g++)if(!t.server.fetchFilters[g](t,f[1],e,f[0]))return;T&&f[1].flags.indexOf("\\Seen")<0&&(f[1].flags.push("\\Seen"),u.push(f[1]));let d=xr(t,f[1],o,A,p);c.push(f[1]),l.push({tag:"*",attributes:[f[0],{type:"ATOM",value:"FETCH"},d]})})}catch(h){let m=h;return u.forEach(T=>t.server.removeFlag(T.flags,"\\Seen")),t.sendStatus(e,s,m.imapResponse==="NO"?"NO":"BAD",m.message,m.code,i+" FAILED"),n()}return l.forEach((h,m)=>t.send(h,i,e,s,c[m])),t.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:i+" Completed"}]},i,e,s),t.notifyFlagChanges(u),n()}var vc=(r,t,e,s)=>dn(!1,r,t,e,s),yo=vc;E();E();var me=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Vt(r){let t=String(r||"").toLowerCase();return me.findIndex(e=>e.toLowerCase()===t)}function Ee(r,t,e){return r=Number(r),e=Number(e),t<0||t>11||!Number.isInteger(r)||r<1?!1:r<=new Date(Date.UTC(e,t+1,0)).getUTCDate()}function Mr(r,t,e){return Ee(r,t,e)?String(e).padStart(4,"0")+"-"+String(t+1).padStart(2,"0")+"-"+String(r).padStart(2,"0"):!1}function wr(r){if(!r||typeof r!="string")return!1;let t=r.match(/^( \d|\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{4}) (\d{2}):(\d{2}):(\d{2}) [-+](\d{2})(\d{2})$/i);return t?Ee(t[1],Vt(t[2]),t[3])&&Number(t[4])<24&&Number(t[5])<60&&Number(t[6])<61&&Number(t[8])<60:!1}function Dr(r){let t=String(r||"").match(/^\s*(\d{1,2})-([A-Za-z]{3})-(\d{4})(?: (\d{2}):(\d{2}):(\d{2}) ([+-]\d{4}))?/);if(!t||!Ee(t[1],Vt(t[2]),t[3]))return null;let e=t[4]===void 0?{}:{hours:Number(t[4]),minutes:Number(t[5]),seconds:Number(t[6]),zone:t[7]};return Object.assign({day:Number(t[1]),month:Vt(t[2]),year:Number(t[3])},e)}function Lr(r){let t=(r||"").toString().replace(/\([^()]*\)/g," ").match(/^\s*(?:[A-Za-z]+\s*,)?\s*(\d{1,2})\s+([A-Za-z]{3})\s+(\d{2,4})(?:\s+(\d{1,2})\s*:\s*(\d{2})(?:\s*:\s*(\d{2}))?(?:\s+([+-]\d{4}|[A-Za-z]+))?)?/);if(!t)return null;let e=Number(t[3]);t[3].length===2?e+=e<50?2e3:1900:t[3].length===3&&(e+=1900);let s=Number(t[1]),n=Vt(t[2]);if(!Ee(s,n,e))return null;let i=t[4]===void 0?{}:{hours:Number(t[4]),minutes:Number(t[5]),seconds:Number(t[6]||0),zone:t[7]};return Object.assign({day:s,month:n,year:e},i)}var So={UT:0,GMT:0,EST:-5,EDT:-4,CST:-6,CDT:-5,MST:-7,MDT:-6,PST:-8,PDT:-7};function pn(r){let t=r.zone||"",e=0;if(/^[+-]\d{4}$/.test(t)){let s=t.charAt(0)==="-"?-1:1,n=Number(t.substr(1,2)),i=Number(t.substr(3,2));i<60&&(e=s*(n*60+i))}else Object.hasOwn(So,t.toUpperCase())&&(e=So[t.toUpperCase()]*60);return Date.UTC(r.year,r.month,r.day,r.hours||0,r.minutes||0,r.seconds||0)-e*60*1e3}E();var mn=/=\?([^?\s*]+)(?:\*[^?\s]*)?\?([BbQq])\?([^?\s]*)\?=/g,Fc=new TextDecoder("utf-8");function Rr(r){return Fc.decode(I.Buffer.from(r,"binary"))}var En=new Map;function Pc(r,t){if(r=r.toLowerCase(),!En.has(r)){let s=!1;try{s=new TextDecoder(r)}catch{}En.set(r,s)}let e=En.get(r);return e?e.decode(t):!1}function re(r){let t=String(r||"");if(t.indexOf("=?")<0&&!/[\u0080-\u00ff]/.test(t))return t;let e="",s=null,n=0,i=()=>{if(s){let o=Pc(s.charset,I.Buffer.concat(s.octets));e+=o===!1?s.source:o,s=null}};mn.lastIndex=0;let a;for(;a=mn.exec(t);){let o=t.substring(n,a.index);s&&/^\s*$/.test(o)||(i(),e+=Rr(o)),n=mn.lastIndex;let l=a[2].toUpperCase()==="B"?I.Buffer.from(a[3],"base64"):I.Buffer.from(a[3].replace(/_/g," ").replace(/=([0-9a-fA-F]{2})/g,(c,h)=>String.fromCharCode(parseInt(h,16))),"binary");s&&s.charset.toLowerCase()!==a[1].toLowerCase()&&i(),s||(s={charset:a[1],octets:[],source:""}),s.octets.push(l),s.source+=(s.source?o:"")+a[0]}return i(),e+Rr(t.substr(n))}var Xc={ALL:[],ANSWERED:[],BCC:["string"],BEFORE:["date"],BODY:["string"],CC:["string"],DELETED:[],DRAFT:[],FLAGGED:[],FROM:["string"],HEADER:["string","string"],KEYWORD:["string"],LARGER:["number64"],NEW:[],NOT:["key"],OLD:[],ON:["date"],OR:["key","key"],RECENT:[],SEEN:[],SENTBEFORE:["date"],SENTON:["date"],SENTSINCE:["date"],SINCE:["date"],SMALLER:["number64"],SUBJECT:["string"],TEXT:["string"],TO:["string"],UID:["sequence"],UNANSWERED:[],UNDELETED:[],UNDRAFT:[],UNFLAGGED:[],UNKEYWORD:["string"],UNSEEN:[]},bo=["US-ASCII","UTF-8"];function Q(r){let t=new Error(r);return t.imapResponse="BAD",t}function Gc(r){let t=(r||"").toString().match(/^(\d{1,2})-([A-Za-z]{3})-(\d{4})$/),e=t&&Mr(Number(t[1]),Vt(t[2]),Number(t[3]));if(!e)throw Q("Invalid date argument "+r);return e}function yn(r){let t=Dr(r);return t?Mr(t.day,t.month,t.year):!1}function Ur(r){return yn(r.internaldate)}function gn(r){let t=Lr(rt(r).tree.parsedHeader.date);return t?Mr(t.day,t.month,t.year):Ur(r)}function ge(r){let t=(e,s)=>{if(Array.isArray(e))return e.map(t);if(!e||["STRING","ATOM","LITERAL","SEQUENCE"].indexOf(e.type)<0)throw Q("Invalid search criteria argument #"+(s+1));return e.value};return r.map(t)}function Ae(r,t,e,s,n){let i=[];s.code==="BADCHARSET"?i.push({type:"SECTION",section:[{type:"ATOM",value:"BADCHARSET"},s.charsets.map(a=>({type:"ATOM",value:a}))]}):s.responseCode&&i.push({type:"SECTION",section:s.responseCode.map(a=>({type:"ATOM",value:String(a)}))}),i.push({type:"TEXT",value:s.message}),r.send({tag:t.tag,command:s.imapResponse==="BAD"?"BAD":"NO",attributes:i},n,t,e)}function Tn(r){return r.replace(/[A-Z]+/g,t=>t.toLowerCase())}function An(r,t){return Tn(r).indexOf(t)>=0}function Io(r){let t=Object.assign({},Xc),e=r.searchHandlers;return Object.keys(e).forEach(s=>{if(!(s in t)){let n=e[s];t[s]=typeof n.argumentTypes=="function"?n.argumentTypes:new Array(Math.max(n.length-3,0)).fill("string")}}),t}function Oo(r,t){let e=Io(r),s=n=>{let i=0;return n.some((a,o)=>{if(Array.isArray(a))return s(a);if(i)return i--,!1;let u=(a&&a.value||"").toString(),l=u.toUpperCase();if(l==="CHARSET"&&o===0)i=1;else if(Object.hasOwn(e,l)){let c=e[l];typeof c=="function"&&(c=c(n.slice(o+1).map(h=>Array.isArray(h)?h:(h&&h.value||"").toString()))),i=c.filter(h=>h!=="key").length}else if(/^[\d*][\d*,:]*$/.test(u))return!0;return!1})};return s([].concat(t||[]))}function wt(r,t,e,s){let n=s||((M,x)=>r.getMessageRange(M,x)),i={},a=new Set,o=Io(r.server),u=r.server.searchHandlers;e=[].concat(e||[]);let l=r.searchCharset||r.defaultSearchCharset||"US-ASCII";if(typeof e[0]=="string"&&e[0].toUpperCase()==="CHARSET"){if(r.searchCharset)throw Q("CHARSET is not allowed, search strings are always "+r.searchCharset+" in this session");e.shift();let M=e.shift();if(typeof M!="string")throw Q("CHARSET expects a charset name");if(bo.indexOf(M.toUpperCase())<0){let x=new Error("Unsupported charset "+M);throw x.imapResponse="NO",x.code="BADCHARSET",x.charsets=bo,x}l=M.toUpperCase()}let c=(M,x)=>{if(l==="US-ASCII"&&/[\u0080-\u00ff]/.test(x))throw Q(M+" argument has 8-bit characters, use CHARSET UTF-8");if(l==="UTF-8"&&!kt(I.Buffer.from(x,"binary")))throw Q(M+" argument is not valid UTF-8");return x};if(!e.length)throw Q("SEARCH expects search criteria, empty query given");let h=M=>{if(!M.length)throw Q("Unexpected end of search criteria");let x=M.shift();if(Array.isArray(x))return{key:"AND",args:m([].concat(x))};let _=x.toUpperCase();if(!Object.prototype.hasOwnProperty.call(o,_)||r.disabledSearchKeys&&r.disabledSearchKeys.has(_)){let D;try{D=n(x,!1)}catch(B){throw/^[\d,:*]+$/.test(x)?B:Q("Invalid search key "+x)}return{key:"_SEQ",args:[D]}}a.add(_);let X=o[_],z=typeof X=="function"?X(M):X,N=z.map(D=>{if(D==="key")return h(M);if(!M.length||typeof M[0]!="string")throw Q(_+" expects "+z.length+" argument"+(z.length>1?"s":""));let B=M.shift();if(typeof D=="function")return D(B);switch(D){case"date":return Gc(B);case"number":case"number64":{let V=D==="number64"&&r.number64;if(!mt(B,V?Ft:4294967295))throw Q(_+" expects a number"+(V?"64":""));return Number(B)}case"sequence":return n(B,!0);default:return c(_,B)}});return{key:_,args:N}},m=M=>{if(!M.length)throw Q("Empty search criteria list");let x=[];for(;M.length;)x.push(h(M));return x},T={key:"AND",args:m(e)},A=M=>new Set(M.map(x=>x[1])),p=M=>{(M.key==="_SEQ"||M.key==="UID")&&(M.set=A(M.args[0])),["BODY","TEXT"].indexOf(M.key)>=0?M.needle=Tn(M.args[0]):["BCC","CC","FROM","HEADER","SUBJECT","TO"].indexOf(M.key)>=0&&(M.needle=Tn(Rr(M.args[M.key==="HEADER"?1:0]))),M.args.forEach(x=>{x&&typeof x=="object"&&x.key&&p(x)})};p(T);let f=(M,x)=>M.flags.indexOf(x)>=0,d=(M,x,_)=>(x=x.toLowerCase(),(rt(M).tree.header||[]).some(X=>{let z=X.indexOf(":"),N=(z<0?X:X.substr(0,z)).trim().toLowerCase(),D=z<0?"":X.substr(z+1).replace(/\r?\n(?=[ \t])/g,"");return N===x&&An(re(D),_)})),g=(M,x,_)=>{let X=M.args;if(Object.prototype.hasOwnProperty.call(u,M.key))return!!u[M.key](r,x,_,...X);switch(M.key){case"AND":return X.every(z=>g(z,x,_));case"_SEQ":case"UID":return M.set.has(x);case"ALL":return!0;case"ANSWERED":return f(x,"\\Answered");case"BCC":case"CC":case"FROM":case"SUBJECT":case"TO":return d(x,M.key,M.needle);case"HEADER":return d(x,X[0],M.needle);case"BEFORE":{let z=Ur(x);return!!z&&z<X[0]}case"ON":return Ur(x)===X[0];case"SINCE":{let z=Ur(x);return!!z&&z>=X[0]}case"SENTBEFORE":{let z=gn(x);return!!z&&z<X[0]}case"SENTON":return gn(x)===X[0];case"SENTSINCE":{let z=gn(x);return!!z&&z>=X[0]}case"BODY":return An(Rt(rt(x).tree,!0),M.needle);case"TEXT":return An(rt(x).raw,M.needle);case"DELETED":return f(x,"\\Deleted");case"DRAFT":return f(x,"\\Draft");case"FLAGGED":return f(x,"\\Flagged");case"KEYWORD":return f(x,X[0]);case"LARGER":return rt(x).raw.length>X[0];case"SMALLER":return rt(x).raw.length<X[0];case"NEW":return r.isRecent(x)&&!f(x,"\\Seen");case"OLD":return!r.isRecent(x);case"RECENT":return r.isRecent(x);case"SEEN":return f(x,"\\Seen");case"NOT":return!g(X[0],x,_);case"OR":return g(X[0],x,_)||g(X[1],x,_);case"UNANSWERED":return!f(x,"\\Answered");case"UNDELETED":return!f(x,"\\Deleted");case"UNDRAFT":return!f(x,"\\Draft");case"UNFLAGGED":return!f(x,"\\Flagged");case"UNKEYWORD":return!f(x,X[0]);case"UNSEEN":return!f(x,"\\Seen");default:return!1}},b=r.server.searchLimits.reduce((M,x)=>x(r,M,T)||M,t),C=b!==t&&new Set(b),v=[];return t.forEach((M,x)=>{C&&!C.has(M)||g(T,M,x+1)&&(i[M.uid]=x+1,v.push(M))}),{list:v,numbers:i,keys:a,matches:(M,x)=>g(T,M,x)}}E();function Nt(r,t){r.enableAvailable=r.enableAvailable||[],r.enableAvailable.indexOf(t)<0&&r.enableAvailable.push(t)}function Et(r,t){return!!r.enabled&&r.enabled.indexOf(t)>=0}function Sn(r){r.registerCapability("ENABLE"),r.enableAvailable=r.enableAvailable||[],r.connectionHandlers.push(t=>{t.enabled=t.enabled||[]}),r.resetHandlers.push(t=>{t.enabled=[]}),r.setCommandHandler("ENABLE",(t,e,s,n)=>{let i,a,o;if(t.everSelected)return t.sendStatus(e,s,"BAD","ENABLE is not allowed after SELECT or EXAMINE"),n();if(!e.attributes)return t.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:"ENABLE expects capability list"}]},"INVALID COMMAND",e,s),n();for(a=0,o=e.attributes.length;a<o;a++)if(!e.attributes[a]||e.attributes[a].type!=="ATOM")return t.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:"Attribute nr "+(a+1)+" is not an ATOM"}]},"INVALID COMMAND",e,s),n();let u=[];for(a=0,o=e.attributes.length;a<o;a++){let l=e.attributes[a].value.toUpperCase();i=r.enableAvailable.find(c=>c.toUpperCase()===l),i&&t.enabled.indexOf(i)<0&&(t.enabled.push(i),u.push(i))}return t.send({tag:"*",command:"ENABLED",attributes:u.map(l=>({type:"ATOM",value:l}))},"ENABLED",e,s,u),t.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"ENABLE completed"}]},"ENABLE",e,s),n()},{states:J.AUTHENTICATED})}function In(r){r.registerCapability("CONDSTORE"),Nt(r,"CONDSTORE");let t=p=>Math.max(Number(p.HIGHESTMODSEQ)||0,1),e=p=>(p.HIGHESTMODSEQ=t(p)+1,p.HIGHESTMODSEQ);r.resetHandlers.push(p=>{p.condstoreEnabled=!1});let s=p=>!!p.condstoreEnabled||Et(p,"CONDSTORE")||Et(p,"QRESYNC");r.condstore={isEnabled:s,getHighestModseq:t};let n=(p,f,d,g)=>{p.send({tag:"*",command:"OK",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"HIGHESTMODSEQ"},t(f)]},{type:"TEXT",value:"Highest"}]},"CONDSTORE INFO",d,g)},i=(p,f,d)=>{if(s(p)){p.condstoreEnabled=!0;return}p.condstoreEnabled=!0,p.state==="Selected"&&p.selectedMailbox&&n(p,p.selectedMailbox,f,d)};r.messageHandlers.push((p,f,d)=>{let g=Number(f.MODSEQ);g>0&&Number.isSafeInteger(g)?(f.MODSEQ=g,d.HIGHESTMODSEQ=Math.max(t(d),g)):f.MODSEQ=e(d)}),r.on("expunge",p=>{e(p)}),r.on("flags",(p,f)=>{f.forEach(d=>{d.MODSEQ=e(p)})}),r.closedChecks.push(()=>!0),r.allowedStatus.push("HIGHESTMODSEQ"),r.statusHandlers.HIGHESTMODSEQ=(p,f)=>t(f);let a=(p,f)=>{let d=r.getCommandHandler(p);d&&r.setCommandHandler(p,(g,b,C,v)=>f(d,g,b,C,v))},o=(p,f,d,g,b)=>(p.sendStatus(f,d,"BAD",b,!1,"CONDSTORE FAILED"),g()),u=(p,f)=>!!p&&p.type==="ATOM"&&mt(p.value,Ft)&&(f||BigInt(p.value)>0n),l=(p,f,d,g,b)=>{Vc(d.attributes&&d.attributes[1],d.attributes,1)&&(f.condstoreEnabled=!0,d.condstoreOption=!0),p(f,d,g,b)};a("SELECT",l),a("EXAMINE",l),a("STATUS",(p,f,d,g,b)=>{let C=d.attributes&&d.attributes[1];Array.isArray(C)&&C.some(v=>v&&v.type==="ATOM"&&String(v.value).toUpperCase()==="HIGHESTMODSEQ")&&i(f,d,g),p(f,d,g,b)});let c=(p,f,d,g,b)=>{let C=d.attributes||[],v=Math.max(C.length-1,2),M=wo(C[v],"CHANGEDSINCE",C,v);if(M){if(!u(M))return o(f,d,g,b,"Invalid syntax for CHANGEDSINCE, number expected");d.changedsince=Number(M.value),jc(d)}(M||Do(d))&&i(f,d,g),p(f,d,g,b)};a("FETCH",c),a("UID FETCH",c);let h=(p,f,d,g,b)=>{let C=wo(d.attributes&&d.attributes[1],"UNCHANGEDSINCE",d.attributes,1);if(C){if(!u(C,!0))return o(f,d,g,b,"Invalid syntax for UNCHANGEDSINCE, number expected");d.unchangedsince=Number(C.value),i(f,d,g)}d.condstoreStore={isUid:(d.command||"").toUpperCase()==="UID STORE",messages:new Map,modified:[],done:!1},p(f,d,g,b)};a("STORE",h),a("UID STORE",h);let m=(p,f,d,...g)=>f.MODSEQ>=g[g.length-1];m.argumentTypes=p=>typeof p[0]=="string"&&/^\d+$/.test(p[0])?[No]:[_c,kc,No],r.searchHandlers.MODSEQ=m;let T=p=>p.reduce((f,d)=>Math.max(f,d.MODSEQ),0);r.fetchHandlers.MODSEQ=function(p,f){return[f.MODSEQ]},r.fetchFilters.push((p,f,d,g)=>"changedsince"in d&&!(d.changedsince<f.MODSEQ)?!1:(d.condstoreFetch||(d.condstoreFetch=new Map),d.condstoreFetch.set(g,{message:f,seen:f.flags.indexOf("\\Seen")>=0}),!0)),r.storeFilters.push((p,f,d,g)=>{let b=d.condstoreStore;return b?"unchangedsince"in d&&f.MODSEQ>d.unchangedsince?(b.modified.push(b.isUid?f.uid:g),!1):(b.messages.set(f,{index:g,before:Co(f),bumped:!1,reported:!1}),!0):!0});let A=(p,f,d)=>{!d.bumped&&Co(f)!==d.before&&(d.bumped=!0,f.MODSEQ=e(p.selectedMailbox))};r.outputHandlers.push((p,f,d,g,b,C)=>{if(d==="FLAG NOTIFICATION"&&f&&C&&s(p)){bn(f.attributes[2],C.MODSEQ);return}if(!g||!f)return;if(d==="FLAG UPDATE"&&g.condstoreStore&&C&&g.condstoreStore.messages.has(C)){let M=g.condstoreStore.messages.get(C);A(p,C,M),M.reported=!0,s(p)&&(bn(f.attributes[2],C.MODSEQ),xo(f.attributes[2],C.uid));return}let v=["SEARCH","SORT","THREAD"].includes(f.command)&&[f.command,"UID "+f.command].includes(d);if((v||d==="ESEARCH")&&f.tag==="*"&&C&&C.keys&&C.keys.has("MODSEQ")){if(i(p,g,b),C.list.length&&f.command!=="THREAD"){let M=[{type:"ATOM",value:"MODSEQ"},T(C.list)];f.attributes.push(...v?[M]:M)}return}if(f.tag==="*"&&g.condstoreFetch&&f.attributes&&f.attributes[1]&&f.attributes[1].value==="FETCH"&&g.condstoreFetch.has(f.attributes[0])){let M=g.condstoreFetch.get(f.attributes[0]),x=M.message,_=!1;!M.seen&&x.flags.indexOf("\\Seen")>=0&&p.selectedMailbox&&(M.seen=!0,x.MODSEQ=e(p.selectedMailbox),_=!0);let X=f.attributes[2];Array.isArray(X)&&(On(X,"MODSEQ")>=0||_&&s(p))&&bn(X,x.MODSEQ),Array.isArray(X)&&_&&s(p)&&xo(X,x.uid);return}if(f.tag===g.tag&&g.condstoreStore&&!g.condstoreStore.done){let M=g.condstoreStore;M.done=!0,M.messages.forEach((x,_)=>{if(A(p,_,x),!x.reported&&s(p)&&(x.bumped||"unchangedsince"in g)){let X=[{type:"ATOM",value:"MODSEQ"},[_.MODSEQ]];X.unshift({type:"ATOM",value:"UID"},_.uid),p.send({tag:"*",attributes:[x.index,{type:"ATOM",value:"FETCH"},X]},"CONDSTORE MODSEQ UPDATE",g,b,_)}}),(f.command==="OK"||f.command==="NO")&&M.modified.length&&(f.attributes=[{type:"SECTION",section:[{type:"ATOM",value:"MODIFIED"},{type:"SEQUENCE",value:M.modified.sort((x,_)=>x-_).join(",")}]}].concat((f.attributes||[]).filter(x=>f.command==="OK"||!x||x.type!=="SECTION")));return}if(d==="ENABLED"&&Array.isArray(C)&&C.indexOf("CONDSTORE")>=0){p.condstoreEnabled||(p.condstoreEnabled=!0,p.state==="Selected"&&p.selectedMailbox&&(g.condstoreReportHighest=!0));return}if(d==="ENABLE"&&g.condstoreReportHighest&&p.selectedMailbox){g.condstoreReportHighest=!1,n(p,p.selectedMailbox,g,b);return}if((d==="EXAMINE"||d==="SELECT")&&f.tag===g.tag&&p.selectedMailbox){if(g.condstoreOption){let M=f.attributes&&f.attributes.slice(-1)[0];!M||M.type!=="TEXT"?f.attributes=(f.attributes||[]).concat({type:"TEXT",value:"CONDSTORE is now enabled"}):M.value+=", CONDSTORE is now enabled"}n(p,p.selectedMailbox,g,b)}})}function No(r){if(!mt(r,Ft))throw Q("MODSEQ expects a mod-sequence value");return Number(r)}function _c(r){let t=r.match(/^\/flags\/(\\?)(.+)$/i);if(!t||ks.test(t[2])||t[1]&&t[2].toUpperCase()==="RECENT")throw Q('MODSEQ expects an entry name like "/flags/\\\\seen"');return r}function kc(r){if(!["PRIV","SHARED","ALL"].includes(r.toUpperCase()))throw Q("MODSEQ expects entry type priv, shared or all");return r}function Co(r){return JSON.stringify([r.flags||[],r["X-GM-LABELS"]||[]])}function On(r,t){if(!Array.isArray(r))return-1;for(let e=0;e<r.length;e+=2)if(r[e]&&r[e].type==="ATOM"&&String(r[e].value).toUpperCase()===t)return e;return-1}function bn(r,t){if(!Array.isArray(r))return;let e=On(r,"MODSEQ");e>=0?r[e+1]=[t]:r.push({type:"ATOM",value:"MODSEQ"},[t])}function xo(r,t){Array.isArray(r)&&On(r,"UID")<0&&r.push({type:"ATOM",value:"UID"},t)}function Mo(r){return!!r&&r.type==="ATOM"&&String(r.value).toUpperCase()==="MODSEQ"}function Do(r){let t=r.attributes&&r.attributes[1];return Array.isArray(t)?t.some(Mo):Mo(t)}function jc(r){if(!r.attributes||!r.attributes[1]||Do(r))return;let t=r.attributes[1];if(!Array.isArray(t)){let e=String(t.value).toUpperCase(),s=t.type==="ATOM"&&Object.hasOwn(ve,e)&&ve[e];t=s?s.map(n=>({type:"ATOM",value:n})):[t].concat(r.attributes.splice(2))}r.attributes[1]=t.concat({type:"ATOM",value:"MODSEQ"})}function Vc(r,t,e){if(!r)return!1;let s=!1;if(Array.isArray(r)){for(let n=r.length-1;n>=0;n--)if(r[n]&&r[n].type==="ATOM"&&r[n].value.toUpperCase()==="CONDSTORE"){r.splice(n,1),s=!0;break}r.length||t.splice(e,1)}return!!s}function wo(r,t,e,s){if(!r)return!1;let n=!1;if(Array.isArray(r)){for(let i=0;i<r.length;i+=2)if(r[i]&&r[i].type==="ATOM"&&r[i].value.toUpperCase()===t.toUpperCase()){n=r[i+1]||{type:"NIL"},r.splice(i,2);break}r.length||e.splice(s,1)}return n}E();E();E();function se(r){return Br(Array.from(new Set(r)).sort((t,e)=>t-e))}function Br(r){let t=[];return r.forEach(e=>{let s=t[t.length-1];s&&s[1]+1===e?s[1]=e:t.push([e,e])}),t.map(e=>e[0]===e[1]?String(e[0]):e[0]+":"+e[1]).join(",")}function Fe(r,t){let e=r&&["ATOM","SEQUENCE"].includes(r.type)?String(r.value):"",s=e.match(/^(-?)([1-9][0-9]*):(-?)([1-9][0-9]*)$/);if(!s||s[1]!==s[3]||s[1]&&!t)throw Q("PARTIAL expects a range like 1:100"+(t?" or -1:-100":""));let n=Number(s[2]),i=Number(s[4]);if(n>4294967295||i>4294967295)throw Q("PARTIAL range is out of bounds");return{range:e,from:Math.min(n,i),to:Math.max(n,i),fromEnd:!!s[1]}}function Hr(r,t){return t.fromEnd?r.slice(Math.max(r.length-t.to,0),Math.max(r.length-t.from+1,0)):r.slice(t.from-1,t.to)}function vr(r){r.searchReturnOptions.has("PARTIAL")||(r.searchReturnOptions.set("PARTIAL",{data:!0,once:!0,parse:t=>Fe(t,!!r.partialRangeLast)}),r.searchReturnOptions.set("ALL",Object.assign({},r.searchReturnOptions.get("ALL"),{once:!0})),r.searchReturnChecks.push(t=>t.has("PARTIAL")&&t.has("ALL")&&"PARTIAL and ALL can not be used together"))}function Xt(r,t){let e=t.get("PARTIAL");if(!r.length||t.has("ALL")||t.has("COUNT")||!e&&!t.has("MIN")&&!t.has("MAX"))return r;let s=new Set(e?Hr(r,e):[]);return t.has("MIN")&&s.add(r[0]),t.has("MAX")&&s.add(r[r.length-1]),r.filter(n=>s.has(n))}function Nn(r,t){let e=[{type:"ATOM",value:"TAG"},{type:"STRING",value:r}];return t&&e.push({type:"ATOM",value:"MAILBOX"},{type:"MAILBOX",value:t.path},{type:"ATOM",value:"UIDVALIDITY"},t.uidvalidity),e}function Te(r,t,e,s,n,i){let a=(i||e.list).map(c=>t?c.uid:e.numbers[c.uid]);i||a.sort((c,h)=>c-h);let o=i?Br:se,u=[Nn(r,n)];t&&u.push({type:"ATOM",value:"UID"});let l=(c,h)=>u.push({type:"ATOM",value:c},h);if(a.length&&s.has("MIN")&&l("MIN",a[0]),a.length&&s.has("MAX")&&l("MAX",a[a.length-1]),a.length&&(s.has("ALL")||!s.size)&&l("ALL",{type:"SEQUENCE",value:o(a)}),s.has("PARTIAL")){let c=s.get("PARTIAL"),h=Hr(a,c);l("PARTIAL",[{type:"ATOM",value:c.range},h.length?{type:"SEQUENCE",value:o(h)}:null])}return s.has("COUNT")&&l("COUNT",a.length),{tag:"*",command:"ESEARCH",attributes:u}}var Lo=r=>{let t=r&&r[0];return!!t&&t.type==="ATOM"&&String(t.value).toUpperCase()==="RETURN"};function yt(r){if(r.searchReturnOptions)return;r.registerCapability("ESEARCH"),r.searchReturnOptions=new Map(["MIN","MAX","ALL","COUNT"].map(e=>[e,{data:!0}])),r.searchReturnChecks=[],r.parseSearchReturn=(e,s,n)=>{if(!Array.isArray(e))throw Q("RETURN expects a parenthesized list of result options");let i=new Map,a=new Set;for(let o=0;o<e.length;o++){let u=e[o],l=u&&u.type==="ATOM"?String(u.value).toUpperCase():"",c=r.searchReturnOptions.get(l);if(!c)throw Q("Unknown SEARCH result option"+(l?" "+l:""));if(c.once&&i.has(l))throw Q("SEARCH result option "+l+" can be used only once");a.add(l);let h=c.parse?c.parse(e[++o]):!0;c.hint||i.set(l,h)}for(let o of r.searchReturnChecks){let u=o(i,s,n,a);if(u)throw Q(u)}return i},r.isSilentReturn=e=>e.size>0&&![...e.keys()].some(s=>{let n=r.searchReturnOptions.get(s);return n.data||n.response});let t=(e,s,n,i,a)=>{if(!Lo(n.attributes))return e(s,n,i,a);try{n.searchReturn=r.parseSearchReturn(n.attributes[1],s,n)}catch(o){return s.sendStatus(n,i,"BAD",o.message,!1,(n.command||"").toUpperCase()+" FAILED"),a()}n.attributes=n.attributes.slice(2),e(s,n,i,a)};r.acceptSearchReturn=e=>{let s=r.getCommandHandler(e);r.setCommandHandler(e,(n,i,a,o)=>t(s,n,i,a,o))},r.acceptSearchReturn("SEARCH"),r.acceptSearchReturn("UID SEARCH"),r.connectionHandlers.push(e=>{let s=e.usesSequenceNumbers;e.usesSequenceNumbers=function(n){return Lo(n.attributes)&&(n=Object.assign({},n,{attributes:n.attributes.slice(2)})),s.call(this,n)}}),r.outputHandlers.push((e,s,n,i,a,o)=>{if(!i||!i.searchReturn||s.tag!=="*"||s.command!=="SEARCH"||n!=="SEARCH"&&n!=="UID SEARCH"||!o||!Array.isArray(o.list))return;s.skipResponse=!0;let u=i.searchReturn;r.isSilentReturn(u)||e.send(Te(i.tag,n==="UID SEARCH",o,u),"ESEARCH",i,a,Object.assign({},o,{list:Xt(o.list,u)}))})}var qc=10,Ro=new Set(["SELECT","EXAMINE","CLOSE","UNSELECT"]),Qc=new Set(["SEARCH","UID SEARCH","SORT","UID SORT"]),Cn=r=>(r.searchContexts||(r.searchContexts=new Map),r.searchContexts),Uo=(r,t)=>{let e=[];r.forEach(([n,i])=>{let a=e[e.length-1],o=a&&(t||!n?a.position:a.position+a.values.length);a&&n===o?a.values.push(i):e.push({position:n,values:[i]})});let s=[];return e.forEach(n=>{let i=n.position?Br(n.values):se(n.values);s.push(n.position,{type:"SEQUENCE",value:i})}),s},Bo=(r,t,e,s)=>{let n=[Nn(t.tag,t.correlatorMailbox)];t.isUid&&n.push({type:"ATOM",value:"UID"}),e.length&&n.push({type:"ATOM",value:"REMOVEFROM"},Uo(e,!0)),s.length&&n.push({type:"ATOM",value:"ADDTO"},Uo(s,!1)),r.send({tag:"*",command:"ESEARCH",attributes:n},"ESEARCH UPDATE",null,null,t)},Yc=r=>{let t=r.searchContexts,e=r.selectedMailbox,s=e?e.messages:[],n=new Map(s.map((i,a)=>[i,a+1]));t.forEach((i,a)=>{if(i.mailbox!==e){t.delete(a);return}let o=s.filter((m,T)=>i.matches(m,T+1)),u=m=>i.isUid?m.uid:n.get(m),l=new Set(o),c=[],h=[];if(!i.compare)i.results.forEach(m=>{!l.has(m)&&n.has(m)&&c.push([0,u(m)])}),o.forEach(m=>{i.results.has(m)||h.push([0,u(m)])});else{let m=0;i.order.forEach(T=>{l.has(T)?m++:n.has(T)&&c.push([m+1,u(T)])}),i.order=o.sort(i.compare),i.order.forEach((T,A)=>{i.results.has(T)||h.push([A+1,u(T)])})}i.results=l,(c.length||h.length)&&Bo(r,i,c,h)})},Kc=(r,t,e)=>{r.searchContexts.forEach(s=>{if(s.mailbox!==r.selectedMailbox)return;let n=[];t.forEach(i=>{if(!s.results.delete(i))return;let a=0;s.order&&(a=s.order.indexOf(i)+1,s.order.splice(a-1,1)),(s.isUid||e)&&n.push([a,s.isUid?i.uid:e])}),n.length&&Bo(r,s,n,[])})};function Pe(r){if(r.addSearchContext)return;yt(r),r.registerCapability("CONTEXT=SEARCH");let t=Math.max(Number(r.options.maxSearchContexts)||qc,1);r.searchReturnOptions.set("CONTEXT",{hint:!0}),r.searchReturnOptions.set("UPDATE",{data:!1,response:!0,once:!0}),vr(r),r.searchReturnChecks.push((e,s,n)=>e.has("UPDATE")&&Cn(s).has(n.tag)&&"Tag "+n.tag+" is already in use by an updating search"),r.addSearchContext=(e,s,n,i,a,o)=>{let u=Cn(e);if(u.size>=t){e.send({tag:"*",command:"NO",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"NOUPDATE"},{type:"STRING",value:s.tag}]},{type:"TEXT",value:"Too many updating contexts"}]},"NOUPDATE",s,n);return}u.set(s.tag,{tag:s.tag,isUid:a,matches:i.matches,results:new Set(i.list),compare:i.compare||null,order:i.compare?i.sorted.slice():null,mailbox:e.selectedMailbox,correlatorMailbox:o||null})},r.setCommandHandler("CANCELUPDATE",(e,s,n,i)=>{let a=s.attributes||[];if(!a.length||a.some(l=>!l||l.type!=="STRING"))return e.sendStatus(s,n,"BAD","CANCELUPDATE expects one or more quoted tags",!1,"CANCELUPDATE FAILED"),i();let o=Cn(e);return a.find(l=>!o.has(l.value))?(e.sendStatus(s,n,"NO","Unknown tag",!1,"CANCELUPDATE FAILED"),i()):(a.forEach(l=>o.delete(l.value)),e.sendStatus(s,n,"OK","Updates cancelled",!1,"CANCELUPDATE"),i())},{states:J.SELECTED}),r.resetHandlers.push(e=>{e.searchContexts=null}),r.connectionHandlers.push(e=>{let s=e.processNotifications;e.processNotifications=function(n,i){s.call(this,n,i);let a=(n&&n.command||"").toUpperCase();this.searchContexts&&this.searchContexts.size&&!this.notificationQueue.length&&!Ro.has(a)&&Yc(this)}}),r.outputHandlers.push((e,s,n,i,a,o)=>{let u=s.tag==="*"&&(s.message?[s.message]:s.command==="VANISHED"&&s.messages);if(u&&e.searchContexts){Kc(e,u,s.message?s.attributes[0]:null);return}if(!i)return;let l=(i.command||"").toUpperCase();if(s.tag===i.tag&&Ro.has(l)){e.searchContexts=null;return}if(!(!Qc.has(l)||!i.searchReturn||!i.searchReturn.has("UPDATE"))){if(s.tag==="*"&&l.endsWith(String(s.command))&&n===l&&o&&Array.isArray(o.list)){i.contextResult=o;return}s.tag===i.tag&&s.command==="OK"&&i.contextResult&&r.addSearchContext(e,i,a,i.contextResult,l.startsWith("UID "))}})}E();E();E();E();var xn=new Map([[452,453],[454,453],[455,456],[457,456],[458,459],[460,459],[497,498],[499,498],[8115,8124],[8131,8140],[8179,8188]]);for(let r of[8064,8080,8096])for(let t=0;t<8;t++)xn.set(r+t,r+t+8);function Ut(r){let t="";for(let e of r){let s=e.codePointAt(0);if(xn.has(s)){t+=String.fromCodePoint(xn.get(s));continue}let n=e.toUpperCase();t+=[...n].length===1?n:e}return I.Buffer.from(t.normalize("NFKD"),"utf-8")}var Mn="\\[[^[\\]]*\\] *",zc=new RegExp("^(?:"+Mn+")*(?:re|fwd?) *(?:"+Mn+")?:","i"),Wc=new RegExp("^"+Mn);function Fr(r){let t=!1,e=re(r).replace(/\r?\n(?=[ \t])/g,"").replace(/[\t\r\n]/g," ").replace(/ {2,}/g," ");for(;;){let s=e.length;for(;;)if(e.charAt(s-1)===" ")s--;else if(s>=5&&e.substring(s-5,s).toLowerCase()==="(fwd)")t=!0,s-=5;else break;for(e=e.substring(0,s);;){let n;if(e.charAt(0)===" ")e=e.substr(1);else if(n=e.match(zc))t=!0,e=e.substr(n[0].length);else if((n=e.match(Wc))&&n[0].length<e.length)e=e.substr(n[0].length);else break}if(/^\[fwd:/i.test(e)&&/\]$/.test(e)){t=!0,e=e.slice(5,-1);continue}return{subject:e,isReply:t}}}function wn(r){let t=Dr(r.internaldate);return t?pn(t):0}function Pr(r){let t=Lr(rt(r).tree.parsedHeader.date);return t?((t.hours===void 0||t.hours>23||t.minutes>59||t.seconds>60)&&Object.assign(t,{hours:0,minutes:0,seconds:0}),pn(t)):wn(r)}function Ho(r,t){let e=Pt(rt(r).tree.parsedHeader[t]);return e&&e[0]||null}function Xr(r,t){let e=Ho(r,t);return e&&e[2]?re(e[2]):""}function Dn(r,t){let e=Ho(r,t),s=e&&e[0]?re(e[0]):"";return s||!e||!e[2]?s:re(e[3]?e[2]+"@"+e[3]:e[2])}function Gr(r){let t=[].concat(r||[]).join(" "),e=[],s=0,n=!1,i=null;for(let a=0;a<t.length;a++){let o=t.charAt(a);if(n)o==="\\"?(i!==null&&(i+=t.charAt(a+1)),a++):o==='"'?n=!1:i!==null&&(i+=o);else if(s)o==="\\"?a++:o==="("?s++:o===")"&&s--;else if(o==='"')n=!0;else if(o==="(")s++;else if(o==="<")i="";else if(o===">"){if(i!==null){let u=i.lastIndexOf("@");u>0&&u<i.length-1&&e.push(i)}i=null}else i!==null&&!/\s/.test(o)&&(i+=o)}return e}function _r(r,t,e,s){let n=t.command.toUpperCase(),i=s[0];try{if(s.length<2)throw Q(n+" expects a charset and search criteria");if(!i||["ATOM","STRING"].indexOf(i.type)<0)throw Q("Charset must be an atom or a quoted string");let a=ge(s.slice(1));if(r.searchCharset){if(i.value.toUpperCase()!==r.searchCharset)throw Q("Charset must be "+r.searchCharset+" in this session");return wt(r,r.getSessionMessages(),a)}let o=["CHARSET",i.value].concat(a);return wt(r,r.getSessionMessages(),o)}catch(a){return Ae(r,t,e,a,n+" FAILED"),!1}}function ne(r){if(r.sortKeys)return;r.registerCapability("SORT"),r.sortKeys={ARRIVAL:s=>wn(s),CC:s=>Ut(Xr(s,"cc")),DATE:s=>Pr(s),FROM:s=>Ut(Xr(s,"from")),SIZE:s=>rt(s).raw.length,SUBJECT:s=>Ut(Fr(rt(s).tree.parsedHeader.subject).subject),TO:s=>Ut(Xr(s,"to"))};let t=(s,n)=>I.Buffer.isBuffer(s)?I.Buffer.compare(s,n):s-n;r.sortComparator=s=>{let n=new WeakMap,i=a=>(n.has(a)||n.set(a,s.map(o=>r.sortKeys[o.key](a))),n.get(a));return(a,o)=>{let u=i(a),l=i(o);for(let c=0;c<s.length;c++){let h=t(u[c],l[c]);if(h)return s[c].reverse?-h:h}return a.uid-o.uid}};let e=(s,n,i,a,o)=>{let u=s?"UID SORT":"SORT",l=i.attributes||[],c=f=>(n.sendStatus(i,a,"BAD",f,!1,u+" FAILED"),o());if(!Array.isArray(l[0])||!l[0].length)return c(u+" expects a list of sort criteria");let h=[],m=!1;for(let f of l[0]){let d=f&&f.type==="ATOM"?f.value.toUpperCase():"";if(d==="REVERSE"&&!m){m=!0;continue}if(!Object.hasOwn(r.sortKeys,d))return c("Invalid sort criterion "+(f&&typeof f.value=="string"?f.value:""));h.push({key:d,reverse:m}),m=!1}if(m)return c("REVERSE must be followed by a sort key");let T=_r(n,i,a,l.slice(1));if(!T)return o();let A=r.sortComparator(h),p=T.list.slice().sort(A);return n.send({tag:"*",command:"SORT",attributes:p.map(f=>s?f.uid:T.numbers[f.uid])},u,i,a,Object.assign(T,{sorted:p,compare:A})),n.sendStatus(i,a,"OK",u+" completed",!1,u),o()};r.setCommandHandler("SORT",e.bind(null,!1),{states:J.SELECTED,searchCriteria:2,noExpunge:!0}),r.setCommandHandler("UID SORT",e.bind(null,!0),{states:J.SELECTED,searchCriteria:2})}var vo=r=>r==="SORT"||r==="UID SORT";function Xe(r){r.esortLoaded||(r.esortLoaded=!0,ne(r),yt(r),r.registerCapability("ESORT"),r.acceptSearchReturn("SORT"),r.acceptSearchReturn("UID SORT"),r.searchReturnChecks.push((t,e,s,n)=>{if(!vo((s.command||"").toUpperCase())||r.contextSort)return!1;let i=["CONTEXT","UPDATE","PARTIAL"].find(a=>n.has(a)&&(a!=="PARTIAL"||!r.partialRangeLast));return!!i&&i+" is not supported for SORT"}),r.outputHandlers.push((t,e,s,n,i,a)=>{if(!n||!n.searchReturn||e.tag!=="*"||e.command!=="SORT"||!vo(s)||!a||!a.sorted)return;e.skipResponse=!0;let o=n.searchReturn;r.isSilentReturn(o)||t.send(Te(n.tag,s==="UID SORT",a,o,null,a.sorted),"ESEARCH",n,i,Object.assign({},a,{list:Xt(a.sorted,o)}))}))}function Ln(r){Xe(r),Pe(r),r.registerCapability("CONTEXT=SORT"),r.contextSort=!0}E();var $c=new RegExp("^\\\\["+lt["ATOM-CHAR"]().replace(/[\\\]^-]/g,"\\$&")+"]+$");function Rn(r){r.registerCapability("CREATE-SPECIAL-USE");let t=r.getCommandHandler("CREATE"),e=[].concat(r.options["special-use"]||["\\Archive","\\Drafts","\\Flagged","\\Junk","\\Sent","\\Trash"]);r.setCommandHandler("CREATE",(s,n,i,a)=>{let o,u,l,c=[];if(n.attributes&&Array.isArray(n.attributes[1])){for(o=0;o<n.attributes[1].length;o+=2)n.attributes[1][o]&&n.attributes[1][o].type==="ATOM"&&n.attributes[1][o].value.toUpperCase()==="USE"&&Array.isArray(n.attributes[1][o+1])&&(l=n.attributes[1][o+1],n.attributes[1].splice(o,2),o-=2);n.attributes[1].length||n.attributes.splice(1,1)}if(l)for(o=0,u=l.length;o<u;o++){let h=l[o];if(!$(h)||!$c.test(h.value))return s.send({tag:n.tag,command:"BAD",attributes:[{type:"TEXT",value:"Invalid syntax for special use flag #"+(o+1)}]},"CREATE-SPECIAL-USE FAILED",n,i),a();let m=e.find(T=>T.toLowerCase()===String(l[o].value).toLowerCase());if(!m)return s.send({tag:n.tag,command:"NO",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"USEATTR"}]},{type:"TEXT",value:l[o].value+" not supported"}]},"CREATE-SPECIAL-USE FAILED",n,i),a();c.indexOf(m)<0&&c.push(m)}c.length&&(n.mailboxSpecialUse=c),t(s,n,i,a)}),r.outputHandlers.push((s,n,i,a,o,u)=>{i==="CREATE"&&u&&a.mailboxSpecialUse&&(u["special-use"]=a.mailboxSpecialUse)})}E();function Un(r){r.registerCapability("ID"),r.setCommandHandler("ID",(t,e,s,n)=>{let i=Object.create(null),a=null,o,u,l="";if(!e.attributes||e.attributes.length!==1)return qt("ID expects 1 attribute",t,e,s,n);let c=e.attributes[0];if(c&&!Array.isArray(c)||c&&c.length%2)return qt("ID expects valid parameter list",t,e,s,n);if(c&&c.length>60)return qt("ID allows at most 30 field-value pairs",t,e,s,n);if(c&&c.length)for(o=0,u=c.length;o<u;o++)if(o%2===0)if(c[o]&&["STRING","LITERAL"].indexOf(c[o].type)>=0){if(l=c[o].value,l.length>30)return qt("ID field names can be at most 30 octets",t,e,s,n);if(Object.keys(i).some(h=>h.toLowerCase()===l.toLowerCase()))return qt("ID field names must not repeat",t,e,s,n)}else return qt("ID expects valid parameter list",t,e,s,n);else if(!c[o]||["STRING","LITERAL"].indexOf(c[o].type)>=0){if(c[o]&&c[o].value.length>1024)return qt("ID values can be at most 1024 octets",t,e,s,n);i[l]=c[o]&&c[o].value||null}else return qt("ID expects valid parameter list",t,e,s,n);if(r.options.id){let h=[];a=h,Object.keys(r.options.id).forEach(m=>{h.push({type:"STRING",value:m}),h.push({type:"STRING",value:(r.options.id[m]||"").toString()})})}t.send({tag:"*",command:"ID",attributes:[a]},"ID",e,s,i),t.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"ID command completed"}]},"ID",e,s,i),n()},{states:J.ANY})}function qt(r,t,e,s,n){return t.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:r}]},"INVALID COMMAND",e,s),n()}E();function Bn(r){r.registerCapability("IDLE"),r.setCommandHandler("IDLE",(t,e,s,n)=>{let i=setTimeout(()=>{t.socket&&!t.socket.destroyed&&(t.send({tag:"*",command:"BYE",attributes:[{type:"TEXT",value:"IDLE terminated"}]},"IDLE EXPIRED",e,s),t.end())},18e5);i.unref?.();let a=()=>clearTimeout(i),o=t.socket;return o&&o.once("close",a),t.directNotifications=!0,t.inputHandler=function(u){a(),o&&o.removeListener("close",a),t.inputHandler=!1,t.directNotifications=!1,u.toUpperCase()==="DONE"?t.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"IDLE terminated"}]},"IDLE",e,s):t.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:"Invalid Idle continuation"}]},"INVALID IDLE",e,s)},t.sendContinuation("idling","IDLE"),t.processNotifications(),n()},{states:J.AUTHENTICATED,noArguments:!0})}E();E();var Jc=/[\u0000-\u001f\u007f-\u009f\u2028\u2029]|^\ufeff|\p{Cn}/u;function Hn(r){let t=new Error(r);return t.imapResponse="BAD",t}function Fo(r){if(r===!1||Jc.test(r))throw Hn("Mailbox name must be valid Net-Unicode without control characters (RFC 9755 section 3)");if(r.normalize("NFC")!==r)throw Hn("Mailbox name must be in Unicode Normalization Form C (RFC 5198 section 2, RFC 9051 section 5.1)");return r}function Zc(r){let t=pe(r);if(t)throw Hn(t);return Fo(cn(r)),r}function tf(r){let t=I.Buffer.from(r,"binary");return Cr(Fo(kt(t)&&t.toString("utf-8")))}function ef(r){let t=cn(r);return t===!1?r:I.Buffer.from(t,"utf-8").toString("binary")}function ye(r){let t=r.server,e=Et(r,"UTF8=ACCEPT"),s=Et(r,"IMAP4rev2"),n=e||s;if(r.utf8Enabled=n,r.parserOptions.utf8=!!t.utf8Accept||s,r.compilerOptions.utf8=n,r.searchCharset=e?"UTF-8":!1,r.defaultSearchCharset=s?"UTF-8":!1,n)r.importMailboxName=tf,r.exportMailboxName=ef;else{let i=r;delete i.exportMailboxName,t.utf8Accept?r.importMailboxName=Zc:delete i.importMailboxName}}E();function Ge(r){if(r.capabilities["LITERAL+"])throw new Error("LITERAL- can not be enabled together with LITERAL+");r.registerCapability("LITERAL-"),r.impliedLiteralMinus=!1,r.literalPlus=!0,r.nonSyncLiteralLimit=4096}var vn="IMAP4rev2",rf=new Set(["NEW","OLD","RECENT","UNRECENT"]),sf=new Set(["RECENT"]),nf=new Set(["DELETED"]),af=new Set(["RFC822","RFC822.HEADER","RFC822.TEXT"]),of=["$Forwarded","$MDNSent","$Junk","$NotJunk","$Phishing"],Se=r=>!!r.imap4rev2,Po=r=>r&&r.type==="ATOM"?String(r.value).toUpperCase():"";function kr(r){r.registerCapability("IMAP4rev2"),Nt(r,vn),!r.capabilities["LITERAL+"]&&!r.capabilities["LITERAL-"]&&(Ge(r),r.impliedLiteralMinus=!0),r.mailboxHandlers.push((o,u)=>{u.allowPermanentFlags||of.forEach(l=>o.ensureFlag(u.permanentFlags,l))});let t=o=>{let u=o.imap4rev2=Et(o,vn);ye(o),o.messageGlobal=u,o.disabledSearchKeys=u?rf:null,o.number64=o.parserOptions.number64=u,o.disabledStatusItems=u?sf:null,o.addedStatusItems=u?nf:null,u?o.getFlags=l=>l.flags:delete o.getFlags};r.connectionHandlers.push(t),r.resetHandlers.push(t);let e=(o,u,l,c,h)=>(o.sendStatus(u,l,"BAD",h),c()),s=(o,u)=>{let l=r.getCommandHandler(o);r.setCommandHandler(o,(c,h,m,T)=>u(l,c,h,m,T))};Object.entries({CHECK:"NOOP",LSUB:"LIST (SUBSCRIBED)"}).forEach(([o,u])=>{s(o,(l,c,h,m,T)=>{if(Se(c))return e(c,h,m,T,o+" is not part of IMAP4rev2, use "+u+" (RFC 9051 Appendix E)");l(c,h,m,T)})});let n=(o,u,l,c,h)=>{let m=(l.attributes||[])[1];if(Se(u)&&[].concat(m||[]).some(T=>af.has(Po(T))))return e(u,l,c,h,"RFC822, RFC822.HEADER and RFC822.TEXT are not part of IMAP4rev2, use BODY[] (RFC 9051 Appendix E)");o(u,l,c,h)};s("FETCH",n),s("UID FETCH",n);let i=(o,u,l,c,h)=>{Se(u)&&Po((l.attributes||[])[0])!=="RETURN"&&(l.searchReturn=r.parseSearchReturn([],u,l)),o(u,l,c,h)};s("SEARCH",i),s("UID SEARCH",i),r.closedChecks.push(Se);let a=(o,u,l,c)=>{let h=u.flags.concat(u["special-use"]||[]);o.send({tag:"*",command:"LIST",attributes:[h.map(m=>({type:"ATOM",value:m})),r.getSeparator(u),{type:"MAILBOX",value:u.path}]},"SELECT LIST",l,c,u)};r.outputHandlers.push((o,u,l,c,h)=>{if(l==="RECENT NOTIFICATION"&&Se(o)){u.skipResponse=!0;return}if(!c||!u||!Se(o))return;let m=String(c.command||"").toUpperCase();if(!(m!=="SELECT"&&m!=="EXAMINE")){if(l===m+" RECENT"||l===m+" UNSEEN"){u.skipResponse=!0;return}l===m&&u.tag===c.tag&&u.command==="OK"&&o.selectedMailbox&&a(o,o.selectedMailbox,c,h)}}),r.outputHandlers.push((o,u,l,c,h,m)=>{l==="ENABLED"&&Array.isArray(m)&&m.indexOf(vn)>=0&&t(o)})}kr.requires=["ENABLE","NAMESPACE","UNSELECT","UIDPLUS","ESEARCH","SEARCHRES","IDLE","SASL-IR","LIST-EXTENDED","LIST-STATUS","MOVE","BINARY","SPECIAL-USE","STATUS=SIZE","AUTH=PLAIN"];E();E();function jr(r,t){if(Object.is(r,t))return!0;if(!r||!t||typeof r!="object"||typeof t!="object"||Object.getPrototypeOf(r)!==Object.getPrototypeOf(t))return!1;if(r instanceof Map||r instanceof Set)return jr(Array.from(r),Array.from(t));let e=Object.keys(r);return e.length===Object.keys(t).length&&e.every(s=>Object.prototype.hasOwnProperty.call(t,s)&&jr(r[s],t[s]))}var uf=r=>Array.isArray(r[0])||Array.isArray(r[1])||r.length>2;function _e(r){let t=jt(r);if(t.enabled)return;t.enabled=!0,r.registerCapability("LIST-EXTENDED"),t.selectionOptions.SUBSCRIBED={type:"base",returnOption:"SUBSCRIBED",includeNonExistent:!0,match:o=>!!o.subscribed},t.selectionOptions.REMOTE={type:"independent"},t.selectionOptions.RECURSIVEMATCH={type:"modifier"},t.returnOptions.SUBSCRIBED={},t.returnOptions.CHILDREN={};let e=(o,u,l,c)=>{let h=new Map;for(let m=0;m<o.length;m++){let T=o[m];if(!T||T.type!=="ATOM")throw new Error("Invalid "+l+" option");let A=T.value.toUpperCase(),p=u[A];if(!p)throw new Error("Unknown "+l+" option "+A);let f=!0;if(p.parse){if(!Array.isArray(o[m+1]))throw new Error(A+" "+l+" option requires a value");f=p.parse(o[++m],c)}else if(Array.isArray(o[m+1]))throw new Error(A+" "+l+" option takes no value");if(h.has(A)&&!jr(h.get(A),f))throw new Error(A+" "+l+" option is repeated with a different value");h.set(A,f)}return h},s=(o,u)=>{let l=new Map,c=new Map,h=0;Array.isArray(o[0])&&(l=e(o[0],t.selectionOptions,"selection",u),h++);let m=o[h],T=o[h+1],A=o.slice(h+2);if(!at(m))throw new Error("LIST expects a reference name");if(T=Array.isArray(T)?T:[T],!T.length||!T.every(at))throw new Error("LIST expects a mailbox pattern or a list of patterns");if(A.length){if(A.length!==2||!A[0]||A[0].type!=="ATOM"||A[0].value.toUpperCase()!=="RETURN"||!Array.isArray(A[1]))throw new Error("LIST expects RETURN and a list of return options after the patterns");c=e(A[1],t.returnOptions,"return",u)}let p=[...l.keys()].map(f=>t.selectionOptions[f].type);if(p.includes("modifier")&&!p.includes("base"))throw new Error("RECURSIVEMATCH must be used together with a selection option like SUBSCRIBED");return l.forEach((f,d)=>{let g=t.selectionOptions[d].returnOption;g&&!c.has(g)&&c.set(g,!0)}),{selection:l,reference:m.value,patterns:T.map(f=>f.value).filter(f=>f),returns:c}},n=o=>o.flags.indexOf("\\Noselect")<0,i=(o,u,l,c)=>r.listAttributes(o,{exists:u,subscribed:c.has("SUBSCRIBED")&&o.subscribed,hasChildren:l}).map(h=>({type:"ATOM",value:h})),a=r.getCommandHandler("LIST");r.setCommandHandler("LIST",(o,u,l,c)=>{let h=u.attributes||[];if(!uf(h))return a(o,u,l,c);let m;try{m=s(h,o)}catch(v){return o.sendStatus(u,l,"BAD",v.message,!1,"INVALID COMMAND"),c()}let T=[...m.selection.keys()].map(v=>({name:v,...t.selectionOptions[v]})),A=T.filter(v=>v.match),p=T.some(v=>v.includeNonExistent),f=m.selection.has("RECURSIVEMATCH"),d=T.filter(v=>v.type==="base").map(v=>({type:"STRING",value:v.name})),g=v=>(p||n(v))&&A.every(M=>M.match(v,o)),b=r.folderCache;p&&(b=Object.assign(Object.create(null),b,r.getSubscriptionTree()));let C=new Set;return m.patterns.forEach(v=>{r.matchFolders(m.reference,v,M=>o.exportMailboxName(M),b).forEach(M=>C.add(M))}),C.forEach(v=>{let M=n(v),x=g(v),_=r.getDescendants(v.path,b),X=_.some(n),z=!1;if(f&&(z=_.some(B=>g(B)&&(x||!C.has(B)))),!(x||z||!A.length&&!M&&X))return;let D=[i(v,M,X,m.returns),r.getSeparator(v),o.exportMailboxName(v.path)];z&&D.push([{type:"STRING",value:"CHILDINFO"},d]),o.send({tag:"*",command:"LIST",attributes:D},"LIST ITEM",u,l,v),m.returns.forEach((B,V)=>{let G=t.returnOptions[V];G.onItem&&G.onItem(o,v,B,{matched:x,exists:M},u,l)})}),o.sendStatus(u,l,"OK","Completed",!1,"LIST"),c()})}E();E();var lf={MESSAGES:(r,t)=>t.messages.length,RECENT:(r,t,e)=>e.recent,UIDNEXT:(r,t)=>t.uidnext,UIDVALIDITY:(r,t)=>t.uidvalidity,UNSEEN:(r,t,e)=>e.unseen||0,DELETED:(r,t,e)=>e.flags["\\Deleted"]||0};function Vr(r,t,e){if(!Array.isArray(t)||!t.length)throw new Error("Expecting a list of status items");let s=e&&e.disabledStatusItems,n=e&&e.addedStatusItems;return t.map((i,a)=>{let o=i&&i.type==="ATOM"&&i.value.toUpperCase();if(!o||r.allowedStatus.indexOf(o)<0&&!(n&&n.has(o))||s&&s.has(o))throw new Error("Invalid status element ("+(a+1)+")");return o})}function qr(r,t,e,s,n,i){r.send(Qr(r,t,e,s),"STATUS",n,i)}function Qr(r,t,e,s){let n=r.server,i=n.getStatus(e),a=[];return s.forEach(o=>{a.push({type:"ATOM",value:o},(n.statusHandlers[o]||lf[o])(r,e,i))}),{tag:"*",command:"STATUS",attributes:[{type:"MAILBOX",value:t},a]}}function Fn(r){_e(r),r.registerCapability("LIST-STATUS"),jt(r).returnOptions.STATUS={parse:(t,e)=>Vr(r,t,e),onItem:(t,e,s,n,i,a)=>{n.matched&&n.exists&&qr(t,e.path,e,s,i,a)}}}E();function Pn(r){if(r.capabilities["LITERAL-"]&&!r.impliedLiteralMinus)throw new Error("LITERAL+ can not be enabled together with LITERAL-");delete r.capabilities["LITERAL-"],r.registerCapability("LITERAL+"),r.literalPlus=!0,r.nonSyncLiteralLimit=1/0}E();function Xn(r){r.registerCapability("LOGINDISABLED",e=>!e.secureConnection&&e.state==="Not Authenticated");let t=r.getCommandHandler("LOGIN");r.setCommandHandler("LOGIN",(e,s,n,i)=>{if(!e.secureConnection)return e.send({tag:s.tag,command:"NO",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"PRIVACYREQUIRED"}]},{type:"TEXT",value:"Run STARTTLS first"}]},"LOGIN FAILED",s,n),i();t(e,s,n,i)})}E();var cf=1e3,ff=new Set(["FETCH","UID FETCH","STORE","UID STORE","MOVE","UID MOVE","UID EXPUNGE"]),hf=new Set(["SEARCH","UID SEARCH"]),Xo=new Set(["SORT","UID SORT","THREAD","UID THREAD"]);function Gn(r,t){if(r.messageLimit)throw new Error(t+" can not be enabled together with "+r.messageLimit.name);let e="messageLimit"in r.options?r.options.messageLimit:cf;if(!Number.isSafeInteger(e)||e<1||e>4294967295)throw new TypeError("Invalid messageLimit option, expecting a positive integer");return r.messageLimit={name:t,limit:e},e}function _n(r,t){r.appendChecks.push((e,s,n,i)=>{if(n.length<=t)return!1;if(i.command)return{code:["MESSAGELIMIT",t],text:i.command+" exceeds the limit of "+t+" messages, nothing was appended"};if(!i.move){let a=n[n.length-t].uid;return{code:["MESSAGELIMIT",t,a],text:"Too many messages to copy, try a smaller subset"}}return!1})}function kn(r){let t=Gn(r,"MESSAGELIMIT");r.registerCapability("MESSAGELIMIT="+t),_n(r,t);let e=o=>String(o.command||"").toUpperCase();r.rangeLimits.push((o,u,l)=>{let c=e(u);if(!ff.has(c)||u.partialFetch)return!1;let h=c==="UID EXPUNGE"?l.filter(T=>T[1].flags.indexOf("\\Deleted")>=0):l;if(h.length<=t)return!1;let m=new Set(h.slice(0,-t));return u.messageLimitUid=h[h.length-t][1].uid,u.highestFirst=!0,l.filter(T=>!m.has(T)).reverse()}),r.commandChecks.push((o,u)=>{let l=r.capabilities.PARTIAL&&u.attributes&&u.attributes[2],c=e(u);if(!Array.isArray(l)||c!=="FETCH"&&c!=="UID FETCH")return!1;let h=l.findIndex((T,A)=>!(A%2)&&T&&T.type==="ATOM"&&String(T.value).toUpperCase()==="PARTIAL"),m;try{m=h>=0&&Fe(l[h+1],!0)}catch{return!1}return m&&m.to-m.from+1>t?{command:"NO",code:["MESSAGELIMIT",t],text:c+" exceeds the limit of "+t+" messages"}:!1}),r.searchLimits.push((o,u,l)=>{let c=o._runningCommand&&o._runningCommand.parsed,h=c?e(c):"";if(u.length<=t||!hf.has(h)&&!Xo.has(h))return!1;let m=u.filter(T=>Go(l,T));if(m.length<=t)return!1;if(Xo.has(h)){let T=new Error(h+" exceeds the limit of "+t+" messages, narrow it down with UIDAFTER or UIDBEFORE");throw T.imapResponse="NO",T.responseCode=["MESSAGELIMIT",t],T}return c.messageLimitUid=m[m.length-t].uid,m.slice(-t)});let s=o=>{if(!Mt(o))throw Q("UIDAFTER and UIDBEFORE expect a UID");return Number(o)},n=(o,u,l,c)=>u.uid>c;n.argumentTypes=()=>[s];let i=(o,u,l,c)=>u.uid<c;i.argumentTypes=()=>[s],r.searchHandlers.UIDAFTER=n,r.searchHandlers.UIDBEFORE=i;let a=(o,u,l,c,h)=>{if(c&&c.messageLimitUid&&u.tag==="*"&&u.command==="SEARCH"&&Array.isArray(u.attributes)){let p=u.attributes.filter(Array.isArray);u.attributes=u.attributes.filter(f=>!Array.isArray(f)).reverse().concat(p);return}if(!c||!c.messageLimitUid||u.tag!==c.tag)return;let m=c.messageLimitUid;if(c.messageLimitUid=!1,u.command!=="OK")return;let T={type:"SECTION",section:[{type:"ATOM",value:"MESSAGELIMIT"},t,m]},A=u.attributes||[];if(A[0]&&A[0].type==="SECTION"){o.send({tag:"*",command:"NO",attributes:[T,{type:"TEXT",value:"Only the last "+t+" messages were processed"}]},"MESSAGELIMIT",c,h);return}u.attributes=[T].concat(A)};r.once("pluginsLoaded",()=>r.outputHandlers.push(a))}function Go(r,t){return r.args.every(e=>{switch(e.key){case"AND":return Go(e,t);case"_SEQ":case"UID":return e.set.has(t);case"UIDAFTER":return t.uid>e.args[0];case"UIDBEFORE":return t.uid<e.args[0];default:return!0}})}E();var df=64*1024,pf=100,mf=new Set(["/shared/admin"]),Ef="/private/specialuse";function Yr(r,t){if(typeof r!="string"||r.charAt(0)!=="/")return'Entry name must begin with "/"';if(/[^\x20-\x7f]/.test(r))return"Entry name must not contain non-ASCII or control characters";if(/[*%]/.test(r))return'Entry name must not contain "*" or "%"';if(r.indexOf("//")>=0)return'Entry name must not contain consecutive "/" characters';if(r.charAt(r.length-1)==="/")return'Entry name must not end with "/"';let e=r.toLowerCase().substr(1).split("/");return e[0]!=="private"&&e[0]!=="shared"?"Entry name must begin with /private or /shared":t&&e.length<2?"Entry name must have at least 2 components":t&&e[1]==="vendor"&&e.length<4?"Vendor entry names must have at least 4 components":!1}function gf(r,t){if(t==null)return null;if(t instanceof Uint8Array)t=I.Buffer.from(t).toString("binary");else if(typeof t=="string")/[Ā-]/.test(t)&&(t=I.Buffer.from(t,"utf-8").toString("binary"));else throw new Error("Invalid value for metadata entry "+r+", expecting a string");return t}function _o(r){return{type:"MAILBOX",value:r}}function jn(r,t){if(r.metadataState){t&&!r.metadataState.mailboxes&&(r.metadataState.mailboxes=!0,delete r.capabilities["METADATA-SERVER"],r.registerCapability("METADATA"),r.enableAvailable.splice(r.enableAvailable.indexOf("METADATA-SERVER"),1,"METADATA"));return}r.parserOptions.literal8=!0;let e=t?"METADATA":"METADATA-SERVER";r.registerCapability(e),Nt(r,e);let s=r.options,n=r.metadataState={mailboxes:t,maxSize:Number(s.metadataMaxSize)||df,maxEntries:Number(s.metadataMaxEntries)||pf,allowPrivate:s.metadataPrivate!==!1,server:{path:"",metadata:s.metadata}},i=new WeakSet,a=f=>{if(!f.metadata)return Object.create(null);if(i.has(f.metadata))return f.metadata;let d=Object.create(null),g=f.metadata;return Object.keys(g).forEach(b=>{let C=Yr(b,!0);if(C)throw new Error("Invalid metadata entry name "+JSON.stringify(b)+": "+C);let v=gf(b,g[b]);v!==null&&(d[b.toLowerCase()]=v)}),o(f,d)},o=(f,d)=>(i.add(d),f.metadata=d,d),u=f=>{let d=Object.create(null);if(f.path&&r.capabilities["SPECIAL-USE"]){let g=[].concat(f["special-use"]||[]);d[Ef]=g.length?g.join(" "):null}return d},l=f=>Et(f,n.mailboxes?"METADATA":"METADATA-SERVER"),c=(f,d,g,b)=>{if(b==="")return n.server;if(!n.mailboxes)return f.sendStatus(d,g,"NO","Mailbox annotations are not supported, only server annotations"),!1;let C=f.server.getMailbox(b);return!C||C.flags.indexOf("\\NonExistent")>=0?(f.sendStatus(d,g,"NO","Mailbox does not exist","NONEXISTENT"),!1):C},h=(f,d,g,b,C)=>(f.sendStatus(d,g,"BAD",b),C());r.setCommandHandler("GETMETADATA",(f,d,g,b)=>{let C=d.attributes||[],v=Array.isArray(C[0])?1:0,M=!1,x=0;if(C.length!==v+2||!at(C[v]))return h(f,d,g,"GETMETADATA expects options, a mailbox name and entries",b);if(v){let k=C[0];if(!k.length)return h(f,d,g,"Empty option list",b);for(let q=0;q<k.length;q+=2){let tt=k[q]&&k[q].type==="ATOM"?k[q].value.toUpperCase():!1,Z=k[q+1]&&k[q+1].type==="ATOM"?k[q+1].value:!1;if(tt==="MAXSIZE"){if(!mt(Z))return h(f,d,g,"Invalid value for MAXSIZE",b);M=Number(Z)}else if(tt==="DEPTH"){if(!Z||!/^(0|1|infinity)$/i.test(Z))return h(f,d,g,"Invalid value for DEPTH",b);x=Z.toLowerCase()==="infinity"?1/0:Number(Z)}else return h(f,d,g,"Unknown GETMETADATA option",b)}}let _;try{_=f.importMailboxName(C[v].value)}catch(k){return h(f,d,g,k.message,b)}let X=[].concat(C[v+1]);if(!X.length||!X.every(at))return h(f,d,g,"GETMETADATA expects an entry name or a list of entry names",b);for(let k of X){let q=Yr(k.value);if(q)return h(f,d,g,q,b)}let z=c(f,d,g,_);if(!z)return b();let N=Object.assign(Object.create(null),a(z),u(z)),D=x?Object.keys(N).filter(k=>N[k]!==null).sort():[],B=new Map;for(let k of X){let q=k.value.toLowerCase(),tt=N[q]??null;(!x||tt!==null)&&B.set(q,tt);let Z=q+"/";D.forEach(ut=>{ut.startsWith(Z)&&(x===1/0||ut.indexOf("/",Z.length)<0)&&B.set(ut,N[ut])})}let V=-1,G=[];return B.forEach((k,q)=>{if(M!==!1&&k!==null&&k.length>M){V=Math.max(V,k.length);return}G.push({type:"ATOM",value:q},k===null?null:{type:k.indexOf("\0")>=0?"LITERAL8":"STRING",value:k})}),G.length&&f.send({tag:"*",command:"METADATA",attributes:[_o(z.path),G]},"METADATA",d,g,z),f.sendStatus(d,g,"OK","GETMETADATA completed",V>=0&&["METADATA","LONGENTRIES",V]),b()},{states:J.AUTHENTICATED});let m=(f,d)=>{let g=r.activeConnection,b=a(f),C=u(f),v=Object.assign(Object.create(null),b),M=[];for(let[_,X]of d){if(!f.path&&g&&mf.has(_)||_ in C)return{text:"The "+_+" entry is read-only",code:"CANNOT"};if(!n.allowPrivate&&_.startsWith("/private/"))return{text:"Private annotations are not supported",code:["METADATA","NOPRIVATE"]};if(X!==null&&X.length>n.maxSize)return{text:"Value of "+_+" is too large",code:["METADATA","MAXSIZE",n.maxSize]};(b[_]??null)!==X&&M.push(_),X===null?delete v[_]:v[_]=X}let x=Object.keys(v).length;return x>n.maxEntries&&x>Object.keys(b).length?{text:"Too many annotations",code:["METADATA","TOOMANY"]}:(o(f,v),M.length&&r.notify({tag:"*",command:"METADATA",attributes:[_o(f.path)].concat(M.map(_=>({type:"ATOM",value:_})))},!1,g,l),null)};r.setCommandHandler("SETMETADATA",(f,d,g,b)=>{let C=d.attributes||[];if(C.length!==2||!at(C[0])||!Array.isArray(C[1]))return h(f,d,g,"SETMETADATA expects a mailbox name and a list of entries and values",b);let v=C[1];if(!v.length||v.length%2)return h(f,d,g,"SETMETADATA expects entry and value pairs",b);let M=new Map;for(let X=0;X<v.length;X+=2){if(!at(v[X]))return h(f,d,g,"Entry name must be a string",b);let z=Yr(v[X].value,!0);if(z)return h(f,d,g,z,b);let N=v[X+1];if(N!==null&&(!N||["STRING","LITERAL","LITERAL8"].indexOf(N.type)<0))return h(f,d,g,"Entry value must be a string, a literal, a literal8 or NIL",b);if(N&&N.type!=="LITERAL8"&&/\r(?!\n)|(?:^|[^\r])\n/.test(N.value))return h(f,d,g,"Line ends in a value must be CRLF",b);M.set(v[X].value.toLowerCase(),N?N.value:null)}let x=c(f,d,g,C[0].value);if(!x)return b();let _=m(x,M);return _?(f.sendStatus(d,g,"NO",_.text,_.code),b()):(f.sendStatus(d,g,"OK","SETMETADATA completed"),b())},{states:J.AUTHENTICATED,mailboxArguments:[0],literal8:!0}),r.on("mailbox",f=>{if(f.type==="rename"&&f.oldPath==="INBOX"){let d=r.getMailbox("INBOX"),g=r.getMailbox(f.path);d&&g&&g!==d&&d.metadata&&o(g,Object.assign(Object.create(null),a(d)))}else if(f.type==="delete"){let d=r.getMailbox(f.path);d&&d!==f.mailbox&&delete d.metadata}}),r.on("reset",()=>{n.server={path:"",metadata:s.metadata}});let T=f=>{if(f==="")return n.server;if(!n.mailboxes)throw K("Mailbox annotations need the METADATA plugin, METADATA-SERVER has server annotations only","INVALID");return r.control.requireMailbox(f)},A=f=>{let d=a(T(f)),g={};return Object.keys(d).forEach(b=>{g[b]=I.Buffer.from(d[b],"binary").toString("utf-8")}),g},p=(f,d)=>{let g=T(f);if(!d||typeof d!="object"||Array.isArray(d))throw K("setMetadata expects an object of entry names and values (null removes an entry)","INVALID");let b=new Map;Object.keys(d).forEach(v=>{let M=d[v],x=Yr(v,!0);if(x)throw K(x,"INVALID");if(M!==null&&typeof M!="string")throw K("Value of "+v+" must be a string or null","INVALID");b.set(v.toLowerCase(),M===null?null:I.Buffer.from(M,"utf-8").toString("binary"))});let C=m(g,b);if(C)throw K(C.text,typeof C.code=="string"?C.code:"INVALID");return A(f)};r.control.register("getMetadata",A,[{method:"GET",path:"/v1/metadata",summary:"Server annotations (METADATA plugins)",handler:()=>r.control.getMetadata("")},{method:"GET",path:"/v1/mailboxes/{path}/metadata",summary:"Mailbox annotations (METADATA plugin)",handler:({params:f})=>r.control.getMetadata(f.path)}]),r.control.register("setMetadata",p,[{method:"PUT",path:"/v1/metadata",summary:'Sets server annotations ({ "/shared/comment": "text" }, null removes one, METADATA plugins)',handler:({body:f})=>r.control.setMetadata("",f)},{method:"PUT",path:"/v1/mailboxes/{path}/metadata",summary:"Sets mailbox annotations (METADATA plugin)",handler:({params:f,body:d})=>r.control.setMetadata(f.path,d)}])}function Kr(r){jn(r,!0)}Kr.requires=["ENABLE"];E();function zr(r){jn(r,!1)}zr.requires=["ENABLE"];E();E();function Vn(r,t,e,s){return qn(r,t,e,s,!1)}function qn(r,t,e,s,n){let i=n?"UID COPY":"COPY";if(!t.attributes||t.attributes.length!==2||!t.attributes[0]||["ATOM","SEQUENCE"].indexOf(t.attributes[0].type)<0||!t.attributes[1]||["ATOM","STRING","LITERAL"].indexOf(t.attributes[1].type)<0)return r.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:i+" expects sequence set and a mailbox name"}]},"INVALID COMMAND",t,e),s();let a=Qn(r,t,e,n,i+" FAIL");if(!a)return s();r.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:i+" Completed"}]},i,t,e,a),s()}function Qn(r,t,e,s,n,i){let a=t.attributes,o=r.limitRange(t,r.getCommandRange(a[0].value,s)),u=r.getTargetMailbox(a[1].value,t,e,n);if(!u)return!1;let l=o.map(m=>m[1]);if(l.some(m=>m.ghost))return r.sendStatus(t,e,"NO","Some of the requested messages no longer exist","EXPUNGEISSUED",n),!1;if(!r.checkAppend(u,l,t,e,n,{move:!!i,source:r.selectedMailbox}))return!1;let c=[],h=[];return(t.highestFirst?l.slice().reverse():l).forEach(m=>{c.push(m.uid),h.push(r.server.copyMessage(u,m).message.uid)}),{mailbox:u,sourceUids:c,targetUids:h,messages:l}}function Yn(r){r.registerCapability("MOVE");let t=function(s,n,i,a,o){function u(c){return s?"UID "+c:c}if(!i.attributes||i.attributes.length!==2||!i.attributes[0]||["ATOM","SEQUENCE"].indexOf(i.attributes[0].type)<0||!i.attributes[1]||["ATOM","STRING","LITERAL"].indexOf(i.attributes[1].type)<0)return n.send({tag:i.tag,command:"BAD",attributes:[{type:"TEXT",value:u("MOVE expects sequence set and a mailbox name")}]},"INVALID COMMAND",i,a),o();if(n.refuseReadOnly(i,a,u("MOVE FAIL")))return o();let l=Qn(n,i,a,s,u("MOVE FAIL"),!0);if(!l)return o();n.send({tag:"*",command:"OK",attributes:[{type:"TEXT",value:"Copied"}],skipResponse:!0},u("MOVE COPYUID"),i,a,l),n.expungeSpecificMessages(n.selectedMailbox,l.messages,!1,!0,!!i.highestFirst),n.send({tag:i.tag,command:"OK",attributes:[{type:"TEXT",value:"Done"}]},u("MOVE OK"),i,a),o()},e={states:J.SELECTED,mailboxArguments:[1]};r.setCommandHandler("MOVE",t.bind(null,!1),Object.assign({sequenceSet:0},e)),r.setCommandHandler("UID MOVE",t.bind(null,!0),e)}E();function Kn(r){r.registerCapability("MULTIAPPEND"),r.multiAppend=!0,r.appendChecks.push((t,e,s,n)=>n.command&&s.some(i=>!i.resolve&&!i.raw.length)?{text:"Zero-length message literal, APPEND cancelled"}:!1)}E();var ko={SELECTED:!1,INBOXES:!1,PERSONAL:!1,SUBSCRIBED:!1,SUBTREE:!0,"SUBTREE-ONE":!0,MAILBOXES:!0};function Af(r,t){if(!Array.isArray(t)||!t.length)throw Q("IN expects a parenthesized list of mailbox specifiers");let e=[];for(let s=0;s<t.length;s++){let n=t[s];if(Array.isArray(n))throw Q("Unknown ESEARCH scope option");let i=n&&n.type==="ATOM"?String(n.value).toUpperCase():"";if(!Object.hasOwn(ko,i))throw Q("Invalid mailbox specifier"+(i?" "+n.value:""));let a={filter:i,names:[]};if(ko[i]){let o=t[++s],u=Array.isArray(o)?o:[o];if(!u.length||!u.every(at))throw Q(i.toLowerCase()+" expects a mailbox name or a list of mailbox names");u.forEach(l=>a.names.push(r.importMailboxName(l.value)))}e.push(a)}return e}function Tf(r,t){let e=t||[];return $(e[0],"IN")?{sources:Af(r,e[1]),attributes:e.slice(2)}:{sources:null,attributes:e}}function zn(r){yt(r),r.registerCapability("MULTISEARCH");let t=a=>!!a&&a.flags.indexOf("\\Noselect")<0,e=()=>Object.keys(r.folderCache).map(o=>r.folderCache[o]).sort((o,u)=>o.path==="INBOX"?-1:u.path==="INBOX"?1:0),s=(a,o,u)=>{if(!u(a)||!o||!a.folders)return;let l=a.folders;Object.keys(l).forEach(c=>s(l[c],o-1,u))},n=(a,o)=>{let u=[],l=new Set,c=(h,m)=>{!h||l.has(h)||!t(h)||r.searchAccessChecks.every(T=>T(a,h,!!m))&&(l.add(h),u.push(h))};return o.forEach(h=>{switch(h.filter){case"SELECTED":c(a.selectedMailbox,!0);break;case"INBOXES":c(r.getMailbox("INBOX"),!1);break;case"PERSONAL":e().filter(m=>r.isPersonal(m)).forEach(m=>c(m,!1));break;case"SUBSCRIBED":e().filter(m=>m.subscribed).forEach(m=>c(m,!1));break;case"MAILBOXES":h.names.forEach(m=>c(r.getMailbox(m),!0));break;default:{let m=h.filter==="SUBTREE"?1/0:1,T=new Set;h.names.forEach(A=>{let p=r.getMailbox(A);p&&s(p,m,f=>T.has(f)?!1:(T.add(f),c(f,f===p),!0))})}}}),u},i=(a,o,u,l)=>{let c=(b,C)=>(a.sendStatus(o,u,b,C,!1,"ESEARCH FAILED"),l()),h,m=new Map,T;try{let b=Tf(a,o.attributes);h=b.sources||[{filter:"SELECTED",names:[]}];let C=b.attributes;if($(C[0],"RETURN")&&(m=o.searchReturn=r.parseSearchReturn(C[1],a,o),C=C.slice(2)),!C.length)throw Q("ESEARCH expects search criteria");T=ge(C)}catch(b){return c("BAD",b.message)}let A=h.every(b=>b.filter==="SELECTED");if(h.some(b=>b.filter==="SELECTED")&&!a.selectedMailbox)return c("BAD","No mailbox is selected");if(m.has("SAVE")&&!A)return c("BAD","SAVE can only be used when searching the selected mailbox");if(m.has("UPDATE")&&!a.selectedMailbox)return c("BAD","UPDATE needs a selected mailbox");let p=n(a,h),f=[];try{let b=C=>{if(C&&C===a.selectedMailbox)return wt(a,a.getSessionMessages(),T);let v=C?C.messages:[];return wt(a,v,T,(M,x)=>r.getMessageRange(v,M,x))};p.length||b(a.selectedMailbox||null),p.forEach(C=>f.push({mailbox:C,result:b(C)}))}catch(b){return Ae(a,o,u,b,"ESEARCH FAILED"),l()}let d=r.isSilentReturn(m);f.forEach(({mailbox:b,result:C})=>{!C.list.length||d||a.send(Te(o.tag,!0,C,m,b),"ESEARCH",o,u,Object.assign({},C,{list:Xt(C.list,m)}))});let g=f.find(b=>b.mailbox===a.selectedMailbox);return m.has("SAVE")&&(o.searchresFound=g?Xt(g.result.list,m):[]),m.has("UPDATE")&&g&&r.addSearchContext(a,o,u,g.result,!0,g.mailbox),a.sendStatus(o,u,"OK","ESEARCH completed",!1,"ESEARCH"),l()};r.setCommandHandler("ESEARCH",i,{states:J.AUTHENTICATED,searchCriteria:0}),r.connectionHandlers.push(a=>{let o=a.usesSequenceNumbers;a.usesSequenceNumbers=function(u){return(u.command||"").toUpperCase()==="ESEARCH"&&$((u.attributes||[])[0],"IN")&&(u=Object.assign({},u,{attributes:u.attributes.slice(2)})),o.call(this,u)}})}E();function Wn(r){r.registerCapability("NAMESPACE"),r.setCommandHandler("NAMESPACE",(t,e,s,n)=>{let i={personal:[],user:[],shared:[]};return Object.keys(r.storage).forEach(a=>{let o=r.storage[a];a==="INBOX"||!o||Object.hasOwn(i,o.type)&&i[o.type].push([t.exportMailboxName(a),o.separator])}),t.send({tag:"*",command:"NAMESPACE",attributes:[i.personal.length?i.personal:null,i.user.length?i.user:null,i.shared.length?i.shared:null]},"NAMESPACE",e,s,i),t.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"Completed"}]},"NAMESPACE",e,s,i),n()},{states:J.AUTHENTICATED,noArguments:!0})}E();var Wr=["MessageNew","MessageExpunge","FlagChange","AnnotationChange"],yf=new Map(Wr.concat(["MailboxName","SubscriptionChange","MailboxMetadataChange","ServerMetadataChange"]).map(r=>[r.toUpperCase(),r])),Sf=["SELECTED","SELECTED-DELAYED"],bf=["INBOXES","PERSONAL","SUBSCRIBED","SUBTREE","MAILBOXES"],If=["BODY","BODY.PEEK","BINARY","BINARY.PEEK","BINARY.SIZE"];function $n(r){r.registerCapability("NOTIFY");let t=N=>!!N.notifyState,e=()=>{let N=["MessageNew","MessageExpunge","FlagChange","MailboxName","SubscriptionChange"];return r.capabilities.METADATA&&N.push("MailboxMetadataChange"),(r.capabilities.METADATA||r.capabilities["METADATA-SERVER"])&&N.push("ServerMetadataChange"),N},s=(N,D,B,V)=>{let G=r.acl&&r.acl.getRights(N,D,V);return!G||[...B].every(k=>G.has(k))},n=(N,D,B)=>s(N,D,"l",B),i=(N,D,B)=>s(N,D,"lr",B),a=N=>N.toUpperCase()==="INBOX"?"INBOX":N,o=(N,D,B,V)=>{switch(N.filter){case"INBOXES":case"PERSONAL":return r.isPersonal(D);case"SUBSCRIBED":return!!V||!!(B&&B.subscribed);case"SUBTREE":return N.paths.indexOf(D)>=0||N.prefixes.some(G=>D.substr(0,G.length)===G);case"MAILBOXES":return N.paths.indexOf(D)>=0}return!1},u=(N,D,B,V)=>{let G=new Set;return N.notifyState.groups.forEach(k=>{o(k,D,B,V)&&k.events.forEach(q=>G.add(q))}),B&&B===N.selectedMailbox&&Wr.forEach(k=>G.delete(k)),G},l=N=>!!(N.notifyState.selected&&N.notifyState.selected.delayed)&&!N.directNotifications&&N.hasPendingExpunge(),c=N=>{!N.socket||!N.notificationQueue.length||N._runningCommand||!t(N)||l(N)||N.processNotifications()},h=N=>{N.notifyFlushPending||(N.notifyFlushPending=!0,L(()=>{N.notifyFlushPending=!1,c(N)}))},m=(N,D)=>{let B=D;if(B.tag="*",B.notification=!0,!N._runningCommand&&l(N)){N.send(B,"NOTIFY EVENT");return}N.notificationQueue.push(B),h(N)},T=N=>[...r.connections].filter(D=>D!==N&&t(D)),A=(N,D,B,V)=>{if(B=B.slice(),V.has("FlagChange")){let G=r.getStatus(D),k=G&&G.unseen||0;N.notifyState.unseen.get(D)!==k&&(N.notifyState.unseen.set(D,k),B.push("UNSEEN"))}return r.condstore&&r.condstore.isEnabled(N)&&B.push("HIGHESTMODSEQ"),B.length?Qr(N,D.path,D,B):!1},p=(N,D,B,V)=>{T(V).forEach(G=>{if(N===G.selectedMailbox||!i(G,N))return;let k=u(G,N.path,N);if(!k.has(D))return;let q=A(G,N,D==="FlagChange"&&r.condstore&&r.condstore.isEnabled(G)?["UIDVALIDITY"]:B,k);q&&m(G,q)})},f=(N,D)=>r.hasDescendant(D,B=>n(N,B)&&B.flags.indexOf("\\NonExistent")<0),d=(N,D,B)=>{B=B||{};let V=r.getMailbox(D),G=B.exists!==!1&&!!V&&n(N,V),q=[r.listAttributes(G?V:null,{exists:G,subscribed:G&&V.subscribed,extra:B.noAccess?["\\NoAccess"]:[],hasChildren:f(N,D)}).map(tt=>({type:"ATOM",value:tt})),r.getSeparator(D),{type:"MAILBOX",value:D}];return B.oldPath&&q.push([{type:"STRING",value:"OLDNAME"},[{type:"STRING",value:N.exportMailboxName(B.oldPath)}]]),{tag:"*",command:"LIST",attributes:q}},g=(N,D,B,V)=>{[D,r.getParentPath(D)].forEach(G=>{if(!G)return;let k=G===D?B:r.getMailbox(G);u(N,G,k).has("MailboxName")&&m(N,d(N,G,G===D?{exists:V}:{}))})},b=(N,D)=>{D!==N.selectedMailbox&&i(N,D)&&u(N,D.path,D).has("FlagChange")&&m(N,A(N,D,["MESSAGES","UIDNEXT","UIDVALIDITY"],new Set(["FlagChange"])))};r.on("mailbox",N=>{let D=r.getMailbox(N.path);T(N.origin).forEach(B=>{switch(N.type){case"create":D&&n(B,D)&&(g(B,N.path,D,!0),b(B,D));break;case"delete":N.mailbox&&n(B,N.mailbox)&&g(B,N.path,D,!!D);break;case"rename":if(D&&n(B,D)){let V=u(B,N.path,D);u(B,N.oldPath).forEach(G=>V.add(G)),V.has("MailboxName")&&m(B,d(B,N.path,{oldPath:N.oldPath})),b(B,D)}break;case"subscribe":case"unsubscribe":D&&n(B,D)&&u(B,N.path,D,!0).has("SubscriptionChange")&&m(B,d(B,N.path));break}})}),r.on("acl",(N,D)=>{T(null).forEach(B=>{let V={list:n(B,N,D),read:i(B,N,D)},G={list:n(B,N),read:i(B,N)};if(V.list!==G.list)g(B,N.path,N,G.list);else if(G.list&&V.read!==G.read){let k=u(B,N.path,N);Wr.some(q=>k.has(q))&&m(B,d(B,N.path,{noAccess:!G.read}))}})}),r.on("expunge",(N,D,B)=>p(N,"MessageExpunge",["MESSAGES","UIDNEXT"],B)),r.on("notify",N=>{let D=N.command||{},B=typeof N.mailbox=="string"?r.getMailbox(N.mailbox):N.mailbox;if(B&&D.flagUpdate)p(B,"FlagChange",[],N.origin);else if(B&&D.message&&$(D.attributes&&D.attributes[1],"EXISTS"))p(B,"MessageNew",["MESSAGES","UIDNEXT"],N.origin);else if(D.command==="METADATA"&&D.attributes&&D.attributes[0]){let V=D.attributes[0].value,G=V===""?null:r.getMailbox(V);T(N.origin).forEach(k=>{let q;V===""?q=k.notifyState.groups.some(tt=>tt.events.has("ServerMetadataChange")):q=!!G&&i(k,G)&&u(k,V,G).has("MailboxMetadataChange"),q&&(N.notifyHandled=N.notifyHandled||new Set,N.notifyHandled.add(k),m(k,Object.assign({},D)))})}}),r.notifyFilters.push((N,D)=>!(D.notifyHandled&&D.notifyHandled.has(N)));let C=N=>{if(N.flagUpdate)return"FlagChange";let D=N.attributes&&N.attributes[1];return $(D,"EXPUNGE")?"MessageExpunge":$(D,"EXISTS")?N.message?"MessageNew":"MessageExpunge":!1},v=(N,D,B,V)=>{let G=D.map(q=>Object.assign({},q)),k;try{k=xr(N,V,G)}catch{return!1}return{tag:"*",notification:!0,attributes:[B,{type:"ATOM",value:"FETCH"},k],fetchedMessage:V}};r.connectionHandlers.push(N=>{N.notifyState=null;let D=N.queueNotification;N.queueNotification=function(B,V){let G=V&&V.mailbox&&C(B);if(!t(this)||!G||V.origin===this)return D.call(this,B,V);let k=this.notifyState.selected;if(!(!k||!k.events.has(G)||!i(this,this.selectedMailbox))){if(this.notificationQueue.push(B),G==="MessageNew"&&k.fetch){let q=v(this,k.fetch,B.attributes[0],B.message);q&&this.notificationQueue.push(q)}h(this)}}}),r.resetHandlers.push(N=>{N.notifyState=null}),r.outputHandlers.push((N,D)=>{D.tag!=="*"&&!D.notification&&t(N)&&N.notificationQueue.length&&h(N)}),r.notifyOverflow=N=>{T(null).filter(D=>!N||D===N).forEach(D=>{D.notifyState={selected:null,groups:[],unseen:new WeakMap},m(D,{command:"OK",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"NOTIFICATIONOVERFLOW"}]},{type:"TEXT",value:"Too many notifications, NOTIFY is turned off"}]})})};let M=(N,D)=>{if(!D.length)throw Q("MessageNew expects a list of fetch attributes");return D.map(B=>{let V=$(B)&&B.value.toUpperCase();if(!V||!(r.fetchHandlers[V]||At[V]))throw Q("Invalid fetch attribute for MessageNew");if((B.section||B.partial)&&If.indexOf(V)>=0){let G=[Object.assign({},B)];try{xr(N,{raw:`Subject: test\r
|
|
24
|
+
`}}}function Us(s,e){if(!e)return s;if(e.length!==2||!(e[1]>0))throw new Error("Invalid partial range, expecting <start.length>");return s.substr(e[0],e[1])}pe.BODY=function(s,e,t){let r=ne(e);if(!t.section){if(t.partial)throw new Error("BODY without a section does not take a partial range");return bn(r.tree,{body:!0,upperCaseKeys:!0,messageGlobal:s.messageGlobal})}return{type:"LITERAL",value:Us(pf(r,t,s.messageGlobal),t.partial)}};pe.INTERNALDATE=function(s,e){return e.internaldate};pe.RFC822=function(s,e){return{type:"LITERAL",value:ne(e).raw}};pe.RFC822.setsSeen=!0;pe["RFC822.SIZE"]=function(s,e){return ne(e).raw.length};pe["RFC822.HEADER"]=function(s,e){return{type:"LITERAL",value:Ds(ne(e).tree)}};pe["RFC822.TEXT"]=function(s,e){return{type:"LITERAL",value:Be(ne(e).tree,!0)}};pe["RFC822.TEXT"].setsSeen=!0;var mf=/^[1-9]\d*(?:\.[1-9]\d*)*$/,Tn=new WeakMap;function _a(s){let e=new Error(s);return e.imapResponse="NO",e.code="UNKNOWN-CTE",e}function Ga(s){let e=s.parsedHeader["content-type"];return(e&&e.value||"").toLowerCase()}function Xa(s){return(s.parsedHeader["content-transfer-encoding"]||"7bit").toString().trim().toLowerCase()}function ja(s,e){let t=Ga(s);return!s.boundary&&!/^multipart\//.test(t)&&t!=="message/rfc822"&&(!e||t!=="message/global")}function gf(s){let e=s.replace(/[^A-Za-z0-9+/=]/g,"").split("=")[0];return e.length%4===1&&(e=e.slice(0,-1)),b.Buffer.from(e,"base64").toString("binary")}function Ef(s){return s.replace(/[ \t]+(?=\r\n|$)/g,"").replace(/=(?:\r\n|$)/g,"").replace(/=([0-9A-Fa-f]{2})/g,(e,t)=>String.fromCharCode(parseInt(t,16)))}function Va(s,e,t){let r=t.value.toUpperCase(),n=t.section;if(!n)throw new Error(r+" requires a section");if(!n.length)throw new Error(r+"[] is not allowed, BINARY applies to leaf body parts only (RFC 9051 section 6.4.5)");if(n.length!==1||n[0].type!=="ATOM"||!mf.test(n[0].value))throw new Error("Invalid "+r+" section, expecting a part number (RFC 3516 section 7)");let i=bt(ne(e).tree,n[0].value,s.messageGlobal);if(!i)return"";if(!ja(i,s.messageGlobal))throw new Error(r+"["+n[0].value+"] is not a leaf body part (RFC 9051 section 6.4.5)");return Tn.has(i)||Tn.set(i,Af(i)),Tn.get(i)}function Af(s){let e=Be(s,!0),t=Xa(s),r;if(Ls.includes(t))r=e;else if(t==="base64")r=gf(e);else if(t==="quoted-printable")r=Ef(e);else throw _a("Unknown Content-Transfer-Encoding "+JSON.stringify(t).replace(/[^\x20-\x7e]/g,"?"));return/^text\//.test(Ga(s))?_t(r):r}function Sn(s,e,t){let r=Us(Va(s,e,t),t.partial);return{type:r.indexOf("\0")>=0?"LITERAL8":"LITERAL",value:r}}Sn.setsSeen=!0;function yf(s,e,t){if(t.partial)throw new Error("BINARY.SIZE does not take a partial range");return Va(s,e,t).length}function bf(s){let e=Gt(s),t=n=>{if(n.childNodes)return n.childNodes.map(t).includes(!0);let i=at(n,!0);if(i)return t(i)?(n.body=Be(i),!0):!1;let o=Xa(n);return!ja(n,!0)||!n.body||!(o==="binary"||Ls.includes(o)&&n.body.indexOf("\0")>=0)?!1:(n.body=b.Buffer.from(n.body,"binary").toString("base64").match(/.{1,76}/g).join(`\r
|
|
25
|
+
`),n.header=n.header.filter(a=>!/^content-transfer-encoding\s*:/i.test(a)).concat("Content-Transfer-Encoding: base64"),!0)},r=t(e)?Be(e):s;if(r.indexOf("\0")>=0)throw _a("NUL octets are only allowed in the body of a part with the binary, 7bit or 8bit encoding");return r}function In(s){s.registerCapability("BINARY"),s.parserOptions.literal8=!0,s.parserOptions.allowSection.push("BINARY","BINARY.PEEK","BINARY.SIZE"),s.fetchHandlers.BINARY=Sn,s.fetchHandlers["BINARY.PEEK"]=(e,t,r)=>Sn(e,t,r),s.fetchHandlers["BINARY.SIZE"]=yf,s.appendLiteral8=e=>{try{return bf(e)}catch(t){throw nt(t.message,t.code)}}}g();g();var Tf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+,";function qa(s){if(typeof s!="string")return"Invalid mailbox name";let e=0;for(;e<s.length;){let t=s.charCodeAt(e);if(t<32||t>126)return"Mailbox name must use modified UTF-7 for non-ASCII characters (RFC 3501 section 5.1.3)";if(s.charAt(e)!=="&"){e++;continue}if(s.charAt(e+1)==="-"){e+=2;continue}let r=s.indexOf("-",e+1);if(r<0)return'Modified BASE64 in mailbox name must end with "-" (RFC 3501 section 5.1.3)';let n=Sf(s.slice(e+1,r));if(n)return n;if(s.charAt(r+1)==="&"&&s.charAt(r+2)!=="-")return"Mailbox name contains a superfluous shift (RFC 3501 section 5.1.3)";e=r+1}return!1}function Sf(s){let e=0,t=0,r=[];for(let n=0;n<s.length;n++){let i=Tf.indexOf(s.charAt(n));if(i<0)return"Invalid modified BASE64 in mailbox name (RFC 3501 section 5.1.3)";e=e<<6|i,t+=6,t>=16&&(t-=16,r.push(e>>t&65535),e&=(1<<t)-1)}if(!r.length||t>=6||e!==0)return"Invalid modified BASE64 in mailbox name (RFC 3501 section 5.1.3)";for(let n=0;n<r.length;n++){let i=r[n];if(i>=32&&i<=126)return"Modified BASE64 must not encode printable US-ASCII (RFC 3501 section 5.1.3)";if(i>=55296&&i<=56319){if(!(r[n+1]>=56320&&r[n+1]<=57343))return"Invalid UTF-16 in mailbox name";n++}else if(i>=56320&&i<=57343)return"Invalid UTF-16 in mailbox name"}return!1}function vs(s){return s.replace(/&|[^\x20-\x7e]+/g,e=>e==="&"?"&-":"&"+b.Buffer.from(e,"utf16le").swap16().toString("base64").replace(/=+$/,"").replace(/\//g,",")+"-")}function On(s){return qa(s)?!1:s.replace(/&([^-]*)-/g,(e,t)=>t?b.Buffer.from(t.replace(/,/g,"/"),"base64").swap16().toString("utf16le"):"&")}var Tt=qa;function xn(s){s.registerCapability("CATENATE"),s.registerCapability("URL-PARTIAL"),s.appendDataHandlers.CATENATE=(e,t)=>{if(!Array.isArray(t)||!t.length||t.length%2)throw _e("CATENATE expects a list of TEXT literals and URLs");let r=[];for(let n=0;n<t.length;n+=2){let i=t[n]&&t[n].type==="ATOM"?String(t[n].value).toUpperCase():"",o=t[n+1];if(i==="TEXT"&&o&&o.type==="LITERAL")r.push({text:o.value});else if(i==="URL"&&o&&["ATOM","STRING","LITERAL"].indexOf(o.type)>=0)r.push({url:o.value});else throw _e("Invalid CATENATE part "+(n/2+1))}return()=>{let n=e.getMaxLiteralSize(),i="";for(let o of r)if(i+="text"in o?o.text:wf(e,o.url),i.length>n)throw nt("Catenated message is too large","TOOBIG");return i}}}var If=/^[A-Za-z0-9\-._~!$'()*+,&=:@/;%]*$/,Of=/^\/([^;]+?)(?:;UIDVALIDITY=([^/;]*))?\/;UID=([^/;]*)(?:\/;SECTION=([^/;]*))?(?:\/;PARTIAL=([^/;]*))?$/i;function Se(s,e){if(!s)return nt(e);let t=s.replace(/[^\x20-\x5c\x5e-\x7e]/g,r=>"%"+r.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0"));return nt(e,"BADURL",[{type:"TEXT",value:t}])}function xf(s){let e=s.split("/").slice(1),t=[];return e.forEach((r,n)=>{let i=n===e.length-1;if(r==="."||r===".."){r===".."&&t.pop(),i&&t.push("");return}t.push(r)}),"/"+t.join("/")}function Qa(s){return s.replace(/%([0-9a-f]{2})/gi,(e,t)=>String.fromCharCode(parseInt(t,16)))}function Cf(s,e,t){if(!t||!/^[\x20-\x7e]+$/.test(t))return!1;let r;try{let o=st.parser("X FETCH 1 BODY.PEEK["+t+"]");r=o.attributes.length===2&&!o.attributes[1].partial&&o.attributes[1]}catch{return!1}if(!r||!r.section||!r.section.length||r.section[0].type!=="ATOM")return!1;let n=String(r.section[0].value).toUpperCase(),i=(n.match(/^[1-9]\d*(?:\.[1-9]\d*)*/)||[""])[0];if(i){let o=bt(ne(e).tree,i),a=n.substr(i.length+1);if(!o||a&&a!=="MIME"&&!o.message)return!1}try{return Te.BODY(s,e,{section:r.section}).value}catch{return!1}}function wf(s,e){if(!e)throw Se(e,"Empty URL does not refer to a message");if(/^[a-z][a-z0-9+.-]*:/i.test(e)||e.substr(0,2)==="//")throw Se(e,"Only absolute-path URLs of this server are supported, e.g. /INBOX/;UID=1");if(e.charAt(0)!=="/")throw Se(e,"Relative-path URLs are not allowed (RFC 5092 section 7.2)");if(!If.test(e)||/%(?![0-9a-f]{2})/i.test(e))throw Se(e,"Invalid characters in URL");let t=xf(e).match(Of);if(!t)throw Se(e,"URL does not refer to a message or a message part");let[,r,n,i,o,a]=t;if(n!==void 0&&!Le(n)||!Le(i))throw Se(e,"Invalid UIDVALIDITY or UID in URL");let u;try{u=new TextDecoder("utf-8",{fatal:!0}).decode(b.Buffer.from(Qa(r),"binary"))}catch{throw Se(e,"Mailbox name in URL is not valid UTF-8")}let l=s.server.getMailbox(vs(u));if(!l||l.flags.indexOf("\\Noselect")>=0)throw Se(e,"Mailbox does not exist");for(let p of s.server.urlAccessChecks){let y=p(s,l,e);if(y)throw Se(e,y.text||"Permission denied")}if(n!==void 0&&Number(n)!==l.uidvalidity)throw Se(e,"UIDVALIDITY does not match");let c=l.messages.find(p=>p.uid===Number(i));if(!c)throw Se(e,"Message does not exist");let f=c.raw;if(o!==void 0&&(f=Cf(s,c,Qa(o)),f===!1))throw Se(e,"Invalid section or the message part does not exist");if(a!==void 0){let p=a.match(/^(\d+)(?:\.(\d+))?$/);if(!p||!Ae(p[1])||p[2]!==void 0&&!Le(p[2]))throw Se(e,"Invalid partial range");f=f.substr(Number(p[1]),p[2]?Number(p[2]):void 0)}return f}g();function Cn(){throw new Error("The COMPRESS plugin is not available in the browser")}g();g();var jt={ALL:["FLAGS","INTERNALDATE","RFC822.SIZE","ENVELOPE"],FAST:["FLAGS","INTERNALDATE","RFC822.SIZE"],FULL:["FLAGS","INTERNALDATE","RFC822.SIZE","ENVELOPE","BODY"]};function Ya(s){return s.map(e=>{let t=Object.assign({},e,{value:e.value.replace(/\.PEEK\b/i,"")});return t.partial&&(t.partial=t.partial.slice(0,1)),t})}function Ka(s,e){return e.map((t,r)=>{let n=(t.value||"").toUpperCase(),i=s.server.fetchHandlers[n]||Te[n];if(!i)throw new Error("Invalid FETCH argument "+(n||"#"+(r+1)));return i})}function Bs(s,e,t,r,n){let i=r||Ka(s,t),o=n||Ya(t),a=[];return t.forEach((u,l)=>a.push(o[l],i[l](s,e,u))),a}function wn(s,e,t,r,n){let i=s?"UID FETCH":"FETCH";if(!t.attributes||t.attributes.length!==2||!t.attributes[0]||["ATOM","SEQUENCE"].indexOf(t.attributes[0].type)<0||!t.attributes[1]||["ATOM"].indexOf(t.attributes[1].type)<0&&!Array.isArray(t.attributes[1]))return e.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:i+" expects sequence set and message item names"}]},"INVALID COMMAND",t,r),n();let o=e.limitRange(t,e.getCommandRange(t.attributes[0].value,s)),a=[].concat(t.attributes[1]||[]);t.attributes[1].type==="ATOM"&&Object.prototype.hasOwnProperty.call(jt,t.attributes[1].value.toUpperCase())&&(a=jt[t.attributes[1].value.toUpperCase()].slice());let u=[],l=[],c=[];try{let f=!1,p=!1,y=!1;a.forEach((h,d)=>{if(!h||typeof h!="string"&&h.type!=="ATOM")throw new Error("Invalid FETCH argument #"+(d+1));typeof h=="string"&&(h=a[d]={type:"ATOM",value:h});let E=h.value.toUpperCase();E==="FLAGS"&&(p=!0),E==="UID"&&(f=!0);let I=e.server.fetchHandlers[E]||Te[E];e.canSetSeen()&&(E==="BODY"&&h.section||I&&I.setsSeen)&&(y=!0)}),y&&!p&&a.push({type:"ATOM",value:"FLAGS"}),s&&!f&&a.push({type:"ATOM",value:"UID"});let A=Ka(e,a),m=Ya(a);o.forEach(h=>{for(let E=0,I=e.server.fetchFilters.length;E<I;E++)if(!e.server.fetchFilters[E](e,h[1],t,h[0]))return;y&&h[1].flags.indexOf("\\Seen")<0&&(h[1].flags.push("\\Seen"),u.push(h[1]));let d=Bs(e,h[1],a,A,m);c.push(h[1]),l.push({tag:"*",attributes:[h[0],{type:"ATOM",value:"FETCH"},d]})})}catch(f){let p=f;return u.forEach(y=>e.server.removeFlag(y.flags,"\\Seen")),e.sendStatus(t,r,p.imapResponse==="NO"?"NO":"BAD",p.message,p.code,i+" FAILED"),n()}return l.forEach((f,p)=>e.send(f,i,t,r,c[p])),e.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:i+" Completed"}]},i,t,r),e.notifyFlagChanges(u),n()}var Nf=(s,e,t,r)=>wn(!1,s,e,t,r),za=Nf;g();g();var St=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function ze(s){let e=String(s||"").toLowerCase();return St.findIndex(t=>t.toLowerCase()===e)}function It(s,e,t){return s=Number(s),t=Number(t),e<0||e>11||!Number.isInteger(s)||s<1?!1:s<=new Date(Date.UTC(t,e+1,0)).getUTCDate()}function Hs(s,e,t){return It(s,e,t)?String(t).padStart(4,"0")+"-"+String(e+1).padStart(2,"0")+"-"+String(s).padStart(2,"0"):!1}function ks(s){if(!s||typeof s!="string")return!1;let e=s.match(/^( \d|\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{4}) (\d{2}):(\d{2}):(\d{2}) [-+](\d{2})(\d{2})$/i);return e?It(e[1],ze(e[2]),e[3])&&Number(e[4])<24&&Number(e[5])<60&&Number(e[6])<61&&Number(e[8])<60:!1}function Ps(s){let e=String(s||"").match(/^\s*(\d{1,2})-([A-Za-z]{3})-(\d{4})(?: (\d{2}):(\d{2}):(\d{2}) ([+-]\d{4}))?/);if(!e||!It(e[1],ze(e[2]),e[3]))return null;let t=e[4]===void 0?{}:{hours:Number(e[4]),minutes:Number(e[5]),seconds:Number(e[6]),zone:e[7]};return Object.assign({day:Number(e[1]),month:ze(e[2]),year:Number(e[3])},t)}function Fs(s){let e=(s||"").toString().replace(/\([^()]*\)/g," ").match(/^\s*(?:[A-Za-z]+\s*,)?\s*(\d{1,2})\s+([A-Za-z]{3})\s+(\d{2,4})(?:\s+(\d{1,2})\s*:\s*(\d{2})(?:\s*:\s*(\d{2}))?(?:\s+([+-]\d{4}|[A-Za-z]+))?)?/);if(!e)return null;let t=Number(e[3]);e[3].length===2?t+=t<50?2e3:1900:e[3].length===3&&(t+=1900);let r=Number(e[1]),n=ze(e[2]);if(!It(r,n,t))return null;let i=e[4]===void 0?{}:{hours:Number(e[4]),minutes:Number(e[5]),seconds:Number(e[6]||0),zone:e[7]};return Object.assign({day:r,month:n,year:t},i)}var Wa={UT:0,GMT:0,EST:-5,EDT:-4,CST:-6,CDT:-5,MST:-7,MDT:-6,PST:-8,PDT:-7};function Nn(s){let e=s.zone||"",t=0;if(/^[+-]\d{4}$/.test(e)){let r=e.charAt(0)==="-"?-1:1,n=Number(e.substr(1,2)),i=Number(e.substr(3,2));i<60&&(t=r*(n*60+i))}else Object.hasOwn(Wa,e.toUpperCase())&&(t=Wa[e.toUpperCase()]*60);return Date.UTC(s.year,s.month,s.day,s.hours||0,s.minutes||0,s.seconds||0)-t*60*1e3}g();var Mn=/=\?([^?\s*]+)(?:\*[^?\s]*)?\?([BbQq])\?([^?\s]*)\?=/g,Mf=new TextDecoder("utf-8");function _s(s){return Mf.decode(b.Buffer.from(s,"binary"))}var Rn=new Map;function Rf(s,e){if(s=s.toLowerCase(),!Rn.has(s)){let r=!1;try{r=new TextDecoder(s)}catch{}Rn.set(s,r)}let t=Rn.get(s);return t?t.decode(e):!1}function ut(s){let e=String(s||"");if(e.indexOf("=?")<0&&!/[\u0080-\u00ff]/.test(e))return e;let t="",r=null,n=0,i=()=>{if(r){let a=Rf(r.charset,b.Buffer.concat(r.octets));t+=a===!1?r.source:a,r=null}};Mn.lastIndex=0;let o;for(;o=Mn.exec(e);){let a=e.substring(n,o.index);r&&/^\s*$/.test(a)||(i(),t+=_s(a)),n=Mn.lastIndex;let l=o[2].toUpperCase()==="B"?b.Buffer.from(o[3],"base64"):b.Buffer.from(o[3].replace(/_/g," ").replace(/=([0-9a-fA-F]{2})/g,(c,f)=>String.fromCharCode(parseInt(f,16))),"binary");r&&r.charset.toLowerCase()!==o[1].toLowerCase()&&i(),r||(r={charset:o[1],octets:[],source:""}),r.octets.push(l),r.source+=(r.source?a:"")+o[0]}return i(),t+_s(e.substr(n))}var Lf={ALL:[],ANSWERED:[],BCC:["string"],BEFORE:["date"],BODY:["string"],CC:["string"],DELETED:[],DRAFT:[],FLAGGED:[],FROM:["string"],HEADER:["string","string"],KEYWORD:["string"],LARGER:["number64"],NEW:[],NOT:["key"],OLD:[],ON:["date"],OR:["key","key"],RECENT:[],SEEN:[],SENTBEFORE:["date"],SENTON:["date"],SENTSINCE:["date"],SINCE:["date"],SMALLER:["number64"],SUBJECT:["string"],TEXT:["string"],TO:["string"],UID:["sequence"],UNANSWERED:[],UNDELETED:[],UNDRAFT:[],UNFLAGGED:[],UNKEYWORD:["string"],UNSEEN:[]},$a=["US-ASCII","UTF-8"];function Q(s){let e=new Error(s);return e.imapResponse="BAD",e}function Df(s){let e=(s||"").toString().match(/^(\d{1,2})-([A-Za-z]{3})-(\d{4})$/),t=e&&Hs(Number(e[1]),ze(e[2]),Number(e[3]));if(!t)throw Q("Invalid date argument "+s);return t}function vn(s){let e=Ps(s);return e?Hs(e.day,e.month,e.year):!1}function Gs(s){return vn(s.internaldate)}function Ln(s){let e=Fs(ne(s).tree.parsedHeader.date);return e?Hs(e.day,e.month,e.year):Gs(s)}function Ot(s){let e=(t,r)=>{if(Array.isArray(t))return t.map(e);if(!t||["STRING","ATOM","LITERAL","SEQUENCE"].indexOf(t.type)<0)throw Q("Invalid search criteria argument #"+(r+1));return t.value};return s.map(e)}function xt(s,e,t,r,n){let i=[];r.code==="BADCHARSET"?i.push({type:"SECTION",section:[{type:"ATOM",value:"BADCHARSET"},r.charsets.map(o=>({type:"ATOM",value:o}))]}):r.responseCode&&i.push({type:"SECTION",section:r.responseCode.map(o=>({type:"ATOM",value:String(o)}))}),i.push({type:"TEXT",value:r.message}),s.send({tag:e.tag,command:r.imapResponse==="BAD"?"BAD":"NO",attributes:i},n,e,t)}function Un(s){return s.replace(/[A-Z]+/g,e=>e.toLowerCase())}function Dn(s,e){return Un(s).indexOf(e)>=0}function Ja(s){let e=Object.assign({},Lf),t=s.searchHandlers;return Object.keys(t).forEach(r=>{if(!(r in e)){let n=t[r];e[r]=typeof n.argumentTypes=="function"?n.argumentTypes:new Array(Math.max(n.length-3,0)).fill("string")}}),e}function Za(s,e){let t=Ja(s),r=n=>{let i=0;return n.some((o,a)=>{if(Array.isArray(o))return r(o);if(i)return i--,!1;let u=(o&&o.value||"").toString(),l=u.toUpperCase();if(l==="CHARSET"&&a===0)i=1;else if(Object.hasOwn(t,l)){let c=t[l];typeof c=="function"&&(c=c(n.slice(a+1).map(f=>Array.isArray(f)?f:(f&&f.value||"").toString()))),i=c.filter(f=>f!=="key").length}else if(/^[\d*][\d*,:]*$/.test(u))return!0;return!1})};return r([].concat(e||[]))}function De(s,e,t,r){let n=r||((N,w)=>s.getMessageRange(N,w)),i={},o=new Set,a=Ja(s.server),u=s.server.searchHandlers;t=[].concat(t||[]);let l=s.searchCharset||s.defaultSearchCharset||"US-ASCII";if(typeof t[0]=="string"&&t[0].toUpperCase()==="CHARSET"){if(s.searchCharset)throw Q("CHARSET is not allowed, search strings are always "+s.searchCharset+" in this session");t.shift();let N=t.shift();if(typeof N!="string")throw Q("CHARSET expects a charset name");if($a.indexOf(N.toUpperCase())<0){let w=new Error("Unsupported charset "+N);throw w.imapResponse="NO",w.code="BADCHARSET",w.charsets=$a,w}l=N.toUpperCase()}let c=(N,w)=>{if(l==="US-ASCII"&&/[\u0080-\u00ff]/.test(w))throw Q(N+" argument has 8-bit characters, use CHARSET UTF-8");if(l==="UTF-8"&&!Ye(b.Buffer.from(w,"binary")))throw Q(N+" argument is not valid UTF-8");return w};if(!t.length)throw Q("SEARCH expects search criteria, empty query given");let f=N=>{if(!N.length)throw Q("Unexpected end of search criteria");let w=N.shift();if(Array.isArray(w))return{key:"AND",args:p([].concat(w))};let G=w.toUpperCase();if(!Object.prototype.hasOwnProperty.call(a,G)||s.disabledSearchKeys&&s.disabledSearchKeys.has(G)){let L;try{L=n(w,!1)}catch(v){throw/^[\d,:*]+$/.test(w)?v:Q("Invalid search key "+w)}return{key:"_SEQ",args:[L]}}o.add(G);let F=a[G],W=typeof F=="function"?F(N):F,x=W.map(L=>{if(L==="key")return f(N);if(!N.length||typeof N[0]!="string")throw Q(G+" expects "+W.length+" argument"+(W.length>1?"s":""));let v=N.shift();if(typeof L=="function")return L(v);switch(L){case"date":return Df(v);case"number":case"number64":{let V=L==="number64"&&s.number64;if(!Ae(v,V?Ge:4294967295))throw Q(G+" expects a number"+(V?"64":""));return Number(v)}case"sequence":return n(v,!0);default:return c(G,v)}});return{key:G,args:x}},p=N=>{if(!N.length)throw Q("Empty search criteria list");let w=[];for(;N.length;)w.push(f(N));return w},y={key:"AND",args:p(t)},A=N=>new Set(N.map(w=>w[1])),m=N=>{(N.key==="_SEQ"||N.key==="UID")&&(N.set=A(N.args[0])),["BODY","TEXT"].indexOf(N.key)>=0?N.needle=Un(N.args[0]):["BCC","CC","FROM","HEADER","SUBJECT","TO"].indexOf(N.key)>=0&&(N.needle=Un(_s(N.args[N.key==="HEADER"?1:0]))),N.args.forEach(w=>{w&&typeof w=="object"&&w.key&&m(w)})};m(y);let h=(N,w)=>N.flags.indexOf(w)>=0,d=(N,w,G)=>(w=w.toLowerCase(),(ne(N).tree.header||[]).some(F=>{let W=F.indexOf(":"),x=(W<0?F:F.substr(0,W)).trim().toLowerCase(),L=W<0?"":F.substr(W+1).replace(/\r?\n(?=[ \t])/g,"");return x===w&&Dn(ut(L),G)})),E=(N,w,G)=>{let F=N.args;if(Object.prototype.hasOwnProperty.call(u,N.key))return!!u[N.key](s,w,G,...F);switch(N.key){case"AND":return F.every(W=>E(W,w,G));case"_SEQ":case"UID":return N.set.has(w);case"ALL":return!0;case"ANSWERED":return h(w,"\\Answered");case"BCC":case"CC":case"FROM":case"SUBJECT":case"TO":return d(w,N.key,N.needle);case"HEADER":return d(w,F[0],N.needle);case"BEFORE":{let W=Gs(w);return!!W&&W<F[0]}case"ON":return Gs(w)===F[0];case"SINCE":{let W=Gs(w);return!!W&&W>=F[0]}case"SENTBEFORE":{let W=Ln(w);return!!W&&W<F[0]}case"SENTON":return Ln(w)===F[0];case"SENTSINCE":{let W=Ln(w);return!!W&&W>=F[0]}case"BODY":return Dn(Be(ne(w).tree,!0),N.needle);case"TEXT":return Dn(ne(w).raw,N.needle);case"DELETED":return h(w,"\\Deleted");case"DRAFT":return h(w,"\\Draft");case"FLAGGED":return h(w,"\\Flagged");case"KEYWORD":return h(w,F[0]);case"LARGER":return ne(w).raw.length>F[0];case"SMALLER":return ne(w).raw.length<F[0];case"NEW":return s.isRecent(w)&&!h(w,"\\Seen");case"OLD":return!s.isRecent(w);case"RECENT":return s.isRecent(w);case"SEEN":return h(w,"\\Seen");case"NOT":return!E(F[0],w,G);case"OR":return E(F[0],w,G)||E(F[1],w,G);case"UNANSWERED":return!h(w,"\\Answered");case"UNDELETED":return!h(w,"\\Deleted");case"UNDRAFT":return!h(w,"\\Draft");case"UNFLAGGED":return!h(w,"\\Flagged");case"UNKEYWORD":return!h(w,F[0]);case"UNSEEN":return!h(w,"\\Seen");default:return!1}},I=s.server.searchLimits.reduce((N,w)=>w(s,N,y)||N,e),C=I!==e&&new Set(I),H=[];return e.forEach((N,w)=>{C&&!C.has(N)||E(y,N,w+1)&&(i[N.uid]=w+1,H.push(N))}),{list:H,numbers:i,keys:o,matches:(N,w)=>E(y,N,w)}}g();function Ne(s,e){s.enableAvailable=s.enableAvailable||[],s.enableAvailable.indexOf(e)<0&&s.enableAvailable.push(e)}function ye(s,e){return!!s.enabled&&s.enabled.indexOf(e)>=0}function Bn(s){s.registerCapability("ENABLE"),s.enableAvailable=s.enableAvailable||[],s.connectionHandlers.push(e=>{e.enabled=e.enabled||[]}),s.resetHandlers.push(e=>{e.enabled=[]}),s.setCommandHandler("ENABLE",(e,t,r,n)=>{let i,o,a;if(e.everSelected)return e.sendStatus(t,r,"BAD","ENABLE is not allowed after SELECT or EXAMINE"),n();if(!t.attributes)return e.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:"ENABLE expects capability list"}]},"INVALID COMMAND",t,r),n();for(o=0,a=t.attributes.length;o<a;o++)if(!t.attributes[o]||t.attributes[o].type!=="ATOM")return e.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:"Attribute nr "+(o+1)+" is not an ATOM"}]},"INVALID COMMAND",t,r),n();let u=[];for(o=0,a=t.attributes.length;o<a;o++){let l=t.attributes[o].value.toUpperCase();i=s.enableAvailable.find(c=>c.toUpperCase()===l),i&&e.enabled.indexOf(i)<0&&(e.enabled.push(i),u.push(i))}return e.send({tag:"*",command:"ENABLED",attributes:u.map(l=>({type:"ATOM",value:l}))},"ENABLED",t,r,u),e.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"ENABLE completed"}]},"ENABLE",t,r),n()},{states:Z.AUTHENTICATED})}function kn(s){s.registerCapability("CONDSTORE"),Ne(s,"CONDSTORE");let e=m=>Math.max(Number(m.HIGHESTMODSEQ)||0,1),t=m=>(m.HIGHESTMODSEQ=e(m)+1,m.HIGHESTMODSEQ);s.resetHandlers.push(m=>{m.condstoreEnabled=!1});let r=m=>!!m.condstoreEnabled||ye(m,"CONDSTORE")||ye(m,"QRESYNC");s.condstore={isEnabled:r,getHighestModseq:e};let n=(m,h,d,E)=>{m.send({tag:"*",command:"OK",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"HIGHESTMODSEQ"},e(h)]},{type:"TEXT",value:"Highest"}]},"CONDSTORE INFO",d,E)},i=(m,h,d)=>{if(r(m)){m.condstoreEnabled=!0;return}m.condstoreEnabled=!0,m.state==="Selected"&&m.selectedMailbox&&n(m,m.selectedMailbox,h,d)};s.messageHandlers.push((m,h,d)=>{let E=Number(h.MODSEQ);E>0&&Number.isSafeInteger(E)?(h.MODSEQ=E,d.HIGHESTMODSEQ=Math.max(e(d),E)):h.MODSEQ=t(d)}),s.on("expunge",m=>{t(m)}),s.on("flags",(m,h)=>{h.forEach(d=>{d.MODSEQ=t(m)})}),s.closedChecks.push(()=>!0),s.allowedStatus.push("HIGHESTMODSEQ"),s.statusHandlers.HIGHESTMODSEQ=(m,h)=>e(h);let o=(m,h)=>{let d=s.getCommandHandler(m);d&&s.setCommandHandler(m,(E,I,C,H)=>h(d,E,I,C,H))},a=(m,h,d,E,I)=>(m.sendStatus(h,d,"BAD",I,!1,"CONDSTORE FAILED"),E()),u=(m,h)=>!!m&&m.type==="ATOM"&&Ae(m.value,Ge)&&(h||BigInt(m.value)>0n),l=(m,h,d,E,I)=>{Hf(d.attributes&&d.attributes[1],d.attributes,1)&&(h.condstoreEnabled=!0,d.condstoreOption=!0),m(h,d,E,I)};o("SELECT",l),o("EXAMINE",l),o("STATUS",(m,h,d,E,I)=>{let C=d.attributes&&d.attributes[1];Array.isArray(C)&&C.some(H=>H&&H.type==="ATOM"&&String(H.value).toUpperCase()==="HIGHESTMODSEQ")&&i(h,d,E),m(h,d,E,I)});let c=(m,h,d,E,I)=>{let C=d.attributes||[],H=Math.max(C.length-1,2),N=nu(C[H],"CHANGEDSINCE",C,H);if(N){if(!u(N))return a(h,d,E,I,"Invalid syntax for CHANGEDSINCE, number expected");d.changedsince=Number(N.value),Bf(d)}(N||iu(d))&&i(h,d,E),m(h,d,E,I)};o("FETCH",c),o("UID FETCH",c);let f=(m,h,d,E,I)=>{let C=nu(d.attributes&&d.attributes[1],"UNCHANGEDSINCE",d.attributes,1);if(C){if(!u(C,!0))return a(h,d,E,I,"Invalid syntax for UNCHANGEDSINCE, number expected");d.unchangedsince=Number(C.value),i(h,d,E)}d.condstoreStore={isUid:(d.command||"").toUpperCase()==="UID STORE",messages:new Map,modified:[],done:!1},m(h,d,E,I)};o("STORE",f),o("UID STORE",f);let p=(m,h,d,...E)=>h.MODSEQ>=E[E.length-1];p.argumentTypes=m=>typeof m[0]=="string"&&/^\d+$/.test(m[0])?[eu]:[Uf,vf,eu],s.searchHandlers.MODSEQ=p;let y=m=>m.reduce((h,d)=>Math.max(h,d.MODSEQ),0);s.fetchHandlers.MODSEQ=function(m,h){return[h.MODSEQ]},s.fetchFilters.push((m,h,d,E)=>"changedsince"in d&&!(d.changedsince<h.MODSEQ)?!1:(d.condstoreFetch||(d.condstoreFetch=new Map),d.condstoreFetch.set(E,{message:h,seen:h.flags.indexOf("\\Seen")>=0}),!0)),s.storeFilters.push((m,h,d,E)=>{let I=d.condstoreStore;return I?"unchangedsince"in d&&h.MODSEQ>d.unchangedsince?(I.modified.push(I.isUid?h.uid:E),!1):(I.messages.set(h,{index:E,before:tu(h),bumped:!1,reported:!1}),!0):!0});let A=(m,h,d)=>{!d.bumped&&tu(h)!==d.before&&(d.bumped=!0,h.MODSEQ=t(m.selectedMailbox))};s.outputHandlers.push((m,h,d,E,I,C)=>{if(d==="FLAG NOTIFICATION"&&h&&C&&r(m)){Hn(h.attributes[2],C.MODSEQ);return}if(!E||!h)return;if(d==="FLAG UPDATE"&&E.condstoreStore&&C&&E.condstoreStore.messages.has(C)){let N=E.condstoreStore.messages.get(C);A(m,C,N),N.reported=!0,r(m)&&(Hn(h.attributes[2],C.MODSEQ),su(h.attributes[2],C.uid));return}let H=["SEARCH","SORT","THREAD"].includes(h.command)&&[h.command,"UID "+h.command].includes(d);if((H||d==="ESEARCH")&&h.tag==="*"&&C&&C.keys&&C.keys.has("MODSEQ")){if(i(m,E,I),C.list.length&&h.command!=="THREAD"){let N=[{type:"ATOM",value:"MODSEQ"},y(C.list)];h.attributes.push(...H?[N]:N)}return}if(h.tag==="*"&&E.condstoreFetch&&h.attributes&&h.attributes[1]&&h.attributes[1].value==="FETCH"&&E.condstoreFetch.has(h.attributes[0])){let N=E.condstoreFetch.get(h.attributes[0]),w=N.message,G=!1;!N.seen&&w.flags.indexOf("\\Seen")>=0&&m.selectedMailbox&&(N.seen=!0,w.MODSEQ=t(m.selectedMailbox),G=!0);let F=h.attributes[2];Array.isArray(F)&&(Pn(F,"MODSEQ")>=0||G&&r(m))&&Hn(F,w.MODSEQ),Array.isArray(F)&&G&&r(m)&&su(F,w.uid);return}if(h.tag===E.tag&&E.condstoreStore&&!E.condstoreStore.done){let N=E.condstoreStore;N.done=!0,N.messages.forEach((w,G)=>{if(A(m,G,w),!w.reported&&r(m)&&(w.bumped||"unchangedsince"in E)){let F=[{type:"ATOM",value:"MODSEQ"},[G.MODSEQ]];F.unshift({type:"ATOM",value:"UID"},G.uid),m.send({tag:"*",attributes:[w.index,{type:"ATOM",value:"FETCH"},F]},"CONDSTORE MODSEQ UPDATE",E,I,G)}}),(h.command==="OK"||h.command==="NO")&&N.modified.length&&(h.attributes=[{type:"SECTION",section:[{type:"ATOM",value:"MODIFIED"},{type:"SEQUENCE",value:N.modified.sort((w,G)=>w-G).join(",")}]}].concat((h.attributes||[]).filter(w=>h.command==="OK"||!w||w.type!=="SECTION")));return}if(d==="ENABLED"&&Array.isArray(C)&&C.indexOf("CONDSTORE")>=0){m.condstoreEnabled||(m.condstoreEnabled=!0,m.state==="Selected"&&m.selectedMailbox&&(E.condstoreReportHighest=!0));return}if(d==="ENABLE"&&E.condstoreReportHighest&&m.selectedMailbox){E.condstoreReportHighest=!1,n(m,m.selectedMailbox,E,I);return}if((d==="EXAMINE"||d==="SELECT")&&h.tag===E.tag&&m.selectedMailbox){if(E.condstoreOption){let N=h.attributes&&h.attributes.slice(-1)[0];!N||N.type!=="TEXT"?h.attributes=(h.attributes||[]).concat({type:"TEXT",value:"CONDSTORE is now enabled"}):N.value+=", CONDSTORE is now enabled"}n(m,m.selectedMailbox,E,I)}})}function eu(s){if(!Ae(s,Ge))throw Q("MODSEQ expects a mod-sequence value");return Number(s)}function Uf(s){let e=s.match(/^\/flags\/(\\?)(.+)$/i);if(!e||sn.test(e[2])||e[1]&&e[2].toUpperCase()==="RECENT")throw Q('MODSEQ expects an entry name like "/flags/\\\\seen"');return s}function vf(s){if(!["PRIV","SHARED","ALL"].includes(s.toUpperCase()))throw Q("MODSEQ expects entry type priv, shared or all");return s}function tu(s){return JSON.stringify([s.flags||[],s["X-GM-LABELS"]||[]])}function Pn(s,e){if(!Array.isArray(s))return-1;for(let t=0;t<s.length;t+=2)if(s[t]&&s[t].type==="ATOM"&&String(s[t].value).toUpperCase()===e)return t;return-1}function Hn(s,e){if(!Array.isArray(s))return;let t=Pn(s,"MODSEQ");t>=0?s[t+1]=[e]:s.push({type:"ATOM",value:"MODSEQ"},[e])}function su(s,e){Array.isArray(s)&&Pn(s,"UID")<0&&s.push({type:"ATOM",value:"UID"},e)}function ru(s){return!!s&&s.type==="ATOM"&&String(s.value).toUpperCase()==="MODSEQ"}function iu(s){let e=s.attributes&&s.attributes[1];return Array.isArray(e)?e.some(ru):ru(e)}function Bf(s){if(!s.attributes||!s.attributes[1]||iu(s))return;let e=s.attributes[1];if(!Array.isArray(e)){let t=String(e.value).toUpperCase(),r=e.type==="ATOM"&&Object.hasOwn(jt,t)&&jt[t];e=r?r.map(n=>({type:"ATOM",value:n})):[e].concat(s.attributes.splice(2))}s.attributes[1]=e.concat({type:"ATOM",value:"MODSEQ"})}function Hf(s,e,t){if(!s)return!1;let r=!1;if(Array.isArray(s)){for(let n=s.length-1;n>=0;n--)if(s[n]&&s[n].type==="ATOM"&&s[n].value.toUpperCase()==="CONDSTORE"){s.splice(n,1),r=!0;break}s.length||e.splice(t,1)}return!!r}function nu(s,e,t,r){if(!s)return!1;let n=!1;if(Array.isArray(s)){for(let i=0;i<s.length;i+=2)if(s[i]&&s[i].type==="ATOM"&&s[i].value.toUpperCase()===e.toUpperCase()){n=s[i+1]||{type:"NIL"},s.splice(i,2);break}s.length||t.splice(r,1)}return n}g();g();g();function lt(s){return Xs(Array.from(new Set(s)).sort((e,t)=>e-t))}function Xs(s){let e=[];return s.forEach(t=>{let r=e[e.length-1];r&&r[1]+1===t?r[1]=t:e.push([t,t])}),e.map(t=>t[0]===t[1]?String(t[0]):t[0]+":"+t[1]).join(",")}function Vt(s,e){let t=s&&["ATOM","SEQUENCE"].includes(s.type)?String(s.value):"",r=t.match(/^(-?)([1-9][0-9]*):(-?)([1-9][0-9]*)$/);if(!r||r[1]!==r[3]||r[1]&&!e)throw Q("PARTIAL expects a range like 1:100"+(e?" or -1:-100":""));let n=Number(r[2]),i=Number(r[4]);if(n>4294967295||i>4294967295)throw Q("PARTIAL range is out of bounds");return{range:t,from:Math.min(n,i),to:Math.max(n,i),fromEnd:!!r[1]}}function js(s,e){return e.fromEnd?s.slice(Math.max(s.length-e.to,0),Math.max(s.length-e.from+1,0)):s.slice(e.from-1,e.to)}function Vs(s){s.searchReturnOptions.has("PARTIAL")||(s.searchReturnOptions.set("PARTIAL",{data:!0,once:!0,parse:e=>Vt(e,!!s.partialRangeLast)}),s.searchReturnOptions.set("ALL",Object.assign({},s.searchReturnOptions.get("ALL"),{once:!0})),s.searchReturnChecks.push(e=>e.has("PARTIAL")&&e.has("ALL")&&"PARTIAL and ALL can not be used together"))}function je(s,e){let t=e.get("PARTIAL");if(!s.length||e.has("ALL")||e.has("COUNT")||!t&&!e.has("MIN")&&!e.has("MAX"))return s;let r=new Set(t?js(s,t):[]);return e.has("MIN")&&r.add(s[0]),e.has("MAX")&&r.add(s[s.length-1]),s.filter(n=>r.has(n))}function Fn(s,e){let t=[{type:"ATOM",value:"TAG"},{type:"STRING",value:s}];return e&&t.push({type:"ATOM",value:"MAILBOX"},{type:"MAILBOX",value:e.path},{type:"ATOM",value:"UIDVALIDITY"},e.uidvalidity),t}function Ct(s,e,t,r,n,i){let o=(i||t.list).map(c=>e?c.uid:t.numbers[c.uid]);i||o.sort((c,f)=>c-f);let a=i?Xs:lt,u=[Fn(s,n)];e&&u.push({type:"ATOM",value:"UID"});let l=(c,f)=>u.push({type:"ATOM",value:c},f);if(o.length&&r.has("MIN")&&l("MIN",o[0]),o.length&&r.has("MAX")&&l("MAX",o[o.length-1]),o.length&&(r.has("ALL")||!r.size)&&l("ALL",{type:"SEQUENCE",value:a(o)}),r.has("PARTIAL")){let c=r.get("PARTIAL"),f=js(o,c);l("PARTIAL",[{type:"ATOM",value:c.range},f.length?{type:"SEQUENCE",value:a(f)}:null])}return r.has("COUNT")&&l("COUNT",o.length),{tag:"*",command:"ESEARCH",attributes:u}}var ou=s=>{let e=s&&s[0];return!!e&&e.type==="ATOM"&&String(e.value).toUpperCase()==="RETURN"};function Ie(s){if(s.searchReturnOptions)return;s.registerCapability("ESEARCH"),s.searchReturnOptions=new Map(["MIN","MAX","ALL","COUNT"].map(t=>[t,{data:!0}])),s.searchReturnChecks=[],s.parseSearchReturn=(t,r,n)=>{if(!Array.isArray(t))throw Q("RETURN expects a parenthesized list of result options");let i=new Map,o=new Set;for(let a=0;a<t.length;a++){let u=t[a],l=u&&u.type==="ATOM"?String(u.value).toUpperCase():"",c=s.searchReturnOptions.get(l);if(!c)throw Q("Unknown SEARCH result option"+(l?" "+l:""));if(c.once&&i.has(l))throw Q("SEARCH result option "+l+" can be used only once");o.add(l);let f=c.parse?c.parse(t[++a]):!0;c.hint||i.set(l,f)}for(let a of s.searchReturnChecks){let u=a(i,r,n,o);if(u)throw Q(u)}return i},s.isSilentReturn=t=>t.size>0&&![...t.keys()].some(r=>{let n=s.searchReturnOptions.get(r);return n.data||n.response});let e=(t,r,n,i,o)=>{if(!ou(n.attributes))return t(r,n,i,o);try{n.searchReturn=s.parseSearchReturn(n.attributes[1],r,n)}catch(a){return r.sendStatus(n,i,"BAD",a.message,!1,(n.command||"").toUpperCase()+" FAILED"),o()}n.attributes=n.attributes.slice(2),t(r,n,i,o)};s.acceptSearchReturn=t=>{let r=s.getCommandHandler(t);s.setCommandHandler(t,(n,i,o,a)=>e(r,n,i,o,a))},s.acceptSearchReturn("SEARCH"),s.acceptSearchReturn("UID SEARCH"),s.connectionHandlers.push(t=>{let r=t.usesSequenceNumbers;t.usesSequenceNumbers=function(n){return ou(n.attributes)&&(n=Object.assign({},n,{attributes:n.attributes.slice(2)})),r.call(this,n)}}),s.outputHandlers.push((t,r,n,i,o,a)=>{if(!i||!i.searchReturn||r.tag!=="*"||r.command!=="SEARCH"||n!=="SEARCH"&&n!=="UID SEARCH"||!a||!Array.isArray(a.list))return;r.skipResponse=!0;let u=i.searchReturn;s.isSilentReturn(u)||t.send(Ct(i.tag,n==="UID SEARCH",a,u),"ESEARCH",i,o,Object.assign({},a,{list:je(a.list,u)}))})}var kf=10,au=new Set(["SELECT","EXAMINE","CLOSE","UNSELECT"]),Pf=new Set(["SEARCH","UID SEARCH","SORT","UID SORT"]),_n=s=>(s.searchContexts||(s.searchContexts=new Map),s.searchContexts),uu=(s,e)=>{let t=[];s.forEach(([n,i])=>{let o=t[t.length-1],a=o&&(e||!n?o.position:o.position+o.values.length);o&&n===a?o.values.push(i):t.push({position:n,values:[i]})});let r=[];return t.forEach(n=>{let i=n.position?Xs(n.values):lt(n.values);r.push(n.position,{type:"SEQUENCE",value:i})}),r},lu=(s,e,t,r)=>{let n=[Fn(e.tag,e.correlatorMailbox)];e.isUid&&n.push({type:"ATOM",value:"UID"}),t.length&&n.push({type:"ATOM",value:"REMOVEFROM"},uu(t,!0)),r.length&&n.push({type:"ATOM",value:"ADDTO"},uu(r,!1)),s.send({tag:"*",command:"ESEARCH",attributes:n},"ESEARCH UPDATE",null,null,e)},Ff=s=>{let e=s.searchContexts,t=s.selectedMailbox,r=t?t.messages:[],n=new Map(r.map((i,o)=>[i,o+1]));e.forEach((i,o)=>{if(i.mailbox!==t){e.delete(o);return}let a=r.filter((p,y)=>i.matches(p,y+1)),u=p=>i.isUid?p.uid:n.get(p),l=new Set(a),c=[],f=[];if(!i.compare)i.results.forEach(p=>{!l.has(p)&&n.has(p)&&c.push([0,u(p)])}),a.forEach(p=>{i.results.has(p)||f.push([0,u(p)])});else{let p=0;i.order.forEach(y=>{l.has(y)?p++:n.has(y)&&c.push([p+1,u(y)])}),i.order=a.sort(i.compare),i.order.forEach((y,A)=>{i.results.has(y)||f.push([A+1,u(y)])})}i.results=l,(c.length||f.length)&&lu(s,i,c,f)})},_f=(s,e,t)=>{s.searchContexts.forEach(r=>{if(r.mailbox!==s.selectedMailbox)return;let n=[];e.forEach(i=>{if(!r.results.delete(i))return;let o=0;r.order&&(o=r.order.indexOf(i)+1,r.order.splice(o-1,1)),(r.isUid||t)&&n.push([o,r.isUid?i.uid:t])}),n.length&&lu(s,r,n,[])})};function qt(s){if(s.addSearchContext)return;Ie(s),s.registerCapability("CONTEXT=SEARCH");let e=Math.max(Number(s.options.maxSearchContexts)||kf,1);s.searchReturnOptions.set("CONTEXT",{hint:!0}),s.searchReturnOptions.set("UPDATE",{data:!1,response:!0,once:!0}),Vs(s),s.searchReturnChecks.push((t,r,n)=>t.has("UPDATE")&&_n(r).has(n.tag)&&"Tag "+n.tag+" is already in use by an updating search"),s.addSearchContext=(t,r,n,i,o,a)=>{let u=_n(t);if(u.size>=e){t.send({tag:"*",command:"NO",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"NOUPDATE"},{type:"STRING",value:r.tag}]},{type:"TEXT",value:"Too many updating contexts"}]},"NOUPDATE",r,n);return}u.set(r.tag,{tag:r.tag,isUid:o,matches:i.matches,results:new Set(i.list),compare:i.compare||null,order:i.compare?i.sorted.slice():null,mailbox:t.selectedMailbox,correlatorMailbox:a||null})},s.setCommandHandler("CANCELUPDATE",(t,r,n,i)=>{let o=r.attributes||[];if(!o.length||o.some(l=>!l||l.type!=="STRING"))return t.sendStatus(r,n,"BAD","CANCELUPDATE expects one or more quoted tags",!1,"CANCELUPDATE FAILED"),i();let a=_n(t);return o.find(l=>!a.has(l.value))?(t.sendStatus(r,n,"NO","Unknown tag",!1,"CANCELUPDATE FAILED"),i()):(o.forEach(l=>a.delete(l.value)),t.sendStatus(r,n,"OK","Updates cancelled",!1,"CANCELUPDATE"),i())},{states:Z.SELECTED}),s.resetHandlers.push(t=>{t.searchContexts=null}),s.connectionHandlers.push(t=>{let r=t.processNotifications;t.processNotifications=function(n,i){r.call(this,n,i);let o=(n&&n.command||"").toUpperCase();this.searchContexts&&this.searchContexts.size&&!this.notificationQueue.length&&!au.has(o)&&Ff(this)}}),s.outputHandlers.push((t,r,n,i,o,a)=>{let u=r.tag==="*"&&(r.message?[r.message]:r.command==="VANISHED"&&r.messages);if(u&&t.searchContexts){_f(t,u,r.message?r.attributes[0]:null);return}if(!i)return;let l=(i.command||"").toUpperCase();if(r.tag===i.tag&&au.has(l)){t.searchContexts=null;return}if(!(!Pf.has(l)||!i.searchReturn||!i.searchReturn.has("UPDATE"))){if(r.tag==="*"&&l.endsWith(String(r.command))&&n===l&&a&&Array.isArray(a.list)){i.contextResult=a;return}r.tag===i.tag&&r.command==="OK"&&i.contextResult&&s.addSearchContext(t,i,o,i.contextResult,l.startsWith("UID "))}})}g();g();g();g();var Gn=new Map([[452,453],[454,453],[455,456],[457,456],[458,459],[460,459],[497,498],[499,498],[8115,8124],[8131,8140],[8179,8188]]);for(let s of[8064,8080,8096])for(let e=0;e<8;e++)Gn.set(s+e,s+e+8);function He(s){let e="";for(let t of s){let r=t.codePointAt(0);if(Gn.has(r)){e+=String.fromCodePoint(Gn.get(r));continue}let n=t.toUpperCase();e+=[...n].length===1?n:t}return b.Buffer.from(e.normalize("NFKD"),"utf-8")}var Xn="\\[[^[\\]]*\\] *",Gf=new RegExp("^(?:"+Xn+")*(?:re|fwd?) *(?:"+Xn+")?:","i"),Xf=new RegExp("^"+Xn);function qs(s){let e=!1,t=ut(s).replace(/\r?\n(?=[ \t])/g,"").replace(/[\t\r\n]/g," ").replace(/ {2,}/g," ");for(;;){let r=t.length;for(;;)if(t.charAt(r-1)===" ")r--;else if(r>=5&&t.substring(r-5,r).toLowerCase()==="(fwd)")e=!0,r-=5;else break;for(t=t.substring(0,r);;){let n;if(t.charAt(0)===" ")t=t.substr(1);else if(n=t.match(Gf))e=!0,t=t.substr(n[0].length);else if((n=t.match(Xf))&&n[0].length<t.length)t=t.substr(n[0].length);else break}if(/^\[fwd:/i.test(t)&&/\]$/.test(t)){e=!0,t=t.slice(5,-1);continue}return{subject:t,isReply:e}}}function jn(s){let e=Ps(s.internaldate);return e?Nn(e):0}function Qs(s){let e=Fs(ne(s).tree.parsedHeader.date);return e?((e.hours===void 0||e.hours>23||e.minutes>59||e.seconds>60)&&Object.assign(e,{hours:0,minutes:0,seconds:0}),Nn(e)):jn(s)}function cu(s,e){let t=Xe(ne(s).tree.parsedHeader[e]);return t&&t[0]||null}function Ys(s,e){let t=cu(s,e);return t&&t[2]?ut(t[2]):""}function Vn(s,e){let t=cu(s,e),r=t&&t[0]?ut(t[0]):"";return r||!t||!t[2]?r:ut(t[3]?t[2]+"@"+t[3]:t[2])}function Ks(s){let e=[].concat(s||[]).join(" "),t=[],r=0,n=!1,i=null;for(let o=0;o<e.length;o++){let a=e.charAt(o);if(n)a==="\\"?(i!==null&&(i+=e.charAt(o+1)),o++):a==='"'?n=!1:i!==null&&(i+=a);else if(r)a==="\\"?o++:a==="("?r++:a===")"&&r--;else if(a==='"')n=!0;else if(a==="(")r++;else if(a==="<")i="";else if(a===">"){if(i!==null){let u=i.lastIndexOf("@");u>0&&u<i.length-1&&t.push(i)}i=null}else i!==null&&!/\s/.test(a)&&(i+=a)}return t}function zs(s,e,t,r){let n=e.command.toUpperCase(),i=r[0];try{if(r.length<2)throw Q(n+" expects a charset and search criteria");if(!i||["ATOM","STRING"].indexOf(i.type)<0)throw Q("Charset must be an atom or a quoted string");let o=Ot(r.slice(1));if(s.searchCharset){if(i.value.toUpperCase()!==s.searchCharset)throw Q("Charset must be "+s.searchCharset+" in this session");return De(s,s.getSessionMessages(),o)}let a=["CHARSET",i.value].concat(o);return De(s,s.getSessionMessages(),a)}catch(o){return xt(s,e,t,o,n+" FAILED"),!1}}function ct(s){if(s.sortKeys)return;s.registerCapability("SORT"),s.sortKeys={ARRIVAL:r=>jn(r),CC:r=>He(Ys(r,"cc")),DATE:r=>Qs(r),FROM:r=>He(Ys(r,"from")),SIZE:r=>ne(r).raw.length,SUBJECT:r=>He(qs(ne(r).tree.parsedHeader.subject).subject),TO:r=>He(Ys(r,"to"))};let e=(r,n)=>b.Buffer.isBuffer(r)?b.Buffer.compare(r,n):r-n;s.sortComparator=r=>{let n=new WeakMap,i=o=>(n.has(o)||n.set(o,r.map(a=>s.sortKeys[a.key](o))),n.get(o));return(o,a)=>{let u=i(o),l=i(a);for(let c=0;c<r.length;c++){let f=e(u[c],l[c]);if(f)return r[c].reverse?-f:f}return o.uid-a.uid}};let t=(r,n,i,o,a)=>{let u=r?"UID SORT":"SORT",l=i.attributes||[],c=h=>(n.sendStatus(i,o,"BAD",h,!1,u+" FAILED"),a());if(!Array.isArray(l[0])||!l[0].length)return c(u+" expects a list of sort criteria");let f=[],p=!1;for(let h of l[0]){let d=h&&h.type==="ATOM"?h.value.toUpperCase():"";if(d==="REVERSE"&&!p){p=!0;continue}if(!Object.hasOwn(s.sortKeys,d))return c("Invalid sort criterion "+(h&&typeof h.value=="string"?h.value:""));f.push({key:d,reverse:p}),p=!1}if(p)return c("REVERSE must be followed by a sort key");let y=zs(n,i,o,l.slice(1));if(!y)return a();let A=s.sortComparator(f),m=y.list.slice().sort(A);return n.send({tag:"*",command:"SORT",attributes:m.map(h=>r?h.uid:y.numbers[h.uid])},u,i,o,Object.assign(y,{sorted:m,compare:A})),n.sendStatus(i,o,"OK",u+" completed",!1,u),a()};s.setCommandHandler("SORT",t.bind(null,!1),{states:Z.SELECTED,searchCriteria:2,noExpunge:!0}),s.setCommandHandler("UID SORT",t.bind(null,!0),{states:Z.SELECTED,searchCriteria:2})}var fu=s=>s==="SORT"||s==="UID SORT";function Qt(s){s.esortLoaded||(s.esortLoaded=!0,ct(s),Ie(s),s.registerCapability("ESORT"),s.acceptSearchReturn("SORT"),s.acceptSearchReturn("UID SORT"),s.searchReturnChecks.push((e,t,r,n)=>{if(!fu((r.command||"").toUpperCase())||s.contextSort)return!1;let i=["CONTEXT","UPDATE","PARTIAL"].find(o=>n.has(o)&&(o!=="PARTIAL"||!s.partialRangeLast));return!!i&&i+" is not supported for SORT"}),s.outputHandlers.push((e,t,r,n,i,o)=>{if(!n||!n.searchReturn||t.tag!=="*"||t.command!=="SORT"||!fu(r)||!o||!o.sorted)return;t.skipResponse=!0;let a=n.searchReturn;s.isSilentReturn(a)||e.send(Ct(n.tag,r==="UID SORT",o,a,null,o.sorted),"ESEARCH",n,i,Object.assign({},o,{list:je(o.sorted,a)}))}))}function qn(s){Qt(s),qt(s),s.registerCapability("CONTEXT=SORT"),s.contextSort=!0}g();var jf=new RegExp("^\\\\["+he["ATOM-CHAR"]().replace(/[\\\]^-]/g,"\\$&")+"]+$");function Qn(s){s.registerCapability("CREATE-SPECIAL-USE");let e=s.getCommandHandler("CREATE"),t=[].concat(s.options["special-use"]||["\\Archive","\\Drafts","\\Flagged","\\Junk","\\Sent","\\Trash"]);s.setCommandHandler("CREATE",(r,n,i,o)=>{let a,u,l,c=[];if(n.attributes&&Array.isArray(n.attributes[1])){for(a=0;a<n.attributes[1].length;a+=2)n.attributes[1][a]&&n.attributes[1][a].type==="ATOM"&&n.attributes[1][a].value.toUpperCase()==="USE"&&Array.isArray(n.attributes[1][a+1])&&(l=n.attributes[1][a+1],n.attributes[1].splice(a,2),a-=2);n.attributes[1].length||n.attributes.splice(1,1)}if(l)for(a=0,u=l.length;a<u;a++){let f=l[a];if(!J(f)||!jf.test(f.value))return r.send({tag:n.tag,command:"BAD",attributes:[{type:"TEXT",value:"Invalid syntax for special use flag #"+(a+1)}]},"CREATE-SPECIAL-USE FAILED",n,i),o();let p=t.find(y=>y.toLowerCase()===String(l[a].value).toLowerCase());if(!p)return r.send({tag:n.tag,command:"NO",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"USEATTR"}]},{type:"TEXT",value:l[a].value+" not supported"}]},"CREATE-SPECIAL-USE FAILED",n,i),o();c.indexOf(p)<0&&c.push(p)}c.length&&(n.mailboxSpecialUse=c),e(r,n,i,o)}),s.outputHandlers.push((r,n,i,o,a,u)=>{i==="CREATE"&&u&&o.mailboxSpecialUse&&(u["special-use"]=o.mailboxSpecialUse)})}g();function Yn(s){s.registerCapability("ID"),s.setCommandHandler("ID",(e,t,r,n)=>{let i=Object.create(null),o=null,a,u,l="";if(!t.attributes||t.attributes.length!==1)return We("ID expects 1 attribute",e,t,r,n);let c=t.attributes[0];if(c&&!Array.isArray(c)||c&&c.length%2)return We("ID expects valid parameter list",e,t,r,n);if(c&&c.length>60)return We("ID allows at most 30 field-value pairs",e,t,r,n);if(c&&c.length)for(a=0,u=c.length;a<u;a++)if(a%2===0)if(c[a]&&["STRING","LITERAL"].indexOf(c[a].type)>=0){if(l=c[a].value,l.length>30)return We("ID field names can be at most 30 octets",e,t,r,n);if(Object.keys(i).some(f=>f.toLowerCase()===l.toLowerCase()))return We("ID field names must not repeat",e,t,r,n)}else return We("ID expects valid parameter list",e,t,r,n);else if(!c[a]||["STRING","LITERAL"].indexOf(c[a].type)>=0){if(c[a]&&c[a].value.length>1024)return We("ID values can be at most 1024 octets",e,t,r,n);i[l]=c[a]&&c[a].value||null}else return We("ID expects valid parameter list",e,t,r,n);if(s.options.id){let f=[];o=f,Object.keys(s.options.id).forEach(p=>{f.push({type:"STRING",value:p}),f.push({type:"STRING",value:(s.options.id[p]||"").toString()})})}e.send({tag:"*",command:"ID",attributes:[o]},"ID",t,r,i),e.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"ID command completed"}]},"ID",t,r,i),n()},{states:Z.ANY})}function We(s,e,t,r,n){return e.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:s}]},"INVALID COMMAND",t,r),n()}g();function Kn(s){s.registerCapability("IDLE"),s.setCommandHandler("IDLE",(e,t,r,n)=>{let i=setTimeout(()=>{e.socket&&!e.socket.destroyed&&(e.send({tag:"*",command:"BYE",attributes:[{type:"TEXT",value:"IDLE terminated"}]},"IDLE EXPIRED",t,r),e.end())},18e5);i.unref?.();let o=()=>clearTimeout(i),a=e.socket;return a&&a.once("close",o),e.directNotifications=!0,e.inputHandler=function(u){o(),a&&a.removeListener("close",o),e.inputHandler=!1,e.directNotifications=!1,u.toUpperCase()==="DONE"?e.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"IDLE terminated"}]},"IDLE",t,r):e.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:"Invalid Idle continuation"}]},"INVALID IDLE",t,r)},e.sendContinuation("idling","IDLE"),e.processNotifications(),n()},{states:Z.AUTHENTICATED,noArguments:!0})}g();g();var Vf=/[\u0000-\u001f\u007f-\u009f\u2028\u2029]|^\ufeff|\p{Cn}/u;function zn(s){let e=new Error(s);return e.imapResponse="BAD",e}function hu(s){if(s===!1||Vf.test(s))throw zn("Mailbox name must be valid Net-Unicode without control characters (RFC 9755 section 3)");if(s.normalize("NFC")!==s)throw zn("Mailbox name must be in Unicode Normalization Form C (RFC 5198 section 2, RFC 9051 section 5.1)");return s}function qf(s){let e=Tt(s);if(e)throw zn(e);return hu(On(s)),s}function Qf(s){let e=b.Buffer.from(s,"binary");return vs(hu(Ye(e)&&e.toString("utf-8")))}function Yf(s){let e=On(s);return e===!1?s:b.Buffer.from(e,"utf-8").toString("binary")}function wt(s){let e=s.server,t=ye(s,"UTF8=ACCEPT"),r=ye(s,"IMAP4rev2"),n=t||r;if(s.utf8Enabled=n,s.parserOptions.utf8=!!e.utf8Accept||r,s.compilerOptions.utf8=n,s.searchCharset=t?"UTF-8":!1,s.defaultSearchCharset=r?"UTF-8":!1,n)s.importMailboxName=Qf,s.exportMailboxName=Yf;else{let i=s;delete i.exportMailboxName,e.utf8Accept?s.importMailboxName=qf:delete i.importMailboxName}}g();function Yt(s){if(s.capabilities["LITERAL+"])throw new Error("LITERAL- can not be enabled together with LITERAL+");s.registerCapability("LITERAL-"),s.impliedLiteralMinus=!1,s.literalPlus=!0,s.nonSyncLiteralLimit=4096}var Wn="IMAP4rev2",Kf=new Set(["NEW","OLD","RECENT","UNRECENT"]),zf=new Set(["RECENT"]),Wf=new Set(["DELETED"]),$f=new Set(["RFC822","RFC822.HEADER","RFC822.TEXT"]),Jf=["$Forwarded","$MDNSent","$Junk","$NotJunk","$Phishing"],Nt=s=>!!s.imap4rev2,du=s=>s&&s.type==="ATOM"?String(s.value).toUpperCase():"";function Ws(s){s.registerCapability("IMAP4rev2"),Ne(s,Wn),!s.capabilities["LITERAL+"]&&!s.capabilities["LITERAL-"]&&(Yt(s),s.impliedLiteralMinus=!0),s.mailboxHandlers.push((a,u)=>{u.allowPermanentFlags||Jf.forEach(l=>a.ensureFlag(u.permanentFlags,l))});let e=a=>{let u=a.imap4rev2=ye(a,Wn);wt(a),a.messageGlobal=u,a.disabledSearchKeys=u?Kf:null,a.number64=a.parserOptions.number64=u,a.disabledStatusItems=u?zf:null,a.addedStatusItems=u?Wf:null,u?a.getFlags=l=>l.flags:delete a.getFlags};s.connectionHandlers.push(e),s.resetHandlers.push(e);let t=(a,u,l,c,f)=>(a.sendStatus(u,l,"BAD",f),c()),r=(a,u)=>{let l=s.getCommandHandler(a);s.setCommandHandler(a,(c,f,p,y)=>u(l,c,f,p,y))};Object.entries({CHECK:"NOOP",LSUB:"LIST (SUBSCRIBED)"}).forEach(([a,u])=>{r(a,(l,c,f,p,y)=>{if(Nt(c))return t(c,f,p,y,a+" is not part of IMAP4rev2, use "+u+" (RFC 9051 Appendix E)");l(c,f,p,y)})});let n=(a,u,l,c,f)=>{let p=(l.attributes||[])[1];if(Nt(u)&&[].concat(p||[]).some(y=>$f.has(du(y))))return t(u,l,c,f,"RFC822, RFC822.HEADER and RFC822.TEXT are not part of IMAP4rev2, use BODY[] (RFC 9051 Appendix E)");a(u,l,c,f)};r("FETCH",n),r("UID FETCH",n);let i=(a,u,l,c,f)=>{Nt(u)&&du((l.attributes||[])[0])!=="RETURN"&&(l.searchReturn=s.parseSearchReturn([],u,l)),a(u,l,c,f)};r("SEARCH",i),r("UID SEARCH",i),s.closedChecks.push(Nt);let o=(a,u,l,c)=>{let f=u.flags.concat(u["special-use"]||[]);a.send({tag:"*",command:"LIST",attributes:[f.map(p=>({type:"ATOM",value:p})),s.getSeparator(u),{type:"MAILBOX",value:u.path}]},"SELECT LIST",l,c,u)};s.outputHandlers.push((a,u,l,c,f)=>{if(l==="RECENT NOTIFICATION"&&Nt(a)){u.skipResponse=!0;return}if(!c||!u||!Nt(a))return;let p=String(c.command||"").toUpperCase();if(!(p!=="SELECT"&&p!=="EXAMINE")){if(l===p+" RECENT"||l===p+" UNSEEN"){u.skipResponse=!0;return}l===p&&u.tag===c.tag&&u.command==="OK"&&a.selectedMailbox&&o(a,a.selectedMailbox,c,f)}}),s.outputHandlers.push((a,u,l,c,f,p)=>{l==="ENABLED"&&Array.isArray(p)&&p.indexOf(Wn)>=0&&e(a)})}Ws.requires=["ENABLE","NAMESPACE","UNSELECT","UIDPLUS","ESEARCH","SEARCHRES","IDLE","SASL-IR","LIST-EXTENDED","LIST-STATUS","MOVE","BINARY","SPECIAL-USE","STATUS=SIZE","AUTH=PLAIN"];g();g();function $s(s,e){if(Object.is(s,e))return!0;if(!s||!e||typeof s!="object"||typeof e!="object"||Object.getPrototypeOf(s)!==Object.getPrototypeOf(e))return!1;if(s instanceof Map||s instanceof Set)return $s(Array.from(s),Array.from(e));let t=Object.keys(s);return t.length===Object.keys(e).length&&t.every(r=>Object.prototype.hasOwnProperty.call(e,r)&&$s(s[r],e[r]))}var Zf=s=>Array.isArray(s[0])||Array.isArray(s[1])||s.length>2;function Kt(s){let e=Ke(s);if(e.enabled)return;e.enabled=!0,s.registerCapability("LIST-EXTENDED"),e.selectionOptions.SUBSCRIBED={type:"base",returnOption:"SUBSCRIBED",includeNonExistent:!0,match:a=>!!a.subscribed},e.selectionOptions.REMOTE={type:"independent"},e.selectionOptions.RECURSIVEMATCH={type:"modifier"},e.returnOptions.SUBSCRIBED={},e.returnOptions.CHILDREN={};let t=(a,u,l,c)=>{let f=new Map;for(let p=0;p<a.length;p++){let y=a[p];if(!y||y.type!=="ATOM")throw new Error("Invalid "+l+" option");let A=y.value.toUpperCase(),m=u[A];if(!m)throw new Error("Unknown "+l+" option "+A);let h=!0;if(m.parse){if(!Array.isArray(a[p+1]))throw new Error(A+" "+l+" option requires a value");h=m.parse(a[++p],c)}else if(Array.isArray(a[p+1]))throw new Error(A+" "+l+" option takes no value");if(f.has(A)&&!$s(f.get(A),h))throw new Error(A+" "+l+" option is repeated with a different value");f.set(A,h)}return f},r=(a,u)=>{let l=new Map,c=new Map,f=0;Array.isArray(a[0])&&(l=t(a[0],e.selectionOptions,"selection",u),f++);let p=a[f],y=a[f+1],A=a.slice(f+2);if(!ue(p))throw new Error("LIST expects a reference name");if(y=Array.isArray(y)?y:[y],!y.length||!y.every(ue))throw new Error("LIST expects a mailbox pattern or a list of patterns");if(A.length){if(A.length!==2||!A[0]||A[0].type!=="ATOM"||A[0].value.toUpperCase()!=="RETURN"||!Array.isArray(A[1]))throw new Error("LIST expects RETURN and a list of return options after the patterns");c=t(A[1],e.returnOptions,"return",u)}let m=[...l.keys()].map(h=>e.selectionOptions[h].type);if(m.includes("modifier")&&!m.includes("base"))throw new Error("RECURSIVEMATCH must be used together with a selection option like SUBSCRIBED");return l.forEach((h,d)=>{let E=e.selectionOptions[d].returnOption;E&&!c.has(E)&&c.set(E,!0)}),{selection:l,reference:p.value,patterns:y.map(h=>h.value).filter(h=>h),returns:c}},n=a=>a.flags.indexOf("\\Noselect")<0,i=(a,u,l,c)=>s.listAttributes(a,{exists:u,subscribed:c.has("SUBSCRIBED")&&a.subscribed,hasChildren:l}).map(f=>({type:"ATOM",value:f})),o=s.getCommandHandler("LIST");s.setCommandHandler("LIST",(a,u,l,c)=>{let f=u.attributes||[];if(!Zf(f))return o(a,u,l,c);let p;try{p=r(f,a)}catch(H){return a.sendStatus(u,l,"BAD",H.message,!1,"INVALID COMMAND"),c()}let y=[...p.selection.keys()].map(H=>({name:H,...e.selectionOptions[H]})),A=y.filter(H=>H.match),m=y.some(H=>H.includeNonExistent),h=p.selection.has("RECURSIVEMATCH"),d=y.filter(H=>H.type==="base").map(H=>({type:"STRING",value:H.name})),E=H=>(m||n(H))&&A.every(N=>N.match(H,a)),I=s.folderCache;m&&(I=Object.assign(Object.create(null),I,s.getSubscriptionTree()));let C=new Set;return p.patterns.forEach(H=>{s.matchFolders(p.reference,H,N=>a.exportMailboxName(N),I).forEach(N=>C.add(N))}),C.forEach(H=>{let N=n(H),w=E(H),G=s.getDescendants(H.path,I),F=G.some(n),W=!1;if(h&&(W=G.some(v=>E(v)&&(w||!C.has(v)))),!(w||W||!A.length&&!N&&F))return;let L=[i(H,N,F,p.returns),s.getSeparator(H),a.exportMailboxName(H.path)];W&&L.push([{type:"STRING",value:"CHILDINFO"},d]),a.send({tag:"*",command:"LIST",attributes:L},"LIST ITEM",u,l,H),p.returns.forEach((v,V)=>{let _=e.returnOptions[V];_.onItem&&_.onItem(a,H,v,{matched:w,exists:N},u,l)})}),a.sendStatus(u,l,"OK","Completed",!1,"LIST"),c()})}g();g();var eh={MESSAGES:(s,e)=>e.messages.length,RECENT:(s,e,t)=>t.recent,UIDNEXT:(s,e)=>e.uidnext,UIDVALIDITY:(s,e)=>e.uidvalidity,UNSEEN:(s,e,t)=>t.unseen||0,DELETED:(s,e,t)=>t.flags["\\Deleted"]||0};function Js(s,e,t){if(!Array.isArray(e)||!e.length)throw new Error("Expecting a list of status items");let r=t&&t.disabledStatusItems,n=t&&t.addedStatusItems;return e.map((i,o)=>{let a=i&&i.type==="ATOM"&&i.value.toUpperCase();if(!a||s.allowedStatus.indexOf(a)<0&&!(n&&n.has(a))||r&&r.has(a))throw new Error("Invalid status element ("+(o+1)+")");return a})}function Zs(s,e,t,r,n,i){s.send(er(s,e,t,r),"STATUS",n,i)}function er(s,e,t,r){let n=s.server,i=n.getStatus(t),o=[];return r.forEach(a=>{o.push({type:"ATOM",value:a},(n.statusHandlers[a]||eh[a])(s,t,i))}),{tag:"*",command:"STATUS",attributes:[{type:"MAILBOX",value:e},o]}}function $n(s){Kt(s),s.registerCapability("LIST-STATUS"),Ke(s).returnOptions.STATUS={parse:(e,t)=>Js(s,e,t),onItem:(e,t,r,n,i,o)=>{n.matched&&n.exists&&Zs(e,t.path,t,r,i,o)}}}g();function Jn(s){if(s.capabilities["LITERAL-"]&&!s.impliedLiteralMinus)throw new Error("LITERAL+ can not be enabled together with LITERAL-");delete s.capabilities["LITERAL-"],s.registerCapability("LITERAL+"),s.literalPlus=!0,s.nonSyncLiteralLimit=1/0}g();function Zn(s){s.registerCapability("LOGINDISABLED",t=>!t.secureConnection&&t.state==="Not Authenticated");let e=s.getCommandHandler("LOGIN");s.setCommandHandler("LOGIN",(t,r,n,i)=>{if(!t.secureConnection)return t.send({tag:r.tag,command:"NO",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"PRIVACYREQUIRED"}]},{type:"TEXT",value:"Run STARTTLS first"}]},"LOGIN FAILED",r,n),i();e(t,r,n,i)})}g();var th=1e3,sh=new Set(["FETCH","UID FETCH","STORE","UID STORE","MOVE","UID MOVE","UID EXPUNGE"]),rh=new Set(["SEARCH","UID SEARCH"]),pu=new Set(["SORT","UID SORT","THREAD","UID THREAD"]);function ei(s,e){if(s.messageLimit)throw new Error(e+" can not be enabled together with "+s.messageLimit.name);let t="messageLimit"in s.options?s.options.messageLimit:th;if(!Number.isSafeInteger(t)||t<1||t>4294967295)throw new TypeError("Invalid messageLimit option, expecting a positive integer");return s.messageLimit={name:e,limit:t},t}function ti(s,e){s.appendChecks.push((t,r,n,i)=>{if(n.length<=e)return!1;if(i.command)return{code:["MESSAGELIMIT",e],text:i.command+" exceeds the limit of "+e+" messages, nothing was appended"};if(!i.move){let o=n[n.length-e].uid;return{code:["MESSAGELIMIT",e,o],text:"Too many messages to copy, try a smaller subset"}}return!1})}function si(s){let e=ei(s,"MESSAGELIMIT");s.registerCapability("MESSAGELIMIT="+e),ti(s,e);let t=a=>String(a.command||"").toUpperCase();s.rangeLimits.push((a,u,l)=>{let c=t(u);if(!sh.has(c)||u.partialFetch)return!1;let f=c==="UID EXPUNGE"?l.filter(y=>y[1].flags.indexOf("\\Deleted")>=0):l;if(f.length<=e)return!1;let p=new Set(f.slice(0,-e));return u.messageLimitUid=f[f.length-e][1].uid,u.highestFirst=!0,l.filter(y=>!p.has(y)).reverse()}),s.commandChecks.push((a,u)=>{let l=s.capabilities.PARTIAL&&u.attributes&&u.attributes[2],c=t(u);if(!Array.isArray(l)||c!=="FETCH"&&c!=="UID FETCH")return!1;let f=l.findIndex((y,A)=>!(A%2)&&y&&y.type==="ATOM"&&String(y.value).toUpperCase()==="PARTIAL"),p;try{p=f>=0&&Vt(l[f+1],!0)}catch{return!1}return p&&p.to-p.from+1>e?{command:"NO",code:["MESSAGELIMIT",e],text:c+" exceeds the limit of "+e+" messages"}:!1}),s.searchLimits.push((a,u,l)=>{let c=a._runningCommand&&a._runningCommand.parsed,f=c?t(c):"";if(u.length<=e||!rh.has(f)&&!pu.has(f))return!1;let p=u.filter(y=>mu(l,y));if(p.length<=e)return!1;if(pu.has(f)){let y=new Error(f+" exceeds the limit of "+e+" messages, narrow it down with UIDAFTER or UIDBEFORE");throw y.imapResponse="NO",y.responseCode=["MESSAGELIMIT",e],y}return c.messageLimitUid=p[p.length-e].uid,p.slice(-e)});let r=a=>{if(!Le(a))throw Q("UIDAFTER and UIDBEFORE expect a UID");return Number(a)},n=(a,u,l,c)=>u.uid>c;n.argumentTypes=()=>[r];let i=(a,u,l,c)=>u.uid<c;i.argumentTypes=()=>[r],s.searchHandlers.UIDAFTER=n,s.searchHandlers.UIDBEFORE=i;let o=(a,u,l,c,f)=>{if(c&&c.messageLimitUid&&u.tag==="*"&&u.command==="SEARCH"&&Array.isArray(u.attributes)){let m=u.attributes.filter(Array.isArray);u.attributes=u.attributes.filter(h=>!Array.isArray(h)).reverse().concat(m);return}if(!c||!c.messageLimitUid||u.tag!==c.tag)return;let p=c.messageLimitUid;if(c.messageLimitUid=!1,u.command!=="OK")return;let y={type:"SECTION",section:[{type:"ATOM",value:"MESSAGELIMIT"},e,p]},A=u.attributes||[];if(A[0]&&A[0].type==="SECTION"){a.send({tag:"*",command:"NO",attributes:[y,{type:"TEXT",value:"Only the last "+e+" messages were processed"}]},"MESSAGELIMIT",c,f);return}u.attributes=[y].concat(A)};s.once("pluginsLoaded",()=>s.outputHandlers.push(o))}function mu(s,e){return s.args.every(t=>{switch(t.key){case"AND":return mu(t,e);case"_SEQ":case"UID":return t.set.has(e);case"UIDAFTER":return e.uid>t.args[0];case"UIDBEFORE":return e.uid<t.args[0];default:return!0}})}g();var nh=64*1024,ih=100,oh=new Set(["/shared/admin"]),ah="/private/specialuse";function tr(s,e){if(typeof s!="string"||s.charAt(0)!=="/")return'Entry name must begin with "/"';if(/[^\x20-\x7f]/.test(s))return"Entry name must not contain non-ASCII or control characters";if(/[*%]/.test(s))return'Entry name must not contain "*" or "%"';if(s.indexOf("//")>=0)return'Entry name must not contain consecutive "/" characters';if(s.charAt(s.length-1)==="/")return'Entry name must not end with "/"';let t=s.toLowerCase().substr(1).split("/");return t[0]!=="private"&&t[0]!=="shared"?"Entry name must begin with /private or /shared":e&&t.length<2?"Entry name must have at least 2 components":e&&t[1]==="vendor"&&t.length<4?"Vendor entry names must have at least 4 components":!1}function uh(s,e){if(e==null)return null;if(e instanceof Uint8Array)e=b.Buffer.from(e).toString("binary");else if(typeof e=="string")/[Ā-]/.test(e)&&(e=b.Buffer.from(e,"utf-8").toString("binary"));else throw new Error("Invalid value for metadata entry "+s+", expecting a string");return e}function gu(s){return{type:"MAILBOX",value:s}}function ri(s,e){if(s.metadataState){e&&!s.metadataState.mailboxes&&(s.metadataState.mailboxes=!0,delete s.capabilities["METADATA-SERVER"],s.registerCapability("METADATA"),s.enableAvailable.splice(s.enableAvailable.indexOf("METADATA-SERVER"),1,"METADATA"));return}s.parserOptions.literal8=!0;let t=e?"METADATA":"METADATA-SERVER";s.registerCapability(t),Ne(s,t);let r=s.options,n=s.metadataState={mailboxes:e,maxSize:Number(r.metadataMaxSize)||nh,maxEntries:Number(r.metadataMaxEntries)||ih,allowPrivate:r.metadataPrivate!==!1,server:{path:"",metadata:r.metadata}},i=new WeakSet,o=h=>{if(!h.metadata)return Object.create(null);if(i.has(h.metadata))return h.metadata;let d=Object.create(null),E=h.metadata;return Object.keys(E).forEach(I=>{let C=tr(I,!0);if(C)throw new Error("Invalid metadata entry name "+JSON.stringify(I)+": "+C);let H=uh(I,E[I]);H!==null&&(d[I.toLowerCase()]=H)}),a(h,d)},a=(h,d)=>(i.add(d),h.metadata=d,d),u=h=>{let d=Object.create(null);if(h.path&&s.capabilities["SPECIAL-USE"]){let E=[].concat(h["special-use"]||[]);d[ah]=E.length?E.join(" "):null}return d},l=h=>ye(h,n.mailboxes?"METADATA":"METADATA-SERVER"),c=(h,d,E,I)=>{if(I==="")return n.server;if(!n.mailboxes)return h.sendStatus(d,E,"NO","Mailbox annotations are not supported, only server annotations"),!1;let C=h.server.getMailbox(I);return!C||C.flags.indexOf("\\NonExistent")>=0?(h.sendStatus(d,E,"NO","Mailbox does not exist","NONEXISTENT"),!1):C},f=(h,d,E,I,C)=>(h.sendStatus(d,E,"BAD",I),C());s.setCommandHandler("GETMETADATA",(h,d,E,I)=>{let C=d.attributes||[],H=Array.isArray(C[0])?1:0,N=!1,w=0;if(C.length!==H+2||!ue(C[H]))return f(h,d,E,"GETMETADATA expects options, a mailbox name and entries",I);if(H){let X=C[0];if(!X.length)return f(h,d,E,"Empty option list",I);for(let q=0;q<X.length;q+=2){let se=X[q]&&X[q].type==="ATOM"?X[q].value.toUpperCase():!1,ee=X[q+1]&&X[q+1].type==="ATOM"?X[q+1].value:!1;if(se==="MAXSIZE"){if(!Ae(ee))return f(h,d,E,"Invalid value for MAXSIZE",I);N=Number(ee)}else if(se==="DEPTH"){if(!ee||!/^(0|1|infinity)$/i.test(ee))return f(h,d,E,"Invalid value for DEPTH",I);w=ee.toLowerCase()==="infinity"?1/0:Number(ee)}else return f(h,d,E,"Unknown GETMETADATA option",I)}}let G;try{G=h.importMailboxName(C[H].value)}catch(X){return f(h,d,E,X.message,I)}let F=[].concat(C[H+1]);if(!F.length||!F.every(ue))return f(h,d,E,"GETMETADATA expects an entry name or a list of entry names",I);for(let X of F){let q=tr(X.value);if(q)return f(h,d,E,q,I)}let W=c(h,d,E,G);if(!W)return I();let x=Object.assign(Object.create(null),o(W),u(W)),L=w?Object.keys(x).filter(X=>x[X]!==null).sort():[],v=new Map;for(let X of F){let q=X.value.toLowerCase(),se=x[q]??null;(!w||se!==null)&&v.set(q,se);let ee=q+"/";L.forEach(fe=>{fe.startsWith(ee)&&(w===1/0||fe.indexOf("/",ee.length)<0)&&v.set(fe,x[fe])})}let V=-1,_=[];return v.forEach((X,q)=>{if(N!==!1&&X!==null&&X.length>N){V=Math.max(V,X.length);return}_.push({type:"ATOM",value:q},X===null?null:{type:X.indexOf("\0")>=0?"LITERAL8":"STRING",value:X})}),_.length&&h.send({tag:"*",command:"METADATA",attributes:[gu(W.path),_]},"METADATA",d,E,W),h.sendStatus(d,E,"OK","GETMETADATA completed",V>=0&&["METADATA","LONGENTRIES",V]),I()},{states:Z.AUTHENTICATED});let p=(h,d)=>{let E=s.activeConnection,I=o(h),C=u(h),H=Object.assign(Object.create(null),I),N=[];for(let[G,F]of d){if(!h.path&&E&&oh.has(G)||G in C)return{text:"The "+G+" entry is read-only",code:"CANNOT"};if(!n.allowPrivate&&G.startsWith("/private/"))return{text:"Private annotations are not supported",code:["METADATA","NOPRIVATE"]};if(F!==null&&F.length>n.maxSize)return{text:"Value of "+G+" is too large",code:["METADATA","MAXSIZE",n.maxSize]};(I[G]??null)!==F&&N.push(G),F===null?delete H[G]:H[G]=F}let w=Object.keys(H).length;return w>n.maxEntries&&w>Object.keys(I).length?{text:"Too many annotations",code:["METADATA","TOOMANY"]}:(a(h,H),N.length&&s.notify({tag:"*",command:"METADATA",attributes:[gu(h.path)].concat(N.map(G=>({type:"ATOM",value:G})))},!1,E,l),null)};s.setCommandHandler("SETMETADATA",(h,d,E,I)=>{let C=d.attributes||[];if(C.length!==2||!ue(C[0])||!Array.isArray(C[1]))return f(h,d,E,"SETMETADATA expects a mailbox name and a list of entries and values",I);let H=C[1];if(!H.length||H.length%2)return f(h,d,E,"SETMETADATA expects entry and value pairs",I);let N=new Map;for(let F=0;F<H.length;F+=2){if(!ue(H[F]))return f(h,d,E,"Entry name must be a string",I);let W=tr(H[F].value,!0);if(W)return f(h,d,E,W,I);let x=H[F+1];if(x!==null&&(!x||["STRING","LITERAL","LITERAL8"].indexOf(x.type)<0))return f(h,d,E,"Entry value must be a string, a literal, a literal8 or NIL",I);if(x&&x.type!=="LITERAL8"&&/\r(?!\n)|(?:^|[^\r])\n/.test(x.value))return f(h,d,E,"Line ends in a value must be CRLF",I);N.set(H[F].value.toLowerCase(),x?x.value:null)}let w=c(h,d,E,C[0].value);if(!w)return I();let G=p(w,N);return G?(h.sendStatus(d,E,"NO",G.text,G.code),I()):(h.sendStatus(d,E,"OK","SETMETADATA completed"),I())},{states:Z.AUTHENTICATED,mailboxArguments:[0],literal8:!0}),s.on("mailbox",h=>{if(h.type==="rename"&&h.oldPath==="INBOX"){let d=s.getMailbox("INBOX"),E=s.getMailbox(h.path);d&&E&&E!==d&&d.metadata&&a(E,Object.assign(Object.create(null),o(d)))}else if(h.type==="delete"){let d=s.getMailbox(h.path);d&&d!==h.mailbox&&delete d.metadata}}),s.on("reset",()=>{n.server={path:"",metadata:r.metadata}});let y=h=>{if(h==="")return n.server;if(!n.mailboxes)throw K("Mailbox annotations need the METADATA plugin, METADATA-SERVER has server annotations only","INVALID");return s.control.requireMailbox(h)},A=h=>{let d=o(y(h)),E={};return Object.keys(d).forEach(I=>{E[I]=b.Buffer.from(d[I],"binary").toString("utf-8")}),E},m=(h,d)=>{let E=y(h);if(!d||typeof d!="object"||Array.isArray(d))throw K("setMetadata expects an object of entry names and values (null removes an entry)","INVALID");let I=new Map;Object.keys(d).forEach(H=>{let N=d[H],w=tr(H,!0);if(w)throw K(w,"INVALID");if(N!==null&&typeof N!="string")throw K("Value of "+H+" must be a string or null","INVALID");I.set(H.toLowerCase(),N===null?null:b.Buffer.from(N,"utf-8").toString("binary"))});let C=p(E,I);if(C)throw K(C.text,typeof C.code=="string"?C.code:"INVALID");return A(h)};s.control.register("getMetadata",A,[{method:"GET",path:"/v1/metadata",summary:"Server annotations (METADATA plugins)",handler:()=>s.control.getMetadata("")},{method:"GET",path:"/v1/mailboxes/{path}/metadata",summary:"Mailbox annotations (METADATA plugin)",handler:({params:h})=>s.control.getMetadata(h.path)}]),s.control.register("setMetadata",m,[{method:"PUT",path:"/v1/metadata",summary:'Sets server annotations ({ "/shared/comment": "text" }, null removes one, METADATA plugins)',handler:({body:h})=>s.control.setMetadata("",h)},{method:"PUT",path:"/v1/mailboxes/{path}/metadata",summary:"Sets mailbox annotations (METADATA plugin)",handler:({params:h,body:d})=>s.control.setMetadata(h.path,d)}])}function sr(s){ri(s,!0)}sr.requires=["ENABLE"];g();function rr(s){ri(s,!1)}rr.requires=["ENABLE"];g();g();function ni(s,e,t,r){return ii(s,e,t,r,!1)}function ii(s,e,t,r,n){let i=n?"UID COPY":"COPY";if(!e.attributes||e.attributes.length!==2||!e.attributes[0]||["ATOM","SEQUENCE"].indexOf(e.attributes[0].type)<0||!e.attributes[1]||["ATOM","STRING","LITERAL"].indexOf(e.attributes[1].type)<0)return s.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:i+" expects sequence set and a mailbox name"}]},"INVALID COMMAND",e,t),r();let o=oi(s,e,t,n,i+" FAIL");if(!o)return r();s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:i+" Completed"}]},i,e,t,o),r()}function oi(s,e,t,r,n,i){let o=e.attributes,a=s.limitRange(e,s.getCommandRange(o[0].value,r)),u=s.getTargetMailbox(o[1].value,e,t,n);if(!u)return!1;let l=a.map(p=>p[1]);if(l.some(p=>p.ghost))return s.sendStatus(e,t,"NO","Some of the requested messages no longer exist","EXPUNGEISSUED",n),!1;if(!s.checkAppend(u,l,e,t,n,{move:!!i,source:s.selectedMailbox}))return!1;let c=[],f=[];return(e.highestFirst?l.slice().reverse():l).forEach(p=>{c.push(p.uid),f.push(s.server.copyMessage(u,p).message.uid)}),{mailbox:u,sourceUids:c,targetUids:f,messages:l}}function ai(s){s.registerCapability("MOVE");let e=function(r,n,i,o,a){function u(c){return r?"UID "+c:c}if(!i.attributes||i.attributes.length!==2||!i.attributes[0]||["ATOM","SEQUENCE"].indexOf(i.attributes[0].type)<0||!i.attributes[1]||["ATOM","STRING","LITERAL"].indexOf(i.attributes[1].type)<0)return n.send({tag:i.tag,command:"BAD",attributes:[{type:"TEXT",value:u("MOVE expects sequence set and a mailbox name")}]},"INVALID COMMAND",i,o),a();if(n.refuseReadOnly(i,o,u("MOVE FAIL")))return a();let l=oi(n,i,o,r,u("MOVE FAIL"),!0);if(!l)return a();n.send({tag:"*",command:"OK",attributes:[{type:"TEXT",value:"Copied"}],skipResponse:!0},u("MOVE COPYUID"),i,o,l),n.expungeSpecificMessages(n.selectedMailbox,l.messages,!1,!0,!!i.highestFirst),n.send({tag:i.tag,command:"OK",attributes:[{type:"TEXT",value:"Done"}]},u("MOVE OK"),i,o),a()},t={states:Z.SELECTED,mailboxArguments:[1]};s.setCommandHandler("MOVE",e.bind(null,!1),Object.assign({sequenceSet:0},t)),s.setCommandHandler("UID MOVE",e.bind(null,!0),t)}g();function ui(s){s.registerCapability("MULTIAPPEND"),s.multiAppend=!0,s.appendChecks.push((e,t,r,n)=>n.command&&r.some(i=>!i.resolve&&!i.raw.length)?{text:"Zero-length message literal, APPEND cancelled"}:!1)}g();var Eu={SELECTED:!1,INBOXES:!1,PERSONAL:!1,SUBSCRIBED:!1,SUBTREE:!0,"SUBTREE-ONE":!0,MAILBOXES:!0};function lh(s,e){if(!Array.isArray(e)||!e.length)throw Q("IN expects a parenthesized list of mailbox specifiers");let t=[];for(let r=0;r<e.length;r++){let n=e[r];if(Array.isArray(n))throw Q("Unknown ESEARCH scope option");let i=n&&n.type==="ATOM"?String(n.value).toUpperCase():"";if(!Object.hasOwn(Eu,i))throw Q("Invalid mailbox specifier"+(i?" "+n.value:""));let o={filter:i,names:[]};if(Eu[i]){let a=e[++r],u=Array.isArray(a)?a:[a];if(!u.length||!u.every(ue))throw Q(i.toLowerCase()+" expects a mailbox name or a list of mailbox names");u.forEach(l=>o.names.push(s.importMailboxName(l.value)))}t.push(o)}return t}function ch(s,e){let t=e||[];return J(t[0],"IN")?{sources:lh(s,t[1]),attributes:t.slice(2)}:{sources:null,attributes:t}}function li(s){Ie(s),s.registerCapability("MULTISEARCH");let e=o=>!!o&&o.flags.indexOf("\\Noselect")<0,t=()=>Object.keys(s.folderCache).map(a=>s.folderCache[a]).sort((a,u)=>a.path==="INBOX"?-1:u.path==="INBOX"?1:0),r=(o,a,u)=>{if(!u(o)||!a||!o.folders)return;let l=o.folders;Object.keys(l).forEach(c=>r(l[c],a-1,u))},n=(o,a)=>{let u=[],l=new Set,c=(f,p)=>{!f||l.has(f)||!e(f)||s.searchAccessChecks.every(y=>y(o,f,!!p))&&(l.add(f),u.push(f))};return a.forEach(f=>{switch(f.filter){case"SELECTED":c(o.selectedMailbox,!0);break;case"INBOXES":c(s.getMailbox("INBOX"),!1);break;case"PERSONAL":t().filter(p=>s.isPersonal(p)).forEach(p=>c(p,!1));break;case"SUBSCRIBED":t().filter(p=>p.subscribed).forEach(p=>c(p,!1));break;case"MAILBOXES":f.names.forEach(p=>c(s.getMailbox(p),!0));break;default:{let p=f.filter==="SUBTREE"?1/0:1,y=new Set;f.names.forEach(A=>{let m=s.getMailbox(A);m&&r(m,p,h=>y.has(h)?!1:(y.add(h),c(h,h===m),!0))})}}}),u},i=(o,a,u,l)=>{let c=(I,C)=>(o.sendStatus(a,u,I,C,!1,"ESEARCH FAILED"),l()),f,p=new Map,y;try{let I=ch(o,a.attributes);f=I.sources||[{filter:"SELECTED",names:[]}];let C=I.attributes;if(J(C[0],"RETURN")&&(p=a.searchReturn=s.parseSearchReturn(C[1],o,a),C=C.slice(2)),!C.length)throw Q("ESEARCH expects search criteria");y=Ot(C)}catch(I){return c("BAD",I.message)}let A=f.every(I=>I.filter==="SELECTED");if(f.some(I=>I.filter==="SELECTED")&&!o.selectedMailbox)return c("BAD","No mailbox is selected");if(p.has("SAVE")&&!A)return c("BAD","SAVE can only be used when searching the selected mailbox");if(p.has("UPDATE")&&!o.selectedMailbox)return c("BAD","UPDATE needs a selected mailbox");let m=n(o,f),h=[];try{let I=C=>{if(C&&C===o.selectedMailbox)return De(o,o.getSessionMessages(),y);let H=C?C.messages:[];return De(o,H,y,(N,w)=>s.getMessageRange(H,N,w))};m.length||I(o.selectedMailbox||null),m.forEach(C=>h.push({mailbox:C,result:I(C)}))}catch(I){return xt(o,a,u,I,"ESEARCH FAILED"),l()}let d=s.isSilentReturn(p);h.forEach(({mailbox:I,result:C})=>{!C.list.length||d||o.send(Ct(a.tag,!0,C,p,I),"ESEARCH",a,u,Object.assign({},C,{list:je(C.list,p)}))});let E=h.find(I=>I.mailbox===o.selectedMailbox);return p.has("SAVE")&&(a.searchresFound=E?je(E.result.list,p):[]),p.has("UPDATE")&&E&&s.addSearchContext(o,a,u,E.result,!0,E.mailbox),o.sendStatus(a,u,"OK","ESEARCH completed",!1,"ESEARCH"),l()};s.setCommandHandler("ESEARCH",i,{states:Z.AUTHENTICATED,searchCriteria:0}),s.connectionHandlers.push(o=>{let a=o.usesSequenceNumbers;o.usesSequenceNumbers=function(u){return(u.command||"").toUpperCase()==="ESEARCH"&&J((u.attributes||[])[0],"IN")&&(u=Object.assign({},u,{attributes:u.attributes.slice(2)})),a.call(this,u)}})}g();function ci(s){s.registerCapability("NAMESPACE"),s.setCommandHandler("NAMESPACE",(e,t,r,n)=>{let i={personal:[],user:[],shared:[]};return Object.keys(s.storage).forEach(o=>{let a=s.storage[o];o==="INBOX"||!a||Object.hasOwn(i,a.type)&&i[a.type].push([e.exportMailboxName(o),a.separator])}),e.send({tag:"*",command:"NAMESPACE",attributes:[i.personal.length?i.personal:null,i.user.length?i.user:null,i.shared.length?i.shared:null]},"NAMESPACE",t,r,i),e.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"Completed"}]},"NAMESPACE",t,r,i),n()},{states:Z.AUTHENTICATED,noArguments:!0})}g();var nr=["MessageNew","MessageExpunge","FlagChange","AnnotationChange"],fh=new Map(nr.concat(["MailboxName","SubscriptionChange","MailboxMetadataChange","ServerMetadataChange"]).map(s=>[s.toUpperCase(),s])),hh=["SELECTED","SELECTED-DELAYED"],dh=["INBOXES","PERSONAL","SUBSCRIBED","SUBTREE","MAILBOXES"],ph=["BODY","BODY.PEEK","BINARY","BINARY.PEEK","BINARY.SIZE"];function fi(s){s.registerCapability("NOTIFY");let e=x=>!!x.notifyState,t=()=>{let x=["MessageNew","MessageExpunge","FlagChange","MailboxName","SubscriptionChange"];return s.capabilities.METADATA&&x.push("MailboxMetadataChange"),(s.capabilities.METADATA||s.capabilities["METADATA-SERVER"])&&x.push("ServerMetadataChange"),x},r=(x,L,v,V)=>{let _=s.acl&&s.acl.getRights(x,L,V);return!_||[...v].every(X=>_.has(X))},n=(x,L,v)=>r(x,L,"l",v),i=(x,L,v)=>r(x,L,"lr",v),o=x=>x.toUpperCase()==="INBOX"?"INBOX":x,a=(x,L,v,V)=>{switch(x.filter){case"INBOXES":case"PERSONAL":return s.isPersonal(L);case"SUBSCRIBED":return!!V||!!(v&&v.subscribed);case"SUBTREE":return x.paths.indexOf(L)>=0||x.prefixes.some(_=>L.substr(0,_.length)===_);case"MAILBOXES":return x.paths.indexOf(L)>=0}return!1},u=(x,L,v,V)=>{let _=new Set;return x.notifyState.groups.forEach(X=>{a(X,L,v,V)&&X.events.forEach(q=>_.add(q))}),v&&v===x.selectedMailbox&&nr.forEach(X=>_.delete(X)),_},l=x=>!!(x.notifyState.selected&&x.notifyState.selected.delayed)&&!x.directNotifications&&x.hasPendingExpunge(),c=x=>{!x.socket||!x.notificationQueue.length||x._runningCommand||!e(x)||l(x)||x.processNotifications()},f=x=>{x.notifyFlushPending||(x.notifyFlushPending=!0,R(()=>{x.notifyFlushPending=!1,c(x)}))},p=(x,L)=>{let v=L;if(v.tag="*",v.notification=!0,!x._runningCommand&&l(x)){x.send(v,"NOTIFY EVENT");return}x.notificationQueue.push(v),f(x)},y=x=>[...s.connections].filter(L=>L!==x&&e(L)),A=(x,L,v,V)=>{if(v=v.slice(),V.has("FlagChange")){let _=s.getStatus(L),X=_&&_.unseen||0;x.notifyState.unseen.get(L)!==X&&(x.notifyState.unseen.set(L,X),v.push("UNSEEN"))}return s.condstore&&s.condstore.isEnabled(x)&&v.push("HIGHESTMODSEQ"),v.length?er(x,L.path,L,v):!1},m=(x,L,v,V)=>{y(V).forEach(_=>{if(x===_.selectedMailbox||!i(_,x))return;let X=u(_,x.path,x);if(!X.has(L))return;let q=A(_,x,L==="FlagChange"&&s.condstore&&s.condstore.isEnabled(_)?["UIDVALIDITY"]:v,X);q&&p(_,q)})},h=(x,L)=>s.hasDescendant(L,v=>n(x,v)&&v.flags.indexOf("\\NonExistent")<0),d=(x,L,v)=>{v=v||{};let V=s.getMailbox(L),_=v.exists!==!1&&!!V&&n(x,V),q=[s.listAttributes(_?V:null,{exists:_,subscribed:_&&V.subscribed,extra:v.noAccess?["\\NoAccess"]:[],hasChildren:h(x,L)}).map(se=>({type:"ATOM",value:se})),s.getSeparator(L),{type:"MAILBOX",value:L}];return v.oldPath&&q.push([{type:"STRING",value:"OLDNAME"},[{type:"STRING",value:x.exportMailboxName(v.oldPath)}]]),{tag:"*",command:"LIST",attributes:q}},E=(x,L,v,V)=>{[L,s.getParentPath(L)].forEach(_=>{if(!_)return;let X=_===L?v:s.getMailbox(_);u(x,_,X).has("MailboxName")&&p(x,d(x,_,_===L?{exists:V}:{}))})},I=(x,L)=>{L!==x.selectedMailbox&&i(x,L)&&u(x,L.path,L).has("FlagChange")&&p(x,A(x,L,["MESSAGES","UIDNEXT","UIDVALIDITY"],new Set(["FlagChange"])))};s.on("mailbox",x=>{let L=s.getMailbox(x.path);y(x.origin).forEach(v=>{switch(x.type){case"create":L&&n(v,L)&&(E(v,x.path,L,!0),I(v,L));break;case"delete":x.mailbox&&n(v,x.mailbox)&&E(v,x.path,L,!!L);break;case"rename":if(L&&n(v,L)){let V=u(v,x.path,L);u(v,x.oldPath).forEach(_=>V.add(_)),V.has("MailboxName")&&p(v,d(v,x.path,{oldPath:x.oldPath})),I(v,L)}break;case"subscribe":case"unsubscribe":L&&n(v,L)&&u(v,x.path,L,!0).has("SubscriptionChange")&&p(v,d(v,x.path));break}})}),s.on("acl",(x,L)=>{y(null).forEach(v=>{let V={list:n(v,x,L),read:i(v,x,L)},_={list:n(v,x),read:i(v,x)};if(V.list!==_.list)E(v,x.path,x,_.list);else if(_.list&&V.read!==_.read){let X=u(v,x.path,x);nr.some(q=>X.has(q))&&p(v,d(v,x.path,{noAccess:!_.read}))}})}),s.on("expunge",(x,L,v)=>m(x,"MessageExpunge",["MESSAGES","UIDNEXT"],v)),s.on("notify",x=>{let L=x.command||{},v=typeof x.mailbox=="string"?s.getMailbox(x.mailbox):x.mailbox;if(v&&L.flagUpdate)m(v,"FlagChange",[],x.origin);else if(v&&L.message&&J(L.attributes&&L.attributes[1],"EXISTS"))m(v,"MessageNew",["MESSAGES","UIDNEXT"],x.origin);else if(L.command==="METADATA"&&L.attributes&&L.attributes[0]){let V=L.attributes[0].value,_=V===""?null:s.getMailbox(V);y(x.origin).forEach(X=>{let q;V===""?q=X.notifyState.groups.some(se=>se.events.has("ServerMetadataChange")):q=!!_&&i(X,_)&&u(X,V,_).has("MailboxMetadataChange"),q&&(x.notifyHandled=x.notifyHandled||new Set,x.notifyHandled.add(X),p(X,Object.assign({},L)))})}}),s.notifyFilters.push((x,L)=>!(L.notifyHandled&&L.notifyHandled.has(x)));let C=x=>{if(x.flagUpdate)return"FlagChange";let L=x.attributes&&x.attributes[1];return J(L,"EXPUNGE")?"MessageExpunge":J(L,"EXISTS")?x.message?"MessageNew":"MessageExpunge":!1},H=(x,L,v,V)=>{let _=L.map(q=>Object.assign({},q)),X;try{X=Bs(x,V,_)}catch{return!1}return{tag:"*",notification:!0,attributes:[v,{type:"ATOM",value:"FETCH"},X],fetchedMessage:V}};s.connectionHandlers.push(x=>{x.notifyState=null;let L=x.queueNotification;x.queueNotification=function(v,V){let _=V&&V.mailbox&&C(v);if(!e(this)||!_||V.origin===this)return L.call(this,v,V);let X=this.notifyState.selected;if(!(!X||!X.events.has(_)||!i(this,this.selectedMailbox))){if(this.notificationQueue.push(v),_==="MessageNew"&&X.fetch){let q=H(this,X.fetch,v.attributes[0],v.message);q&&this.notificationQueue.push(q)}f(this)}}}),s.resetHandlers.push(x=>{x.notifyState=null}),s.outputHandlers.push((x,L)=>{L.tag!=="*"&&!L.notification&&e(x)&&x.notificationQueue.length&&f(x)}),s.notifyOverflow=x=>{y(null).filter(L=>!x||L===x).forEach(L=>{L.notifyState={selected:null,groups:[],unseen:new WeakMap},p(L,{command:"OK",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"NOTIFICATIONOVERFLOW"}]},{type:"TEXT",value:"Too many notifications, NOTIFY is turned off"}]})})};let N=(x,L)=>{if(!L.length)throw Q("MessageNew expects a list of fetch attributes");return L.map(v=>{let V=J(v)&&v.value.toUpperCase();if(!V||!(s.fetchHandlers[V]||Te[V]))throw Q("Invalid fetch attribute for MessageNew");if((v.section||v.partial)&&ph.indexOf(V)>=0){let _=[Object.assign({},v)];try{Bs(x,{raw:`Subject: test\r
|
|
26
26
|
\r
|
|
27
27
|
Test\r
|
|
28
|
-
`,flags:[],uid:1},G)}catch(k){throw Q(k.message)}}return B})},x=(N,D,B,V)=>{let G=new Set,k=null;if($(D,"NONE"))return{events:G,fetch:k};if(!Array.isArray(D)||!D.length)throw Q("Expecting a list of events or NONE");for(let q=0;q<D.length;q++){let tt=D[q];if(!$(tt)||tt.section||tt.partial)throw Q("Invalid event");let Z=yf.get(tt.value.toUpperCase());if(Array.isArray(D[q+1])&&Z==="MessageNew"){if(!B)throw Q("Fetch attributes for MessageNew are only allowed with SELECTED or SELECTED-DELAYED");k=M(N,D[++q])}if(!Z){V.push(tt.value);continue}if(B&&Wr.indexOf(Z)<0)throw Q(Z+" can not be used with SELECTED or SELECTED-DELAYED");G.add(Z)}if(G.has("MessageNew")!==G.has("MessageExpunge"))throw Q("MessageNew and MessageExpunge must be used together");if((G.has("FlagChange")||G.has("AnnotationChange"))&&!G.has("MessageNew"))throw Q("FlagChange and AnnotationChange require MessageNew and MessageExpunge");return{events:G,fetch:k}},_=(N,D)=>{let B=Array.isArray(D)?D:[D];if(!B.length||!B.every(at))throw Q("Expecting a mailbox name or a list of mailbox names");return B.map(V=>a(N.importMailboxName(V.value)))},X=(N,D)=>{let B={selected:null,groups:[],unseen:new WeakMap},V=[];if($(D[0],"NONE")){if(D.length!==1)throw Q("NOTIFY NONE does not take any arguments");return{state:B,status:!1,unknown:V}}if(!$(D[0],"SET"))throw Q("NOTIFY expects SET or NONE");let G=$(D[1],"STATUS"),k=D.slice(G?2:1);if(!k.length)throw Q("NOTIFY SET expects event groups");return k.forEach(q=>{if(!Array.isArray(q)||!$(q[0]))throw Q("Invalid event group");let tt=q[0].value.toUpperCase();if(Sf.indexOf(tt)>=0){if(q.length!==2)throw Q("Invalid event group");if(B.selected)throw Q("Only one of SELECTED and SELECTED-DELAYED can be used");B.selected=Object.assign({delayed:tt==="SELECTED-DELAYED"},x(N,q[1],!0,V))}else if(bf.indexOf(tt)>=0){let Z=tt==="SUBTREE"||tt==="MAILBOXES";if(q.length!==(Z?3:2))throw Q("Invalid event group");let ut=Z?_(N,q[1]):[],{events:$e}=x(N,q[q.length-1],!1,V),ps=tt==="SUBTREE"?ut.map(Oe=>Oe+r.getSeparator(Oe)):[];B.groups.push({filter:tt,paths:ut,prefixes:ps,events:$e})}else throw Q("Unknown mailbox filter "+q[0].value)}),{state:B,status:G,unknown:V}},z=(N,D,B,V)=>{Object.keys(r.folderCache).sort((k,q)=>k==="INBOX"?-1:q==="INBOX"?1:k.localeCompare(q)).forEach(k=>{let q=r.folderCache[k];if(q===N.selectedMailbox||q.flags.some(ut=>/^\\(Noselect|NonExistent)$/i.test(ut)))return;let tt=u(N,k,q);if(!tt.size||!n(N,q))return;if(!i(N,q)){N.send(d(N,k,{noAccess:!0}),"NOTIFY LIST",B,V);return}if(!D||!tt.has("MessageNew"))return;let Z=["MESSAGES","UIDNEXT","UIDVALIDITY"];if(tt.has("FlagChange")){Z.push("UNSEEN");let ut=r.getStatus(q);N.notifyState.unseen.set(q,ut&&ut.unseen||0),r.condstore&&Z.push("HIGHESTMODSEQ")}N.send(Qr(N,k,q,Z),"NOTIFY STATUS",B,V)})};r.setCommandHandler("NOTIFY",(N,D,B,V)=>{let G;try{G=X(N,D.attributes||[])}catch(Z){return N.sendStatus(D,B,"BAD",Z.imapResponse==="BAD"?Z.message:"Invalid NOTIFY arguments"),V()}let k=e(),q=[G.state.selected].concat(G.state.groups).filter(Z=>!!Z);return G.unknown.concat(...q.map(Z=>[...Z.events].filter(ut=>k.indexOf(ut)<0))).length?(N.send({tag:D.tag,command:"NO",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"BADEVENT"},k.map(Z=>({type:"ATOM",value:Z}))]},{type:"TEXT",value:"Unsupported NOTIFY events"}]},"NOTIFY FAILED",D,B),V()):(N.notifyState=G.state,z(N,G.status,D,B),N.sendStatus(D,B,"OK","NOTIFY completed"),V())},{states:J.AUTHENTICATED})}E();var Of=new TextDecoder("utf-8",{fatal:!0});function Nf(r){let t=r.toString("binary");if(t==="")return{kvsepOnly:!0};let e=t.match(/^(?:F,)?(n|y|p=[A-Za-z0-9.-]+),(?:a=([^,]+))?,/);if(!e||t.charAt(e[0].length)!=="")return{error:"Invalid GS2 header"};let s=!1;if(e[2]){if(/=(?!2C|3D)/.test(e[2])||e[2].includes("\0"))return{error:"Invalid authorization identity"};try{s=Of.decode(I.Buffer.from(e[2].replace(/=2C/g,",").replace(/=3D/g,"="),"binary"))}catch{return{error:"Invalid UTF-8 in the authorization identity"}}}let n=t.substr(e[0].length+1).split("");if(n.pop()!==""||n.pop()!=="")return{error:"The client response must end with %x01"};let i=Object.create(null);for(let a of n){let o=a.match(/^([A-Za-z]+)=([\x20-\x7e\t\r\n]*)$/);if(!o)return{error:"Invalid key/value pair"};i[o[1]]=o[2]}return{channelBinding:e[1].charAt(0)==="p",authzid:s,pairs:i}}function Jn(r){r.registerCapability("AUTH=OAUTHBEARER",a=>a.state==="Not Authenticated");let t=(a,o,u,l,c)=>{a.sendStatus(o,u,l,c,l==="NO"&&"AUTHENTICATIONFAILED","AUTHENTICATE OAUTHBEARER FAILED")},e=a=>{if(a.channelBinding)return"invalid_request";let{auth:o,port:u}=a.pairs;if(typeof u=="string"&&!/^[1-9][0-9]*$/.test(u))return"invalid_request";let l=typeof o=="string"&&o.match(/^Bearer +([A-Za-z0-9\-._~+/]+=*)$/i);if(!l)return o===""?"invalid_token":"invalid_request";let c=l[1],h=a.authzid;h===!1&&(h=Object.keys(r.users).find(T=>{let A=r.users[T];return A&&A.xoauth2&&A.xoauth2.accessToken===c}));let m=r.getUser(h);return!m||!m.xoauth2||m.xoauth2.accessToken!==c?"invalid_token":(a.username=h,!1)},s=(a,o,u,l)=>{let c=a.decodeSaslResponse(l);return c||t(a,o,u,"BAD","Invalid base64 in SASL response"),c},n=(a,o,u,l)=>{a.inputHandler=c=>{if(a.inputHandler=!1,c==="*")return t(a,o,u,"BAD","Authentication cancelled");let h=s(a,o,u,c);h&&l(h)}},i=(a,o,u,l)=>{let c=Nf(l);if(c.error)return t(a,o,u,"BAD",c.error+" in the OAUTHBEARER client response");if(c.kvsepOnly)return t(a,o,u,"NO","SASL authentication failed");let h=e(c);if(!h)return a.state="Authenticated",a.username=c.username,a.sendStatus(o,u,"OK","SASL authentication succeeded",!1,"AUTHENTICATE OAUTHBEARER SUCCESS");n(a,o,u,m=>{if(m.toString("binary")!=="")return t(a,o,u,"BAD","The client must answer the error result with a single %x01 (RFC 7628 section 3.2.3)");t(a,o,u,"NO","SASL authentication failed")}),a.send({tag:"+",attributes:[{type:"ATOM",value:I.Buffer.from(JSON.stringify({status:h})).toString("base64")}]},"AUTHENTICATE OAUTHBEARER CHALLENGE",o,u)};r.setCommandHandler("AUTHENTICATE OAUTHBEARER",(a,o,u,l)=>{let c=o.attributes||[];if(!c.length)return n(a,o,u,m=>i(a,o,u,m)),a.sendContinuation("","AUTHENTICATE OAUTHBEARER"),l();if(c.length!==1||!c[0]||c[0].type!=="ATOM")return t(a,o,u,"BAD","Invalid arguments for AUTHENTICATE OAUTHBEARER"),l();if(!r.capabilities["SASL-IR"]||!r.capabilities["SASL-IR"](a))return t(a,o,u,"BAD","SASL-IR must be enabled to send Initial Response with the request"),l();let h=s(a,o,u,c[0].value);return h&&i(a,o,u,h),l()})}E();var jo=/^[A-Za-z0-9_-]{1,255}$/,Cf=/^Message-ID[ \t]*:(.*)$/im,xf=/^References[ \t]*:(.*)$/im,Mf=/^In-Reply-To[ \t]*:(.*)$/im,$r=Symbol("mailboxid-uidvalidity");function Zn(r){r.registerCapability("OBJECTID");let t=new Map,e={F:0,M:0,T:0},s=new Map,n=new Map,i=new Map,a=A=>{let p;do p=A+ ++e[A];while(t.has(p));return t.set(p,A),p},o=(A,p,f)=>{if(typeof A!="string"||!jo.test(A))throw new Error("Invalid "+p+" value "+JSON.stringify(A)+" in "+f)},u=(A,p)=>{if(t.has(A)&&t.get(A)!==p)throw new Error("Object identifier "+JSON.stringify(A)+" is already used for another kind of object");t.set(A,p)},l=A=>{if(A[$r]===A.uidvalidity&&s.get(A.MAILBOXID)===A)return A.MAILBOXID;let p;return A.MAILBOXID&&A[$r]===void 0&&!s.has(A.MAILBOXID)?(p=A.MAILBOXID,o(p,"MAILBOXID","mailbox "+A.path),u(p,"F")):p=a("F"),A.MAILBOXID=p,A[$r]=A.uidvalidity,s.set(p,A),p};r.mailboxHandlers.push((A,p)=>{if(!(p.flags.indexOf("\\Noselect")>=0)){if(p.MAILBOXID&&p[$r]===void 0&&s.has(p.MAILBOXID))throw new Error("Duplicate MAILBOXID value "+JSON.stringify(p.MAILBOXID)+" in mailbox "+p.path);l(p)}}),r.control.mailboxInfoHandlers.push((A,p)=>{A.flags.indexOf("\\Noselect")<0&&(p.mailboxId=l(A))}),r.control.messageInfoHandlers.push((A,p)=>{p.emailId=A.EMAILID,p.threadId=A.THREADID}),r.messageHandlers.push((A,p,f)=>{let d="a message of mailbox "+f.path;p.EMAILID?(o(p.EMAILID,"EMAILID",d),u(p.EMAILID,"M")):p.EMAILID=a("M"),p.THREADID&&(o(p.THREADID,"THREADID",d),u(p.THREADID,"T"));let g=n.get(p.EMAILID);if(g&&p.THREADID&&p.THREADID!==g)throw new Error("Messages with EMAILID "+JSON.stringify(p.EMAILID)+" must have the same THREADID");let b=wf(p.raw);p.THREADID=p.THREADID||g||c(b.references)||a("T"),n.set(p.EMAILID,p.THREADID),[b.messageId].concat(b.references).forEach(C=>{C&&!i.has(C)&&i.set(C,p.THREADID)})});let c=A=>{for(let p=A.length-1;p>=0;p--)if(i.has(A[p]))return i.get(A[p]);return!1};r.copyHandlers.push((A,p,f)=>{p.EMAILID&&(f.EMAILID=p.EMAILID,f.THREADID=p.THREADID)}),r.allowedStatus.push("MAILBOXID"),r.statusHandlers.MAILBOXID=(A,p)=>[{type:"ATOM",value:l(p)}],r.fetchHandlers.EMAILID=(A,p)=>[{type:"ATOM",value:p.EMAILID}],r.fetchHandlers.THREADID=(A,p)=>[{type:"ATOM",value:p.THREADID}];let h=A=>{if(!jo.test(A))throw Q("Invalid object identifier");return A},m=A=>{let p=(f,d,g,b)=>d[A]===b;p.argumentTypes=()=>[h],r.searchHandlers[A]=p};m("EMAILID"),m("THREADID");let T=A=>({type:"SECTION",section:[{type:"ATOM",value:"MAILBOXID"},[{type:"ATOM",value:l(A)}]]});r.outputHandlers.push((A,p,f,d,g,b)=>{if(f==="CREATE"&&p.command==="OK"&&b){p.attributes=[T(b)].concat(p.attributes||[]);return}(f==="SELECT"||f==="EXAMINE")&&d&&p.tag===d.tag&&p.command==="OK"&&A.selectedMailbox&&A.send({tag:"*",command:"OK",attributes:[T(A.selectedMailbox),{type:"TEXT",value:"Ok"}]},f+" MAILBOXID",d,g)})}function wf(r){r=r||"";let t=r.search(/\r?\n\r?\n/),e=(t>=0?r.substr(0,t):r).replace(/\r?\n(?=[ \t])/g,""),s=n=>{let i=e.match(n);return i?i[1].match(/<[^<>\s]+>/g)||[]:[]};return{messageId:s(Cf)[0]||!1,references:s(xf).concat(s(Mf))}}E();var Df=r=>!!r&&r.type==="ATOM"&&String(r.value).toUpperCase()==="PARTIAL";function ti(r){yt(r),r.registerCapability("PARTIAL"),r.partialRangeLast=!0,vr(r);let t=(e,s,n,i,a)=>{let o=n.attributes&&n.attributes[2];if(Array.isArray(o)){for(let u=0;u<o.length;u+=2)if(Df(o[u])){try{if(n.partialFetch)throw new Error("PARTIAL can be used only once");n.partialFetch=Fe(o[u+1],!0)}catch(l){return s.sendStatus(n,i,"BAD",l.message,!1,(n.command||"").toUpperCase()+" FAILED"),a()}o.splice(u,2),u-=2}o.length||n.attributes.splice(2,1)}e(s,n,i,a)};["FETCH","UID FETCH"].forEach(e=>{let s=r.getCommandHandler(e);r.setCommandHandler(e,(n,i,a,o)=>t(s,n,i,a,o))}),r.fetchFilters.unshift((e,s,n)=>{if(!n.partialFetch)return!0;if(!n.partialFetchSet){let i=(n.command||"").toUpperCase()==="UID FETCH",a=e.getMessageRange(n.attributes[0].value,i).map(o=>o[1]);n.partialFetchSet=new Set(Hr(a,n.partialFetch))}return n.partialFetchSet.has(s)})}E();function si(r){r.registerCapability("PREVIEW");let t=new WeakMap,e=s=>{if(typeof s.preview=="string")return Ko(s.preview,Rf);let n=t.get(s);return n&&n.source===s.raw?n.preview:void 0};r.fetchHandlers.PREVIEW=function(s,n,i){let a=e(n);if(a===void 0){if(i.previewLazy)return null;a=Bf(rt(n).tree),t.set(n,{source:n.raw,preview:a})}return I.Buffer.from(a,"utf8").toString("binary")},["FETCH","UID FETCH"].forEach(s=>{let n=r.getCommandHandler(s);r.setCommandHandler(s,(i,a,o,u)=>{try{Uf(a)}catch(l){return i.sendStatus(a,o,"BAD",l.message,!1,"PREVIEW FAILED"),u()}n(i,a,o,u)})})}var Lf=200,Rf=256,ei=64*1024,Yo=r=>Array.isArray(r)&&r.length>0&&r.every(t=>$(t,"LAZY"));function Vo(r,t){if(!t.length)throw new Error("PREVIEW modifier list can not be empty");if(!Yo(t))throw new Error("Unknown PREVIEW modifier");return Object.assign({},r,{previewLazy:!0})}function Uf(r){let t=r.attributes;if(!Array.isArray(t))return;let e=t[1];if(Array.isArray(e)){for(let s=e.length-2;s>=0;s--)$(e[s],"PREVIEW")&&Array.isArray(e[s+1])&&(e[s]=Vo(e[s],e[s+1]),e.splice(s+1,1));return}$(e,"PREVIEW")&&Array.isArray(t[2])&&(t.length>3||Yo(t[2]))&&(t[1]=Vo(e,t[2]),t.splice(2,1))}function Bf(r){let t=ri(r);if(!t)return"";let e=Hf(t);return e===!1?"":Ko(t.parsedHeader["content-type"].subtype==="html"?Gf(e):Ff(e),Lf)}function ri(r){let{type:t,subtype:e}=r.parsedHeader["content-type"],s=r.parsedHeader["content-disposition"];if(s&&s.type==="attachment")return!1;if(t==="multipart"){if(e==="encrypted")return!1;let n=te(r)||[];if(e==="alternative"){let i=n.map(ri).filter(a=>!!a);return i.find(a=>a.parsedHeader["content-type"].subtype==="plain")||i[0]||!1}for(let i of n){let a=ri(i);if(a)return a}return!1}return t==="text"&&(e==="plain"||e==="html")?r:!1}function Hf(r){let t=String(r.parsedHeader["content-transfer-encoding"]||"7bit").toLowerCase(),e=r.body,s;switch(t){case"7bit":case"8bit":case"binary":s=I.Buffer.from(e.slice(0,ei),"binary");break;case"base64":s=I.Buffer.from(e.slice(0,ei*4/3),"base64");break;case"quoted-printable":s=vf(e.slice(0,ei));break;default:return!1}let n=String(r.parsedHeader["content-type"].params.charset||"").trim().toLowerCase(),i;if(n&&!["us-ascii","ascii"].includes(n))try{i=new TextDecoder(n)}catch{}return(i||new TextDecoder("utf-8")).decode(s)}function vf(r){let t=r.split(`\r
|
|
29
|
-
`).map(
|
|
30
|
-
`).replace(/=\r\n/g,"").replace(/=([0-9A-Fa-f]{2})/g,(
|
|
31
|
-
`);return t.trim()?t:r}var Pf=new Set(["a","abbr","b","bdi","bdo","big","cite","code","del","dfn","em","font","i","ins","kbd","mark","q","s","samp","small","span","strike","strong","sub","sup","time","tt","u","var","wbr"]),Xf="nbsp iexcl cent pound curren yen brvbar sect uml copy ordf laquo not shy reg macr deg plusmn sup2 sup3 acute micro para middot cedil sup1 ordm raquo frac14 frac12 frac34 iquest Agrave Aacute Acirc Atilde Auml Aring AElig Ccedil Egrave Eacute Ecirc Euml Igrave Iacute Icirc Iuml ETH Ntilde Ograve Oacute Ocirc Otilde Ouml times Oslash Ugrave Uacute Ucirc Uuml Yacute THORN szlig agrave aacute acirc atilde auml aring aelig ccedil egrave eacute ecirc euml igrave iacute icirc iuml eth ntilde ograve oacute ocirc otilde ouml divide oslash ugrave uacute ucirc uuml yacute thorn yuml",qo=Object.assign(Object.fromEntries(Xf.split(" ").map((r,t)=>[r,String.fromCharCode(160+t)])),{amp:"&",lt:"<",gt:">",quot:'"',apos:"'",trade:"\u2122",hellip:"\u2026",mdash:"\u2014",ndash:"\u2013",lsquo:"\u2018",rsquo:"\u2019",ldquo:"\u201C",rdquo:"\u201D",bull:"\u2022",euro:"\u20AC",zwnj:"\u200C",zwj:"\u200D"});function Gf(r){r=r.replace(/<!--[\s\S]*?(?:-->|$)/g," ").replace(/<(head|script|style|title|template)\b[^<>]*>[\s\S]*?(?:<\/\1\s*>|$)/gi," ");let t=Qo(_f(r));return t.trim()?t:Qo(r)}function _f(r){let t=/<(\/?)blockquote\b[^<>]*>?/gi,e="",s=0,n=0,i;for(;i=t.exec(r);)s||(e+=r.slice(n,i.index)+" "),s=i[1]?Math.max(s-1,0):s+1,n=t.lastIndex;return s?e:e+r.slice(n)}function Qo(r){return r.replace(/<!\[CDATA\[([\s\S]*?)(?:\]\]>|$)/g,"$1").replace(/<\/?([A-Za-z][A-Za-z0-9-]*)(?![A-Za-z0-9-])[^<>]*>|<[!?][^<>]*>/g,(t,e)=>e&&Pf.has(e.toLowerCase())?"":" ").replace(/&(#[0-9]+|#[xX][0-9A-Fa-f]+|[A-Za-z][A-Za-z0-9]*);/g,(t,e)=>{if(e[0]==="#"){let s=/^#x/i.test(e)?parseInt(e.slice(2),16):parseInt(e.slice(1),10);return s>0&&s<=1114111&&(s<55296||s>57343)?String.fromCodePoint(s):"\uFFFD"}return Object.hasOwn(qo,e)?qo[e]:t})}function Ko(r,t){let e=r.replace(/[^\P{Cc}\t\n\v\f\r]|\u00ad/gu,"").replace(/[\s\u200b]+/g," ").trim();return Array.from(e).slice(0,t).join("").trimEnd()}E();E();function Jr(r){let t=!!r.message&&!!r.attributes&&r.attributes[1];return!!t&&t.type==="ATOM"&&String(t.value).toUpperCase()==="EXPUNGE"}function Zr(r){if(!r.some(Jr))return r;let t=[];return r.forEach(e=>{Jr(e)?Array.isArray(t[t.length-1])?t[t.length-1].push(e.message):t.push([e.message]):t.push(e)}),t.map(e=>Array.isArray(e)?{tag:"*",command:"VANISHED",attributes:[{type:"SEQUENCE",value:se(e.map(s=>s.uid))}],notification:!0,messages:e}:e)}var kf=new Set(["EXPUNGE","UID EXPUNGE","MOVE","UID MOVE","REPLACE","UID REPLACE"]);function ts(r){r.registerCapability("QRESYNC"),Nt(r,"QRESYNC"),r.resetHandlers.push(p=>{p.qresyncExpunged=!1});let t=new WeakMap,e=p=>Et(p,"QRESYNC"),{isEnabled:s,getHighestModseq:n}=r.condstore,i=(p,f)=>((!p.qresyncExpunged||p.qresyncExpunged.uidvalidity!==p.uidvalidity)&&(p.qresyncExpunged={uidvalidity:p.uidvalidity,since:f||n(p),list:[]}),p.qresyncExpunged),a=r.indexFolders;r.indexFolders=function(...p){let f=a.apply(this,p);return Object.keys(this.folderCache).forEach(d=>i(this.folderCache[d])),f},r.on("expunge",(p,f,d)=>{let g=n(p),b=i(p,g-1).list;f.forEach(C=>{let v=b[b.length-1];v&&v.modseq===g&&v.to+1===C.uid?v.to=C.uid:b.push({from:C.uid,to:C.uid,modseq:g}),t.set(C,g)}),d&&(d.qresyncExpunged=!0)});let o=(p,f,d,g,b)=>{let{since:C,list:v}=i(p),M;return g>=C?M=zo(ii(v.filter(x=>x.modseq>g).map(x=>[x.from,x.to])),d):M=zo(d,[[(b||0)+1,p.uidnext-1]]),Vf(M,f).map(x=>x[0]===x[1]?String(x[0]):x[0]+":"+x[1]).join(",")},u=(p,f,d,g,b)=>(p.sendStatus(f,d,"BAD",b,!1,"QRESYNC FAILED"),g()),l=(p,f)=>{let d=r.getCommandHandler(p);d&&r.setCommandHandler(p,(g,b,C,v)=>f(d,g,b,C,v))},c=(p,f,d,g,b)=>{let C=d.attributes&&d.attributes[1],v=_=>$(_,"QRESYNC"),M=Array.isArray(C)?C.findIndex(v):-1;if(M<0)return p(f,d,g,b);if(!e(f))return u(f,d,g,b,"QRESYNC parameter requires ENABLE QRESYNC");if(C.findLastIndex(v)!==M)return u(f,d,g,b,"QRESYNC parameter can be used only once");let x;try{x=qf(C[M+1])}catch(_){return u(f,d,g,b,_.message)}C.splice(M,2),C.length||d.attributes.splice(1,1),d.qresync=x,p(f,d,g,b)};l("SELECT",c),l("EXAMINE",c);let h=(p,f,d,g,b,C)=>{let v=g.attributes&&g.attributes[2],M=_=>$(_,"VANISHED"),x=Array.isArray(v)?v.findIndex(M):-1;if(x<0)return f(d,g,b,C);if(!p)return u(d,g,b,C,"VANISHED is only allowed with UID FETCH");if(!e(d))return u(d,g,b,C,"VANISHED requires ENABLE QRESYNC");if(v.findLastIndex(M)!==x)return u(d,g,b,C,"VANISHED can be used only once");if(!v.some(_=>$(_,"CHANGEDSINCE")))return u(d,g,b,C,"VANISHED requires CHANGEDSINCE");v.splice(x,1),g.qresyncVanished=!0,f(d,g,b,C)};l("FETCH",h.bind(null,!1)),l("UID FETCH",h.bind(null,!0)),r.connectionHandlers.push(p=>{let f=p.prepareNotifications;p.prepareNotifications=function(d){return d=f.call(this,d),e(this)?Zr(d):d}});let m=(p,f,d,g)=>{f&&p.send({tag:"*",command:"VANISHED",attributes:[[{type:"ATOM",value:"EARLIER"}],{type:"SEQUENCE",value:f}]},"VANISHED EARLIER",d,g)},T=(p,f,d)=>{let g=p.selectedMailbox,b=f.qresync;if(b.uidvalidity!==g.uidvalidity)return;let C=b.knownUids||(g.uidnext>1?[[1,g.uidnext-1]]:[]),v=0;if(b.seqMatch){let x=Wo(b.seqMatch.uids);for(let _ of Wo(b.seqMatch.sequences)){let X=x.next().value,z=g.messages[_-1];if(!z||z.uid!==X)break;v=X}}m(p,o(g,g.messages,C,b.modseq,v),f,d);let M=r.fetchHandlers.FLAGS||At.FLAGS;g.messages.forEach((x,_)=>{x.MODSEQ<=b.modseq||!Qf(C,x.uid)||p.send({tag:"*",attributes:[_+1,{type:"ATOM",value:"FETCH"},[{type:"ATOM",value:"UID"},x.uid,{type:"ATOM",value:"FLAGS"},M(p,x,{type:"ATOM",value:"FLAGS"}),{type:"ATOM",value:"MODSEQ"},[x.MODSEQ]]]},"QRESYNC FETCH",f,d,x)})},A=p=>({type:"SECTION",section:[{type:"ATOM",value:"HIGHESTMODSEQ"},p]});r.outputHandlers.push((p,f,d,g,b)=>{if(!g||!f||f.tag==="+")return;let C=f.tag!=="*"&&f.tag===g.tag;if(g.qresyncVanished&&(f.tag==="*"&&d==="UID FETCH"||C&&f.command==="OK")){g.qresyncVanished=!1;let M=p.selectedMailbox,x=jf(g.attributes[0].value,M.uidnext-1);x&&m(p,o(M,p.getSessionMessages(),x,g.changedsince),g,b);return}if(!C)return;if(g.qresync&&f.command==="OK"&&(d==="SELECT"||d==="EXAMINE")&&p.selectedMailbox){T(p,g,b);return}let v=p.qresyncExpunged;if(p.qresyncExpunged=!1,v&&f.command==="OK"&&kf.has(String(g.command).toUpperCase())&&p.selectedMailbox&&s(p)){f.attributes&&f.attributes[0]&&f.attributes[0].type==="SECTION"||(f.attributes=[A(n(p.selectedMailbox))].concat(f.attributes||[]));return}if(s(p)){let M=0;p.notificationQueue.forEach(x=>{let _=Jr(x)&&x.message&&t.get(x.message);_&&(!M||_<M)&&(M=_)}),M>1&&p.send({tag:"*",command:"OK",attributes:[A(M-1),{type:"TEXT",value:"Expunges not reported yet"}]},"QRESYNC HIGHESTMODSEQ",g,b)}})}function ni(r,t){if(!r||Array.isArray(r)||["ATOM","SEQUENCE"].indexOf(r.type)<0||!mr(r.value,!0))throw new Error("Invalid QRESYNC "+t+', a sequence set without "*" expected');return r.value.split(",").map(e=>{let s=e.split(":").map(Number);return[s[0],s.length>1?s[1]:s[0]]})}function jf(r,t){return/^[\d*:,]+$/.test(String(r))?ii(String(r).split(",").map(e=>e.split(":").map(s=>s==="*"?t:Number(s)))):!1}function zo(r,t){let e=[],s=0,n=0;for(;s<r.length&&n<t.length;){let i=Math.max(r[s][0],t[n][0]),a=Math.min(r[s][1],t[n][1]);i<=a&&e.push([i,a]),r[s][1]<t[n][1]?s++:n++}return e}function Vf(r,t){let e=[],s=0;return r.forEach(([n,i])=>{let a=n;for(;s<t.length&&t[s].uid<n;)s++;for(;s<t.length&&t[s].uid<=i;s++)t[s].uid>a&&e.push([a,t[s].uid-1]),a=t[s].uid+1;a<=i&&e.push([a,i])}),e}function ii(r){let t=r.map(s=>[Math.min(...s),Math.max(...s)]).sort((s,n)=>s[0]-n[0]),e=[];return t.forEach(s=>{let n=e[e.length-1];n&&s[0]<=n[1]+1?n[1]=Math.max(n[1],s[1]):e.push(s)}),e}function*Wo(r){for(let[t,e]of r)for(let s=t;s<=e;s++)yield s}function $o(r,t){let e=0,s=0;return r.forEach(([n,i])=>{if(n>i||n<=e)throw new Error("Invalid QRESYNC "+t+", numbers must be in ascending order");e=i,s+=i-n+1}),s}function qf(r){if(!Array.isArray(r)||r.length<2||r.length>4)throw new Error("QRESYNC expects (uidvalidity modseq [known-uids] [(known-sequence-set known-uid-set)])");let[t,e]=r;if(!$(t)||!Mt(t.value))throw new Error("Invalid QRESYNC uidvalidity, a non-zero number expected");if(!$(e)||!mt(e.value,Ft)||BigInt(e.value)<1n)throw new Error("Invalid QRESYNC mod-sequence, a positive number expected");let s={uidvalidity:Number(t.value),modseq:Number(e.value),knownUids:!1,seqMatch:!1},n=r.slice(2);if(n.length&&!Array.isArray(n[0])&&(s.knownUids=ii(ni(n.shift(),"known-uids"))),n.length){let i=n.shift();if(!Array.isArray(i)||i.length!==2||n.length)throw new Error("Invalid QRESYNC parameters, (known-sequence-set known-uid-set) expected last");let a=ni(i[0],"known-sequence-set"),o=ni(i[1],"known-uid-set"),u=$o(a,"known-sequence-set");if($o(o,"known-uid-set")!==u)throw new Error("Invalid QRESYNC sets, known-sequence-set and known-uid-set must have as many numbers");s.seqMatch={sequences:a,uids:o}}return s}function Qf(r,t){return r.some(e=>t>=e[0]&&t<=e[1])}ts.requires=["ENABLE","CONDSTORE"];E();var be=["STORAGE","MESSAGE","MAILBOX"],Yf="User quota";function ai(r){let t=r.options.quota||{},e={name:typeof t.root=="string"?t.root:Yf,soft:!!t.soft,limits:{}},s={};be.forEach(f=>{if(t[f]===void 0||t[f]===null)return;let d=Number(t[f]);if(!Number.isSafeInteger(d)||d<0)throw new Error("Invalid quota limit for "+f+": "+JSON.stringify(t[f]));s[f]=d});let n=()=>{e.limits=Object.assign({},s)};n(),r.on("reset",n),r.registerCapability("QUOTA"),be.forEach(f=>r.registerCapability("QUOTA=RES-"+f)),r.registerCapability("QUOTASET");let i=f=>r.isPersonal(f),a=f=>f.flags.indexOf("\\Noselect")<0,o=f=>f.reduce((d,g)=>d+Ue(g.raw).length,0),u=()=>{let f={MESSAGE:0,MAILBOX:0,bytes:0};return Object.keys(r.folderCache).forEach(d=>{let g=r.folderCache[d];!a(g)||!i(g)||(f.MAILBOX++,f.MESSAGE+=g.messages.length,f.bytes+=o(g.messages))}),f},l=(f,d,g)=>{let b=u();b.STORAGE=Math.ceil(b.bytes/1024);let C=[];be.forEach(v=>{v in e.limits&&C.push({type:"ATOM",value:v},b[v],e.limits[v])}),f.send({tag:"*",command:"QUOTA",attributes:[{type:"STRING",value:e.name},C]},"QUOTA",d,g)},c=f=>{if(!(f.MESSAGE&&"MESSAGE"in e.limits||f.bytes&&"STORAGE"in e.limits||f.MAILBOX&&"MAILBOX"in e.limits))return;let g=u();if(f.MESSAGE&&"MESSAGE"in e.limits&&g.MESSAGE+f.MESSAGE>e.limits.MESSAGE||f.bytes&&"STORAGE"in e.limits&&g.bytes+f.bytes>e.limits.STORAGE*1024||f.MAILBOX&&"MAILBOX"in e.limits&&g.MAILBOX+f.MAILBOX>e.limits.MAILBOX)return e.soft?{code:"OVERQUOTA",text:"Soft quota has been exceeded",soft:!0}:{code:"OVERQUOTA",text:"Quota exceeded"}};r.appendChecks.push((f,d,g,b)=>{if(!g.length||!i(d)||b.move&&b.source&&i(b.source))return;let C={MESSAGE:g.length,bytes:o(g)};return b.replaced&&f&&f.selectedMailbox&&i(f.selectedMailbox)&&(C.MESSAGE--,C.bytes-=o([b.replaced])),c(C)});let h=f=>{let d=r.getMailbox(r.stripSeparator(f,r.getSeparator(f))),g=!d||!a(d)?1:0;for(let b=r.getParentPath(f);b;b=r.getParentPath(b))r.getMailbox(b)||g++;return g},m=(f,d)=>{let g=r.getCommandHandler(f);r.setCommandHandler(f,(b,C,v,M)=>{let x=d(C.attributes);if(typeof x=="string"&&x.toUpperCase()!=="INBOX"&&i(x)&&!b.applyChecks([c({MAILBOX:h(x)})],C,v,f+" FAILED"))return M();g(b,C,v,M)})},T=(f,d)=>at((f||[])[d])&&f[d].value;m("CREATE",f=>f&&f.length===1?T(f,0):!1),m("RENAME",f=>{let d=T(f,0);return f&&f.length===2&&typeof d=="string"&&d.toUpperCase()==="INBOX"?T(f,1):!1}),r.setCommandHandler("GETQUOTA",(f,d,g,b)=>!d.attributes||d.attributes.length!==1||!at(d.attributes[0])?(f.sendStatus(d,g,"BAD","GETQUOTA expects a quota root name"),b()):d.attributes[0].value!==e.name?(f.sendStatus(d,g,"NO","Quota root does not exist","NONEXISTENT"),b()):(l(f,d,g),f.sendStatus(d,g,"OK","GETQUOTA completed"),b()),{states:J.AUTHENTICATED,astringArguments:[0]}),r.setCommandHandler("GETQUOTAROOT",(f,d,g,b)=>{if(!d.attributes||d.attributes.length!==1||!at(d.attributes[0]))return f.sendStatus(d,g,"BAD","GETQUOTAROOT expects a mailbox name"),b();let C=d.attributes[0].value;C.toUpperCase()==="INBOX"&&(C="INBOX");let v=i(C);return f.send({tag:"*",command:"QUOTAROOT",attributes:[{type:"MAILBOX",value:C}].concat(v?{type:"STRING",value:e.name}:[])},"QUOTAROOT",d,g),v&&l(f,d,g),f.sendStatus(d,g,"OK","GETQUOTAROOT completed"),b()},{states:J.AUTHENTICATED,mailboxArguments:[0]}),r.setCommandHandler("SETQUOTA",(f,d,g,b)=>{let C=d.attributes&&d.attributes[1];if(!d.attributes||d.attributes.length!==2||!at(d.attributes[0])||!Array.isArray(C)||C.length%2)return f.sendStatus(d,g,"BAD","SETQUOTA expects a quota root name and a list of resource limits"),b();let v={};for(let M=0;M<C.length;M+=2){let x=C[M],_=C[M+1];if(!x||x.type!=="ATOM"||!_||_.type!=="ATOM"||!mt(_.value,Ft))return f.sendStatus(d,g,"BAD","Invalid resource limit"),b();let X=x.value.toUpperCase();if(be.indexOf(X)<0||X in v)return f.sendStatus(d,g,"NO","Can not set a limit for "+X,"CANNOT"),b();let z=Number(_.value);if(!Number.isSafeInteger(z))return f.sendStatus(d,g,"NO","Limit is too large for "+X,"LIMIT"),b();v[X]=z}return d.attributes[0].value!==e.name?(f.sendStatus(d,g,"NO","Quota root does not exist","NONEXISTENT"),b()):(e.limits=v,l(f,d,g),f.sendStatus(d,g,"OK","SETQUOTA completed"),b())},{states:J.AUTHENTICATED,astringArguments:[0]}),["DELETED","DELETED-STORAGE"].forEach(f=>{r.allowedStatus.indexOf(f)<0&&r.allowedStatus.push(f)}),r.statusHandlers["DELETED-STORAGE"]=(f,d)=>o(d.messages.filter(g=>g.flags.indexOf("\\Deleted")>=0));let A=()=>{let f=u();return{root:e.name,limits:Object.assign({},e.limits),usage:{STORAGE:Math.ceil(f.bytes/1024),MESSAGE:f.MESSAGE,MAILBOX:f.MAILBOX}}},p=f=>{if(!f||typeof f!="object"||Array.isArray(f))throw K("setQuota expects an object of resource limits, e.g. { STORAGE: 1024 }","INVALID");let d={};return Object.keys(f).forEach(g=>{let b=g.toUpperCase(),C=f[g];if(be.indexOf(b)<0)throw K("Unknown quota resource "+g+", expected "+be.join(", "),"INVALID");if(typeof C!="number"||!Number.isSafeInteger(C)||C<0)throw K("Limit of "+b+" must be a non-negative integer","INVALID");d[b]=C}),e.limits=d,A()};r.control.register("getQuota",A,[{method:"GET",path:"/v1/quota",summary:"Quota root, limits and usage (QUOTA plugin)",handler:()=>r.control.getQuota()}]),r.control.register("setQuota",p,[{method:"PUT",path:"/v1/quota",summary:"Replaces the quota limits ({ STORAGE, MESSAGE, MAILBOX }, QUOTA plugin)",handler:({body:f})=>r.control.setQuota(f)}])}E();var Jo=r=>r==="*"||Mt(r);function oi(r){r.registerCapability("REPLACE");let t=function(s,n,i,a,o){let u=s?"UID REPLACE":"REPLACE",l=[].concat(i.attributes||[]),c=l.shift(),h=l.shift();if(!c||["ATOM","SEQUENCE"].indexOf(c.type)<0||!Jo(String(c.value)))return n.sendStatus(i,a,"BAD",u+" expects a message number, a mailbox name and a message",!1,"INVALID COMMAND"),o();let m=Zo(n,s,c.value);if(m.error)return n.sendStatus(i,a,m.error.command,m.error.text,m.error.code||!1,m.error.command==="BAD"?"INVALID COMMAND":u+" FAILED"),o();let T=m.message,A=Ys(n,i,a,h,l,{command:u,maxMessages:1,replaced:T});if(!A)return o();let p=Ks(n,A);n.send({tag:"*",command:"OK",attributes:[{type:"TEXT",value:"Replacement message saved"}],skipResponse:!0},"REPLACE APPENDUID",i,a,p),n.expungeSpecificMessages(n.selectedMailbox,[T],!1,!0),n.sendStatus(i,a,"OK",u+" completed",!1,u),o()};r.literalFilters.push((s,n,i)=>{if(n!=="REPLACE"&&n!=="UID REPLACE"||s.isBusy())return!1;let a=i.match(/^\S+ (?:UID )?REPLACE ([^ ]+) /i);return a&&Jo(a[1])&&Zo(s,n==="UID REPLACE",a[1]).error||!1});let e={states:J.SELECTED,mailboxArguments:[1],literal8:"BINARY",appendMessage:!0};r.setCommandHandler("REPLACE",t.bind(null,!1),Object.assign({sequenceSet:0},e)),r.setCommandHandler("UID REPLACE",t.bind(null,!0),e)}function Zo(r,t,e){let s=r.getSessionMessages(),n;if(t){let a=e==="*"?s.length?s[s.length-1].uid:0:Number(e);n=s.find(o=>o.uid===a)}else{let a=e==="*"?s.length:Number(e);if(!a||a>s.length)return{error:{command:"BAD",text:"Invalid message sequence number"}};n=s[a-1]}if(!n||n.ghost)return{error:{command:"NO",text:"No such message"}};let i=r.readOnlyRefusal();return i?{error:i}:{message:n}}E();function ui(r){r.registerCapability("SASL-IR",t=>t.state==="Not Authenticated")}E();function li(r){r.registerCapability("SAVEDATE");let t=s=>!!s&&s.SAVEDATE!==!1;r.messageHandlers.push((s,n,i)=>{if(!t(i)){delete n.SAVEDATE;return}let a=s.normalizeDateTime(n.SAVEDATE||s.now());if(!s.validateInternalDate(a))throw new Error("Invalid SAVEDATE value "+JSON.stringify(a)+" in mailbox "+i.path);n.SAVEDATE=a}),r.fetchHandlers.SAVEDATE=(s,n)=>n.SAVEDATE||null;let e=(s,n)=>{let i=(a,o,u,l)=>{let c=yn(o.SAVEDATE||o.internaldate);return!!c&&n(c,l)};i.argumentTypes=()=>["date"],r.searchHandlers[s]=i};e("SAVEDBEFORE",(s,n)=>s<n),e("SAVEDON",(s,n)=>s===n),e("SAVEDSINCE",(s,n)=>s>=n),r.searchHandlers.SAVEDATESUPPORTED=s=>t(s.selectedMailbox)}E();function ci(r){let t=Gn(r,"SAVELIMIT");r.registerCapability("SAVELIMIT="+t),_n(r,t)}E();var Kf=new Set(["SELECT","EXAMINE","CLOSE","UNSELECT"]),zf=r=>["SEARCH","UID SEARCH","SORT","UID SORT","ESEARCH"].includes(r);function fi(r){yt(r),r.registerCapability("SEARCHRES"),r.searchReturnOptions.set("SAVE",{data:!1}),r.connectionHandlers.push(t=>{let e=t.getMessageRange;t.getMessageRange=function(s,n){if(s!=="$")return e.call(this,s,n);let i=this.searchResult||new Set,a=[];return this.getSessionMessages().forEach((o,u)=>{i.has(o)&&a.push([u+1,o])}),a}}),r.resetHandlers.push(t=>{t.searchResult=null}),r.outputHandlers.push((t,e,s,n,i,a)=>{if(!n||!e||e.tag!==n.tag&&e.command!=="SEARCH"&&e.command!=="SORT")return;let o=(n.command||"").toUpperCase(),u=zf(o)&&n.searchReturn&&n.searchReturn.has("SAVE");if(u&&e.tag==="*"&&(e.command==="SEARCH"||e.command==="SORT")&&s===o&&a&&Array.isArray(a.list)){n.searchresFound=Xt(a.sorted||a.list,n.searchReturn);return}if(e.tag===n.tag){if(Kf.has(o)){t.searchResult=null;return}u&&e.command!=="BAD"&&(t.searchResult=new Set(e.command==="OK"?n.searchresFound:[]))}})}E();function hi(r){ne(r),r.registerCapability("SORT=DISPLAY"),r.sortKeys.DISPLAYFROM=t=>Ut(Dn(t,"from")),r.sortKeys.DISPLAYTO=t=>Ut(Dn(t,"to"))}E();var tu=new Set(["\\All","\\Archive","\\Drafts","\\Flagged","\\Junk","\\Sent","\\Trash","\\Important"]);function di(r){r.registerCapability("SPECIAL-USE");let t=i=>[].concat(i&&i["special-use"]||[]),e=jt(r);e.selectionOptions["SPECIAL-USE"]={type:"independent",returnOption:"SPECIAL-USE",match:i=>i.flags.indexOf("\\Noselect")<0&&t(i).length>0},e.returnOptions["SPECIAL-USE"]={};let s=r.getCommandHandler("LIST");r.setCommandHandler("LIST",(i,a,o,u)=>{if(e.enabled)return s(i,a,o,u);let l;if(a.attributes&&Array.isArray(a.attributes[0])){for(l=a.attributes[0].length-1;l>=0;l--)a.attributes[0][l]&&a.attributes[0][l].type==="ATOM"&&a.attributes[0][l].value.toUpperCase()==="SPECIAL-USE"&&(a.attributes[0].splice(l,1),a.listSpecialUseOnly=!0);a.attributes[0].length||a.attributes.splice(0,1)}if(a.attributes&&a.attributes[2]&&a.attributes[2].type==="ATOM"&&a.attributes[2].value.toUpperCase()==="RETURN"&&Array.isArray(a.attributes[3])){for(l=a.attributes[3].length-1;l>=0;l--)a.attributes[3][l]&&a.attributes[3][l].type==="ATOM"&&a.attributes[3][l].value.toUpperCase()==="SPECIAL-USE"&&a.attributes[3].splice(l,1);a.attributes[3].length||a.attributes.splice(2,2)}s(i,a,o,u)}),r.outputHandlers.push((i,a,o,u,l,c)=>{let h=t(c).map(m=>({type:"ATOM",value:m}));(o==="LIST ITEM"||o==="LSUB ITEM")&&c&&a.attributes&&Array.isArray(a.attributes[0])&&(h.length?a.attributes[0]=a.attributes[0].concat(h):u.listSpecialUseOnly&&(a.skipResponse=!0))}),r.control.mailboxInfoHandlers.push((i,a)=>{a.specialUse=t(i)});let n=(i,a)=>{let o=r.control.requireMailbox(i,!0);if(!Array.isArray(a)||a.some(u=>typeof u!="string"||!tu.has(u)))throw K("Special-use attributes must be a list of "+[...tu].join(", "),"INVALID");return o["special-use"]=[...new Set(a)],r.control.getMailbox(o.path)};r.control.register("setSpecialUse",n,[{method:"PUT",path:"/v1/mailboxes/{path}/special-use",summary:'Sets the special-use attributes of a mailbox ({ specialUse: ["\\Sent"] }, SPECIAL-USE plugin)',handler:({params:i,body:a})=>r.control.setSpecialUse(i.path,a.specialUse)}])}E();function pi(r){r.registerCapability("STARTTLS",t=>!t.secureConnection),r.setCommandHandler("STARTTLS",(t,e,s,n)=>{if(t.secureConnection)return Wf("Connection is already secured",t,e,s,n);t.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"Server ready to start TLS negotiation"}]},"STARTTLS INIT",e,s),t.upgradeConnection(n)})}function Wf(r,t,e,s,n){return t.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:r}]},"INVALID COMMAND",e,s),n()}E();function mi(r){r.registerCapability("STATUS=SIZE"),r.allowedStatus.push("SIZE"),r.statusHandlers.SIZE=(t,e)=>e.messages.reduce((s,n)=>s+At["RFC822.SIZE"](t,n),0)}E();E();function je(r){return{entry:r||null,parent:null,children:[]}}function ke(r,t){for(;!r.entry&&r.children.length;)r=r.children[0];for(;!t.entry&&t.children.length;)t=t.children[0];return r.entry.date-t.entry.date||r.entry.seq-t.entry.seq}function eu(r){let t=[],e=r.slice().reverse();for(;e.length;){let s=e.pop();t.push(s);for(let n=s.children.length-1;n>=0;n--)e.push(s.children[n])}return t}function $f(r,t){let e=[],s=[],n=i=>{for(let a=i.length-1;a>=0;a--)s.push(")",i[a],"(")};for(n(r);s.length;){let i=s.pop();if(typeof i=="string"){e.push(i);continue}let a=i.children;a.length===1?s.push(a[0]):n(a),i.entry&&(a.length&&s.push(" "),e.push(t?i.entry.message.uid:i.entry.seq))}return e.join("")}function Jf(r){let t=(i,a)=>i.subject.id<a.subject.id?-1:i.subject.id>a.subject.id?1:0,e=r.slice().sort((i,a)=>t(i,a)||i.date-a.date||i.seq-a.seq),s=[],n=null;for(let i of e)n&&n.entry.subject.id===i.subject.id?n.children.push(je(i)):(n=je(i),s.push(n));return s.sort(ke)}function Zf(r){let t=new Map,e=[],s=A=>{if(!t.has(A)){let p=je();t.set(A,p),e.push(p)}return t.get(A)},n=(A,p)=>{for(let f=A;f;f=f.parent)if(f===p)return!0;return!1},i=A=>{A.parent&&(A.parent.children.splice(A.parent.children.indexOf(A),1),A.parent=null)},a=(A,p)=>{A!==p&&(!p.children.length||!n(A,p))&&(A.children.push(p),p.parent=A)};for(let A of r){let p=rt(A.message).tree.parsedHeader,f=Gr(p["message-id"])[0],d=f!==void 0&&s(f);(!d||d.entry)&&(d=je(),e.push(d)),d.entry=A;let g=Gr(p.references);g.length||(g=Gr(p["in-reply-to"]).slice(0,1));let b=g.map(s);for(let v=1;v<b.length;v++)b[v].parent||a(b[v-1],b[v]);let C=b[b.length-1]||null;d.parent!==C&&(i(d),C&&a(C,d))}let o=e.filter(A=>!A.parent),u=(A,p)=>A.entry?[A]:A.children.length?p&&A.children.length>1?[A]:A.children:[];for(let A of eu(o).reverse())A.children=A.children.flatMap(p=>u(p,!1)),A.children.forEach(p=>{p.parent=A});let l=o.flatMap(A=>u(A,!0));l.forEach(A=>{A.parent=null}),l.forEach(A=>{A.entry||A.children.sort(ke)}),l.sort(ke);let c=A=>A.entry?A.entry.subject:A.children[0].entry.subject,h=A=>!!A.entry&&A.entry.subject.isReply,m=new Map;for(let A of l){let p=c(A);if(!p.id)continue;let f=m.get(p.id);(!f||f.entry&&(!A.entry||h(f)&&!h(A)))&&m.set(p.id,A)}let T=new Set;for(let A of l){let p=c(A);if(!p.id)continue;let f=m.get(p.id);if(f!==A)if(T.add(A),!f.entry&&!A.entry)A.children.forEach(d=>a(f,d));else if(!f.entry||h(A)&&!h(f))a(f,A);else{let d=je();l[l.indexOf(f)]=d,a(d,f),a(d,A),m.set(p.id,d)}}l=l.filter(A=>!T.has(A));for(let A of eu(l).reverse())A.children.sort(ke);return l.sort(ke),l}var ru={ORDEREDSUBJECT:Jf,REFERENCES:Zf};function es(r,t){if(r.registerCapability("THREAD="+t),r.threadAlgorithms){r.threadAlgorithms[t]=ru[t];return}r.threadAlgorithms={[t]:ru[t]};let e=(s,n,i,a,o)=>{let u=s?"UID THREAD":"THREAD",l=i.attributes||[],c=l[0]&&l[0].type==="ATOM"?l[0].value.toUpperCase():"";if(!Object.hasOwn(r.threadAlgorithms,c))return n.sendStatus(i,a,"BAD",c?"Unsupported threading algorithm "+c:u+" expects a threading algorithm atom",!1,u+" FAILED"),o();let h=_r(n,i,a,l.slice(1));if(!h)return o();let m=h.list.map(T=>{let A=Fr(rt(T).tree.parsedHeader.subject);return{message:T,seq:h.numbers[T.uid],date:Pr(T),subject:{id:Ut(A.subject).toString("binary"),isReply:A.isReply}}});return n.send({tag:"*",command:"THREAD",attributes:m.length?[{type:"TEXT",value:$f(r.threadAlgorithms[c](m),s)}]:[]},u,i,a,h),n.sendStatus(i,a,"OK",u+" completed",!1,u),o()};r.setCommandHandler("THREAD",e.bind(null,!1),{states:J.SELECTED,searchCriteria:2,noExpunge:!0}),r.setCommandHandler("UID THREAD",e.bind(null,!0),{states:J.SELECTED,searchCriteria:2})}function Ei(r){es(r,"ORDEREDSUBJECT")}E();function gi(r){es(r,"REFERENCES")}E();function rs(r){r.registerCapability("UIDONLY"),Nt(r,"UIDONLY");let t=i=>Et(i,"UIDONLY"),e=i=>({command:"BAD",code:"UIDREQUIRED",text:i}),s=(i,a)=>{let o=String(a.command||"").toUpperCase(),u=r.getCommandOptions(o),l=/^UID /.test(o)||o==="ESEARCH";if(!l&&(u.sequenceSet!==!1||u.searchCriteria!==!1))return e(o+" is not allowed once UIDONLY is enabled, use UID "+o);if(l&&u.searchCriteria!==!1&&i.usesSequenceNumbers(a))return e("Message numbers are not allowed in the search criteria once UIDONLY is enabled, use UID <sequence set>");if((o==="SELECT"||o==="EXAMINE")&&a.attributes&&Array.isArray(a.attributes[1])){let c=a.attributes[1],h=c.findIndex(T=>$(T,"QRESYNC")),m=h>=0&&c[h+1];if(Array.isArray(m)&&m.slice(2).some(Array.isArray))return e("QRESYNC message sequence match data is not allowed once UIDONLY is enabled")}return!1};r.commandChecks.push((i,a)=>t(i)&&s(i,a)),r.literalFilters.unshift((i,a)=>t(i)&&s(i,{command:a})),r.connectionHandlers.push(i=>{let a=i.isAmbiguous;i.isAmbiguous=function(u){return!t(this)&&a.call(this,u)};let o=i.prepareNotifications;i.prepareNotifications=function(u){return u=o.call(this,u),t(this)?Zr(u):u}});let n=(i,a,o,u,l,c)=>{if(!a||a.tag!=="*"||!Array.isArray(a.attributes)||!t(i))return;let h=a.attributes;if(a.command==="OK"&&h[0]&&h[0].type==="SECTION"&&$(h[0].section[0],"UNSEEN")){a.skipResponse=!0;return}if(!$(h[1],"FETCH")||!Array.isArray(h[2]))return;let m=h[2],T=m.findIndex((d,g)=>!(g%2)&&$(d,"UID")),A=c&&typeof c.uid=="number"&&c||a.fetchedMessage,p=A?A.uid:T>=0&&m[T+1];if(!p){a.skipResponse=!0;return}u&&!("uidonlyKeepUid"in u)&&(u.uidonlyKeepUid=th(u));let f=m;T>=0&&m.length>2&&!(u&&u.uidonlyKeepUid)&&(f=m.slice(0,T).concat(m.slice(T+2))),a.attributes=[p,{type:"ATOM",value:"UIDFETCH"},f]};r.once("pluginsLoaded",()=>r.outputHandlers.push(n))}function th(r){return String(r.command||"").toUpperCase()!=="UID FETCH"||!r.attributes?!1:[].concat(r.attributes[1]||[]).some(t=>$(t,"UID"))}rs.requires=["ENABLE"];E();function Ai(r){r.registerCapability("UIDPLUS"),r.setCommandHandler("UID EXPUNGE",(t,e,s,n)=>{if(!e.attributes||e.attributes.length!==1||!e.attributes[0]||["ATOM","SEQUENCE"].indexOf(e.attributes[0].type)<0)return t.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:"UID EXPUNGE expects uid sequence set"}]},"INVALID COMMAND",e,s),n();if(t.refuseReadOnly(e,s,"UID EXPUNGE FAILED"))return n();let i=e.attributes[0].value,o=t.limitRange(e,t.getMessageRange(i,!0)).map(u=>u[1]).filter(u=>u.flags.indexOf("\\Deleted")>=0);t.expungeSpecificMessages(t.selectedMailbox,o,!1,!0,!!e.highestFirst),t.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"UID EXPUNGE completed"}]},"UID EXPUNGE",e,s),n()}),r.outputHandlers.push((t,e,s,n,i,a)=>{if(s==="APPEND"||s==="REPLACE APPENDUID"){let o=a.messages.map(u=>u.uid);e.attributes=[{type:"SECTION",section:[{type:"ATOM",value:"APPENDUID"},a.mailbox.uidvalidity,o.length>1?{type:"SEQUENCE",value:se(o)}:o[0]]}].concat(e.attributes),e.skipResponse=!1;return}if(s==="COPY"||s==="UID COPY"||s==="MOVE COPYUID"||s==="UID MOVE COPYUID"){if(!a||!a.sourceUids||!a.sourceUids.length)return;e.attributes=[{type:"SECTION",section:[{type:"ATOM",value:"COPYUID"},a.mailbox.uidvalidity,{type:"SEQUENCE",value:a.sourceUids.join(",")},{type:"SEQUENCE",value:a.targetUids.join(",")}]}].concat(e.attributes),e.skipResponse=!1;return}})}E();function Ti(r){r.registerCapability("UNAUTHENTICATE"),r.setCommandHandler("UNAUTHENTICATE",(t,e,s,n)=>(t.sendStatus(e,s,"OK","Completed, now in not authenticated state"),t.resetSession(),n()),{states:J.AUTHENTICATED,noArguments:!0})}E();function yi(r){r.registerCapability("UNSELECT"),r.setCommandHandler("UNSELECT",(t,e,s,n)=>(t.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"Mailbox closed"}]},"CLOSE",e,s),t.closeMailbox(),n()),{states:J.SELECTED,noArguments:!0})}E();function eh(r){let t=r.match(/\r?\n\r?\n/);return/[\x80-\xff]/.test(t?r.substr(0,t.index):r)}function ss(r){r.registerCapability("UTF8=ACCEPT"),Nt(r,"UTF8=ACCEPT"),r.utf8Accept=!0,r.connectionHandlers.push(ye),r.resetHandlers.push(ye),r.outputHandlers.push((e,s,n,i,a,o)=>{n==="ENABLED"&&Array.isArray(o)&&o.indexOf("UTF8=ACCEPT")>=0&&ye(e)});let t=r.getCommandHandler("APPEND");r.setCommandHandler("APPEND",(e,s,n,i)=>{let a=s.attributes||[],o=a[a.length-1];return!e.utf8Enabled&&a.length>=2&&o&&["LITERAL","LITERAL8"].indexOf(o.type)>=0&&eh(o.value||"")?(e.sendStatus(s,n,"NO","Message header has 8-bit characters, ENABLE UTF8=ACCEPT first (RFC 9755 section 4)"),i()):t(e,s,n,i)})}ss.requires=["ENABLE"];E();var rh="1278455344230334865",sh=2n**64n-1n,su={"in:inbox":["X-GM-LABELS","\\Inbox"],"in:sent":["X-GM-LABELS","\\Sent"],"in:drafts":["X-GM-LABELS","\\Drafts"],"in:trash":["X-GM-LABELS","\\Trash"],"in:spam":["X-GM-LABELS","\\Junk"],"in:anywhere":["ALL"],"is:unread":["UNSEEN"],"is:read":["SEEN"],"is:starred":["FLAGGED"],"is:important":["X-GM-LABELS","\\Important"]},nu={from:"FROM",to:"TO",cc:"CC",bcc:"BCC",subject:"SUBJECT",label:"X-GM-LABELS",larger:"LARGER",smaller:"SMALLER",after:"SINCE",before:"BEFORE",rfc822msgid:"HEADER"},nh=["is","has","list","filename","around","size","older","newer","older_than","newer_than","deliveredto","category"];function Si(r){r.registerCapability("X-GM-EXT-1"),r["HIGHESTX-GM-MSGID"]=BigInt(r.options["HIGHESTX-GM-MSGID"]||rh),r.messageHandlers.push((o,u,l)=>{let c;u["X-GM-MSGID"]?/^\d+$/.test(u["X-GM-MSGID"])&&BigInt(u["X-GM-MSGID"])>o["HIGHESTX-GM-MSGID"]&&(o["HIGHESTX-GM-MSGID"]=BigInt(u["X-GM-MSGID"])):(o["HIGHESTX-GM-MSGID"]+=1n,u["X-GM-MSGID"]=o["HIGHESTX-GM-MSGID"].toString()),u["X-GM-LABELS"]=[].concat(u["X-GM-LABELS"]||[]),l.path.toUpperCase()==="INBOX"?c=["\\Inbox"]:l["special-use"]&&l["special-use"].length?c=[].concat(l["special-use"]):c=[ou(l.path)],c.forEach(h=>{o.ensureFlag(u["X-GM-LABELS"],h)})});let t=new Map;r.once("pluginsLoaded",()=>{r.messageHandlers.push((o,u)=>{let l=u.THREADID&&t.get(u.THREADID);u["X-GM-THRID"]||(u["X-GM-THRID"]=l||u["X-GM-MSGID"]),u.THREADID&&!l&&t.set(u.THREADID,u["X-GM-THRID"])})}),r.fetchHandlers["X-GM-MSGID"]=function(o,u){return{type:"ATOM",value:u["X-GM-MSGID"]}},r.fetchHandlers["X-GM-LABELS"]=function(o,u){return lu(u)};let e=()=>[o=>{if(!/^\d{1,20}$/.test(o)||BigInt(o)>sh)throw Q("Expected a 64 bit unsigned number");return BigInt(o).toString()}];r.searchHandlers["X-GM-MSGID"]=function(o,u,l,c){return u["X-GM-MSGID"]===c},r.searchHandlers["X-GM-MSGID"].argumentTypes=e,r.fetchHandlers["X-GM-THRID"]=function(o,u){return{type:"ATOM",value:u["X-GM-THRID"]}},r.searchHandlers["X-GM-THRID"]=function(o,u,l,c){return u["X-GM-THRID"]===c},r.searchHandlers["X-GM-THRID"].argumentTypes=e,r.searchHandlers["X-GM-LABELS"]=function(o,u,l,c){return u["X-GM-LABELS"].some(h=>au(h)?h.toLowerCase()===c.toLowerCase():o.exportMailboxName(uu(h))===c)};let s=new WeakMap;r.searchHandlers["X-GM-RAW"]=function(o,u,l,c){if(!s.has(c)){let h=o.searchCharset?c:["CHARSET","UTF-8"].concat(c);s.set(c,wt(o,[],h,()=>[]).matches)}return s.get(c)(u,l)},r.searchHandlers["X-GM-RAW"].argumentTypes=()=>[ah];let n=(o,u)=>{o["X-GM-LABELS"]=[],i(o,u)},i=(o,u)=>{u.forEach(l=>r.ensureFlag(o["X-GM-LABELS"],l))};[["X-GM-LABELS",n],["+X-GM-LABELS",i],["-X-GM-LABELS",(o,u)=>{u.forEach(l=>r.removeFlag(o["X-GM-LABELS"],l))}]].forEach(([o,u])=>{let l=(c,h,m)=>u(h,m.map(T=>ih(c,T)));r.storeHandlers[o]=function(c,h,m,T,A,p){l(c,h,m),oh(c,A,p,T,h)},r.storeHandlers[o+".SILENT"]=l,r.storeHandlers[o].astringValues=r.storeHandlers[o+".SILENT"].astringValues=!0}),r.copyHandlers.push((o,u,l)=>{u["X-GM-MSGID"]&&(l["X-GM-MSGID"]=u["X-GM-MSGID"],l["X-GM-THRID"]=u["X-GM-THRID"])})}var au=r=>r.charAt(0)==="\\"&&r.charAt(1)!=="\\",ou=r=>r.charAt(0)==="\\"?"\\"+r:r,uu=r=>r.charAt(0)==="\\"?r.substr(1):r;function ih(r,t){let e=String(t&&t.value||"");return t.type==="ATOM"&&e.charAt(0)==="\\"?e:ou(r.importMailboxName(e))}function lu(r){return r["X-GM-LABELS"].map(t=>au(t)?{type:"ATOM",value:t}:{type:"MAILBOX",value:uu(t)})}function ah(r){let t=[],e=/\s*(?:([(){}])|"([^"]*)"|([^\s(){}"]+?:)"([^"]*)"|([^\s(){}"]+))/gy,s,n=0;for(;n<r.length&&(s=e.exec(r));)n=e.lastIndex,s[1]?t.push({type:s[1]}):typeof s[2]=="string"?t.push({type:"word",value:s[2]}):s[3]?t.push({type:"word",value:s[3]+s[4],operator:s[3].slice(0,-1),operand:s[4]}):t.push({type:"word",value:s[5]});if(r.slice(n).trim())throw Q("X-GM-RAW query has an unterminated quoted string");let i=0,a=()=>t[i],o=c=>{let h=[];for(;i<t.length&&(!a()||a().type!==c);)h.push(u());if(c){if(!a()||a().type!==c)throw Q('X-GM-RAW query is missing "'+c+'"');i++}if(!h.length)throw Q("X-GM-RAW query is empty");return h.length===1?h[0]:h},u=()=>{let c=l();for(;a()&&a().type==="word"&&a().value==="OR"&&t[i+1];)i++,c=["OR",c,l()];return c},l=()=>{let c=t[i++];if(!c||c.type===")"||c.type==="}")throw Q("Unexpected end of X-GM-RAW query");if(c.type==="(")return o(")");if(c.type==="{"){let m=[];for(;a()&&a().type!=="}";)m.push(l());if(!a()||!m.length)throw Q("X-GM-RAW query has an empty or unterminated { } group");return i++,m.reduce((T,A)=>["OR",T,A])}let h=c.value;return h==="-"&&a()&&(a().type==="("||a().type==="{")?["NOT",l()]:h.charAt(0)==="-"&&h.length>1?["NOT",iu(cu(h.substr(1)))]:iu(c)};return[o()]}function cu(r){let t=r.match(/^([a-z_0-9]+):(.+)$/i);return t?{value:r,operator:t[1],operand:t[2]}:{value:r,operator:!1,operand:!1}}function iu(r){let t=r.operator?r:cu(r.value),e=t.operator;if(!e)return["TEXT",r.value];let s=t.operand,n=e.toLowerCase(),i=n+":"+s.toLowerCase(),a=Object.hasOwn(su,i)&&su[i];if(a)return a;let o=Object.hasOwn(nu,n)&&nu[n];if(o)switch(o){case"LARGER":case"SMALLER":{let u=s.match(/^(\d+)([km]?)$/i);if(!u)throw Q("X-GM-RAW "+n+": expects a size");return[o,String(Number(u[1])*{"":1,k:1024,m:1024*1024}[u[2].toLowerCase()])]}case"SINCE":case"BEFORE":{let u=s.match(/^(\d{4})[/-](\d{1,2})[/-](\d{1,2})$/);if(!u||!Ee(Number(u[3]),Number(u[2])-1,Number(u[1])))throw Q("X-GM-RAW "+n+": expects a date as YYYY/MM/DD");return[o,Number(u[3])+"-"+me[Number(u[2])-1]+"-"+u[1]]}case"HEADER":return[o,"Message-ID",s];default:return[o,s]}if(n==="in")return["X-GM-LABELS",s];if(nh.indexOf(n)>=0){let u=new Error("X-GM-RAW operator "+n+":"+s+" is not supported by imapkit");throw u.imapResponse="NO",u}return["TEXT",r.value]}function oh(r,t,e,s,n){let i=[{type:"ATOM",value:"X-GM-LABELS"},lu(n)];(t.command||"").toUpperCase()==="UID STORE"&&(i.push({type:"ATOM",value:"UID"}),i.push(n.uid)),r.send({tag:"*",attributes:[s,{type:"ATOM",value:"FETCH"},i]},"FLAG UPDATE",t,e,n)}E();var uh=new TextDecoder("utf-8",{fatal:!0});function bi(r){r.registerCapability("AUTH=XOAUTH2",t=>t.state==="Not Authenticated"),r.setCommandHandler("AUTHENTICATE XOAUTH2",(t,e,s,n)=>{if(!r.capabilities["SASL-IR"]||!r.capabilities["SASL-IR"](t))return t.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:"SASL-IR must be enabled to support XOAUTH2"}]},"AUTHENTICATE XOAUTH2 FAILED",e,s),n();if(!e.attributes||e.attributes.length!==1||!e.attributes[0]||["STRING","ATOM"].indexOf(e.attributes[0].type)<0)return t.send({tag:e.tag,command:"NO",attributes:[{type:"TEXT",value:"Invalid SASL argument"}]},"AUTHENTICATE XOAUTH2 FAILED",e,s),n();let i=t.decodeSaslResponse(e.attributes[0].value);if(!i)return t.sendStatus(e,s,"BAD","Invalid base64 in SASL response",!1,"AUTHENTICATE XOAUTH2 FAILED"),n();let a=[];try{a=uh.decode(i).split("")}catch{}let o=(a[0]||"").substr(5),u=(a[1]||"").substr(12);if(a.length!==4||!a[0].match(/^user=/)||!a[1].match(/^auth=Bearer /)||!o||!u||a[2]||a[3])return t.send({tag:e.tag,command:"NO",attributes:[{type:"TEXT",value:"Invalid SASL argument."}]},"AUTHENTICATE XOAUTH2 FAILED",e,s),n();let l=t.server.getUser(o);return l?(!l.xoauth2||l.xoauth2.accessToken!==u?(t.send({tag:"+",attributes:[{type:"ATOM",value:I.Buffer.from(JSON.stringify({status:"400",schemes:"Bearer",scope:"https://mail.google.com/"})).toString("base64")}]},"AUTHENTICATE XOAUTH2 FAILED",e,s),t.inputHandler=function(){t.inputHandler=!1,t.send({tag:e.tag,command:"NO",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"AUTHENTICATIONFAILED"}]},{type:"TEXT",value:"SASL authentication failed"}]},"AUTHENTICATE XOAUTH2 FAILED",e,s)}):(t.state="Authenticated",t.username=o,t.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"User logged in"}]},"AUTHENTICATE XOAUTH2 SUCCESS",e,s)),n()):(t.send({tag:e.tag,command:"NO",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"AUTHENTICATIONFAILED"}]},{type:"TEXT",value:"Invalid credentials"}]},"AUTHENTICATE XOAUTH2 FAILED",e,s),n())})}var Ve={acl:en,appendlimit:rn,"auth-plain":sn,binary:ln,catenate:fn,compress:hn,condstore:In,"context-search":Pe,"context-sort":Ln,"create-special-use":Rn,enable:Sn,esearch:yt,esort:Xe,id:Un,idle:Bn,imap4rev2:kr,"list-extended":_e,"list-status":Fn,literalminus:Ge,literalplus:Pn,logindisabled:Xn,messagelimit:kn,metadata:Kr,"metadata-server":zr,move:Yn,multiappend:Kn,multisearch:zn,namespace:Wn,notify:$n,oauthbearer:Jn,objectid:Zn,partial:ti,preview:si,qresync:ts,quota:ai,replace:oi,"sasl-ir":ui,savedate:li,savelimit:ci,searchres:fi,sort:ne,"sort-display":hi,"special-use":di,starttls:pi,"status-size":mi,"thread-orderedsubject":Ei,"thread-references":gi,uidonly:rs,uidplus:Ai,unauthenticate:Ti,unselect:yi,"utf8-accept":ss,"x-gm-ext-1":Si,xoauth2:bi};var fu={"literal+":"literalplus","literal-":"literalminus","compress=deflate":"compress","auth=plain":"auth-plain","auth=xoauth2":"xoauth2","status=size":"status-size","sort=display":"sort-display","thread=orderedsubject":"thread-orderedsubject","thread=references":"thread-references","auth=oauthbearer":"oauthbearer","utf8=accept":"utf8-accept","context=search":"context-search","context=sort":"context-sort"};function lh(){return Object.keys(Ve)}function hu(r){let t=String(r).trim().toLowerCase();return Object.hasOwn(fu,t)&&(t=fu[t]),Object.hasOwn(Ve,t)?t:!1}function ch(r,t,e){let s=new Set,n=new Map;(e||new Map).forEach((a,o)=>{let u=hu(o);u&&n.set(Ve[u],a)});let i=(a,o)=>{let u=a;if(typeof u=="string"){let h=hu(u);if(!h&&u.toUpperCase()==="XTOYBIRD")throw new Error("XTOYBIRD was removed in 5.0.0, use the control API (server.control.snapshot(), server.control.addUser() ...) instead, see the README");if(!h)throw new Error('Unknown plugin "'+u+'". Available plugins: '+lh().join(", "));u=Ve[h]}if(typeof u!="function")throw new TypeError("Invalid plugin, expecting a plugin name or a function");let l=n.get(u);if(l){if(o)throw new Error(o+" requires "+a+', which the "'+l+'" quirk removes');return}if(s.has(u))return;s.add(u);let c=typeof a=="string"?a.trim():u.name;[].concat(u.requires||[]).forEach(h=>i(h,c)),u(r)};[].concat(t||[]).forEach(a=>i(a)),r.emit("pluginsLoaded")}var du=ch;E();E();function Ii(r,t,e,s){let n=["IMAP4rev1"];Object.keys(r.server.capabilities).forEach(i=>{r.server.capabilities[i](r)&&n.push(i)}),r.send({tag:"*",command:"CAPABILITY",attributes:n.map(i=>({type:"TEXT",value:i}))},"CAPABILITY LIST",t,e,n),r.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"Completed"}]},"CAPABILITY COMPLETED",t,e,n),s()}E();function Oi(r,t,e,s){r.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"Completed"}]},"CHECK",t,e),s()}E();function Ni(r,t,e,s){return r.canExpunge()&&r.expungeDeleted(r.selectedMailbox,!0),r.notificationQueue=[],r.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"Mailbox closed"}]},"CLOSE",t,e),r.closeMailbox(),s()}E();function Ci(r,t,e,s){if(!t.attributes||t.attributes.length!==1||!t.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(t.attributes[0].type)<0)return r.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:"CREATE expects mailbox name"}]},"INVALID COMMAND",t,e),s();let n=t.attributes[0].value,i;try{i=gr(r.server,n)}catch(a){let o=a;return r.sendStatus(t,e,"NO",o.message,o.code,"CREATE FAILED"),s()}return r.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"CREATE completed"}]},"CREATE",t,e,i),s()}E();function xi(r,t,e,s){if(!t.attributes||t.attributes.length!==1||!t.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(t.attributes[0].type)<0)return r.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:"DELETE expects mailbox name"}]},"INVALID COMMAND",t,e),s();let n=t.attributes[0].value;try{Ar(r.server,n)}catch(i){let a=i;return r.sendStatus(t,e,"NO",a.message,a.code,"DELETE FAILED"),s()}return r.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"DELETE completed"}]},"DELETE",t,e),s()}E();function Mi(r,t,e,s){return Qs(r,t,e,s,!0)}E();function wi(r,t,e,s){if(r.refuseReadOnly(t,e,"EXPUNGE FAILED"))return s();r.expungeDeleted(r.selectedMailbox,!1,!0),r.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"EXPUNGE Completed"}]},"EXPUNGE",t,e),s()}E();function Di(r,t,e,s){let n;if(!t.attributes||t.attributes.length!==2||!t.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(t.attributes[0].type)<0||!t.attributes[1]||["STRING","LITERAL","ATOM"].indexOf(t.attributes[1].type)<0)return r.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:"LIST expects 2 string arguments"}]},"INVALID COMMAND",t,e),s();if(t.attributes[1].value)n=r.server.matchFolders(t.attributes[0].value,t.attributes[1].value,i=>r.exportMailboxName(i)),n.forEach(i=>{r.send({tag:"*",command:"LIST",attributes:[i.flags.map(a=>({type:"ATOM",value:a})),r.server.getSeparator(i),r.exportMailboxName(i.path)]},"LIST ITEM",t,e,i)});else{let i=r.server,a=t.attributes[0].value||"",o=i.referenceNamespace;try{o=i.getNamespace(r.importMailboxName(a))||o}catch{}let u=o!==!1?i.storage[o]:void 0,l=o!==!1&&o!==i.referenceNamespace?r.exportMailboxName(o):"";u&&r.send({tag:"*",command:"LIST",attributes:[[{type:"ATOM",value:"\\Noselect"}],u.separator,l]},"LIST ITEM",t,e)}return r.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"Completed"}]},"LIST",t,e),s()}E();function Li(r,t,e,s){if(!t.attributes||t.attributes.length!==2||!t.attributes[0]||!t.attributes[1]||["STRING","LITERAL","ATOM"].indexOf(t.attributes[0].type)<0||["STRING","LITERAL","ATOM"].indexOf(t.attributes[1].type)<0)return r.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:"LOGIN takes 2 string arguments"}]},"INVALID COMMAND",t,e),s();if(t.attributes.some(i=>/[\x80-\xff]/.test(i.value)))return r.sendStatus(t,e,"BAD","LOGIN does not take UTF-8 user names or passwords, use AUTHENTICATE (RFC 9755 section 5)"),s();let n=r.server.getUser(t.attributes[0].value);if(!n||n.password!==t.attributes[1].value)return r.sendStatus(t,e,"NO","Login failed: authentication failure","AUTHENTICATIONFAILED","LOGIN FAILED"),s();r.state="Authenticated",r.username=t.attributes[0].value,r.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"User logged in"}]},"LOGIN SUCCESS",t,e),s()}E();function Ri(r,t,e,s){r.state="Logout",r.send({tag:"*",command:"BYE",attributes:[{type:"TEXT",value:"LOGOUT received"}]},"LOGOUT UNTAGGED",t,e),r.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"Completed"}]},"LOGOUT COMPLETED",t,e),r.end(),s()}E();function Ui(r,t,e,s){if(!t.attributes||t.attributes.length!==2||!t.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(t.attributes[0].type)<0||!t.attributes[1]||["STRING","LITERAL","ATOM"].indexOf(t.attributes[1].type)<0)return r.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:"LSUB expects 2 string arguments"}]},"INVALID COMMAND",t,e),s();let n=r.server,i=t.attributes[1].value;return n.matchFolders(t.attributes[0].value,i,o=>r.exportMailboxName(o),n.getSubscriptionTree()).forEach(o=>{let u;if(o.subscribed)u=o.flags.filter(l=>l!=="\\Noselect");else if(i.substr(-1)==="%")u=["\\Noselect"];else return;r.send({tag:"*",command:"LSUB",attributes:[u.map(l=>({type:"ATOM",value:l})),n.getSeparator(o),r.exportMailboxName(o.path)]},"LSUB ITEM",t,e,o)}),r.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"Completed"}]},"LSUB",t,e),s()}E();function Bi(r,t,e,s){r.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"Completed"}]},"NOOP completed",t,e),s()}E();function Hi(r,t,e,s){if(!t.attributes||t.attributes.length!==2||!t.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(t.attributes[0].type)<0||!t.attributes[1]||["STRING","LITERAL","ATOM"].indexOf(t.attributes[1].type)<0)return r.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:"RENAME expects mailbox source and destination names"}]},"INVALID COMMAND",t,e),s();let n=t.attributes[0].value,i=t.attributes[1].value,a;try{a=Tr(r.server,n,i)}catch(o){let u=o;return r.sendStatus(t,e,"NO",u.message,u.code,"RENAME FAILED"),s()}return r.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"RENAME completed"}]},"RENAME",t,e,a.mailbox),s()}E();function vi(r,t,e,s,n){let i=r?"UID SEARCH":"SEARCH";if(!e.attributes||!e.attributes.length)return t.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:i+" expects search criteria, empty query given"}]},i+" FAILED",e,s),n();let a;try{a=wt(t,t.getSessionMessages(),ge(e.attributes))}catch(o){return Ae(t,e,s,o,i+" FAILED"),n()}return t.send({tag:"*",command:"SEARCH",attributes:a.list.map(o=>r?o.uid:a.numbers[o.uid])},i,e,s,a),t.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:i+" completed"}]},i,e,s),n()}var fh=(r,t,e,s)=>vi(!1,r,t,e,s),pu=fh;E();function Fi(r,t,e,s){if(!t.attributes||t.attributes.length!==2||!t.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(t.attributes[0].type)<0||!Array.isArray(t.attributes[1])||!t.attributes[1].length)return r.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:"STATUS expects mailbox argument and a list of status items"}]},"INVALID COMMAND",t,e),s();let n=t.attributes[0].value,i;try{i=Vr(r.server,t.attributes[1],r)}catch(u){return r.sendStatus(t,e,"BAD",u.message,!1,"STATUS FAILED"),s()}let a=r.server.getMailbox(n);if(!a||a.flags.indexOf("\\Noselect")>=0)return r.sendStatus(t,e,"NO","Mailbox does not exist","NONEXISTENT","STATUS FAILED"),s();qr(r,n,a,i,t,e);let o=r.state==="Selected"&&r.selectedMailbox===a;return r.sendStatus(t,e,"OK",o?"Status completed, STATUS SHOULD NOT be used on the selected mailbox":"Status completed",o&&"CLIENTBUG"),s()}E();function mu(r,t){return t=String(t).toUpperCase(),r.server.storeHandlers[t]||dr[t]}function Pi(r,t,e,s,n){let i=r?"UID STORE":"STORE",a=e.attributes&&e.attributes[1],o=$(a)&&mu(t,a.value),u=!!(o&&o.astringValues),l=u?["ATOM","STRING","LITERAL"]:["ATOM","STRING"];if(u&&he(e,s,f=>f[0]===2),!e.attributes||e.attributes.length!==3||!e.attributes[0]||["ATOM","SEQUENCE"].indexOf(e.attributes[0].type)<0||!e.attributes[1]||["ATOM"].indexOf(e.attributes[1].type)<0||!e.attributes[2]||!(l.indexOf(e.attributes[2].type)>=0||Array.isArray(e.attributes[2])))return t.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:i+" expects sequence set, item name and item value"}]},"INVALID COMMAND",e,s),n();if(t.refuseReadOnly(e,s,i+" FAILED"))return n();let c=t.limitRange(e,t.getCommandRange(e.attributes[0].value,r)),h=(e.attributes[1].value||"").toUpperCase(),m=[].concat(e.attributes[2]||[]),T=[],A=!1;try{m.forEach((d,g)=>{if(!d||l.indexOf(d.type)<0)throw new Error("Invalid item value #"+(g+1))});let f=o||mu(t,h);if(!f)throw new Error("Invalid STORE argument "+h);c.forEach(d=>{if(d[1].ghost){A=!0;return}for(let g=0,b=t.server.storeFilters.length;g<b;g++)if(!t.server.storeFilters[g](t,d[1],e,d[0]))return;f(t,d[1],m,d[0],e,s),T.push(d[1])})}catch(f){let d=f;return t.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:d.message}]},i+" FAILED",e,s),n()}let p=A&&!/\.SILENT$/.test(h);t.send({tag:e.tag,command:p?"NO":"OK",attributes:[].concat(p?{type:"SECTION",section:[{type:"ATOM",value:"EXPUNGEISSUED"}]}:[],{type:"TEXT",value:p?"Some of the messages no longer exist":i+" completed"})},i+(p?" FAILED":" COMPLETE"),e,s,T),t.notifyFlagChanges(T),n()}var hh=(r,t,e,s)=>Pi(!1,r,t,e,s),Eu=hh;E();function Xi(r,t,e,s){if(!t.attributes||t.attributes.length!==1||!t.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(t.attributes[0].type)<0)return r.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:"SUBSCRIBE expects mailbox name"}]},"INVALID COMMAND",t,e),s();try{we(r.server,t.attributes[0].value)}catch(n){let i=n;return r.sendStatus(t,e,"NO",i.message,i.code,"SUBSCRIBE FAILED"),s()}return r.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"SUBSCRIBE completed"}]},"SUBSCRIBE",t,e),s()}E();function Gi(r,t,e,s){return qn(r,t,e,s,!0)}E();var dh=(r,t,e,s)=>dn(!0,r,t,e,s),gu=dh;E();var ph=(r,t,e,s)=>vi(!0,r,t,e,s),Au=ph;E();var mh=(r,t,e,s)=>Pi(!0,r,t,e,s),Tu=mh;E();function _i(r,t,e,s){return!t.attributes||t.attributes.length!==1||!t.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(t.attributes[0].type)<0?(r.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:"UNSUBSCRIBE expects mailbox name"}]},"INVALID COMMAND",t,e),s()):(yr(r.server,t.attributes[0].value),r.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"UNSUBSCRIBE completed"}]},"UNSUBSCRIBE",t,e),s())}var yu={APPEND:zs,CAPABILITY:Ii,CHECK:Oi,CLOSE:Ni,COPY:Vn,CREATE:Ci,DELETE:xi,EXAMINE:Mi,EXPUNGE:wi,FETCH:yo,LIST:Di,LOGIN:Li,LOGOUT:Ri,LSUB:Ui,NOOP:Bi,RENAME:Hi,SEARCH:pu,SELECT:Vs,STATUS:Fi,STORE:Eu,SUBSCRIBE:Xi,"UID COPY":Gi,"UID FETCH":gu,"UID SEARCH":Au,"UID STORE":Tu,UNSUBSCRIBE:_i};E();function Eh(r){if(!(r===void 0||typeof r=="function"))return r===null||typeof r!="object"?r:JSON.parse(JSON.stringify(r))}function ki(r,t){let e={};return Object.keys(r).forEach(s=>{let n=t.has(s)?void 0:Eh(r[s]);n!==void 0&&(e[s]=n)}),e}var gh=new Set(["ghost"]),Ah=new Set(["folders"]),Th=new Set(["path","namespace","messages","folders","subscribed","flags"]),yh=new Set(["\\HasChildren","\\HasNoChildren"]),ns=class{constructor(t){this.server=t,this.routes=[],this.snapshotHandlers=[],this.mailboxInfoHandlers=[],this.messageInfoHandlers=[]}register(t,e,s){if(t in this)throw new Error("Control operation "+t+" exists already");this[t]=(...n)=>this.run(()=>e(...n)),this.routes.push(...s||[])}run(t){return this.server.withOrigin(null,t)}requireMailbox(t,e){let s=typeof t=="string"&&t?this.server.getMailbox(t):void 0;if(!s||e&&s.flags.indexOf("\\Noselect")>=0)throw new nt("Mailbox "+JSON.stringify(t)+" does not exist","NONEXISTENT");return s}checkName(t){this.checkPath(t);let e=pe(t);if(e)throw new nt(e,"INVALID")}checkPath(t){if(typeof t!="string"||!t)throw new nt("Mailbox name must be a non-empty string","INVALID")}requireMessages(t,e){if(!Array.isArray(e)||e.some(i=>!Number.isSafeInteger(i)||i<1))throw new nt("UIDs must be an array of positive integers","INVALID");let s=new Map(t.messages.map(i=>[i.uid,i])),n=e.filter(i=>!s.has(i));if(n.length)throw new nt("No message with UID "+n.join(", ")+" in "+t.path,"NONEXISTENT");return[...new Set(e)].map(i=>s.get(i))}findSessions(t){let e=typeof t=="number"?{session:t}:t||{};if(e.session===void 0&&e.user===void 0)throw new nt("Select sessions by number or user","INVALID");return[...this.server.connections].filter(s=>s.isOpen()&&(e.session===void 0||s.sessionNumber===e.session)&&(e.user===void 0||s.username===e.user))}snapshot(){let t=this.server,e=i=>{let a=ki(i,Th);return this.snapshotHandlers.forEach(o=>o(i,a)),a.flags=i.flags.filter(o=>!yh.has(o)),a.subscribed=!!i.subscribed,a.messages=i.messages.map(o=>ki(o,gh)),i.folders&&(a.folders=s(i.folders)),a},s=i=>{let a={};return Object.keys(i).forEach(o=>{a[o]=e(i[o])}),a},n={};return Object.keys(t.storage).forEach(i=>{if(i==="INBOX"){n.INBOX=e(t.storage.INBOX);return}let a=t.storage[i];n[i]=Object.assign(ki(a,Ah),{folders:s(a.folders||{})})}),n}listMailboxes(){return Object.keys(this.server.folderCache).sort().map(t=>this.describeMailbox(this.server.folderCache[t]))}getMailbox(t){return this.describeMailbox(this.requireMailbox(t))}describeMailbox(t){let e=this.server.getStatus(t),s={path:t.path,delimiter:this.server.getSeparator(t),flags:t.flags.slice(),selectable:t.flags.indexOf("\\Noselect")<0,subscribed:!!t.subscribed,messages:t.messages.length,unseen:e?e.unseen:0,uidnext:t.uidnext,uidvalidity:t.uidvalidity,permanentFlags:e?e.permanentFlags.slice():[]};return this.server.condstore&&typeof t.HIGHESTMODSEQ=="number"&&(s.highestModseq=t.HIGHESTMODSEQ),this.mailboxInfoHandlers.forEach(n=>n(t,s)),s}listMessages(t,e={}){let s=this.requireMailbox(t,!0);return(e.uids?this.requireMessages(s,e.uids).sort((i,a)=>i.uid-a.uid):s.messages).map(i=>this.describeMessage(i,!!e.raw))}getMessage(t,e,s={}){let n=this.requireMailbox(t,!0);return this.describeMessage(this.requireMessages(n,[e])[0],s.raw!==!1)}describeMessage(t,e){let s={uid:t.uid,flags:t.flags.slice(),internaldate:t.internaldate,size:t.raw.length};return this.server.condstore&&typeof t.MODSEQ=="number"&&(s.modseq=t.MODSEQ),e&&(s.raw=I.Buffer.from(t.raw,"binary")),this.messageInfoHandlers.forEach(n=>n(t,s)),s}sessions(){return[...this.server.connections].map(t=>t.describe()).sort((t,e)=>t.session-e.session)}addMessage(t,e,s={}){let n=this.requireMailbox(t,!0),{raw:i,flags:a,internaldate:o}=e||{},u;if(typeof i=="string")u=I.Buffer.from(i,"utf-8").toString("binary");else if(i instanceof Uint8Array)u=I.Buffer.from(i).toString("binary");else throw new nt("Message source (raw) must be a string or a Buffer","INVALID");if(!u.length)throw new nt("Message source (raw) can not be empty","INVALID");let l=$s(this.server,n,a||[],!0);if(o!==void 0&&!(o instanceof Date&&!isNaN(o.getTime()))&&!this.server.validateInternalDate(o))throw new nt('Internal date must be a Date or a date-time string like "17-Jul-1996 02:44:25 -0700"',"INVALID");if(s.checks){let h=this.server.appendChecks.map(m=>m(null,n,[{raw:u,flags:l,internaldate:o}],{command:"APPEND"})).find(m=>m&&!m.soft);if(h){let m=Array.isArray(h.code)?h.code[0]:h.code;throw new nt(h.text,typeof m=="string"?m:"CANNOT")}}return{uid:this.run(()=>this.server.appendMessage(n,l,o||null,u)).message.uid,uidvalidity:n.uidvalidity}}setFlags(t,e,s,n="set"){let i=this.requireMailbox(t,!0),a=this.requireMessages(i,e);return this.run(()=>Za(this.server,i,a,s,n)),a.map(o=>({uid:o.uid,flags:o.flags.slice()}))}expungeMessages(t,e){let s=this.requireMailbox(t,!0),n=this.requireMessages(s,e);return this.run(()=>Zt(this.server,s,n)).map(i=>i.uid)}copyMessages(t,e,s){return this.transfer(t,e,s,!1)}moveMessages(t,e,s){return this.transfer(t,e,s,!0)}transfer(t,e,s,n){let i=this.requireMailbox(t,!0),a=this.requireMailbox(s,!0),o=this.requireMessages(i,e).sort((u,l)=>u.uid-l.uid);return this.run(()=>{let u=o.map(l=>({uid:l.uid,targetUid:this.server.copyMessage(a,l).message.uid}));return n&&Zt(this.server,i,o),{uidvalidity:a.uidvalidity,uids:u}})}replaceMessage(t,e,s){let n=this.requireMailbox(t,!0),i=this.requireMessages(n,[e])[0],a=this.addMessage(t,{raw:s&&s.raw,flags:s&&s.flags?s.flags:i.flags.slice(),internaldate:s&&s.internaldate?s.internaldate:i.internaldate});return this.run(()=>Zt(this.server,n,[i])),a}createMailbox(t,e={}){this.checkName(t);let s=this.run(()=>{let n=gr(this.server,t);return e.subscribed&&we(this.server,n.path),n});return this.describeMailbox(s)}deleteMailbox(t){this.checkPath(t),this.run(()=>Ar(this.server,t))}renameMailbox(t,e){this.checkPath(t),this.checkName(e);let s=this.run(()=>Tr(this.server,t,e));return this.getMailbox(s.path)}resetUidValidity(t,e={}){let s=this.requireMailbox(t,!0);return this.run(()=>eo(this.server,s,e||{}))}subscribe(t){return this.checkPath(t),this.run(()=>we(this.server,t))}unsubscribe(t){return this.checkPath(t),this.run(()=>yr(this.server,t))}listUsers(){return Object.keys(this.server.users).sort().map(t=>({name:t,xoauth2:!!(this.server.users[t].xoauth2&&this.server.users[t].xoauth2.accessToken)}))}addUser(t,e){if(typeof t!="string"||!t)throw new nt("User name must be a non-empty string","INVALID");if(Object.hasOwn(this.server.users,t))throw new nt("User "+JSON.stringify(t)+" already exists","ALREADYEXISTS");this.server.users[t]=this.userData({},e)}updateUser(t,e){this.server.users[t]=this.userData(this.requireUser(t),e)}deleteUser(t,e={}){this.requireUser(t),delete this.server.users[t],e.disconnect!==!1&&this.findSessions({user:t}).forEach(s=>s.bye("User was deleted","USER DELETED"))}requireUser(t){if(typeof t!="string"||!Object.hasOwn(this.server.users,t))throw new nt("User "+JSON.stringify(t)+" does not exist","NONEXISTENT");return this.server.users[t]}userData(t,e){let{password:s,xoauth2:n}=e||{},i=Object.assign({},t);if(s!==void 0){if(typeof s!="string")throw new nt("Password must be a string","INVALID");i.password=s}if(n===null)delete i.xoauth2;else if(n!==void 0){if(typeof n!="object"||typeof n.accessToken!="string")throw new nt("xoauth2 must be { accessToken, sessionTimeout }","INVALID");i.xoauth2={accessToken:n.accessToken,sessionTimeout:Number(n.sessionTimeout)||Er}}return i}disconnect(t,e={}){let s=this.findSessions(t);return s.forEach(n=>{e.reset?n.closeNow("reset"):n.bye(e.text||"Disconnected by the server","DISCONNECT")}),s.length}inject(t,e){let s=this.findSessions({session:t})[0];if(!s)throw new nt("Session "+t+" does not exist","NONEXISTENT");if(typeof e!="string"&&!(e instanceof Uint8Array))throw new nt("Data must be a string or a Buffer","INVALID");s.write(I.Buffer.from(e))}reset(){this.server.connections.forEach(t=>{t.isOpen()&&t.bye("Server reset","RESET")}),this.run(()=>{this.server.loadUsers(),this.server.loadStorage(),this.server.emit("reset")})}shutdown(t={}){return new Promise((e,s)=>{let n=i=>i&&i.code!=="ERR_SERVER_NOT_RUNNING"?s(i):e();t.graceful===!1?this.server.close(n):(this.server.closeListeners(!1),this.server.server.close(n))})}};E();var ji=["FETCH","UID FETCH"];function Sh(r){return String(r[0]&&r[0].value||"").toUpperCase().replace(/(^|\.)(MIME|HEADER(\.FIELDS(\.NOT)?)?|TEXT)$/,"")}function Su(r,t){let e=r.attributes&&r.attributes[2];if(!Array.isArray(e)||!r.attributes[1]||r.attributes[1].value!=="FETCH")return;let s=e.slice();for(let n=0;n<s.length-1;n+=2){let i=s[n];i&&i.type==="ATOM"&&String(i.value).toUpperCase()==="BODY"&&Array.isArray(i.section)&&(s[n+1]=t(i,s[n+1]))}return Object.assign({},r,{attributes:[r.attributes[0],r.attributes[1],s]})}var qe={"james-fetchgroup":{description:"Apache James FetchGroup: only the first section asked for a part in one FETCH is answered, later ones for the same part come back empty. BODY[2.MIME] BODY[2] gives a zero-length body, the reverse order loses the headers",rules:[{on:"response",command:ji,untagged:!0,mutate:r=>{let t=new Set;return Su(r,(e,s)=>{let n=Sh(e.section);return t.has(n)?{type:"LITERAL",value:""}:(t.add(n),s)})}}]},"james-late-fetch":{description:"Apache James: now and then (1 in 4) a FETCH response comes after the tagged OK of its command",rules:[{on:"response",command:ji,untagged:!0,chance:.25,defer:"tagged"}]},"yahoo-quoted-sections":{description:"Yahoo: short body sections (up to 100 octets without line breaks) are quoted strings instead of literals",rules:[{on:"response",command:ji,untagged:!0,mutate:r=>Su(r,(t,e)=>e&&e.type==="LITERAL"&&typeof e.value=="string"&&e.value.length<=100&&/^[\x20-\x7e]*$/.test(e.value)?{type:"STRING",value:e.value}:e)}]},"m365-throttle":{description:'Microsoft 365: 1 in 10 commands (not LOGOUT) is refused with "BAD Request is throttled. Suggested Backoff Time: 1000 milliseconds"',rules:[{on:"command",chance:.1,when:r=>r.command!=="LOGOUT",send:`$TAG BAD Request is throttled. Suggested Backoff Time: 1000 milliseconds\r
|
|
32
|
-
`}]},"no-uidplus":{description:"A server without UIDPLUS: no APPENDUID, COPYUID or UID EXPUNGE, even when the plugins list it",removePlugins:["UIDPLUS"]},"no-move":{description:"A server without MOVE, clients have to COPY, STORE \\Deleted and EXPUNGE",removePlugins:["MOVE"]}};function
|
|
28
|
+
`,flags:[],uid:1},_)}catch(X){throw Q(X.message)}}return v})},w=(x,L,v,V)=>{let _=new Set,X=null;if(J(L,"NONE"))return{events:_,fetch:X};if(!Array.isArray(L)||!L.length)throw Q("Expecting a list of events or NONE");for(let q=0;q<L.length;q++){let se=L[q];if(!J(se)||se.section||se.partial)throw Q("Invalid event");let ee=fh.get(se.value.toUpperCase());if(Array.isArray(L[q+1])&&ee==="MessageNew"){if(!v)throw Q("Fetch attributes for MessageNew are only allowed with SELECTED or SELECTED-DELAYED");X=N(x,L[++q])}if(!ee){V.push(se.value);continue}if(v&&nr.indexOf(ee)<0)throw Q(ee+" can not be used with SELECTED or SELECTED-DELAYED");_.add(ee)}if(_.has("MessageNew")!==_.has("MessageExpunge"))throw Q("MessageNew and MessageExpunge must be used together");if((_.has("FlagChange")||_.has("AnnotationChange"))&&!_.has("MessageNew"))throw Q("FlagChange and AnnotationChange require MessageNew and MessageExpunge");return{events:_,fetch:X}},G=(x,L)=>{let v=Array.isArray(L)?L:[L];if(!v.length||!v.every(ue))throw Q("Expecting a mailbox name or a list of mailbox names");return v.map(V=>o(x.importMailboxName(V.value)))},F=(x,L)=>{let v={selected:null,groups:[],unseen:new WeakMap},V=[];if(J(L[0],"NONE")){if(L.length!==1)throw Q("NOTIFY NONE does not take any arguments");return{state:v,status:!1,unknown:V}}if(!J(L[0],"SET"))throw Q("NOTIFY expects SET or NONE");let _=J(L[1],"STATUS"),X=L.slice(_?2:1);if(!X.length)throw Q("NOTIFY SET expects event groups");return X.forEach(q=>{if(!Array.isArray(q)||!J(q[0]))throw Q("Invalid event group");let se=q[0].value.toUpperCase();if(hh.indexOf(se)>=0){if(q.length!==2)throw Q("Invalid event group");if(v.selected)throw Q("Only one of SELECTED and SELECTED-DELAYED can be used");v.selected=Object.assign({delayed:se==="SELECTED-DELAYED"},w(x,q[1],!0,V))}else if(dh.indexOf(se)>=0){let ee=se==="SUBTREE"||se==="MAILBOXES";if(q.length!==(ee?3:2))throw Q("Invalid event group");let fe=ee?G(x,q[1]):[],{events:is}=w(x,q[q.length-1],!1,V),Nr=se==="SUBTREE"?fe.map(Lt=>Lt+s.getSeparator(Lt)):[];v.groups.push({filter:se,paths:fe,prefixes:Nr,events:is})}else throw Q("Unknown mailbox filter "+q[0].value)}),{state:v,status:_,unknown:V}},W=(x,L,v,V)=>{Object.keys(s.folderCache).sort((X,q)=>X==="INBOX"?-1:q==="INBOX"?1:X.localeCompare(q)).forEach(X=>{let q=s.folderCache[X];if(q===x.selectedMailbox||q.flags.some(fe=>/^\\(Noselect|NonExistent)$/i.test(fe)))return;let se=u(x,X,q);if(!se.size||!n(x,q))return;if(!i(x,q)){x.send(d(x,X,{noAccess:!0}),"NOTIFY LIST",v,V);return}if(!L||!se.has("MessageNew"))return;let ee=["MESSAGES","UIDNEXT","UIDVALIDITY"];if(se.has("FlagChange")){ee.push("UNSEEN");let fe=s.getStatus(q);x.notifyState.unseen.set(q,fe&&fe.unseen||0),s.condstore&&ee.push("HIGHESTMODSEQ")}x.send(er(x,X,q,ee),"NOTIFY STATUS",v,V)})};s.setCommandHandler("NOTIFY",(x,L,v,V)=>{let _;try{_=F(x,L.attributes||[])}catch(ee){return x.sendStatus(L,v,"BAD",ee.imapResponse==="BAD"?ee.message:"Invalid NOTIFY arguments"),V()}let X=t(),q=[_.state.selected].concat(_.state.groups).filter(ee=>!!ee);return _.unknown.concat(...q.map(ee=>[...ee.events].filter(fe=>X.indexOf(fe)<0))).length?(x.send({tag:L.tag,command:"NO",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"BADEVENT"},X.map(ee=>({type:"ATOM",value:ee}))]},{type:"TEXT",value:"Unsupported NOTIFY events"}]},"NOTIFY FAILED",L,v),V()):(x.notifyState=_.state,W(x,_.status,L,v),x.sendStatus(L,v,"OK","NOTIFY completed"),V())},{states:Z.AUTHENTICATED})}g();var mh=new TextDecoder("utf-8",{fatal:!0});function gh(s){let e=s.toString("binary");if(e==="")return{kvsepOnly:!0};let t=e.match(/^(?:F,)?(n|y|p=[A-Za-z0-9.-]+),(?:a=([^,]+))?,/);if(!t||e.charAt(t[0].length)!=="")return{error:"Invalid GS2 header"};let r=!1;if(t[2]){if(/=(?!2C|3D)/.test(t[2])||t[2].includes("\0"))return{error:"Invalid authorization identity"};try{r=mh.decode(b.Buffer.from(t[2].replace(/=2C/g,",").replace(/=3D/g,"="),"binary"))}catch{return{error:"Invalid UTF-8 in the authorization identity"}}}let n=e.substr(t[0].length+1).split("");if(n.pop()!==""||n.pop()!=="")return{error:"The client response must end with %x01"};let i=Object.create(null);for(let o of n){let a=o.match(/^([A-Za-z]+)=([\x20-\x7e\t\r\n]*)$/);if(!a)return{error:"Invalid key/value pair"};i[a[1]]=a[2]}return{channelBinding:t[1].charAt(0)==="p",authzid:r,pairs:i}}function hi(s){s.registerCapability("AUTH=OAUTHBEARER",a=>a.state==="Not Authenticated");let e=(a,u,l,c,f)=>{a.sendStatus(u,l,c,f,c==="NO"&&"AUTHENTICATIONFAILED","AUTHENTICATE OAUTHBEARER FAILED")},t=a=>{if(a.channelBinding)return"invalid_request";let{auth:u,port:l}=a.pairs;if(typeof l=="string"&&!/^[1-9][0-9]*$/.test(l))return"invalid_request";let c=typeof u=="string"&&u.match(/^Bearer +([A-Za-z0-9\-._~+/]+=*)$/i);if(!c)return u===""?"invalid_token":"invalid_request";let f=c[1],p=s.checkAccessToken(f,a.authzid===!1?void 0:a.authzid);return"error"in p?p.error:(a.username=p.user,!1)},r=a=>s.oauth&&s.oauth.issuer?{status:a,scope:s.oauth.mailScope,"openid-configuration":s.oauth.discoveryUrl()}:{status:a},n=(a,u,l,c)=>{let f=a.decodeSaslResponse(c);return f||e(a,u,l,"BAD","Invalid base64 in SASL response"),f},i=(a,u,l,c)=>{a.inputHandler=f=>{if(a.inputHandler=!1,f==="*")return e(a,u,l,"BAD","Authentication cancelled");let p=n(a,u,l,f);p&&c(p)}},o=(a,u,l,c)=>{let f=gh(c);if(f.error)return e(a,u,l,"BAD",f.error+" in the OAUTHBEARER client response");if(f.kvsepOnly)return e(a,u,l,"NO","SASL authentication failed");let p=t(f);if(!p)return a.state="Authenticated",a.username=f.username,a.sendStatus(u,l,"OK","SASL authentication succeeded",!1,"AUTHENTICATE OAUTHBEARER SUCCESS");i(a,u,l,y=>{if(y.toString("binary")!=="")return e(a,u,l,"BAD","The client must answer the error result with a single %x01 (RFC 7628 section 3.2.3)");e(a,u,l,"NO","SASL authentication failed")}),a.send({tag:"+",attributes:[{type:"ATOM",value:b.Buffer.from(JSON.stringify(r(p))).toString("base64")}]},"AUTHENTICATE OAUTHBEARER CHALLENGE",u,l)};s.setCommandHandler("AUTHENTICATE OAUTHBEARER",(a,u,l,c)=>{let f=u.attributes||[];if(!f.length)return i(a,u,l,y=>o(a,u,l,y)),a.sendContinuation("","AUTHENTICATE OAUTHBEARER"),c();if(f.length!==1||!f[0]||f[0].type!=="ATOM")return e(a,u,l,"BAD","Invalid arguments for AUTHENTICATE OAUTHBEARER"),c();if(!s.capabilities["SASL-IR"]||!s.capabilities["SASL-IR"](a))return e(a,u,l,"BAD","SASL-IR must be enabled to send Initial Response with the request"),c();let p=n(a,u,l,f[0].value);return p&&o(a,u,l,p),c()})}g();var Au=/^[A-Za-z0-9_-]{1,255}$/,Eh=/^Message-ID[ \t]*:(.*)$/im,Ah=/^References[ \t]*:(.*)$/im,yh=/^In-Reply-To[ \t]*:(.*)$/im,ir=Symbol("mailboxid-uidvalidity");function di(s){s.registerCapability("OBJECTID");let e=new Map,t={F:0,M:0,T:0},r=new Map,n=new Map,i=new Map,o=A=>{let m;do m=A+ ++t[A];while(e.has(m));return e.set(m,A),m},a=(A,m,h)=>{if(typeof A!="string"||!Au.test(A))throw new Error("Invalid "+m+" value "+JSON.stringify(A)+" in "+h)},u=(A,m)=>{if(e.has(A)&&e.get(A)!==m)throw new Error("Object identifier "+JSON.stringify(A)+" is already used for another kind of object");e.set(A,m)},l=A=>{if(A[ir]===A.uidvalidity&&r.get(A.MAILBOXID)===A)return A.MAILBOXID;let m;return A.MAILBOXID&&A[ir]===void 0&&!r.has(A.MAILBOXID)?(m=A.MAILBOXID,a(m,"MAILBOXID","mailbox "+A.path),u(m,"F")):m=o("F"),A.MAILBOXID=m,A[ir]=A.uidvalidity,r.set(m,A),m};s.mailboxHandlers.push((A,m)=>{if(!(m.flags.indexOf("\\Noselect")>=0)){if(m.MAILBOXID&&m[ir]===void 0&&r.has(m.MAILBOXID))throw new Error("Duplicate MAILBOXID value "+JSON.stringify(m.MAILBOXID)+" in mailbox "+m.path);l(m)}}),s.control.mailboxInfoHandlers.push((A,m)=>{A.flags.indexOf("\\Noselect")<0&&(m.mailboxId=l(A))}),s.control.messageInfoHandlers.push((A,m)=>{m.emailId=A.EMAILID,m.threadId=A.THREADID}),s.messageHandlers.push((A,m,h)=>{let d="a message of mailbox "+h.path;m.EMAILID?(a(m.EMAILID,"EMAILID",d),u(m.EMAILID,"M")):m.EMAILID=o("M"),m.THREADID&&(a(m.THREADID,"THREADID",d),u(m.THREADID,"T"));let E=n.get(m.EMAILID);if(E&&m.THREADID&&m.THREADID!==E)throw new Error("Messages with EMAILID "+JSON.stringify(m.EMAILID)+" must have the same THREADID");let I=bh(m.raw);m.THREADID=m.THREADID||E||c(I.references)||o("T"),n.set(m.EMAILID,m.THREADID),[I.messageId].concat(I.references).forEach(C=>{C&&!i.has(C)&&i.set(C,m.THREADID)})});let c=A=>{for(let m=A.length-1;m>=0;m--)if(i.has(A[m]))return i.get(A[m]);return!1};s.copyHandlers.push((A,m,h)=>{m.EMAILID&&(h.EMAILID=m.EMAILID,h.THREADID=m.THREADID)}),s.allowedStatus.push("MAILBOXID"),s.statusHandlers.MAILBOXID=(A,m)=>[{type:"ATOM",value:l(m)}],s.fetchHandlers.EMAILID=(A,m)=>[{type:"ATOM",value:m.EMAILID}],s.fetchHandlers.THREADID=(A,m)=>[{type:"ATOM",value:m.THREADID}];let f=A=>{if(!Au.test(A))throw Q("Invalid object identifier");return A},p=A=>{let m=(h,d,E,I)=>d[A]===I;m.argumentTypes=()=>[f],s.searchHandlers[A]=m};p("EMAILID"),p("THREADID");let y=A=>({type:"SECTION",section:[{type:"ATOM",value:"MAILBOXID"},[{type:"ATOM",value:l(A)}]]});s.outputHandlers.push((A,m,h,d,E,I)=>{if(h==="CREATE"&&m.command==="OK"&&I){m.attributes=[y(I)].concat(m.attributes||[]);return}(h==="SELECT"||h==="EXAMINE")&&d&&m.tag===d.tag&&m.command==="OK"&&A.selectedMailbox&&A.send({tag:"*",command:"OK",attributes:[y(A.selectedMailbox),{type:"TEXT",value:"Ok"}]},h+" MAILBOXID",d,E)})}function bh(s){s=s||"";let e=s.search(/\r?\n\r?\n/),t=(e>=0?s.substr(0,e):s).replace(/\r?\n(?=[ \t])/g,""),r=n=>{let i=t.match(n);return i?i[1].match(/<[^<>\s]+>/g)||[]:[]};return{messageId:r(Eh)[0]||!1,references:r(Ah).concat(r(yh))}}g();var Th=s=>!!s&&s.type==="ATOM"&&String(s.value).toUpperCase()==="PARTIAL";function pi(s){Ie(s),s.registerCapability("PARTIAL"),s.partialRangeLast=!0,Vs(s);let e=(t,r,n,i,o)=>{let a=n.attributes&&n.attributes[2];if(Array.isArray(a)){for(let u=0;u<a.length;u+=2)if(Th(a[u])){try{if(n.partialFetch)throw new Error("PARTIAL can be used only once");n.partialFetch=Vt(a[u+1],!0)}catch(l){return r.sendStatus(n,i,"BAD",l.message,!1,(n.command||"").toUpperCase()+" FAILED"),o()}a.splice(u,2),u-=2}a.length||n.attributes.splice(2,1)}t(r,n,i,o)};["FETCH","UID FETCH"].forEach(t=>{let r=s.getCommandHandler(t);s.setCommandHandler(t,(n,i,o,a)=>e(r,n,i,o,a))}),s.fetchFilters.unshift((t,r,n)=>{if(!n.partialFetch)return!0;if(!n.partialFetchSet){let i=(n.command||"").toUpperCase()==="UID FETCH",o=t.getMessageRange(n.attributes[0].value,i).map(a=>a[1]);n.partialFetchSet=new Set(js(o,n.partialFetch))}return n.partialFetchSet.has(r)})}g();function Ei(s){s.registerCapability("PREVIEW");let e=new WeakMap,t=r=>{if(typeof r.preview=="string")return Iu(r.preview,Ih);let n=e.get(r);return n&&n.source===r.raw?n.preview:void 0};s.fetchHandlers.PREVIEW=function(r,n,i){let o=t(n);if(o===void 0){if(i.previewLazy)return null;o=xh(ne(n).tree),e.set(n,{source:n.raw,preview:o})}return b.Buffer.from(o,"utf8").toString("binary")},["FETCH","UID FETCH"].forEach(r=>{let n=s.getCommandHandler(r);s.setCommandHandler(r,(i,o,a,u)=>{try{Oh(o)}catch(l){return i.sendStatus(o,a,"BAD",l.message,!1,"PREVIEW FAILED"),u()}n(i,o,a,u)})})}var Sh=200,Ih=256,mi=64*1024,Su=s=>Array.isArray(s)&&s.length>0&&s.every(e=>J(e,"LAZY"));function yu(s,e){if(!e.length)throw new Error("PREVIEW modifier list can not be empty");if(!Su(e))throw new Error("Unknown PREVIEW modifier");return Object.assign({},s,{previewLazy:!0})}function Oh(s){let e=s.attributes;if(!Array.isArray(e))return;let t=e[1];if(Array.isArray(t)){for(let r=t.length-2;r>=0;r--)J(t[r],"PREVIEW")&&Array.isArray(t[r+1])&&(t[r]=yu(t[r],t[r+1]),t.splice(r+1,1));return}J(t,"PREVIEW")&&Array.isArray(e[2])&&(e.length>3||Su(e[2]))&&(e[1]=yu(t,e[2]),e.splice(2,1))}function xh(s){let e=gi(s);if(!e)return"";let t=Ch(e);return t===!1?"":Iu(e.parsedHeader["content-type"].subtype==="html"?Lh(t):Nh(t),Sh)}function gi(s){let{type:e,subtype:t}=s.parsedHeader["content-type"],r=s.parsedHeader["content-disposition"];if(r&&r.type==="attachment")return!1;if(e==="multipart"){if(t==="encrypted")return!1;let n=ot(s)||[];if(t==="alternative"){let i=n.map(gi).filter(o=>!!o);return i.find(o=>o.parsedHeader["content-type"].subtype==="plain")||i[0]||!1}for(let i of n){let o=gi(i);if(o)return o}return!1}return e==="text"&&(t==="plain"||t==="html")?s:!1}function Ch(s){let e=String(s.parsedHeader["content-transfer-encoding"]||"7bit").toLowerCase(),t=s.body,r;switch(e){case"7bit":case"8bit":case"binary":r=b.Buffer.from(t.slice(0,mi),"binary");break;case"base64":r=b.Buffer.from(t.slice(0,mi*4/3),"base64");break;case"quoted-printable":r=wh(t.slice(0,mi));break;default:return!1}let n=String(s.parsedHeader["content-type"].params.charset||"").trim().toLowerCase(),i;if(n&&!["us-ascii","ascii"].includes(n))try{i=new TextDecoder(n)}catch{}return(i||new TextDecoder("utf-8")).decode(r)}function wh(s){let e=s.split(`\r
|
|
29
|
+
`).map(t=>{let r=t.length;for(;r>0&&(t[r-1]===" "||t[r-1]===" ");)r--;return t.slice(0,r)}).join(`\r
|
|
30
|
+
`).replace(/=\r\n/g,"").replace(/=([0-9A-Fa-f]{2})/g,(t,r)=>String.fromCharCode(parseInt(r,16)));return b.Buffer.from(e,"binary")}function Nh(s){let e=s.split(/\r?\n/).filter(t=>!/^>/.test(t)).join(`
|
|
31
|
+
`);return e.trim()?e:s}var Mh=new Set(["a","abbr","b","bdi","bdo","big","cite","code","del","dfn","em","font","i","ins","kbd","mark","q","s","samp","small","span","strike","strong","sub","sup","time","tt","u","var","wbr"]),Rh="nbsp iexcl cent pound curren yen brvbar sect uml copy ordf laquo not shy reg macr deg plusmn sup2 sup3 acute micro para middot cedil sup1 ordm raquo frac14 frac12 frac34 iquest Agrave Aacute Acirc Atilde Auml Aring AElig Ccedil Egrave Eacute Ecirc Euml Igrave Iacute Icirc Iuml ETH Ntilde Ograve Oacute Ocirc Otilde Ouml times Oslash Ugrave Uacute Ucirc Uuml Yacute THORN szlig agrave aacute acirc atilde auml aring aelig ccedil egrave eacute ecirc euml igrave iacute icirc iuml eth ntilde ograve oacute ocirc otilde ouml divide oslash ugrave uacute ucirc uuml yacute thorn yuml",bu=Object.assign(Object.fromEntries(Rh.split(" ").map((s,e)=>[s,String.fromCharCode(160+e)])),{amp:"&",lt:"<",gt:">",quot:'"',apos:"'",trade:"\u2122",hellip:"\u2026",mdash:"\u2014",ndash:"\u2013",lsquo:"\u2018",rsquo:"\u2019",ldquo:"\u201C",rdquo:"\u201D",bull:"\u2022",euro:"\u20AC",zwnj:"\u200C",zwj:"\u200D"});function Lh(s){s=s.replace(/<!--[\s\S]*?(?:-->|$)/g," ").replace(/<(head|script|style|title|template)\b[^<>]*>[\s\S]*?(?:<\/\1\s*>|$)/gi," ");let e=Tu(Dh(s));return e.trim()?e:Tu(s)}function Dh(s){let e=/<(\/?)blockquote\b[^<>]*>?/gi,t="",r=0,n=0,i;for(;i=e.exec(s);)r||(t+=s.slice(n,i.index)+" "),r=i[1]?Math.max(r-1,0):r+1,n=e.lastIndex;return r?t:t+s.slice(n)}function Tu(s){return s.replace(/<!\[CDATA\[([\s\S]*?)(?:\]\]>|$)/g,"$1").replace(/<\/?([A-Za-z][A-Za-z0-9-]*)(?![A-Za-z0-9-])[^<>]*>|<[!?][^<>]*>/g,(e,t)=>t&&Mh.has(t.toLowerCase())?"":" ").replace(/&(#[0-9]+|#[xX][0-9A-Fa-f]+|[A-Za-z][A-Za-z0-9]*);/g,(e,t)=>{if(t[0]==="#"){let r=/^#x/i.test(t)?parseInt(t.slice(2),16):parseInt(t.slice(1),10);return r>0&&r<=1114111&&(r<55296||r>57343)?String.fromCodePoint(r):"\uFFFD"}return Object.hasOwn(bu,t)?bu[t]:e})}function Iu(s,e){let t=s.replace(/[^\P{Cc}\t\n\v\f\r]|\u00ad/gu,"").replace(/[\s\u200b]+/g," ").trim();return Array.from(t).slice(0,e).join("").trimEnd()}g();g();function or(s){let e=!!s.message&&!!s.attributes&&s.attributes[1];return!!e&&e.type==="ATOM"&&String(e.value).toUpperCase()==="EXPUNGE"}function ar(s){if(!s.some(or))return s;let e=[];return s.forEach(t=>{or(t)?Array.isArray(e[e.length-1])?e[e.length-1].push(t.message):e.push([t.message]):e.push(t)}),e.map(t=>Array.isArray(t)?{tag:"*",command:"VANISHED",attributes:[{type:"SEQUENCE",value:lt(t.map(r=>r.uid))}],notification:!0,messages:t}:t)}var Uh=new Set(["EXPUNGE","UID EXPUNGE","MOVE","UID MOVE","REPLACE","UID REPLACE"]);function ur(s){s.registerCapability("QRESYNC"),Ne(s,"QRESYNC"),s.resetHandlers.push(m=>{m.qresyncExpunged=!1});let e=new WeakMap,t=m=>ye(m,"QRESYNC"),{isEnabled:r,getHighestModseq:n}=s.condstore,i=(m,h)=>((!m.qresyncExpunged||m.qresyncExpunged.uidvalidity!==m.uidvalidity)&&(m.qresyncExpunged={uidvalidity:m.uidvalidity,since:h||n(m),list:[]}),m.qresyncExpunged),o=s.indexFolders;s.indexFolders=function(...m){let h=o.apply(this,m);return Object.keys(this.folderCache).forEach(d=>i(this.folderCache[d])),h},s.on("expunge",(m,h,d)=>{let E=n(m),I=i(m,E-1).list;h.forEach(C=>{let H=I[I.length-1];H&&H.modseq===E&&H.to+1===C.uid?H.to=C.uid:I.push({from:C.uid,to:C.uid,modseq:E}),e.set(C,E)}),d&&(d.qresyncExpunged=!0)});let a=(m,h,d,E,I)=>{let{since:C,list:H}=i(m),N;return E>=C?N=Ou(yi(H.filter(w=>w.modseq>E).map(w=>[w.from,w.to])),d):N=Ou(d,[[(I||0)+1,m.uidnext-1]]),Bh(N,h).map(w=>w[0]===w[1]?String(w[0]):w[0]+":"+w[1]).join(",")},u=(m,h,d,E,I)=>(m.sendStatus(h,d,"BAD",I,!1,"QRESYNC FAILED"),E()),l=(m,h)=>{let d=s.getCommandHandler(m);d&&s.setCommandHandler(m,(E,I,C,H)=>h(d,E,I,C,H))},c=(m,h,d,E,I)=>{let C=d.attributes&&d.attributes[1],H=G=>J(G,"QRESYNC"),N=Array.isArray(C)?C.findIndex(H):-1;if(N<0)return m(h,d,E,I);if(!t(h))return u(h,d,E,I,"QRESYNC parameter requires ENABLE QRESYNC");if(C.findLastIndex(H)!==N)return u(h,d,E,I,"QRESYNC parameter can be used only once");let w;try{w=Hh(C[N+1])}catch(G){return u(h,d,E,I,G.message)}C.splice(N,2),C.length||d.attributes.splice(1,1),d.qresync=w,m(h,d,E,I)};l("SELECT",c),l("EXAMINE",c);let f=(m,h,d,E,I,C)=>{let H=E.attributes&&E.attributes[2],N=G=>J(G,"VANISHED"),w=Array.isArray(H)?H.findIndex(N):-1;if(w<0)return h(d,E,I,C);if(!m)return u(d,E,I,C,"VANISHED is only allowed with UID FETCH");if(!t(d))return u(d,E,I,C,"VANISHED requires ENABLE QRESYNC");if(H.findLastIndex(N)!==w)return u(d,E,I,C,"VANISHED can be used only once");if(!H.some(G=>J(G,"CHANGEDSINCE")))return u(d,E,I,C,"VANISHED requires CHANGEDSINCE");H.splice(w,1),E.qresyncVanished=!0,h(d,E,I,C)};l("FETCH",f.bind(null,!1)),l("UID FETCH",f.bind(null,!0)),s.connectionHandlers.push(m=>{let h=m.prepareNotifications;m.prepareNotifications=function(d){return d=h.call(this,d),t(this)?ar(d):d}});let p=(m,h,d,E)=>{h&&m.send({tag:"*",command:"VANISHED",attributes:[[{type:"ATOM",value:"EARLIER"}],{type:"SEQUENCE",value:h}]},"VANISHED EARLIER",d,E)},y=(m,h,d)=>{let E=m.selectedMailbox,I=h.qresync;if(I.uidvalidity!==E.uidvalidity)return;let C=I.knownUids||(E.uidnext>1?[[1,E.uidnext-1]]:[]),H=0;if(I.seqMatch){let w=xu(I.seqMatch.uids);for(let G of xu(I.seqMatch.sequences)){let F=w.next().value,W=E.messages[G-1];if(!W||W.uid!==F)break;H=F}}p(m,a(E,E.messages,C,I.modseq,H),h,d);let N=s.fetchHandlers.FLAGS||Te.FLAGS;E.messages.forEach((w,G)=>{w.MODSEQ<=I.modseq||!kh(C,w.uid)||m.send({tag:"*",attributes:[G+1,{type:"ATOM",value:"FETCH"},[{type:"ATOM",value:"UID"},w.uid,{type:"ATOM",value:"FLAGS"},N(m,w,{type:"ATOM",value:"FLAGS"}),{type:"ATOM",value:"MODSEQ"},[w.MODSEQ]]]},"QRESYNC FETCH",h,d,w)})},A=m=>({type:"SECTION",section:[{type:"ATOM",value:"HIGHESTMODSEQ"},m]});s.outputHandlers.push((m,h,d,E,I)=>{if(!E||!h||h.tag==="+")return;let C=h.tag!=="*"&&h.tag===E.tag;if(E.qresyncVanished&&(h.tag==="*"&&d==="UID FETCH"||C&&h.command==="OK")){E.qresyncVanished=!1;let N=m.selectedMailbox,w=vh(E.attributes[0].value,N.uidnext-1);w&&p(m,a(N,m.getSessionMessages(),w,E.changedsince),E,I);return}if(!C)return;if(E.qresync&&h.command==="OK"&&(d==="SELECT"||d==="EXAMINE")&&m.selectedMailbox){y(m,E,I);return}let H=m.qresyncExpunged;if(m.qresyncExpunged=!1,H&&h.command==="OK"&&Uh.has(String(E.command).toUpperCase())&&m.selectedMailbox&&r(m)){h.attributes&&h.attributes[0]&&h.attributes[0].type==="SECTION"||(h.attributes=[A(n(m.selectedMailbox))].concat(h.attributes||[]));return}if(r(m)){let N=0;m.notificationQueue.forEach(w=>{let G=or(w)&&w.message&&e.get(w.message);G&&(!N||G<N)&&(N=G)}),N>1&&m.send({tag:"*",command:"OK",attributes:[A(N-1),{type:"TEXT",value:"Expunges not reported yet"}]},"QRESYNC HIGHESTMODSEQ",E,I)}})}function Ai(s,e){if(!s||Array.isArray(s)||["ATOM","SEQUENCE"].indexOf(s.type)<0||!Is(s.value,!0))throw new Error("Invalid QRESYNC "+e+', a sequence set without "*" expected');return s.value.split(",").map(t=>{let r=t.split(":").map(Number);return[r[0],r.length>1?r[1]:r[0]]})}function vh(s,e){return/^[\d*:,]+$/.test(String(s))?yi(String(s).split(",").map(t=>t.split(":").map(r=>r==="*"?e:Number(r)))):!1}function Ou(s,e){let t=[],r=0,n=0;for(;r<s.length&&n<e.length;){let i=Math.max(s[r][0],e[n][0]),o=Math.min(s[r][1],e[n][1]);i<=o&&t.push([i,o]),s[r][1]<e[n][1]?r++:n++}return t}function Bh(s,e){let t=[],r=0;return s.forEach(([n,i])=>{let o=n;for(;r<e.length&&e[r].uid<n;)r++;for(;r<e.length&&e[r].uid<=i;r++)e[r].uid>o&&t.push([o,e[r].uid-1]),o=e[r].uid+1;o<=i&&t.push([o,i])}),t}function yi(s){let e=s.map(r=>[Math.min(...r),Math.max(...r)]).sort((r,n)=>r[0]-n[0]),t=[];return e.forEach(r=>{let n=t[t.length-1];n&&r[0]<=n[1]+1?n[1]=Math.max(n[1],r[1]):t.push(r)}),t}function*xu(s){for(let[e,t]of s)for(let r=e;r<=t;r++)yield r}function Cu(s,e){let t=0,r=0;return s.forEach(([n,i])=>{if(n>i||n<=t)throw new Error("Invalid QRESYNC "+e+", numbers must be in ascending order");t=i,r+=i-n+1}),r}function Hh(s){if(!Array.isArray(s)||s.length<2||s.length>4)throw new Error("QRESYNC expects (uidvalidity modseq [known-uids] [(known-sequence-set known-uid-set)])");let[e,t]=s;if(!J(e)||!Le(e.value))throw new Error("Invalid QRESYNC uidvalidity, a non-zero number expected");if(!J(t)||!Ae(t.value,Ge)||BigInt(t.value)<1n)throw new Error("Invalid QRESYNC mod-sequence, a positive number expected");let r={uidvalidity:Number(e.value),modseq:Number(t.value),knownUids:!1,seqMatch:!1},n=s.slice(2);if(n.length&&!Array.isArray(n[0])&&(r.knownUids=yi(Ai(n.shift(),"known-uids"))),n.length){let i=n.shift();if(!Array.isArray(i)||i.length!==2||n.length)throw new Error("Invalid QRESYNC parameters, (known-sequence-set known-uid-set) expected last");let o=Ai(i[0],"known-sequence-set"),a=Ai(i[1],"known-uid-set"),u=Cu(o,"known-sequence-set");if(Cu(a,"known-uid-set")!==u)throw new Error("Invalid QRESYNC sets, known-sequence-set and known-uid-set must have as many numbers");r.seqMatch={sequences:o,uids:a}}return r}function kh(s,e){return s.some(t=>e>=t[0]&&e<=t[1])}ur.requires=["ENABLE","CONDSTORE"];g();var Mt=["STORAGE","MESSAGE","MAILBOX"],Ph="User quota";function bi(s){let e=s.options.quota||{},t={name:typeof e.root=="string"?e.root:Ph,soft:!!e.soft,limits:{}},r={};Mt.forEach(h=>{if(e[h]===void 0||e[h]===null)return;let d=Number(e[h]);if(!Number.isSafeInteger(d)||d<0)throw new Error("Invalid quota limit for "+h+": "+JSON.stringify(e[h]));r[h]=d});let n=()=>{t.limits=Object.assign({},r)};n(),s.on("reset",n),s.registerCapability("QUOTA"),Mt.forEach(h=>s.registerCapability("QUOTA=RES-"+h)),s.registerCapability("QUOTASET");let i=h=>s.isPersonal(h),o=h=>h.flags.indexOf("\\Noselect")<0,a=h=>h.reduce((d,E)=>d+_t(E.raw).length,0),u=()=>{let h={MESSAGE:0,MAILBOX:0,bytes:0};return Object.keys(s.folderCache).forEach(d=>{let E=s.folderCache[d];!o(E)||!i(E)||(h.MAILBOX++,h.MESSAGE+=E.messages.length,h.bytes+=a(E.messages))}),h},l=(h,d,E)=>{let I=u();I.STORAGE=Math.ceil(I.bytes/1024);let C=[];Mt.forEach(H=>{H in t.limits&&C.push({type:"ATOM",value:H},I[H],t.limits[H])}),h.send({tag:"*",command:"QUOTA",attributes:[{type:"STRING",value:t.name},C]},"QUOTA",d,E)},c=h=>{if(!(h.MESSAGE&&"MESSAGE"in t.limits||h.bytes&&"STORAGE"in t.limits||h.MAILBOX&&"MAILBOX"in t.limits))return;let E=u();if(h.MESSAGE&&"MESSAGE"in t.limits&&E.MESSAGE+h.MESSAGE>t.limits.MESSAGE||h.bytes&&"STORAGE"in t.limits&&E.bytes+h.bytes>t.limits.STORAGE*1024||h.MAILBOX&&"MAILBOX"in t.limits&&E.MAILBOX+h.MAILBOX>t.limits.MAILBOX)return t.soft?{code:"OVERQUOTA",text:"Soft quota has been exceeded",soft:!0}:{code:"OVERQUOTA",text:"Quota exceeded"}};s.appendChecks.push((h,d,E,I)=>{if(!E.length||!i(d)||I.move&&I.source&&i(I.source))return;let C={MESSAGE:E.length,bytes:a(E)};return I.replaced&&h&&h.selectedMailbox&&i(h.selectedMailbox)&&(C.MESSAGE--,C.bytes-=a([I.replaced])),c(C)});let f=h=>{let d=s.getMailbox(s.stripSeparator(h,s.getSeparator(h))),E=!d||!o(d)?1:0;for(let I=s.getParentPath(h);I;I=s.getParentPath(I))s.getMailbox(I)||E++;return E},p=(h,d)=>{let E=s.getCommandHandler(h);s.setCommandHandler(h,(I,C,H,N)=>{let w=d(C.attributes);if(typeof w=="string"&&w.toUpperCase()!=="INBOX"&&i(w)&&!I.applyChecks([c({MAILBOX:f(w)})],C,H,h+" FAILED"))return N();E(I,C,H,N)})},y=(h,d)=>ue((h||[])[d])&&h[d].value;p("CREATE",h=>h&&h.length===1?y(h,0):!1),p("RENAME",h=>{let d=y(h,0);return h&&h.length===2&&typeof d=="string"&&d.toUpperCase()==="INBOX"?y(h,1):!1}),s.setCommandHandler("GETQUOTA",(h,d,E,I)=>!d.attributes||d.attributes.length!==1||!ue(d.attributes[0])?(h.sendStatus(d,E,"BAD","GETQUOTA expects a quota root name"),I()):d.attributes[0].value!==t.name?(h.sendStatus(d,E,"NO","Quota root does not exist","NONEXISTENT"),I()):(l(h,d,E),h.sendStatus(d,E,"OK","GETQUOTA completed"),I()),{states:Z.AUTHENTICATED,astringArguments:[0]}),s.setCommandHandler("GETQUOTAROOT",(h,d,E,I)=>{if(!d.attributes||d.attributes.length!==1||!ue(d.attributes[0]))return h.sendStatus(d,E,"BAD","GETQUOTAROOT expects a mailbox name"),I();let C=d.attributes[0].value;C.toUpperCase()==="INBOX"&&(C="INBOX");let H=i(C);return h.send({tag:"*",command:"QUOTAROOT",attributes:[{type:"MAILBOX",value:C}].concat(H?{type:"STRING",value:t.name}:[])},"QUOTAROOT",d,E),H&&l(h,d,E),h.sendStatus(d,E,"OK","GETQUOTAROOT completed"),I()},{states:Z.AUTHENTICATED,mailboxArguments:[0]}),s.setCommandHandler("SETQUOTA",(h,d,E,I)=>{let C=d.attributes&&d.attributes[1];if(!d.attributes||d.attributes.length!==2||!ue(d.attributes[0])||!Array.isArray(C)||C.length%2)return h.sendStatus(d,E,"BAD","SETQUOTA expects a quota root name and a list of resource limits"),I();let H={};for(let N=0;N<C.length;N+=2){let w=C[N],G=C[N+1];if(!w||w.type!=="ATOM"||!G||G.type!=="ATOM"||!Ae(G.value,Ge))return h.sendStatus(d,E,"BAD","Invalid resource limit"),I();let F=w.value.toUpperCase();if(Mt.indexOf(F)<0||F in H)return h.sendStatus(d,E,"NO","Can not set a limit for "+F,"CANNOT"),I();let W=Number(G.value);if(!Number.isSafeInteger(W))return h.sendStatus(d,E,"NO","Limit is too large for "+F,"LIMIT"),I();H[F]=W}return d.attributes[0].value!==t.name?(h.sendStatus(d,E,"NO","Quota root does not exist","NONEXISTENT"),I()):(t.limits=H,l(h,d,E),h.sendStatus(d,E,"OK","SETQUOTA completed"),I())},{states:Z.AUTHENTICATED,astringArguments:[0]}),["DELETED","DELETED-STORAGE"].forEach(h=>{s.allowedStatus.indexOf(h)<0&&s.allowedStatus.push(h)}),s.statusHandlers["DELETED-STORAGE"]=(h,d)=>a(d.messages.filter(E=>E.flags.indexOf("\\Deleted")>=0));let A=()=>{let h=u();return{root:t.name,limits:Object.assign({},t.limits),usage:{STORAGE:Math.ceil(h.bytes/1024),MESSAGE:h.MESSAGE,MAILBOX:h.MAILBOX}}},m=h=>{if(!h||typeof h!="object"||Array.isArray(h))throw K("setQuota expects an object of resource limits, e.g. { STORAGE: 1024 }","INVALID");let d={};return Object.keys(h).forEach(E=>{let I=E.toUpperCase(),C=h[E];if(Mt.indexOf(I)<0)throw K("Unknown quota resource "+E+", expected "+Mt.join(", "),"INVALID");if(typeof C!="number"||!Number.isSafeInteger(C)||C<0)throw K("Limit of "+I+" must be a non-negative integer","INVALID");d[I]=C}),t.limits=d,A()};s.control.register("getQuota",A,[{method:"GET",path:"/v1/quota",summary:"Quota root, limits and usage (QUOTA plugin)",handler:()=>s.control.getQuota()}]),s.control.register("setQuota",m,[{method:"PUT",path:"/v1/quota",summary:"Replaces the quota limits ({ STORAGE, MESSAGE, MAILBOX }, QUOTA plugin)",handler:({body:h})=>s.control.setQuota(h)}])}g();var wu=s=>s==="*"||Le(s);function Ti(s){s.registerCapability("REPLACE");let e=function(r,n,i,o,a){let u=r?"UID REPLACE":"REPLACE",l=[].concat(i.attributes||[]),c=l.shift(),f=l.shift();if(!c||["ATOM","SEQUENCE"].indexOf(c.type)<0||!wu(String(c.value)))return n.sendStatus(i,o,"BAD",u+" expects a message number, a mailbox name and a message",!1,"INVALID COMMAND"),a();let p=Nu(n,r,c.value);if(p.error)return n.sendStatus(i,o,p.error.command,p.error.text,p.error.code||!1,p.error.command==="BAD"?"INVALID COMMAND":u+" FAILED"),a();let y=p.message,A=un(n,i,o,f,l,{command:u,maxMessages:1,replaced:y});if(!A)return a();let m=ln(n,A);n.send({tag:"*",command:"OK",attributes:[{type:"TEXT",value:"Replacement message saved"}],skipResponse:!0},"REPLACE APPENDUID",i,o,m),n.expungeSpecificMessages(n.selectedMailbox,[y],!1,!0),n.sendStatus(i,o,"OK",u+" completed",!1,u),a()};s.literalFilters.push((r,n,i)=>{if(n!=="REPLACE"&&n!=="UID REPLACE"||r.isBusy())return!1;let o=i.match(/^\S+ (?:UID )?REPLACE ([^ ]+) /i);return o&&wu(o[1])&&Nu(r,n==="UID REPLACE",o[1]).error||!1});let t={states:Z.SELECTED,mailboxArguments:[1],literal8:"BINARY",appendMessage:!0};s.setCommandHandler("REPLACE",e.bind(null,!1),Object.assign({sequenceSet:0},t)),s.setCommandHandler("UID REPLACE",e.bind(null,!0),t)}function Nu(s,e,t){let r=s.getSessionMessages(),n;if(e){let o=t==="*"?r.length?r[r.length-1].uid:0:Number(t);n=r.find(a=>a.uid===o)}else{let o=t==="*"?r.length:Number(t);if(!o||o>r.length)return{error:{command:"BAD",text:"Invalid message sequence number"}};n=r[o-1]}if(!n||n.ghost)return{error:{command:"NO",text:"No such message"}};let i=s.readOnlyRefusal();return i?{error:i}:{message:n}}g();function Si(s){s.registerCapability("SASL-IR",e=>e.state==="Not Authenticated")}g();function Ii(s){s.registerCapability("SAVEDATE");let e=r=>!!r&&r.SAVEDATE!==!1;s.messageHandlers.push((r,n,i)=>{if(!e(i)){delete n.SAVEDATE;return}let o=r.normalizeDateTime(n.SAVEDATE||r.now());if(!r.validateInternalDate(o))throw new Error("Invalid SAVEDATE value "+JSON.stringify(o)+" in mailbox "+i.path);n.SAVEDATE=o}),s.fetchHandlers.SAVEDATE=(r,n)=>n.SAVEDATE||null;let t=(r,n)=>{let i=(o,a,u,l)=>{let c=vn(a.SAVEDATE||a.internaldate);return!!c&&n(c,l)};i.argumentTypes=()=>["date"],s.searchHandlers[r]=i};t("SAVEDBEFORE",(r,n)=>r<n),t("SAVEDON",(r,n)=>r===n),t("SAVEDSINCE",(r,n)=>r>=n),s.searchHandlers.SAVEDATESUPPORTED=r=>e(r.selectedMailbox)}g();function Oi(s){let e=ei(s,"SAVELIMIT");s.registerCapability("SAVELIMIT="+e),ti(s,e)}g();var Fh=new Set(["SELECT","EXAMINE","CLOSE","UNSELECT"]),_h=s=>["SEARCH","UID SEARCH","SORT","UID SORT","ESEARCH"].includes(s);function xi(s){Ie(s),s.registerCapability("SEARCHRES"),s.searchReturnOptions.set("SAVE",{data:!1}),s.connectionHandlers.push(e=>{let t=e.getMessageRange;e.getMessageRange=function(r,n){if(r!=="$")return t.call(this,r,n);let i=this.searchResult||new Set,o=[];return this.getSessionMessages().forEach((a,u)=>{i.has(a)&&o.push([u+1,a])}),o}}),s.resetHandlers.push(e=>{e.searchResult=null}),s.outputHandlers.push((e,t,r,n,i,o)=>{if(!n||!t||t.tag!==n.tag&&t.command!=="SEARCH"&&t.command!=="SORT")return;let a=(n.command||"").toUpperCase(),u=_h(a)&&n.searchReturn&&n.searchReturn.has("SAVE");if(u&&t.tag==="*"&&(t.command==="SEARCH"||t.command==="SORT")&&r===a&&o&&Array.isArray(o.list)){n.searchresFound=je(o.sorted||o.list,n.searchReturn);return}if(t.tag===n.tag){if(Fh.has(a)){e.searchResult=null;return}u&&t.command!=="BAD"&&(e.searchResult=new Set(t.command==="OK"?n.searchresFound:[]))}})}g();function Ci(s){ct(s),s.registerCapability("SORT=DISPLAY"),s.sortKeys.DISPLAYFROM=e=>He(Vn(e,"from")),s.sortKeys.DISPLAYTO=e=>He(Vn(e,"to"))}g();var Mu=new Set(["\\All","\\Archive","\\Drafts","\\Flagged","\\Junk","\\Sent","\\Trash","\\Important"]);function wi(s){s.registerCapability("SPECIAL-USE");let e=i=>[].concat(i&&i["special-use"]||[]),t=Ke(s);t.selectionOptions["SPECIAL-USE"]={type:"independent",returnOption:"SPECIAL-USE",match:i=>i.flags.indexOf("\\Noselect")<0&&e(i).length>0},t.returnOptions["SPECIAL-USE"]={};let r=s.getCommandHandler("LIST");s.setCommandHandler("LIST",(i,o,a,u)=>{if(t.enabled)return r(i,o,a,u);let l;if(o.attributes&&Array.isArray(o.attributes[0])){for(l=o.attributes[0].length-1;l>=0;l--)o.attributes[0][l]&&o.attributes[0][l].type==="ATOM"&&o.attributes[0][l].value.toUpperCase()==="SPECIAL-USE"&&(o.attributes[0].splice(l,1),o.listSpecialUseOnly=!0);o.attributes[0].length||o.attributes.splice(0,1)}if(o.attributes&&o.attributes[2]&&o.attributes[2].type==="ATOM"&&o.attributes[2].value.toUpperCase()==="RETURN"&&Array.isArray(o.attributes[3])){for(l=o.attributes[3].length-1;l>=0;l--)o.attributes[3][l]&&o.attributes[3][l].type==="ATOM"&&o.attributes[3][l].value.toUpperCase()==="SPECIAL-USE"&&o.attributes[3].splice(l,1);o.attributes[3].length||o.attributes.splice(2,2)}r(i,o,a,u)}),s.outputHandlers.push((i,o,a,u,l,c)=>{let f=e(c).map(p=>({type:"ATOM",value:p}));(a==="LIST ITEM"||a==="LSUB ITEM")&&c&&o.attributes&&Array.isArray(o.attributes[0])&&(f.length?o.attributes[0]=o.attributes[0].concat(f):u.listSpecialUseOnly&&(o.skipResponse=!0))}),s.control.mailboxInfoHandlers.push((i,o)=>{o.specialUse=e(i)});let n=(i,o)=>{let a=s.control.requireMailbox(i,!0);if(!Array.isArray(o)||o.some(u=>typeof u!="string"||!Mu.has(u)))throw K("Special-use attributes must be a list of "+[...Mu].join(", "),"INVALID");return a["special-use"]=[...new Set(o)],s.control.getMailbox(a.path)};s.control.register("setSpecialUse",n,[{method:"PUT",path:"/v1/mailboxes/{path}/special-use",summary:'Sets the special-use attributes of a mailbox ({ specialUse: ["\\Sent"] }, SPECIAL-USE plugin)',handler:({params:i,body:o})=>s.control.setSpecialUse(i.path,o.specialUse)}])}g();function Ni(s){s.registerCapability("STARTTLS",e=>!e.secureConnection),s.setCommandHandler("STARTTLS",(e,t,r,n)=>{if(e.secureConnection)return Gh("Connection is already secured",e,t,r,n);e.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"Server ready to start TLS negotiation"}]},"STARTTLS INIT",t,r),e.upgradeConnection(n)})}function Gh(s,e,t,r,n){return e.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:s}]},"INVALID COMMAND",t,r),n()}g();function Mi(s){s.registerCapability("STATUS=SIZE"),s.allowedStatus.push("SIZE"),s.statusHandlers.SIZE=(e,t)=>t.messages.reduce((r,n)=>r+Te["RFC822.SIZE"](e,n),0)}g();g();function Wt(s){return{entry:s||null,parent:null,children:[]}}function zt(s,e){for(;!s.entry&&s.children.length;)s=s.children[0];for(;!e.entry&&e.children.length;)e=e.children[0];return s.entry.date-e.entry.date||s.entry.seq-e.entry.seq}function Ru(s){let e=[],t=s.slice().reverse();for(;t.length;){let r=t.pop();e.push(r);for(let n=r.children.length-1;n>=0;n--)t.push(r.children[n])}return e}function Xh(s,e){let t=[],r=[],n=i=>{for(let o=i.length-1;o>=0;o--)r.push(")",i[o],"(")};for(n(s);r.length;){let i=r.pop();if(typeof i=="string"){t.push(i);continue}let o=i.children;o.length===1?r.push(o[0]):n(o),i.entry&&(o.length&&r.push(" "),t.push(e?i.entry.message.uid:i.entry.seq))}return t.join("")}function jh(s){let e=(i,o)=>i.subject.id<o.subject.id?-1:i.subject.id>o.subject.id?1:0,t=s.slice().sort((i,o)=>e(i,o)||i.date-o.date||i.seq-o.seq),r=[],n=null;for(let i of t)n&&n.entry.subject.id===i.subject.id?n.children.push(Wt(i)):(n=Wt(i),r.push(n));return r.sort(zt)}function Vh(s){let e=new Map,t=[],r=A=>{if(!e.has(A)){let m=Wt();e.set(A,m),t.push(m)}return e.get(A)},n=(A,m)=>{for(let h=A;h;h=h.parent)if(h===m)return!0;return!1},i=A=>{A.parent&&(A.parent.children.splice(A.parent.children.indexOf(A),1),A.parent=null)},o=(A,m)=>{A!==m&&(!m.children.length||!n(A,m))&&(A.children.push(m),m.parent=A)};for(let A of s){let m=ne(A.message).tree.parsedHeader,h=Ks(m["message-id"])[0],d=h!==void 0&&r(h);(!d||d.entry)&&(d=Wt(),t.push(d)),d.entry=A;let E=Ks(m.references);E.length||(E=Ks(m["in-reply-to"]).slice(0,1));let I=E.map(r);for(let H=1;H<I.length;H++)I[H].parent||o(I[H-1],I[H]);let C=I[I.length-1]||null;d.parent!==C&&(i(d),C&&o(C,d))}let a=t.filter(A=>!A.parent),u=(A,m)=>A.entry?[A]:A.children.length?m&&A.children.length>1?[A]:A.children:[];for(let A of Ru(a).reverse())A.children=A.children.flatMap(m=>u(m,!1)),A.children.forEach(m=>{m.parent=A});let l=a.flatMap(A=>u(A,!0));l.forEach(A=>{A.parent=null}),l.forEach(A=>{A.entry||A.children.sort(zt)}),l.sort(zt);let c=A=>A.entry?A.entry.subject:A.children[0].entry.subject,f=A=>!!A.entry&&A.entry.subject.isReply,p=new Map;for(let A of l){let m=c(A);if(!m.id)continue;let h=p.get(m.id);(!h||h.entry&&(!A.entry||f(h)&&!f(A)))&&p.set(m.id,A)}let y=new Set;for(let A of l){let m=c(A);if(!m.id)continue;let h=p.get(m.id);if(h!==A)if(y.add(A),!h.entry&&!A.entry)A.children.forEach(d=>o(h,d));else if(!h.entry||f(A)&&!f(h))o(h,A);else{let d=Wt();l[l.indexOf(h)]=d,o(d,h),o(d,A),p.set(m.id,d)}}l=l.filter(A=>!y.has(A));for(let A of Ru(l).reverse())A.children.sort(zt);return l.sort(zt),l}var Lu={ORDEREDSUBJECT:jh,REFERENCES:Vh};function lr(s,e){if(s.registerCapability("THREAD="+e),s.threadAlgorithms){s.threadAlgorithms[e]=Lu[e];return}s.threadAlgorithms={[e]:Lu[e]};let t=(r,n,i,o,a)=>{let u=r?"UID THREAD":"THREAD",l=i.attributes||[],c=l[0]&&l[0].type==="ATOM"?l[0].value.toUpperCase():"";if(!Object.hasOwn(s.threadAlgorithms,c))return n.sendStatus(i,o,"BAD",c?"Unsupported threading algorithm "+c:u+" expects a threading algorithm atom",!1,u+" FAILED"),a();let f=zs(n,i,o,l.slice(1));if(!f)return a();let p=f.list.map(y=>{let A=qs(ne(y).tree.parsedHeader.subject);return{message:y,seq:f.numbers[y.uid],date:Qs(y),subject:{id:He(A.subject).toString("binary"),isReply:A.isReply}}});return n.send({tag:"*",command:"THREAD",attributes:p.length?[{type:"TEXT",value:Xh(s.threadAlgorithms[c](p),r)}]:[]},u,i,o,f),n.sendStatus(i,o,"OK",u+" completed",!1,u),a()};s.setCommandHandler("THREAD",t.bind(null,!1),{states:Z.SELECTED,searchCriteria:2,noExpunge:!0}),s.setCommandHandler("UID THREAD",t.bind(null,!0),{states:Z.SELECTED,searchCriteria:2})}function Ri(s){lr(s,"ORDEREDSUBJECT")}g();function Li(s){lr(s,"REFERENCES")}g();function cr(s){s.registerCapability("UIDONLY"),Ne(s,"UIDONLY");let e=i=>ye(i,"UIDONLY"),t=i=>({command:"BAD",code:"UIDREQUIRED",text:i}),r=(i,o)=>{let a=String(o.command||"").toUpperCase(),u=s.getCommandOptions(a),l=/^UID /.test(a)||a==="ESEARCH";if(!l&&(u.sequenceSet!==!1||u.searchCriteria!==!1))return t(a+" is not allowed once UIDONLY is enabled, use UID "+a);if(l&&u.searchCriteria!==!1&&i.usesSequenceNumbers(o))return t("Message numbers are not allowed in the search criteria once UIDONLY is enabled, use UID <sequence set>");if((a==="SELECT"||a==="EXAMINE")&&o.attributes&&Array.isArray(o.attributes[1])){let c=o.attributes[1],f=c.findIndex(y=>J(y,"QRESYNC")),p=f>=0&&c[f+1];if(Array.isArray(p)&&p.slice(2).some(Array.isArray))return t("QRESYNC message sequence match data is not allowed once UIDONLY is enabled")}return!1};s.commandChecks.push((i,o)=>e(i)&&r(i,o)),s.literalFilters.unshift((i,o)=>e(i)&&r(i,{command:o})),s.connectionHandlers.push(i=>{let o=i.isAmbiguous;i.isAmbiguous=function(u){return!e(this)&&o.call(this,u)};let a=i.prepareNotifications;i.prepareNotifications=function(u){return u=a.call(this,u),e(this)?ar(u):u}});let n=(i,o,a,u,l,c)=>{if(!o||o.tag!=="*"||!Array.isArray(o.attributes)||!e(i))return;let f=o.attributes;if(o.command==="OK"&&f[0]&&f[0].type==="SECTION"&&J(f[0].section[0],"UNSEEN")){o.skipResponse=!0;return}if(!J(f[1],"FETCH")||!Array.isArray(f[2]))return;let p=f[2],y=p.findIndex((d,E)=>!(E%2)&&J(d,"UID")),A=c&&typeof c.uid=="number"&&c||o.fetchedMessage,m=A?A.uid:y>=0&&p[y+1];if(!m){o.skipResponse=!0;return}u&&!("uidonlyKeepUid"in u)&&(u.uidonlyKeepUid=qh(u));let h=p;y>=0&&p.length>2&&!(u&&u.uidonlyKeepUid)&&(h=p.slice(0,y).concat(p.slice(y+2))),o.attributes=[m,{type:"ATOM",value:"UIDFETCH"},h]};s.once("pluginsLoaded",()=>s.outputHandlers.push(n))}function qh(s){return String(s.command||"").toUpperCase()!=="UID FETCH"||!s.attributes?!1:[].concat(s.attributes[1]||[]).some(e=>J(e,"UID"))}cr.requires=["ENABLE"];g();function Di(s){s.registerCapability("UIDPLUS"),s.setCommandHandler("UID EXPUNGE",(e,t,r,n)=>{if(!t.attributes||t.attributes.length!==1||!t.attributes[0]||["ATOM","SEQUENCE"].indexOf(t.attributes[0].type)<0)return e.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:"UID EXPUNGE expects uid sequence set"}]},"INVALID COMMAND",t,r),n();if(e.refuseReadOnly(t,r,"UID EXPUNGE FAILED"))return n();let i=t.attributes[0].value,a=e.limitRange(t,e.getMessageRange(i,!0)).map(u=>u[1]).filter(u=>u.flags.indexOf("\\Deleted")>=0);e.expungeSpecificMessages(e.selectedMailbox,a,!1,!0,!!t.highestFirst),e.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"UID EXPUNGE completed"}]},"UID EXPUNGE",t,r),n()}),s.outputHandlers.push((e,t,r,n,i,o)=>{if(r==="APPEND"||r==="REPLACE APPENDUID"){let a=o.messages.map(u=>u.uid);t.attributes=[{type:"SECTION",section:[{type:"ATOM",value:"APPENDUID"},o.mailbox.uidvalidity,a.length>1?{type:"SEQUENCE",value:lt(a)}:a[0]]}].concat(t.attributes),t.skipResponse=!1;return}if(r==="COPY"||r==="UID COPY"||r==="MOVE COPYUID"||r==="UID MOVE COPYUID"){if(!o||!o.sourceUids||!o.sourceUids.length)return;t.attributes=[{type:"SECTION",section:[{type:"ATOM",value:"COPYUID"},o.mailbox.uidvalidity,{type:"SEQUENCE",value:o.sourceUids.join(",")},{type:"SEQUENCE",value:o.targetUids.join(",")}]}].concat(t.attributes),t.skipResponse=!1;return}})}g();function Ui(s){s.registerCapability("UNAUTHENTICATE"),s.setCommandHandler("UNAUTHENTICATE",(e,t,r,n)=>(e.sendStatus(t,r,"OK","Completed, now in not authenticated state"),e.resetSession(),n()),{states:Z.AUTHENTICATED,noArguments:!0})}g();function vi(s){s.registerCapability("UNSELECT"),s.setCommandHandler("UNSELECT",(e,t,r,n)=>(e.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"Mailbox closed"}]},"CLOSE",t,r),e.closeMailbox(),n()),{states:Z.SELECTED,noArguments:!0})}g();function Qh(s){let e=s.match(/\r?\n\r?\n/);return/[\x80-\xff]/.test(e?s.substr(0,e.index):s)}function fr(s){s.registerCapability("UTF8=ACCEPT"),Ne(s,"UTF8=ACCEPT"),s.utf8Accept=!0,s.connectionHandlers.push(wt),s.resetHandlers.push(wt),s.outputHandlers.push((t,r,n,i,o,a)=>{n==="ENABLED"&&Array.isArray(a)&&a.indexOf("UTF8=ACCEPT")>=0&&wt(t)});let e=s.getCommandHandler("APPEND");s.setCommandHandler("APPEND",(t,r,n,i)=>{let o=r.attributes||[],a=o[o.length-1];return!t.utf8Enabled&&o.length>=2&&a&&["LITERAL","LITERAL8"].indexOf(a.type)>=0&&Qh(a.value||"")?(t.sendStatus(r,n,"NO","Message header has 8-bit characters, ENABLE UTF8=ACCEPT first (RFC 9755 section 4)"),i()):e(t,r,n,i)})}fr.requires=["ENABLE"];g();var Yh="1278455344230334865",Kh=2n**64n-1n,Du={"in:inbox":["X-GM-LABELS","\\Inbox"],"in:sent":["X-GM-LABELS","\\Sent"],"in:drafts":["X-GM-LABELS","\\Drafts"],"in:trash":["X-GM-LABELS","\\Trash"],"in:spam":["X-GM-LABELS","\\Junk"],"in:anywhere":["ALL"],"is:unread":["UNSEEN"],"is:read":["SEEN"],"is:starred":["FLAGGED"],"is:important":["X-GM-LABELS","\\Important"]},Uu={from:"FROM",to:"TO",cc:"CC",bcc:"BCC",subject:"SUBJECT",label:"X-GM-LABELS",larger:"LARGER",smaller:"SMALLER",after:"SINCE",before:"BEFORE",rfc822msgid:"HEADER"},zh=["is","has","list","filename","around","size","older","newer","older_than","newer_than","deliveredto","category"];function Bi(s){s.registerCapability("X-GM-EXT-1"),s["HIGHESTX-GM-MSGID"]=BigInt(s.options["HIGHESTX-GM-MSGID"]||Yh),s.messageHandlers.push((a,u,l)=>{let c;u["X-GM-MSGID"]?/^\d+$/.test(u["X-GM-MSGID"])&&BigInt(u["X-GM-MSGID"])>a["HIGHESTX-GM-MSGID"]&&(a["HIGHESTX-GM-MSGID"]=BigInt(u["X-GM-MSGID"])):(a["HIGHESTX-GM-MSGID"]+=1n,u["X-GM-MSGID"]=a["HIGHESTX-GM-MSGID"].toString()),u["X-GM-LABELS"]=[].concat(u["X-GM-LABELS"]||[]),l.path.toUpperCase()==="INBOX"?c=["\\Inbox"]:l["special-use"]&&l["special-use"].length?c=[].concat(l["special-use"]):c=[Hu(l.path)],c.forEach(f=>{a.ensureFlag(u["X-GM-LABELS"],f)})});let e=new Map;s.once("pluginsLoaded",()=>{s.messageHandlers.push((a,u)=>{let l=u.THREADID&&e.get(u.THREADID);u["X-GM-THRID"]||(u["X-GM-THRID"]=l||u["X-GM-MSGID"]),u.THREADID&&!l&&e.set(u.THREADID,u["X-GM-THRID"])})}),s.fetchHandlers["X-GM-MSGID"]=function(a,u){return{type:"ATOM",value:u["X-GM-MSGID"]}},s.fetchHandlers["X-GM-LABELS"]=function(a,u){return Pu(u)};let t=()=>[a=>{if(!/^\d{1,20}$/.test(a)||BigInt(a)>Kh)throw Q("Expected a 64 bit unsigned number");return BigInt(a).toString()}];s.searchHandlers["X-GM-MSGID"]=function(a,u,l,c){return u["X-GM-MSGID"]===c},s.searchHandlers["X-GM-MSGID"].argumentTypes=t,s.fetchHandlers["X-GM-THRID"]=function(a,u){return{type:"ATOM",value:u["X-GM-THRID"]}},s.searchHandlers["X-GM-THRID"]=function(a,u,l,c){return u["X-GM-THRID"]===c},s.searchHandlers["X-GM-THRID"].argumentTypes=t,s.searchHandlers["X-GM-LABELS"]=function(a,u,l,c){return u["X-GM-LABELS"].some(f=>Bu(f)?f.toLowerCase()===c.toLowerCase():a.exportMailboxName(ku(f))===c)};let r=new WeakMap;s.searchHandlers["X-GM-RAW"]=function(a,u,l,c){if(!r.has(c)){let f=a.searchCharset?c:["CHARSET","UTF-8"].concat(c);r.set(c,De(a,[],f,()=>[]).matches)}return r.get(c)(u,l)},s.searchHandlers["X-GM-RAW"].argumentTypes=()=>[$h];let n=(a,u)=>{a["X-GM-LABELS"]=[],i(a,u)},i=(a,u)=>{u.forEach(l=>s.ensureFlag(a["X-GM-LABELS"],l))};[["X-GM-LABELS",n],["+X-GM-LABELS",i],["-X-GM-LABELS",(a,u)=>{u.forEach(l=>s.removeFlag(a["X-GM-LABELS"],l))}]].forEach(([a,u])=>{let l=(c,f,p)=>u(f,p.map(y=>Wh(c,y)));s.storeHandlers[a]=function(c,f,p,y,A,m){l(c,f,p),Jh(c,A,m,y,f)},s.storeHandlers[a+".SILENT"]=l,s.storeHandlers[a].astringValues=s.storeHandlers[a+".SILENT"].astringValues=!0}),s.copyHandlers.push((a,u,l)=>{u["X-GM-MSGID"]&&(l["X-GM-MSGID"]=u["X-GM-MSGID"],l["X-GM-THRID"]=u["X-GM-THRID"])})}var Bu=s=>s.charAt(0)==="\\"&&s.charAt(1)!=="\\",Hu=s=>s.charAt(0)==="\\"?"\\"+s:s,ku=s=>s.charAt(0)==="\\"?s.substr(1):s;function Wh(s,e){let t=String(e&&e.value||"");return e.type==="ATOM"&&t.charAt(0)==="\\"?t:Hu(s.importMailboxName(t))}function Pu(s){return s["X-GM-LABELS"].map(e=>Bu(e)?{type:"ATOM",value:e}:{type:"MAILBOX",value:ku(e)})}function $h(s){let e=[],t=/\s*(?:([(){}])|"([^"]*)"|([^\s(){}"]+?:)"([^"]*)"|([^\s(){}"]+))/gy,r,n=0;for(;n<s.length&&(r=t.exec(s));)n=t.lastIndex,r[1]?e.push({type:r[1]}):typeof r[2]=="string"?e.push({type:"word",value:r[2]}):r[3]?e.push({type:"word",value:r[3]+r[4],operator:r[3].slice(0,-1),operand:r[4]}):e.push({type:"word",value:r[5]});if(s.slice(n).trim())throw Q("X-GM-RAW query has an unterminated quoted string");let i=0,o=()=>e[i],a=c=>{let f=[];for(;i<e.length&&(!o()||o().type!==c);)f.push(u());if(c){if(!o()||o().type!==c)throw Q('X-GM-RAW query is missing "'+c+'"');i++}if(!f.length)throw Q("X-GM-RAW query is empty");return f.length===1?f[0]:f},u=()=>{let c=l();for(;o()&&o().type==="word"&&o().value==="OR"&&e[i+1];)i++,c=["OR",c,l()];return c},l=()=>{let c=e[i++];if(!c||c.type===")"||c.type==="}")throw Q("Unexpected end of X-GM-RAW query");if(c.type==="(")return a(")");if(c.type==="{"){let p=[];for(;o()&&o().type!=="}";)p.push(l());if(!o()||!p.length)throw Q("X-GM-RAW query has an empty or unterminated { } group");return i++,p.reduce((y,A)=>["OR",y,A])}let f=c.value;return f==="-"&&o()&&(o().type==="("||o().type==="{")?["NOT",l()]:f.charAt(0)==="-"&&f.length>1?["NOT",vu(Fu(f.substr(1)))]:vu(c)};return[a()]}function Fu(s){let e=s.match(/^([a-z_0-9]+):(.+)$/i);return e?{value:s,operator:e[1],operand:e[2]}:{value:s,operator:!1,operand:!1}}function vu(s){let e=s.operator?s:Fu(s.value),t=e.operator;if(!t)return["TEXT",s.value];let r=e.operand,n=t.toLowerCase(),i=n+":"+r.toLowerCase(),o=Object.hasOwn(Du,i)&&Du[i];if(o)return o;let a=Object.hasOwn(Uu,n)&&Uu[n];if(a)switch(a){case"LARGER":case"SMALLER":{let u=r.match(/^(\d+)([km]?)$/i);if(!u)throw Q("X-GM-RAW "+n+": expects a size");return[a,String(Number(u[1])*{"":1,k:1024,m:1024*1024}[u[2].toLowerCase()])]}case"SINCE":case"BEFORE":{let u=r.match(/^(\d{4})[/-](\d{1,2})[/-](\d{1,2})$/);if(!u||!It(Number(u[3]),Number(u[2])-1,Number(u[1])))throw Q("X-GM-RAW "+n+": expects a date as YYYY/MM/DD");return[a,Number(u[3])+"-"+St[Number(u[2])-1]+"-"+u[1]]}case"HEADER":return[a,"Message-ID",r];default:return[a,r]}if(n==="in")return["X-GM-LABELS",r];if(zh.indexOf(n)>=0){let u=new Error("X-GM-RAW operator "+n+":"+r+" is not supported by imapkit");throw u.imapResponse="NO",u}return["TEXT",s.value]}function Jh(s,e,t,r,n){let i=[{type:"ATOM",value:"X-GM-LABELS"},Pu(n)];(e.command||"").toUpperCase()==="UID STORE"&&(i.push({type:"ATOM",value:"UID"}),i.push(n.uid)),s.send({tag:"*",attributes:[r,{type:"ATOM",value:"FETCH"},i]},"FLAG UPDATE",e,t,n)}g();var Zh=new TextDecoder("utf-8",{fatal:!0});function Hi(s){s.registerCapability("AUTH=XOAUTH2",e=>e.state==="Not Authenticated"),s.setCommandHandler("AUTHENTICATE XOAUTH2",(e,t,r,n)=>{if(!s.capabilities["SASL-IR"]||!s.capabilities["SASL-IR"](e))return e.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:"SASL-IR must be enabled to support XOAUTH2"}]},"AUTHENTICATE XOAUTH2 FAILED",t,r),n();if(!t.attributes||t.attributes.length!==1||!t.attributes[0]||["STRING","ATOM"].indexOf(t.attributes[0].type)<0)return e.send({tag:t.tag,command:"NO",attributes:[{type:"TEXT",value:"Invalid SASL argument"}]},"AUTHENTICATE XOAUTH2 FAILED",t,r),n();let i=e.decodeSaslResponse(t.attributes[0].value);if(!i)return e.sendStatus(t,r,"BAD","Invalid base64 in SASL response",!1,"AUTHENTICATE XOAUTH2 FAILED"),n();let o=[];try{o=Zh.decode(i).split("")}catch{}let a=(o[0]||"").substr(5),u=(o[1]||"").substr(12);return o.length!==4||!o[0].match(/^user=/)||!o[1].match(/^auth=Bearer /)||!a||!u||o[2]||o[3]?(e.send({tag:t.tag,command:"NO",attributes:[{type:"TEXT",value:"Invalid SASL argument."}]},"AUTHENTICATE XOAUTH2 FAILED",t,r),n()):e.server.getUser(a)?("error"in s.checkAccessToken(u,a)?(e.send({tag:"+",attributes:[{type:"ATOM",value:b.Buffer.from(JSON.stringify({status:"400",schemes:"Bearer",scope:s.oauth?s.oauth.mailScope:"https://mail.google.com/"})).toString("base64")}]},"AUTHENTICATE XOAUTH2 FAILED",t,r),e.inputHandler=function(){e.inputHandler=!1,e.send({tag:t.tag,command:"NO",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"AUTHENTICATIONFAILED"}]},{type:"TEXT",value:"SASL authentication failed"}]},"AUTHENTICATE XOAUTH2 FAILED",t,r)}):(e.state="Authenticated",e.username=a,e.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"User logged in"}]},"AUTHENTICATE XOAUTH2 SUCCESS",t,r)),n()):(e.send({tag:t.tag,command:"NO",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"AUTHENTICATIONFAILED"}]},{type:"TEXT",value:"Invalid credentials"}]},"AUTHENTICATE XOAUTH2 FAILED",t,r),n())})}var $t={acl:gn,appendlimit:En,"auth-plain":An,binary:In,catenate:xn,compress:Cn,condstore:kn,"context-search":qt,"context-sort":qn,"create-special-use":Qn,enable:Bn,esearch:Ie,esort:Qt,id:Yn,idle:Kn,imap4rev2:Ws,"list-extended":Kt,"list-status":$n,literalminus:Yt,literalplus:Jn,logindisabled:Zn,messagelimit:si,metadata:sr,"metadata-server":rr,move:ai,multiappend:ui,multisearch:li,namespace:ci,notify:fi,oauthbearer:hi,objectid:di,partial:pi,preview:Ei,qresync:ur,quota:bi,replace:Ti,"sasl-ir":Si,savedate:Ii,savelimit:Oi,searchres:xi,sort:ct,"sort-display":Ci,"special-use":wi,starttls:Ni,"status-size":Mi,"thread-orderedsubject":Ri,"thread-references":Li,uidonly:cr,uidplus:Di,unauthenticate:Ui,unselect:vi,"utf8-accept":fr,"x-gm-ext-1":Bi,xoauth2:Hi};var _u={"literal+":"literalplus","literal-":"literalminus","compress=deflate":"compress","auth=plain":"auth-plain","auth=xoauth2":"xoauth2","status=size":"status-size","sort=display":"sort-display","thread=orderedsubject":"thread-orderedsubject","thread=references":"thread-references","auth=oauthbearer":"oauthbearer","utf8=accept":"utf8-accept","context=search":"context-search","context=sort":"context-sort"};function ed(){return Object.keys($t)}function Gu(s){let e=String(s).trim().toLowerCase();return Object.hasOwn(_u,e)&&(e=_u[e]),Object.hasOwn($t,e)?e:!1}function td(s,e,t){let r=new Set,n=new Map;(t||new Map).forEach((o,a)=>{let u=Gu(a);u&&n.set($t[u],o)});let i=(o,a)=>{let u=o;if(typeof u=="string"){let f=Gu(u);if(!f&&u.toUpperCase()==="XTOYBIRD")throw new Error("XTOYBIRD was removed in 5.0.0, use the control API (server.control.snapshot(), server.control.addUser() ...) instead, see the README");if(!f)throw new Error('Unknown plugin "'+u+'". Available plugins: '+ed().join(", "));u=$t[f]}if(typeof u!="function")throw new TypeError("Invalid plugin, expecting a plugin name or a function");let l=n.get(u);if(l){if(a)throw new Error(a+" requires "+o+', which the "'+l+'" quirk removes');return}if(r.has(u))return;r.add(u);let c=typeof o=="string"?o.trim():u.name;[].concat(u.requires||[]).forEach(f=>i(f,c)),u(s)};[].concat(e||[]).forEach(o=>i(o)),s.emit("pluginsLoaded")}var Xu=td;g();g();function ki(s,e,t,r){let n=["IMAP4rev1"];Object.keys(s.server.capabilities).forEach(i=>{s.server.capabilities[i](s)&&n.push(i)}),s.send({tag:"*",command:"CAPABILITY",attributes:n.map(i=>({type:"TEXT",value:i}))},"CAPABILITY LIST",e,t,n),s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"Completed"}]},"CAPABILITY COMPLETED",e,t,n),r()}g();function Pi(s,e,t,r){s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"Completed"}]},"CHECK",e,t),r()}g();function Fi(s,e,t,r){return s.canExpunge()&&s.expungeDeleted(s.selectedMailbox,!0),s.notificationQueue=[],s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"Mailbox closed"}]},"CLOSE",e,t),s.closeMailbox(),r()}g();function _i(s,e,t,r){if(!e.attributes||e.attributes.length!==1||!e.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[0].type)<0)return s.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:"CREATE expects mailbox name"}]},"INVALID COMMAND",e,t),r();let n=e.attributes[0].value,i;try{i=xs(s.server,n)}catch(o){let a=o;return s.sendStatus(e,t,"NO",a.message,a.code,"CREATE FAILED"),r()}return s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"CREATE completed"}]},"CREATE",e,t,i),r()}g();function Gi(s,e,t,r){if(!e.attributes||e.attributes.length!==1||!e.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[0].type)<0)return s.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:"DELETE expects mailbox name"}]},"INVALID COMMAND",e,t),r();let n=e.attributes[0].value;try{Cs(s.server,n)}catch(i){let o=i;return s.sendStatus(e,t,"NO",o.message,o.code,"DELETE FAILED"),r()}return s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"DELETE completed"}]},"DELETE",e,t),r()}g();function Xi(s,e,t,r){return an(s,e,t,r,!0)}g();function ji(s,e,t,r){if(s.refuseReadOnly(e,t,"EXPUNGE FAILED"))return r();s.expungeDeleted(s.selectedMailbox,!1,!0),s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"EXPUNGE Completed"}]},"EXPUNGE",e,t),r()}g();function Vi(s,e,t,r){let n;if(!e.attributes||e.attributes.length!==2||!e.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[0].type)<0||!e.attributes[1]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[1].type)<0)return s.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:"LIST expects 2 string arguments"}]},"INVALID COMMAND",e,t),r();if(e.attributes[1].value)n=s.server.matchFolders(e.attributes[0].value,e.attributes[1].value,i=>s.exportMailboxName(i)),n.forEach(i=>{s.send({tag:"*",command:"LIST",attributes:[i.flags.map(o=>({type:"ATOM",value:o})),s.server.getSeparator(i),s.exportMailboxName(i.path)]},"LIST ITEM",e,t,i)});else{let i=s.server,o=e.attributes[0].value||"",a=i.referenceNamespace;try{a=i.getNamespace(s.importMailboxName(o))||a}catch{}let u=a!==!1?i.storage[a]:void 0,l=a!==!1&&a!==i.referenceNamespace?s.exportMailboxName(a):"";u&&s.send({tag:"*",command:"LIST",attributes:[[{type:"ATOM",value:"\\Noselect"}],u.separator,l]},"LIST ITEM",e,t)}return s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"Completed"}]},"LIST",e,t),r()}g();function qi(s,e,t,r){if(!e.attributes||e.attributes.length!==2||!e.attributes[0]||!e.attributes[1]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[0].type)<0||["STRING","LITERAL","ATOM"].indexOf(e.attributes[1].type)<0)return s.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:"LOGIN takes 2 string arguments"}]},"INVALID COMMAND",e,t),r();if(e.attributes.some(i=>/[\x80-\xff]/.test(i.value)))return s.sendStatus(e,t,"BAD","LOGIN does not take UTF-8 user names or passwords, use AUTHENTICATE (RFC 9755 section 5)"),r();let n=s.server.getUser(e.attributes[0].value);if(!n||n.password!==e.attributes[1].value)return s.sendStatus(e,t,"NO","Login failed: authentication failure","AUTHENTICATIONFAILED","LOGIN FAILED"),r();s.state="Authenticated",s.username=e.attributes[0].value,s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"User logged in"}]},"LOGIN SUCCESS",e,t),r()}g();function Qi(s,e,t,r){s.state="Logout",s.send({tag:"*",command:"BYE",attributes:[{type:"TEXT",value:"LOGOUT received"}]},"LOGOUT UNTAGGED",e,t),s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"Completed"}]},"LOGOUT COMPLETED",e,t),s.end(),r()}g();function Yi(s,e,t,r){if(!e.attributes||e.attributes.length!==2||!e.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[0].type)<0||!e.attributes[1]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[1].type)<0)return s.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:"LSUB expects 2 string arguments"}]},"INVALID COMMAND",e,t),r();let n=s.server,i=e.attributes[1].value;return n.matchFolders(e.attributes[0].value,i,a=>s.exportMailboxName(a),n.getSubscriptionTree()).forEach(a=>{let u;if(a.subscribed)u=a.flags.filter(l=>l!=="\\Noselect");else if(i.substr(-1)==="%")u=["\\Noselect"];else return;s.send({tag:"*",command:"LSUB",attributes:[u.map(l=>({type:"ATOM",value:l})),n.getSeparator(a),s.exportMailboxName(a.path)]},"LSUB ITEM",e,t,a)}),s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"Completed"}]},"LSUB",e,t),r()}g();function Ki(s,e,t,r){s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"Completed"}]},"NOOP completed",e,t),r()}g();function zi(s,e,t,r){if(!e.attributes||e.attributes.length!==2||!e.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[0].type)<0||!e.attributes[1]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[1].type)<0)return s.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:"RENAME expects mailbox source and destination names"}]},"INVALID COMMAND",e,t),r();let n=e.attributes[0].value,i=e.attributes[1].value,o;try{o=ws(s.server,n,i)}catch(a){let u=a;return s.sendStatus(e,t,"NO",u.message,u.code,"RENAME FAILED"),r()}return s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"RENAME completed"}]},"RENAME",e,t,o.mailbox),r()}g();function Wi(s,e,t,r,n){let i=s?"UID SEARCH":"SEARCH";if(!t.attributes||!t.attributes.length)return e.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:i+" expects search criteria, empty query given"}]},i+" FAILED",t,r),n();let o;try{o=De(e,e.getSessionMessages(),Ot(t.attributes))}catch(a){return xt(e,t,r,a,i+" FAILED"),n()}return e.send({tag:"*",command:"SEARCH",attributes:o.list.map(a=>s?a.uid:o.numbers[a.uid])},i,t,r,o),e.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:i+" completed"}]},i,t,r),n()}var sd=(s,e,t,r)=>Wi(!1,s,e,t,r),ju=sd;g();function $i(s,e,t,r){if(!e.attributes||e.attributes.length!==2||!e.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[0].type)<0||!Array.isArray(e.attributes[1])||!e.attributes[1].length)return s.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:"STATUS expects mailbox argument and a list of status items"}]},"INVALID COMMAND",e,t),r();let n=e.attributes[0].value,i;try{i=Js(s.server,e.attributes[1],s)}catch(u){return s.sendStatus(e,t,"BAD",u.message,!1,"STATUS FAILED"),r()}let o=s.server.getMailbox(n);if(!o||o.flags.indexOf("\\Noselect")>=0)return s.sendStatus(e,t,"NO","Mailbox does not exist","NONEXISTENT","STATUS FAILED"),r();Zs(s,n,o,i,e,t);let a=s.state==="Selected"&&s.selectedMailbox===o;return s.sendStatus(e,t,"OK",a?"Status completed, STATUS SHOULD NOT be used on the selected mailbox":"Status completed",a&&"CLIENTBUG"),r()}g();function Vu(s,e){return e=String(e).toUpperCase(),s.server.storeHandlers[e]||Ts[e]}function Ji(s,e,t,r,n){let i=s?"UID STORE":"STORE",o=t.attributes&&t.attributes[1],a=J(o)&&Vu(e,o.value),u=!!(a&&a.astringValues),l=u?["ATOM","STRING","LITERAL"]:["ATOM","STRING"];if(u&&yt(t,r,h=>h[0]===2),!t.attributes||t.attributes.length!==3||!t.attributes[0]||["ATOM","SEQUENCE"].indexOf(t.attributes[0].type)<0||!t.attributes[1]||["ATOM"].indexOf(t.attributes[1].type)<0||!t.attributes[2]||!(l.indexOf(t.attributes[2].type)>=0||Array.isArray(t.attributes[2])))return e.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:i+" expects sequence set, item name and item value"}]},"INVALID COMMAND",t,r),n();if(e.refuseReadOnly(t,r,i+" FAILED"))return n();let c=e.limitRange(t,e.getCommandRange(t.attributes[0].value,s)),f=(t.attributes[1].value||"").toUpperCase(),p=[].concat(t.attributes[2]||[]),y=[],A=!1;try{p.forEach((d,E)=>{if(!d||l.indexOf(d.type)<0)throw new Error("Invalid item value #"+(E+1))});let h=a||Vu(e,f);if(!h)throw new Error("Invalid STORE argument "+f);c.forEach(d=>{if(d[1].ghost){A=!0;return}for(let E=0,I=e.server.storeFilters.length;E<I;E++)if(!e.server.storeFilters[E](e,d[1],t,d[0]))return;h(e,d[1],p,d[0],t,r),y.push(d[1])})}catch(h){let d=h;return e.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:d.message}]},i+" FAILED",t,r),n()}let m=A&&!/\.SILENT$/.test(f);e.send({tag:t.tag,command:m?"NO":"OK",attributes:[].concat(m?{type:"SECTION",section:[{type:"ATOM",value:"EXPUNGEISSUED"}]}:[],{type:"TEXT",value:m?"Some of the messages no longer exist":i+" completed"})},i+(m?" FAILED":" COMPLETE"),t,r,y),e.notifyFlagChanges(y),n()}var rd=(s,e,t,r)=>Ji(!1,s,e,t,r),qu=rd;g();function Zi(s,e,t,r){if(!e.attributes||e.attributes.length!==1||!e.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[0].type)<0)return s.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:"SUBSCRIBE expects mailbox name"}]},"INVALID COMMAND",e,t),r();try{Ht(s.server,e.attributes[0].value)}catch(n){let i=n;return s.sendStatus(e,t,"NO",i.message,i.code,"SUBSCRIBE FAILED"),r()}return s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"SUBSCRIBE completed"}]},"SUBSCRIBE",e,t),r()}g();function eo(s,e,t,r){return ii(s,e,t,r,!0)}g();var nd=(s,e,t,r)=>wn(!0,s,e,t,r),Qu=nd;g();var id=(s,e,t,r)=>Wi(!0,s,e,t,r),Yu=id;g();var od=(s,e,t,r)=>Ji(!0,s,e,t,r),Ku=od;g();function to(s,e,t,r){return!e.attributes||e.attributes.length!==1||!e.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[0].type)<0?(s.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:"UNSUBSCRIBE expects mailbox name"}]},"INVALID COMMAND",e,t),r()):(Ns(s.server,e.attributes[0].value),s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"UNSUBSCRIBE completed"}]},"UNSUBSCRIBE",e,t),r())}var zu={APPEND:cn,CAPABILITY:ki,CHECK:Pi,CLOSE:Fi,COPY:ni,CREATE:_i,DELETE:Gi,EXAMINE:Xi,EXPUNGE:ji,FETCH:za,LIST:Vi,LOGIN:qi,LOGOUT:Qi,LSUB:Yi,NOOP:Ki,RENAME:zi,SEARCH:ju,SELECT:nn,STATUS:$i,STORE:qu,SUBSCRIBE:Zi,"UID COPY":eo,"UID FETCH":Qu,"UID SEARCH":Yu,"UID STORE":Ku,UNSUBSCRIBE:to};g();g();var Ju=/^[\x20\x21\x23-\x5b\x5d-\x7e]*$/,so=s=>s.replace(/[^\x20\x21\x23-\x5b\x5d-\x7e]/g," "),ro=s=>typeof s=="string"&&s!==""&&Ju.test(s),Wu=["prompt","approve","deny"],$u=["wrong-state","wrong-iss","no-redirect"];function $e(s,e,t=!1){if(typeof s=="string"&&(Wu.includes(s)||t&&$u.includes(s)))return s;if(s&&typeof s=="object"&&!Array.isArray(s)){let{error:n,description:i}=s;if(ro(n)){if(i!==void 0&&(typeof i!="string"||!Ju.test(i)))throw new z(e+': description must be printable ASCII without " and \\ (RFC 6749 section 4.1.2.1)',"INVALID");return i===void 0?{error:n}:{error:n,description:i}}}let r=Wu.concat(t?$u:[]).map(n=>'"'+n+'"');throw new z(e+" must be "+r.join(", ")+' or { error, description }, e.g. { error: "access_denied" }',"INVALID")}function Jt(s){return typeof s=="string"?s:"error "+s.error}function ad(s){if(!(s===void 0||typeof s=="function"))return s===null||typeof s!="object"?s:JSON.parse(JSON.stringify(s))}function no(s,e){let t={};return Object.keys(s).forEach(r=>{let n=e.has(r)?void 0:ad(s[r]);n!==void 0&&(t[r]=n)}),t}var ud=new Set(["ghost"]),ld=new Set(["folders"]),cd=new Set(["path","namespace","messages","folders","subscribed","flags"]),fd=new Set(["\\HasChildren","\\HasNoChildren"]);function io(s,e){if(!s||typeof s!="object"||Array.isArray(s))throw new z(e+" must be { consent }","INVALID");let{consent:t}=s;return t===void 0?{}:{consent:$e(t,e+".consent")}}var hr=class{constructor(e){this.server=e,this.routes=[],this.snapshotHandlers=[],this.mailboxInfoHandlers=[],this.messageInfoHandlers=[]}register(e,t,r){if(e in this)throw new Error("Control operation "+e+" exists already");this[e]=(...n)=>this.run(()=>t(...n)),this.routes.push(...r||[])}run(e){return this.server.withOrigin(null,e)}requireMailbox(e,t){let r=typeof e=="string"&&e?this.server.getMailbox(e):void 0;if(!r||t&&r.flags.indexOf("\\Noselect")>=0)throw new z("Mailbox "+JSON.stringify(e)+" does not exist","NONEXISTENT");return r}checkName(e){this.checkPath(e);let t=Tt(e);if(t)throw new z(t,"INVALID")}checkPath(e){if(typeof e!="string"||!e)throw new z("Mailbox name must be a non-empty string","INVALID")}requireMessages(e,t){if(!Array.isArray(t)||t.some(i=>!Number.isSafeInteger(i)||i<1))throw new z("UIDs must be an array of positive integers","INVALID");let r=new Map(e.messages.map(i=>[i.uid,i])),n=t.filter(i=>!r.has(i));if(n.length)throw new z("No message with UID "+n.join(", ")+" in "+e.path,"NONEXISTENT");return[...new Set(t)].map(i=>r.get(i))}findSessions(e){let t=typeof e=="number"?{session:e}:e||{};if(t.session===void 0&&t.user===void 0)throw new z("Select sessions by number or user","INVALID");return[...this.server.connections].filter(r=>r.isOpen()&&(t.session===void 0||r.sessionNumber===t.session)&&(t.user===void 0||r.username===t.user))}snapshot(){let e=this.server,t=i=>{let o=no(i,cd);return this.snapshotHandlers.forEach(a=>a(i,o)),o.flags=i.flags.filter(a=>!fd.has(a)),o.subscribed=!!i.subscribed,o.messages=i.messages.map(a=>no(a,ud)),i.folders&&(o.folders=r(i.folders)),o},r=i=>{let o={};return Object.keys(i).forEach(a=>{o[a]=t(i[a])}),o},n={};return Object.keys(e.storage).forEach(i=>{if(i==="INBOX"){n.INBOX=t(e.storage.INBOX);return}let o=e.storage[i];n[i]=Object.assign(no(o,ld),{folders:r(o.folders||{})})}),n}listMailboxes(){return Object.keys(this.server.folderCache).sort().map(e=>this.describeMailbox(this.server.folderCache[e]))}getMailbox(e){return this.describeMailbox(this.requireMailbox(e))}describeMailbox(e){let t=this.server.getStatus(e),r={path:e.path,delimiter:this.server.getSeparator(e),flags:e.flags.slice(),selectable:e.flags.indexOf("\\Noselect")<0,subscribed:!!e.subscribed,messages:e.messages.length,unseen:t?t.unseen:0,uidnext:e.uidnext,uidvalidity:e.uidvalidity,permanentFlags:t?t.permanentFlags.slice():[]};return this.server.condstore&&typeof e.HIGHESTMODSEQ=="number"&&(r.highestModseq=e.HIGHESTMODSEQ),this.mailboxInfoHandlers.forEach(n=>n(e,r)),r}listMessages(e,t={}){let r=this.requireMailbox(e,!0);return(t.uids?this.requireMessages(r,t.uids).sort((i,o)=>i.uid-o.uid):r.messages).map(i=>this.describeMessage(i,!!t.raw))}getMessage(e,t,r={}){let n=this.requireMailbox(e,!0);return this.describeMessage(this.requireMessages(n,[t])[0],r.raw!==!1)}describeMessage(e,t){let r={uid:e.uid,flags:e.flags.slice(),internaldate:e.internaldate,size:e.raw.length};return this.server.condstore&&typeof e.MODSEQ=="number"&&(r.modseq=e.MODSEQ),t&&(r.raw=b.Buffer.from(e.raw,"binary")),this.messageInfoHandlers.forEach(n=>n(e,r)),r}sessions(){return[...this.server.connections].map(e=>e.describe()).sort((e,t)=>e.session-t.session)}addMessage(e,t,r={}){let n=this.requireMailbox(e,!0),{raw:i,flags:o,internaldate:a}=t||{},u;if(typeof i=="string")u=b.Buffer.from(i,"utf-8").toString("binary");else if(i instanceof Uint8Array)u=b.Buffer.from(i).toString("binary");else throw new z("Message source (raw) must be a string or a Buffer","INVALID");if(!u.length)throw new z("Message source (raw) can not be empty","INVALID");let l=hn(this.server,n,o||[],!0);if(a!==void 0&&!(a instanceof Date&&!isNaN(a.getTime()))&&!this.server.validateInternalDate(a))throw new z('Internal date must be a Date or a date-time string like "17-Jul-1996 02:44:25 -0700"',"INVALID");if(r.checks){let f=this.server.appendChecks.map(p=>p(null,n,[{raw:u,flags:l,internaldate:a}],{command:"APPEND"})).find(p=>p&&!p.soft);if(f){let p=Array.isArray(f.code)?f.code[0]:f.code;throw new z(f.text,typeof p=="string"?p:"CANNOT")}}return{uid:this.run(()=>this.server.appendMessage(n,l,a||null,u)).message.uid,uidvalidity:n.uidvalidity}}setFlags(e,t,r,n="set"){let i=this.requireMailbox(e,!0),o=this.requireMessages(i,t);return this.run(()=>Ma(this.server,i,o,r,n)),o.map(a=>({uid:a.uid,flags:a.flags.slice()}))}expungeMessages(e,t){let r=this.requireMailbox(e,!0),n=this.requireMessages(r,t);return this.run(()=>it(this.server,r,n)).map(i=>i.uid)}copyMessages(e,t,r){return this.transfer(e,t,r,!1)}moveMessages(e,t,r){return this.transfer(e,t,r,!0)}transfer(e,t,r,n){let i=this.requireMailbox(e,!0),o=this.requireMailbox(r,!0),a=this.requireMessages(i,t).sort((u,l)=>u.uid-l.uid);return this.run(()=>{let u=a.map(l=>({uid:l.uid,targetUid:this.server.copyMessage(o,l).message.uid}));return n&&it(this.server,i,a),{uidvalidity:o.uidvalidity,uids:u}})}replaceMessage(e,t,r){let n=this.requireMailbox(e,!0),i=this.requireMessages(n,[t])[0],o=this.addMessage(e,{raw:r&&r.raw,flags:r&&r.flags?r.flags:i.flags.slice(),internaldate:r&&r.internaldate?r.internaldate:i.internaldate});return this.run(()=>it(this.server,n,[i])),o}createMailbox(e,t={}){this.checkName(e);let r=this.run(()=>{let n=xs(this.server,e);return t.subscribed&&Ht(this.server,n.path),n});return this.describeMailbox(r)}deleteMailbox(e){this.checkPath(e),this.run(()=>Cs(this.server,e))}renameMailbox(e,t){this.checkPath(e),this.checkName(t);let r=this.run(()=>ws(this.server,e,t));return this.getMailbox(r.path)}resetUidValidity(e,t={}){let r=this.requireMailbox(e,!0);return this.run(()=>La(this.server,r,t||{}))}subscribe(e){return this.checkPath(e),this.run(()=>Ht(this.server,e))}unsubscribe(e){return this.checkPath(e),this.run(()=>Ns(this.server,e))}listUsers(){return Object.keys(this.server.users).sort().map(e=>({name:e,xoauth2:!!(this.server.users[e].xoauth2&&this.server.users[e].xoauth2.accessToken)}))}addUser(e,t){if(typeof e!="string"||!e)throw new z("User name must be a non-empty string","INVALID");if(Object.hasOwn(this.server.users,e))throw new z("User "+JSON.stringify(e)+" already exists","ALREADYEXISTS");this.server.users[e]=this.userData({},t)}updateUser(e,t){this.server.users[e]=this.userData(this.requireUser(e),t)}deleteUser(e,t={}){this.requireUser(e),delete this.server.users[e],t.disconnect!==!1&&this.findSessions({user:e}).forEach(r=>r.bye("User was deleted","USER DELETED"))}requireUser(e){if(typeof e!="string"||!Object.hasOwn(this.server.users,e))throw new z("User "+JSON.stringify(e)+" does not exist","NONEXISTENT");return this.server.users[e]}userData(e,t){let{password:r,xoauth2:n,displayName:i,oauth:o}=t||{},a=Object.assign({},e);if(i===null)delete a.displayName;else if(i!==void 0){if(typeof i!="string")throw new z("displayName must be a string","INVALID");a.displayName=i}if(o===null?delete a.oauth:o!==void 0&&(a.oauth=io(o,"oauth")),r!==void 0){if(typeof r!="string")throw new z("Password must be a string","INVALID");a.password=r}if(n===null)delete a.xoauth2;else if(n!==void 0){if(typeof n!="object"||typeof n.accessToken!="string")throw new z("xoauth2 must be { accessToken, sessionTimeout }","INVALID");a.xoauth2={accessToken:n.accessToken,sessionTimeout:Number(n.sessionTimeout)||Os}}return a}disconnect(e,t={}){let r=this.findSessions(e);return r.forEach(n=>{t.reset?n.closeNow("reset"):n.bye(t.text||"Disconnected by the server","DISCONNECT")}),r.length}inject(e,t){let r=this.findSessions({session:e})[0];if(!r)throw new z("Session "+e+" does not exist","NONEXISTENT");if(typeof t!="string"&&!(t instanceof Uint8Array))throw new z("Data must be a string or a Buffer","INVALID");r.write(b.Buffer.from(t))}reset(){this.server.connections.forEach(e=>{e.isOpen()&&e.bye("Server reset","RESET")}),this.run(()=>{this.server.loadUsers(),this.server.loadStorage(),this.server.emit("reset")})}shutdown(e={}){return new Promise((t,r)=>{let n=i=>i&&i.code!=="ERR_SERVER_NOT_RUNNING"?r(i):t();e.graceful===!1?this.server.close(n):(this.server.closeListeners(!1),this.server.closeImapListeners(n))})}};g();var oo=["FETCH","UID FETCH"];function hd(s){return String(s[0]&&s[0].value||"").toUpperCase().replace(/(^|\.)(MIME|HEADER(\.FIELDS(\.NOT)?)?|TEXT)$/,"")}function Zu(s,e){let t=s.attributes&&s.attributes[2];if(!Array.isArray(t)||!s.attributes[1]||s.attributes[1].value!=="FETCH")return;let r=t.slice();for(let n=0;n<r.length-1;n+=2){let i=r[n];i&&i.type==="ATOM"&&String(i.value).toUpperCase()==="BODY"&&Array.isArray(i.section)&&(r[n+1]=e(i,r[n+1]))}return Object.assign({},s,{attributes:[s.attributes[0],s.attributes[1],r]})}var Zt={"james-fetchgroup":{description:"Apache James FetchGroup: only the first section asked for a part in one FETCH is answered, later ones for the same part come back empty. BODY[2.MIME] BODY[2] gives a zero-length body, the reverse order loses the headers",rules:[{on:"response",command:oo,untagged:!0,mutate:s=>{let e=new Set;return Zu(s,(t,r)=>{let n=hd(t.section);return e.has(n)?{type:"LITERAL",value:""}:(e.add(n),r)})}}]},"james-late-fetch":{description:"Apache James: now and then (1 in 4) a FETCH response comes after the tagged OK of its command",rules:[{on:"response",command:oo,untagged:!0,chance:.25,defer:"tagged"}]},"yahoo-quoted-sections":{description:"Yahoo: short body sections (up to 100 octets without line breaks) are quoted strings instead of literals",rules:[{on:"response",command:oo,untagged:!0,mutate:s=>Zu(s,(e,t)=>t&&t.type==="LITERAL"&&typeof t.value=="string"&&t.value.length<=100&&/^[\x20-\x7e]*$/.test(t.value)?{type:"STRING",value:t.value}:t)}]},"m365-throttle":{description:'Microsoft 365: 1 in 10 commands (not LOGOUT) is refused with "BAD Request is throttled. Suggested Backoff Time: 1000 milliseconds"',rules:[{on:"command",chance:.1,when:s=>s.command!=="LOGOUT",send:`$TAG BAD Request is throttled. Suggested Backoff Time: 1000 milliseconds\r
|
|
32
|
+
`}]},"no-uidplus":{description:"A server without UIDPLUS: no APPENDUID, COPYUID or UID EXPUNGE, even when the plugins list it",removePlugins:["UIDPLUS"]},"no-move":{description:"A server without MOVE, clients have to COPY, STORE \\Deleted and EXPUNGE",removePlugins:["MOVE"]}};function el(s){let e=[],t=new Map;return[].concat(s||[]).forEach(r=>{let n=String(r).toLowerCase(),i=Object.hasOwn(Zt,n)?Zt[n]:null;if(!i)throw new Error('Unknown quirk "'+r+'". Available quirks: '+Object.keys(Zt).join(", "));e.push(...i.rules||[]),(i.removePlugins||[]).forEach(o=>t.set(o,n))}),{rules:e,removePlugins:t}}g();var dd=["acl","metadata","special-use","MAILBOXID","HIGHESTMODSEQ","qresyncExpunged","appendLimit","SAVEDATE","MODSEQ","EMAILID","THREADID","X-GM-LABELS","X-GM-MSGID","X-GM-THRID"],dr={type:"array",items:{type:"string"}},ao={type:"integer",minimum:1,maximum:4294967295},lo={$schema:"https://json-schema.org/draft/2020-12/schema",title:"ImapKit storage",description:'Namespaces by prefix ("INBOX", "", "INBOX.", "#shared/" ...), INBOX is a mailbox of its own',type:"object",properties:{INBOX:{$ref:"#/$defs/mailbox"}},additionalProperties:{$ref:"#/$defs/namespace"},$defs:{message:{oneOf:[{type:"string",description:"the message source"},{type:"object",properties:{raw:{type:"string",description:"the message source (a Buffer also works in JavaScript)"},uid:ao,flags:{oneOf:[{type:"string"},dr]},internaldate:{type:"string",description:'RFC 3501 date-time, e.g. "14-Sep-2013 21:22:28 -0300" (a Date also works in JavaScript)'},recent:{type:"boolean"}}}]},mailbox:{type:"object",properties:{uid:{type:"integer"},uidvalidity:ao,uidnext:ao,flags:dr,permanentFlags:dr,allowPermanentFlags:{type:"boolean"},subscribed:{type:"boolean"},knownFlags:dr,messages:{type:"array",items:{$ref:"#/$defs/message"}},folders:{type:"object",additionalProperties:{$ref:"#/$defs/mailbox"}}}},namespace:{type:"object",properties:{separator:{type:"string",minLength:1,maxLength:1},type:{enum:["personal","user","shared"]},folders:{type:"object",additionalProperties:{$ref:"#/$defs/mailbox"}}}}}},uo=Object.keys(lo.$defs.mailbox.properties),pd=["separator","type"],md=Object.keys(lo.$defs.message.oneOf[1].properties);function gd(s,e){return e.includes(s)||dd.includes(s)?null:e.find(t=>t.toLowerCase()===s.toLowerCase()||s.length>3&&Ed(t,s)===1)||null}function Ed(s,e){let t=Array.from({length:e.length+1},(r,n)=>n);for(let r=1;r<=s.length;r++){let n=t[0];t[0]=r;for(let i=1;i<=e.length;i++){let o=t[i];t[i]=Math.min(t[i]+1,t[i-1]+1,n+(s[r-1]===e[i-1]?0:1)),n=o}}return t[e.length]}var pr=s=>!!s&&typeof s=="object"&&!Array.isArray(s),tl=s=>Array.isArray(s)&&s.every(e=>typeof e=="string"),sl=s=>Number.isSafeInteger(s)&&s>=1&&s<=4294967295;function co(s){let e=(i,o)=>{throw new Error("Invalid storage at "+i+": "+o)},t=(i,o,a)=>{Object.keys(i).forEach(u=>{let l=gd(u,a);l&&e(o,"unknown key "+JSON.stringify(u)+", did you mean "+JSON.stringify(l)+"?")})},r=(i,o)=>{if(!(typeof i=="string"||i instanceof Uint8Array)){if(!pr(i))return e(o,"a message is a string or an object");t(i,o,md),i.raw!==void 0&&typeof i.raw!="string"&&!(i.raw instanceof Uint8Array)&&e(o+".raw","must be a string"),i.uid!==void 0&&!sl(i.uid)&&e(o+".uid","must be an integer from 1 to "+4294967295),i.flags!==void 0&&typeof i.flags!="string"&&!tl(i.flags)&&e(o+".flags","must be a flag or a list of flags");for(let a of["internaldate","SAVEDATE"]){let u=i[a];u===void 0||u===!1||a==="SAVEDATE"&&u===null||(u instanceof Date?isNaN(u.getTime()):!ks(u))&&e(o+"."+a,'must be a date-time string like "14-Sep-2013 21:22:28 -0300" or a Date, not '+JSON.stringify(u))}i.recent!==void 0&&typeof i.recent!="boolean"&&e(o+".recent","must be true or false")}},n=(i,o,a)=>{if(!pr(i))return e(o,"a mailbox is an object");t(i,o,a);for(let u of["uidvalidity","uidnext"])i[u]!==void 0&&!sl(i[u])&&e(o+"."+u,"must be an integer from 1 to "+4294967295);for(let u of["flags","permanentFlags","knownFlags"])i[u]!==void 0&&!tl(i[u])&&e(o+"."+u,"must be a list of strings");for(let u of["allowPermanentFlags","subscribed"])i[u]!==void 0&&typeof i[u]!="boolean"&&e(o+"."+u,"must be true or false");i.messages!==void 0&&(Array.isArray(i.messages)||e(o+".messages","must be a list of messages"),i.messages.forEach((u,l)=>r(u,o+".messages["+l+"]"))),i.folders!==void 0&&(pr(i.folders)||e(o+".folders","must be an object of mailboxes by name"),Object.keys(i.folders).forEach(u=>n(i.folders[u],o+".folders["+JSON.stringify(u)+"]",uo)))};pr(s)||e("the top level","storage is an object of namespaces"),Object.keys(s).forEach(i=>{let o=s[i],a=JSON.stringify(i);if(i==="INBOX")return n(o,a,uo.concat("separator"));n(o,a,uo.concat(pd));let u=o;u.separator!==void 0&&(typeof u.separator!="string"||u.separator.length!==1)&&e(a+".separator","must be a single character"),u.type!==void 0&&!["personal","user","shared"].includes(u.type)&&e(a+".type",'must be "personal", "user" or "shared"')})}g();g();var fo=s=>()=>{throw new Error(s+" is not available in the browser")},Ad=fo("The REST API and the OAuth provider"),yd=fo("The REST API"),bd=fo("The REST API"),ce={createServer:Ad,createHash:yd,timingSafeEqual:bd};var Td=64*1024*1024,Sd={NONEXISTENT:404,NOTFOUND:404,ALREADYEXISTS:409,INVALID:400,UNAUTHORIZED:401,METHOD:405,TOOBIG:413,UNSUPPORTED:415};function ke(s){let e=s.replace(/^\[|\]$/g,"").toLowerCase();return e==="localhost"||e==="::1"||/^(::ffff:)?127\.\d+\.\d+\.\d+$/.test(e)}var es=s=>/^\d+$/.test(s)?Number(s):NaN;function rl(s){let{raw:e,...t}=s;return e?Object.assign(t,{raw:e.toString("base64"),encoding:"base64"}):t}function Id(s,e){if(e!==void 0&&e!=="base64"&&e!=="utf-8")throw K('encoding must be "utf-8" or "base64"',"INVALID");return e==="base64"&&typeof s=="string"?b.Buffer.from(s,"base64"):s}var ho=["session","command","mailbox","append","expunge","flags","acl","script","reset","oauth"],nl=["trace"],po=s=>s?s.sessionNumber:null;function Od(s,e){switch(s){case"mailbox":{let{type:t,path:r,oldPath:n,origin:i}=e[0];return{type:t,path:r,oldPath:n,origin:po(i)}}case"append":case"expunge":return{path:e[0].path,uids:e[1].map(t=>t.uid),origin:po(e[2])};case"trace":{let{session:t,direction:r,data:n}=e[0];return{session:t,direction:r,data:b.Buffer.from(n).toString("base64"),encoding:"base64"}}case"flags":return{path:e[0].path,messages:e[1].map(t=>({uid:t.uid,flags:t.flags.slice()})),origin:po(e[2])};case"acl":return{path:e[0].path};default:return e[0]||{}}}function xd(s,e,t){return(r,n)=>{t.add(r),r.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-store"}),r.write(`: connected
|
|
33
33
|
|
|
34
|
-
`);let i=
|
|
35
|
-
data: `+JSON.stringify(
|
|
34
|
+
`);let i=e.map(a=>{let u=(...l)=>r.write("event: "+a+`
|
|
35
|
+
data: `+JSON.stringify(Od(a,l))+`
|
|
36
36
|
|
|
37
|
-
`);return
|
|
37
|
+
`);return s.on(a,u),{type:a,listener:u}}),o=setInterval(()=>r.write(`: ping
|
|
38
38
|
|
|
39
|
-
`),15e3);a.unref(),n.on("close",()=>{e.delete(s),clearInterval(a),i.forEach(({type:o,listener:u})=>r.removeListener(o,u))})}}function Hh(r,t=new Set){let e=r.control,s=i=>({id:i.id,rule:i.rule,matched:i.matched,hits:i.hits}),n=[{method:"GET",path:"/v1/snapshot",summary:"The storage in the shape of the storage option",handler:()=>e.snapshot()},{method:"POST",path:"/v1/reset",summary:"Restores the mailboxes and users of the server options, disconnects every session",handler:()=>(e.reset(),{reset:!0})},{method:"POST",path:"/v1/shutdown",summary:"Stops accepting connections, the server closes once the last client is gone ({ graceful: false } closes them)",handler:({body:i})=>(L(()=>e.shutdown({graceful:i.graceful!==!1}).catch(()=>!1)),{status:202,body:{shutdown:!0}})},{method:"GET",path:"/v1/sessions",summary:"Connected sessions",handler:()=>e.sessions()},{method:"GET",path:"/v1/events",summary:"Server events as Server-Sent Events (?types=session,command to choose: "+os.join(", ")+")",handler:({query:i})=>{let a=i.get("types"),o=a===null?os:a.split(","),u=o.filter(l=>os.indexOf(l)<0);if(u.length)throw K("Unknown event type "+u.join(", ")+", expected "+os.join(", "),"INVALID");return{stream:Bh(r,o,t)}}},{method:"DELETE",path:"/v1/sessions/{session}",summary:"Disconnects a session with BYE ({ text }) or a TCP reset ({ reset: true })",handler:({params:i,body:a})=>{if(!e.disconnect(Ye(i.session),{text:a.text,reset:a.reset}))throw K("Session "+i.session+" does not exist","NONEXISTENT");return{disconnected:!0}}},{method:"POST",path:"/v1/sessions/{session}/inject",summary:"Writes bytes to a session as they are ({ data, encoding })",handler:({params:i,body:a})=>(e.inject(Ye(i.session),a.encoding==="base64"&&typeof a.data=="string"?I.Buffer.from(a.data,"base64"):a.data),{injected:!0})},{method:"GET",path:"/v1/users",summary:"Users, without credentials",handler:()=>e.listUsers()},{method:"POST",path:"/v1/users",summary:"Adds a user ({ name, password, xoauth2 })",handler:({body:i})=>(e.addUser(i.name,{password:i.password,xoauth2:i.xoauth2}),{status:201,body:{name:i.name}})},{method:"PUT",path:"/v1/users/{name}",summary:"Changes the password or the XOAUTH2 token of a user",handler:({params:i,body:a})=>(e.updateUser(i.name,{password:a.password,xoauth2:a.xoauth2}),{name:i.name})},{method:"DELETE",path:"/v1/users/{name}",summary:"Deletes a user and disconnects its sessions ({ disconnect: false } keeps them)",handler:({params:i,body:a})=>(e.deleteUser(i.name,{disconnect:a.disconnect}),{deleted:!0})},{method:"GET",path:"/v1/mailboxes",summary:"Every mailbox",handler:()=>e.listMailboxes()},{method:"POST",path:"/v1/mailboxes",summary:"Creates a mailbox ({ path, subscribed })",handler:({body:i})=>({status:201,body:e.createMailbox(i.path,{subscribed:i.subscribed})})},{method:"GET",path:"/v1/mailboxes/{path}",summary:"A mailbox",handler:({params:i})=>e.getMailbox(i.path)},{method:"DELETE",path:"/v1/mailboxes/{path}",summary:"Deletes a mailbox, sessions that have it selected get BYE",handler:({params:i})=>(e.deleteMailbox(i.path),{deleted:!0})},{method:"POST",path:"/v1/mailboxes/{path}/rename",summary:"Renames a mailbox ({ newPath })",handler:({params:i,body:a})=>e.renameMailbox(i.path,a.newPath)},{method:"PUT",path:"/v1/mailboxes/{path}/subscription",summary:"Subscribes a mailbox",handler:({params:i})=>({changed:e.subscribe(i.path)})},{method:"DELETE",path:"/v1/mailboxes/{path}/subscription",summary:"Unsubscribes a name",handler:({params:i})=>({changed:e.unsubscribe(i.path)})},{method:"POST",path:"/v1/mailboxes/{path}/uidvalidity",summary:"Gives the mailbox a new UIDVALIDITY ({ uidvalidity, uids, offset, seed })",handler:({params:i,body:a})=>e.resetUidValidity(i.path,a)},{method:"GET",path:"/v1/mailboxes/{path}/messages",summary:"Messages (?uids=1,2 to choose, ?raw=true for the base64 source)",handler:({params:i,query:a})=>{let o=a.get("uids");return e.listMessages(i.path,{uids:o===null?void 0:o.split(",").map(Ye),raw:a.get("raw")==="true"}).map(Cu)}},{method:"POST",path:"/v1/mailboxes/{path}/messages",summary:"Adds a message ({ raw, encoding, flags, internaldate, checks }), like a delivery, checks: true refuses it like APPEND would (quota)",handler:({params:i,body:a})=>({status:201,body:e.addMessage(i.path,{raw:Rh(a.raw,a.encoding),flags:a.flags,internaldate:a.internaldate},{checks:a.checks})})},{method:"POST",path:"/v1/mailboxes/{path}/messages/flags",summary:"Changes flags ({ uids, flags, mode }), mode is set, add or remove",handler:({params:i,body:a})=>e.setFlags(i.path,a.uids,a.flags,a.mode||"set")},{method:"POST",path:"/v1/mailboxes/{path}/messages/expunge",summary:"Removes messages ({ uids })",handler:({params:i,body:a})=>({uids:e.expungeMessages(i.path,a.uids)})},{method:"POST",path:"/v1/mailboxes/{path}/messages/copy",summary:"Copies messages ({ uids, target })",handler:({params:i,body:a})=>e.copyMessages(i.path,a.uids,a.target)},{method:"POST",path:"/v1/mailboxes/{path}/messages/move",summary:"Moves messages ({ uids, target })",handler:({params:i,body:a})=>e.moveMessages(i.path,a.uids,a.target)},{method:"GET",path:"/v1/mailboxes/{path}/messages/{uid}",summary:"A message with its base64 source",handler:({params:i})=>Cu(e.getMessage(i.path,Ye(i.uid)))},{method:"DELETE",path:"/v1/mailboxes/{path}/messages/{uid}",summary:"Removes a message",handler:({params:i})=>({uids:e.expungeMessages(i.path,[Ye(i.uid)])})},{method:"GET",path:"/v1/script/rules",summary:"Script rules with their hit counts",handler:()=>r.script.rules.map(s)},{method:"POST",path:"/v1/script/rules",summary:"Adds a script rule or a list of them, in the JSON form of the --script file",handler:({body:i})=>{let a;try{a=r.script.add(i)}catch(o){throw K(o.message,"INVALID")}return{status:201,body:Array.isArray(a)?a.map(s):s(a)}}},{method:"DELETE",path:"/v1/script/rules",summary:"Removes every script rule",handler:()=>(r.script.clear(),{deleted:!0})},{method:"DELETE",path:"/v1/script/rules/{id}",summary:"Removes a script rule",handler:({params:i})=>{let a=r.script.rules.find(o=>String(o.id)===i.id);if(!a)throw K("Script rule "+i.id+" does not exist","NONEXISTENT");return a.remove(),{deleted:!0}}}];return n.push(...e.routes),n.push({method:"GET",path:"/v1/openapi.json",summary:"This API as an OpenAPI document",handler:()=>vh(n)}),n}function vh(r){let t={};return r.forEach(e=>{let s=(e.path.match(/\{(\w+)\}/g)||[]).map(n=>({name:n.slice(1,-1),in:"path",required:!0,schema:{type:"string"},description:n==="{path}"?'Storage name of the mailbox (modified UTF-7), URL encoded, a "/" in it as %2F':void 0}));t[e.path]=t[e.path]||{},t[e.path][e.method.toLowerCase()]={summary:e.summary,parameters:s,responses:{default:{description:"JSON, errors as { error: { code, message } }"}}}}),{openapi:"3.1.0",info:{title:"ImapKit REST API",version:"1"},components:{securitySchemes:{bearer:{type:"http",scheme:"bearer"}}},paths:t}}function Fh(r,t,e){let s=e.split("/"),n=!1;for(let i of r){let a=i.path.split("/");if(a.length!==s.length)continue;let o={},u=!0;for(let l=0;l<a.length&&u;l++)if(a[l].startsWith("{")){try{o[a[l].slice(1,-1)]=decodeURIComponent(s[l])}catch{throw K("Invalid URL encoding","INVALID")}u=s[l]!==""}else u=a[l]===s[l];if(u){if(i.method===t)return{route:i,params:o};n=!0}}throw n?K("Method "+t+" is not allowed here","METHOD"):K("No such endpoint","NOTFOUND")}function Ph(r,t){let e=/^Bearer (.+)$/i.exec(r||"");if(!e)return!1;let s=n=>Qe.createHash("sha256").update(n).digest();return Qe.timingSafeEqual(s(e[1]),s(t))}function Xh(r){return new Promise((t,e)=>{let s=[],n=0;r.on("data",i=>{if(n+=i.length,n>Dh){e(K("Request body is larger than 64 MiB","TOOBIG")),r.destroy();return}s.push(i)}),r.on("error",e),r.on("end",()=>{let i=I.Buffer.concat(s).toString("utf-8");if(!i)return t({});let a;try{a=JSON.parse(i)}catch{return e(K("Request body is not valid JSON","INVALID"))}if(!a||typeof a!="object")return e(K("Request body must be a JSON object or array","INVALID"));t(a)})})}function xu(r,t){let e=t.host||"127.0.0.1",s=t.token;if(s!==void 0&&(typeof s!="string"||!s))throw new Error("The REST API token must be a non-empty string");if(!s&&!Nu(e))throw new Error("The REST API controls the whole server, it needs a token (rest.token, --rest-token) to listen on "+e);let n=new Set,i=Hh(r,n),a=(l,c,h)=>{let m=JSON.stringify(h);l.writeHead(c,{"Content-Type":"application/json; charset=utf-8","Content-Length":I.Buffer.byteLength(m),"Cache-Control":"no-store"}),l.end(m)},o=async(l,c)=>{if(s){if(!Ph(l.headers.authorization,s))throw c.setHeader("WWW-Authenticate","Bearer"),K("Missing or wrong bearer token","UNAUTHORIZED")}else if(!Nu((l.headers.host||"").replace(/:\d+$/,"")))throw K("Requests must use a loopback host name","UNAUTHORIZED");let h=new URL(l.url||"/","http://localhost"),m=(l.method||"GET").toUpperCase(),{route:T,params:A}=Fh(i,m,h.pathname),p={};if(m!=="GET"){let d=Number(l.headers["content-length"]||0)>0||!!l.headers["transfer-encoding"];if(!/^application\/json\b/i.test(l.headers["content-type"]||"")&&(d||m==="POST"))throw K("Requests must be application/json","UNSUPPORTED");p=await Xh(l)}let f=T.handler({params:A,query:h.searchParams,body:p});if(f&&typeof f=="object"&&typeof f.stream=="function")return f.stream(c,l);if(f&&typeof f=="object"&&"status"in f&&"body"in f){let{status:d,body:g}=f;return a(c,d,g)}a(c,200,f===void 0?{}:f)},u=Qe.createServer((l,c)=>{o(l,c).catch(h=>{let m=h instanceof nt?h.code:"SERVERERROR",T=Lh[m]||(h instanceof nt?409:500);c.headersSent||a(c,T,{error:{code:m,message:h.message}})})});return u.endStreams=()=>n.forEach(l=>l.end()),u}E();var Mu=`-----BEGIN PRIVATE KEY-----
|
|
39
|
+
`),15e3);o.unref(),n.on("close",()=>{t.delete(r),clearInterval(o),i.forEach(({type:a,listener:u})=>s.removeListener(a,u))})}}function Cd(s,e=new Set){let t=s.control,r=i=>({id:i.id,rule:i.rule,matched:i.matched,hits:i.hits}),n=[{method:"GET",path:"/v1/snapshot",summary:"The storage in the shape of the storage option",handler:()=>t.snapshot()},{method:"POST",path:"/v1/reset",summary:"Restores the mailboxes and users of the server options, disconnects every session",handler:()=>(t.reset(),{reset:!0})},{method:"POST",path:"/v1/shutdown",summary:"Stops accepting connections, the server closes once the last client is gone ({ graceful: false } closes them)",handler:({body:i})=>(R(()=>t.shutdown({graceful:i.graceful!==!1}).catch(()=>!1)),{status:202,body:{shutdown:!0}})},{method:"GET",path:"/v1/sessions",summary:"Connected sessions",handler:()=>t.sessions()},{method:"GET",path:"/v1/events",summary:"Server events as Server-Sent Events (?types=session,command to choose: "+ho.concat(nl).join(", ")+", trace only when asked for)",handler:({query:i})=>{let o=i.get("types"),a=o===null?ho:o.split(","),u=ho.concat(nl),l=a.filter(c=>u.indexOf(c)<0);if(l.length)throw K("Unknown event type "+l.join(", ")+", expected "+u.join(", "),"INVALID");return{stream:xd(s,a,e)}}},{method:"DELETE",path:"/v1/sessions/{session}",summary:"Disconnects a session with BYE ({ text }) or a TCP reset ({ reset: true })",handler:({params:i,body:o})=>{if(!t.disconnect(es(i.session),{text:o.text,reset:o.reset}))throw K("Session "+i.session+" does not exist","NONEXISTENT");return{disconnected:!0}}},{method:"POST",path:"/v1/sessions/{session}/inject",summary:"Writes bytes to a session as they are ({ data, encoding })",handler:({params:i,body:o})=>(t.inject(es(i.session),o.encoding==="base64"&&typeof o.data=="string"?b.Buffer.from(o.data,"base64"):o.data),{injected:!0})},{method:"GET",path:"/v1/users",summary:"Users, without credentials",handler:()=>t.listUsers()},{method:"POST",path:"/v1/users",summary:"Adds a user ({ name, password, xoauth2, displayName, oauth })",handler:({body:i})=>(t.addUser(i.name,{password:i.password,xoauth2:i.xoauth2,displayName:i.displayName,oauth:i.oauth}),{status:201,body:{name:i.name}})},{method:"PUT",path:"/v1/users/{name}",summary:"Changes the password, the XOAUTH2 token, the display name (displayName) or the OAuth settings ({ oauth: { consent } }) of a user",handler:({params:i,body:o})=>(t.updateUser(i.name,{password:o.password,xoauth2:o.xoauth2,displayName:o.displayName,oauth:o.oauth}),{name:i.name})},{method:"DELETE",path:"/v1/users/{name}",summary:"Deletes a user and disconnects its sessions ({ disconnect: false } keeps them)",handler:({params:i,body:o})=>(t.deleteUser(i.name,{disconnect:o.disconnect}),{deleted:!0})},{method:"GET",path:"/v1/mailboxes",summary:"Every mailbox",handler:()=>t.listMailboxes()},{method:"POST",path:"/v1/mailboxes",summary:"Creates a mailbox ({ path, subscribed })",handler:({body:i})=>({status:201,body:t.createMailbox(i.path,{subscribed:i.subscribed})})},{method:"GET",path:"/v1/mailboxes/{path}",summary:"A mailbox",handler:({params:i})=>t.getMailbox(i.path)},{method:"DELETE",path:"/v1/mailboxes/{path}",summary:"Deletes a mailbox, sessions that have it selected get BYE",handler:({params:i})=>(t.deleteMailbox(i.path),{deleted:!0})},{method:"POST",path:"/v1/mailboxes/{path}/rename",summary:"Renames a mailbox ({ newPath })",handler:({params:i,body:o})=>t.renameMailbox(i.path,o.newPath)},{method:"PUT",path:"/v1/mailboxes/{path}/subscription",summary:"Subscribes a mailbox",handler:({params:i})=>({changed:t.subscribe(i.path)})},{method:"DELETE",path:"/v1/mailboxes/{path}/subscription",summary:"Unsubscribes a name",handler:({params:i})=>({changed:t.unsubscribe(i.path)})},{method:"POST",path:"/v1/mailboxes/{path}/uidvalidity",summary:"Gives the mailbox a new UIDVALIDITY ({ uidvalidity, uids, offset, seed })",handler:({params:i,body:o})=>t.resetUidValidity(i.path,o)},{method:"GET",path:"/v1/mailboxes/{path}/messages",summary:"Messages (?uids=1,2 to choose, ?raw=true for the base64 source)",handler:({params:i,query:o})=>{let a=o.get("uids");return t.listMessages(i.path,{uids:a===null?void 0:a.split(",").map(es),raw:o.get("raw")==="true"}).map(rl)}},{method:"POST",path:"/v1/mailboxes/{path}/messages",summary:"Adds a message ({ raw, encoding, flags, internaldate, checks }), like a delivery, checks: true refuses it like APPEND would (quota)",handler:({params:i,body:o})=>({status:201,body:t.addMessage(i.path,{raw:Id(o.raw,o.encoding),flags:o.flags,internaldate:o.internaldate},{checks:o.checks})})},{method:"POST",path:"/v1/mailboxes/{path}/messages/flags",summary:"Changes flags ({ uids, flags, mode }), mode is set, add or remove",handler:({params:i,body:o})=>t.setFlags(i.path,o.uids,o.flags,o.mode||"set")},{method:"POST",path:"/v1/mailboxes/{path}/messages/expunge",summary:"Removes messages ({ uids })",handler:({params:i,body:o})=>({uids:t.expungeMessages(i.path,o.uids)})},{method:"POST",path:"/v1/mailboxes/{path}/messages/copy",summary:"Copies messages ({ uids, target })",handler:({params:i,body:o})=>t.copyMessages(i.path,o.uids,o.target)},{method:"POST",path:"/v1/mailboxes/{path}/messages/move",summary:"Moves messages ({ uids, target })",handler:({params:i,body:o})=>t.moveMessages(i.path,o.uids,o.target)},{method:"GET",path:"/v1/mailboxes/{path}/messages/{uid}",summary:"A message with its base64 source",handler:({params:i})=>rl(t.getMessage(i.path,es(i.uid)))},{method:"DELETE",path:"/v1/mailboxes/{path}/messages/{uid}",summary:"Removes a message",handler:({params:i})=>({uids:t.expungeMessages(i.path,[es(i.uid)])})},{method:"GET",path:"/v1/script/rules",summary:"Script rules with their hit counts",handler:()=>s.script.rules.map(r)},{method:"POST",path:"/v1/script/rules",summary:"Adds a script rule or a list of them, in the JSON form of the --script file",handler:({body:i})=>{let o;try{o=s.script.add(i)}catch(a){throw K(a.message,"INVALID")}return{status:201,body:Array.isArray(o)?o.map(r):r(o)}}},{method:"DELETE",path:"/v1/script/rules",summary:"Removes every script rule",handler:()=>(s.script.clear(),{deleted:!0})},{method:"DELETE",path:"/v1/script/rules/{id}",summary:"Removes a script rule",handler:({params:i})=>{let o=s.script.rules.find(a=>String(a.id)===i.id);if(!o)throw K("Script rule "+i.id+" does not exist","NONEXISTENT");return o.remove(),{deleted:!0}}}];return n.push(...t.routes),n.push({method:"GET",path:"/v1/openapi.json",summary:"This API as an OpenAPI document",handler:()=>wd(n)}),n}function wd(s){let e={};return s.forEach(t=>{let r=(t.path.match(/\{(\w+)\}/g)||[]).map(n=>({name:n.slice(1,-1),in:"path",required:!0,schema:{type:"string"},description:n==="{path}"?'Storage name of the mailbox (modified UTF-7), URL encoded, a "/" in it as %2F':void 0}));e[t.path]=e[t.path]||{},e[t.path][t.method.toLowerCase()]={summary:t.summary,parameters:r,responses:{default:{description:"JSON, errors as { error: { code, message } }"}}}}),{openapi:"3.1.0",info:{title:"ImapKit REST API",version:"1"},components:{securitySchemes:{bearer:{type:"http",scheme:"bearer"}}},paths:e}}function Nd(s,e,t){let r=t.split("/"),n=!1;for(let i of s){let o=i.path.split("/");if(o.length!==r.length)continue;let a={},u=!0;for(let l=0;l<o.length&&u;l++)if(o[l].startsWith("{")){try{a[o[l].slice(1,-1)]=decodeURIComponent(r[l])}catch{throw K("Invalid URL encoding","INVALID")}u=r[l]!==""}else u=o[l]===r[l];if(u){if(i.method===e)return{route:i,params:a};n=!0}}throw n?K("Method "+e+" is not allowed here","METHOD"):K("No such endpoint","NOTFOUND")}function Md(s,e){let t=/^Bearer (.+)$/i.exec(s||"");return!!t&&mr(t[1],e)}function mr(s,e){let t=r=>ce.createHash("sha256").update(r).digest();return ce.timingSafeEqual(t(s),t(e))}function mo(s,e,t){return new Promise((r,n)=>{let i=[],o=0;s.on("data",a=>{if(o+=a.length,o>e){n(t()),s.destroy();return}i.push(a)}),s.on("error",n),s.on("end",()=>r(b.Buffer.concat(i)))})}async function Rd(s){let e=(await mo(s,Td,()=>K("Request body is larger than 64 MiB","TOOBIG"))).toString("utf-8");if(!e)return{};let t;try{t=JSON.parse(e)}catch{throw K("Request body is not valid JSON","INVALID")}if(!t||typeof t!="object")throw K("Request body must be a JSON object or array","INVALID");return t}function il(s,e){let t=e.host||"127.0.0.1",r=e.token;if(r!==void 0&&(typeof r!="string"||!r))throw new Error("The REST API token must be a non-empty string");if(!r&&!ke(t))throw new Error("The REST API controls the whole server, it needs a token (rest.token, --rest-token) to listen on "+t);let n=new Set,i=Cd(s,n),o=(l,c,f)=>{let p=JSON.stringify(f);l.writeHead(c,{"Content-Type":"application/json; charset=utf-8","Content-Length":b.Buffer.byteLength(p),"Cache-Control":"no-store"}),l.end(p)},a=async(l,c)=>{if(r){if(!Md(l.headers.authorization,r))throw c.setHeader("WWW-Authenticate","Bearer"),K("Missing or wrong bearer token","UNAUTHORIZED")}else if(!ke((l.headers.host||"").replace(/:\d+$/,"")))throw K("Requests must use a loopback host name","UNAUTHORIZED");let f=new URL(l.url||"/","http://localhost"),p=(l.method||"GET").toUpperCase(),{route:y,params:A}=Nd(i,p,f.pathname),m={};if(p!=="GET"){let d=Number(l.headers["content-length"]||0)>0||!!l.headers["transfer-encoding"];if(!/^application\/json\b/i.test(l.headers["content-type"]||"")&&(d||p==="POST"))throw K("Requests must be application/json","UNSUPPORTED");m=await Rd(l)}let h=y.handler({params:A,query:f.searchParams,body:m});if(h&&typeof h=="object"&&typeof h.stream=="function")return h.stream(c,l);if(h&&typeof h=="object"&&"status"in h&&"body"in h){let{status:d,body:E}=h;return o(c,d,E)}o(c,200,h===void 0?{}:h)},u=ce.createServer((l,c)=>{a(l,c).catch(f=>{let p=f instanceof z?f.code:"SERVERERROR",y=Sd[p]||(f instanceof z?409:500);c.headersSent||o(c,y,{error:{code:p,message:f.message}})})});return u.endStreams=()=>n.forEach(l=>l.end()),u}g();g();var gr=s=>b.Buffer.from(s).toString("base64url");function Eo(s){let e=s?ce.createPrivateKey(s):ce.generateKeyPairSync("rsa",{modulusLength:2048}).privateKey;if(e.asymmetricKeyType!=="rsa")throw new Error("oauth.signingKey must be an RSA private key, ID tokens are signed with RS256");let{n:t,e:r}=ce.createPublicKey(e).export({format:"jwk"}),n=gr(ce.createHash("sha256").update(JSON.stringify({e:r,kty:"RSA",n:t})).digest());return{privateKey:e,kid:n,jwk:{kty:"RSA",use:"sig",alg:"RS256",kid:n,n:t,e:r}}}var go=null;function Ao(){return go||(go=Eo()),go}function ol(s,e){let t=gr(JSON.stringify({alg:"RS256",typ:"JWT",kid:s.kid}))+"."+gr(JSON.stringify(e));return t+"."+gr(ce.sign("sha256",b.Buffer.from(t),s.privateKey))}var Er=["http://127.0.0.1/*","http://localhost/*","http://[::1]/*"],Ld={imapkit:{name:"ImapKit test client",redirectUris:Er},"imapkit-approve":{name:"ImapKit test client (always allows)",redirectUris:Er,consent:"approve"},"imapkit-deny":{name:"ImapKit test client (always denies)",redirectUris:Er,consent:"deny"}},Dd={openid:"Confirm who you are (OpenID Connect ID token)",email:"See your email address",profile:"See your name",offline_access:"Stay signed in (a refresh token)"},al=["none","login","consent","select_account"],yo=/^[\x21\x23-\x5b\x5d-\x7e]+$/,ul=/^[A-Za-z0-9\-._~]{43,128}$/,Ud=new Set(["response_type","client_id","redirect_uri","scope","state","code_challenge","code_challenge_method","nonce","login_hint","prompt","response_mode","request","request_uri"]),ll=600*1e3,vd=24*3600*1e3,ts=(s=32)=>ce.randomBytes(s).toString("base64url");function bo(s){let e=Object.create(null),t=new Set;for(let[r,n]of s)n!==""&&(r in e&&t.add(r),e[r]=n);return{values:e,duplicates:[...t]}}function Bd(s,e){let t=s.endsWith("*"),r=t?s.slice(0,-1):s,n=(a,u)=>t?a.startsWith(u):a===u,i,o;try{i=new URL(r),o=new URL(e)}catch{return!1}return i.protocol==="http:"&&ke(i.hostname)&&!i.port?o.protocol==="http:"&&o.hostname===i.hostname&&n(o.pathname+o.search,i.pathname+i.search):n(e,r)}function Hd(s){let e=new Map;for(let t of Object.keys(s))e.set(t,hl(t,s[t]));return e}function hl(s,e){if(typeof s!="string"||!/^[\x20-\x7e]+$/.test(s))throw new z("OAuth client ID must be a non-empty string of printable ASCII","INVALID");let t="OAuth client "+JSON.stringify(s);if(!e||typeof e!="object")throw new z(t+" must be an object","INVALID");let{name:r,secret:n,redirectUris:i,consent:o}=e;if(r!==void 0&&(typeof r!="string"||!r))throw new z(t+": name must be a non-empty string","INVALID");if(n!==void 0&&(typeof n!="string"||!/^[\x20-\x7e]+$/.test(n)))throw new z(t+": secret must be a non-empty string of printable ASCII","INVALID");let a=i===void 0?Er:i;if(!Array.isArray(a)||!a.length)throw new z(t+": redirectUris must be a non-empty list","INVALID");for(let u of a){let l=typeof u=="string"?u.replace(/\*$/,""):"",c=!!l&&!l.includes("#");try{new URL(l)}catch{c=!1}if(!c)throw new z(t+": redirect URI "+JSON.stringify(u)+" must be an absolute URI without a fragment","INVALID")}return{id:s,name:r||s,secret:n===void 0?null:n,redirectUris:a.slice(),consent:o==null?null:$e(o,t+": consent")}}function cl(s,e,t,r=1/0){if(s===void 0)return e;if(typeof s!="number"||!(s>0)||s>r)throw new Error(t+" must be a positive number"+(r<1/0?" of at most "+r:""));return s}var Ar=class{constructor(e,t){if(this.server=e,this.options=t&&typeof t=="object"?t:{},this.issuer=this.options.issuer?this.checkIssuer(this.options.issuer):"",this.mailScope=this.options.mailScope===void 0?"mail":this.options.mailScope,typeof this.mailScope!="string"||!yo.test(this.mailScope))throw new Error("oauth.mailScope must be a scope token (RFC 6749 section 3.3)");this.scopes=Object.assign({},Dd,{[this.mailScope]:"Read, send and manage your mail over IMAP and SMTP"});for(let[i,o]of Object.entries(this.options.scopes||{})){if(!yo.test(i)||typeof o!="string")throw new Error("oauth.scopes maps scope tokens (RFC 6749 section 3.3) to descriptions, "+JSON.stringify(i)+" is not one");this.scopes[i]=o}this.accessTokenTtl=cl(this.options.accessTokenTtl,3600,"oauth.accessTokenTtl"),this.codeTtl=cl(this.options.codeTtl,60,"oauth.codeTtl",600);let{unknownScopes:r,refreshTokens:n}=this.options;if(r!==void 0&&r!=="refuse"&&r!=="drop")throw new Error('oauth.unknownScopes must be "refuse" or "drop"');if(n!==void 0&&n!=="offline_access"&&n!=="always")throw new Error('oauth.refreshTokens must be "offline_access" or "always"');this.queueCounter=0,this.key=this.options.signingKey?Eo(this.options.signingKey):null,this.reset(),e.on("reset",()=>this.reset()),this.registerControl()}checkIssuer(e){let t=null;try{t=new URL(String(e))}catch{}if(!t||!/^https?:$/.test(t.protocol)||t.search||t.hash||typeof e!="string")throw new Error("oauth.issuer must be an http or https URL without a query or fragment");return e.replace(/\/+$/,"")}reset(){this.clients=Hd(this.options.clients||Ld),this.consent=this.options.consent===void 0?"prompt":$e(this.options.consent,"oauth.consent"),this.decisions=[],this.tokenFaults=[],this.pending=new Map,this.codes=new Map,this.tokens=new Map}nowMs(){return this.server.now().getTime()}listening(e,t){if(!this.options.issuer){let r=e==="0.0.0.0"||e==="::"?"127.0.0.1":e.includes(":")?"["+e+"]":e;this.issuer=(this.options.secure?"https":"http")+"://"+r+":"+t}}discoveryUrl(){return this.issuer+"/.well-known/openid-configuration"}pageUsers(){return this.userNames().map(e=>{let t=this.server.getUser(e)||{};return{name:e,displayName:t.displayName||void 0,consent:t.oauth&&t.oauth.consent}})}endToken(e,t){e[t]=!0,e.endedAt=e.endedAt===null?this.nowMs():e.endedAt}emit(e,t){let r=Object.assign({type:e},t);this.server.options.debug&&console.log("[OAuth] %s %s",e,JSON.stringify(t)),this.server.emit("oauth",r)}authorize(e){this.prune();let{values:t,duplicates:r}=bo(e);if(r.includes("client_id")||r.includes("redirect_uri"))return this.errorPage("client_id or redirect_uri is sent more than once","Every parameter may only be sent once (RFC 6749 section 3.1).");if(!t.client_id)return this.errorPage("The request has no client_id","Add the client_id of a registered client.",this.clientList());let n=this.clients.get(t.client_id);if(!n)return this.errorPage("Unknown client_id "+JSON.stringify(t.client_id),"This client is not registered.",this.clientList());let i=this.resolveRedirect(n,t.redirect_uri);if(typeof i!="string")return i;let o={redirectUri:i,state:t.state},a=(f,p)=>(this.emit("authorize",{client:n.id,result:f,description:p}),this.redirectError(o,f,p)),u=this.checkRequest(n,i,t,r,a);if("type"in u)return u;let{outcome:l,source:c}=this.decide(u);return this.emit("authorize",{client:n.id,user:u.hintUser||null,decision:Jt(l),source:c,prompt:u.prompt}),this.finish(u,l,c)}checkRequest(e,t,r,n,i){if(n.length)return i("invalid_request",n.join(", ")+" sent more than once (RFC 6749 section 3.1)");if(r.request)return i("request_not_supported","Request objects are not supported (OpenID Connect Core 1.0 section 6.1)");if(r.request_uri)return i("request_uri_not_supported","request_uri is not supported (OpenID Connect Core 1.0 section 6.2)");if(!r.response_type)return i("invalid_request","response_type is missing (RFC 6749 section 4.1.1)");if(r.response_type!=="code")return i("unsupported_response_type","Only the authorization code flow, response_type=code, is supported");if(r.response_mode&&r.response_mode!=="query")return i("invalid_request","Only response_mode=query is supported");let o=[],a=this.checkScope(r.scope,o);if(typeof a=="string")return i("invalid_scope",a);let u=this.checkPkce(e,r,o);if(u)return i("invalid_request",u);let l=r.prompt?r.prompt.split(" "):[],c=l.find(p=>!al.includes(p));if(c!==void 0)return i("invalid_request","Unknown prompt value "+JSON.stringify(c)+" (OpenID Connect Core 1.0 section 3.1.2.1)");if(l.includes("none")&&l.length>1)return i("invalid_request","prompt=none can not be combined with other values (OpenID Connect Core 1.0 section 3.1.2.1)");o.push(r.state?{level:"ok",text:"state is present ("+r.state.length+" characters)"}:{level:"warn",text:"no state: the client can not tell this redirect from a forged one (RFC 6749 section 10.12)"}),a.includes("openid")&&o.push(r.nonce?{level:"ok",text:"nonce is present, the ID token carries it"}:{level:"note",text:"no nonce: allowed for the code flow, the ID token carries none"});let f=r.login_hint===void 0?void 0:this.server.getUser(r.login_hint)?r.login_hint:null;return f===null?o.push({level:"warn",text:"login_hint "+JSON.stringify(r.login_hint)+" is not a user of this server"}):f&&o.push({level:"ok",text:"login_hint matches the user "+f}),{client:e,redirectUri:t,redirectUriSent:r.redirect_uri!==void 0,state:r.state,scope:a,codeChallenge:r.code_challenge,codeChallengeMethod:r.code_challenge?r.code_challenge_method||"plain":void 0,nonce:r.nonce,loginHint:r.login_hint,hintUser:f,prompt:l,checks:o,ignored:Object.keys(r).filter(p=>!Ud.has(p))}}resolveRedirect(e,t){let r=e.redirectUris.map(n=>" "+n).join(`
|
|
40
|
+
`);if(t===void 0){let n=e.redirectUris.length===1&&!e.redirectUris[0].endsWith("*")?e.redirectUris[0]:null;return n||this.errorPage("The request has no redirect_uri","Client "+e.id+" has more than one possible redirect URI, the request must name one.",["Registered for "+e.id+`:
|
|
41
|
+
`+r])}return t.includes("#")?this.errorPage("redirect_uri has a fragment","A redirect URI must not include a fragment (RFC 6749 section 3.1.2).",["Received: "+t]):e.redirectUris.some(n=>Bd(n,t))?t:this.errorPage("redirect_uri is not registered for "+e.id,"The authorization server must not redirect to it (RFC 6749 section 4.1.2.1).",["Received: "+t,`Registered (a loopback http URI matches any port, RFC 8252 section 7.3):
|
|
42
|
+
`+r])}checkScope(e,t){if(!e)return"scope is missing, ImapKit has no default scope (RFC 6749 section 3.3)";let r=[...new Set(e.split(" ").filter(Boolean))],n=r.find(a=>!yo.test(a));if(n!==void 0||!r.length)return"Invalid scope "+JSON.stringify(n===void 0?e:n)+" (RFC 6749 section 3.3)";let i=r.filter(a=>!Object.hasOwn(this.scopes,a));if(i.length&&this.options.unknownScopes!=="drop")return"Unknown scope "+i.join(" ")+", known: "+Object.keys(this.scopes).join(" ");let o=r.filter(a=>Object.hasOwn(this.scopes,a));return o.length?(t.push(i.length?{level:"warn",text:"unknown scopes are left out of the grant: "+i.join(" ")}:{level:"ok",text:"every scope is known"}),o.includes(this.mailScope)||t.push({level:"warn",text:"the "+this.mailScope+" scope is missing: IMAP and SMTP will refuse the token"}),o):"None of the requested scopes is known, known: "+Object.keys(this.scopes).join(" ")}checkPkce(e,t,r){let n=t.code_challenge;if(!n)return t.code_challenge_method?"code_challenge_method without code_challenge (RFC 7636 section 4.3)":e.secret?(r.push({level:"warn",text:"no PKCE: confidential clients should use it too (RFC 9700 section 2.1.1)"}),null):"code_challenge is missing, public clients must use PKCE (RFC 9700 section 2.1.1)";let i=t.code_challenge_method||"plain";return i!=="S256"&&i!=="plain"?"Unknown code_challenge_method "+JSON.stringify(i)+" (RFC 7636 section 4.3)":i==="plain"&&!this.options.allowPlainPkce?(t.code_challenge_method?"code_challenge_method=plain":"code_challenge_method is missing, which means plain,")+" but a client that can use S256 must use it (RFC 7636 section 4.2)":!ul.test(n)||i==="S256"&&n.length!==43?"Invalid code_challenge, "+(i==="S256"?"S256 gives 43 base64url characters":"it must be 43 to 128 unreserved characters")+" (RFC 7636 section 4.2)":(r.push({level:i==="S256"?"ok":"warn",text:"PKCE "+i+" code challenge"}),null)}decide(e){let t=this.decisions.find(i=>(i.client===void 0||i.client===e.client.id)&&(i.user===void 0||i.user===e.hintUser));if(t)return--t.remaining<=0&&this.decisions.splice(this.decisions.indexOf(t),1),{outcome:t.decision,source:"queued decision "+t.id};let r=e.hintUser?this.server.getUser(e.hintUser):!1,n=r&&r.oauth&&r.oauth.consent;return n?{outcome:n,source:"user "+e.hintUser}:e.client.consent?{outcome:e.client.consent,source:"client "+e.client.id}:{outcome:this.consent,source:"server default"}}finish(e,t,r,n){let i=(l,c)=>this.redirectError(e,l,c);if(t==="prompt"){if(e.prompt.includes("none"))return i("consent_required","prompt=none, but the consent policy ("+r+") shows the consent page");let l=Object.assign({},e,{id:ts(18),expiresAt:this.nowMs()+ll,source:r});return this.pending.set(l.id,l),{type:"consent",request:l}}if(t==="deny")return i("access_denied","The sign-in was denied ("+r+")");if(typeof t=="object")return i(t.error,t.description||"Answered by "+r);if(t==="no-redirect")return{type:"page",page:{status:200,tone:"info",title:"Not redirecting",message:"The decision ("+r+") leaves this sign-in unanswered, so the client never gets its redirect. Use it to test how the client times out."}};let o=n||this.pickUser(e);if(!o)return i("access_denied",e.loginHint===void 0?"The server has no users":"login_hint "+JSON.stringify(e.loginHint)+" is not a user of this server");let a=this.issueCode(e,o);this.emit("code",{client:e.client.id,user:o,scope:e.scope.join(" "),source:r,fault:t==="approve"?null:t});let u={code:a};return(e.state!==void 0||t==="wrong-state")&&(u.state=t==="wrong-state"?(e.state||"")+"x-wrong-state":e.state),{type:"redirect",location:this.redirectUrl(e.redirectUri,u,t==="wrong-iss")}}pickUser(e){return e.loginHint!==void 0?e.hintUser||null:this.userNames()[0]||null}userNames(){return Object.keys(this.server.users).sort((e,t)=>e==="testuser"?-1:t==="testuser"?1:e.localeCompare(t))}answerConsent(e){this.prune();let t=e.get("request")||"",r=this.pending.get(t);if(!r)return this.errorPage("This sign-in is no longer open","It was answered already, it expired after 10 minutes, or the server was reset or restarted. Start the sign-in again from the client.");let n=e.get("action"),i=e.get("user")||"";if(n!=="allow"&&n!=="deny"&&n!=="outcome")return this.errorPage("Unknown action","The form sent action "+JSON.stringify(n)+".");if(n!=="deny"&&!this.server.getUser(i))return this.errorPage("Choose an account","User "+JSON.stringify(i)+" does not exist. Go back and pick an account.");let o=n==="allow"?"approve":"deny";if(n==="outcome"){let a=e.get("outcome")||"",u=e.get("description")||void 0;try{o=$e(a.startsWith("error:")?{error:a.slice(6),description:u}:a,"outcome",!0)}catch(l){return this.errorPage("Unknown outcome",l.message)}}return this.pending.delete(t),e.get("remember")==="on"&&(o==="approve"||o==="deny")&&(r.client.consent=o,this.emit("remember",{client:r.client.id,consent:o})),this.emit("consent",{client:r.client.id,user:n==="deny"?null:i,decision:Jt(o)}),this.finish(r,o,"consent page",i)}prune(){let e=this.nowMs();this.tokens.forEach((t,r)=>{let n=t.endedAt!==null?t.endedAt:t.expiresAt;n!==null&&n+vd<=e&&this.tokens.delete(r)}),this.pending.forEach((t,r)=>t.expiresAt<=e&&this.pending.delete(r)),this.codes.forEach((t,r)=>t.expiresAt+ll<=e&&this.codes.delete(r))}issueCode(e,t){let r=ts();return this.codes.set(r,{clientId:e.client.id,user:t,redirectUri:e.redirectUri,redirectUriSent:e.redirectUriSent,scope:e.scope,challenge:e.codeChallenge,method:e.codeChallengeMethod,nonce:e.nonce,expiresAt:this.nowMs()+this.codeTtl*1e3,authTime:Math.floor(this.nowMs()/1e3),grantId:ts(12),used:!1}),r}redirectUrl(e,t,r=!1){let n=new URL(e);for(let[i,o]of Object.entries(t))n.searchParams.set(i,o);return n.searchParams.set("iss",r?"https://wrong-issuer.invalid":this.issuer),n.toString()}redirectError(e,t,r){let n={error:t,error_description:so(r)};return e.state!==void 0&&(n.state=e.state),{type:"redirect",location:this.redirectUrl(e.redirectUri,n)}}errorPage(e,t,r){return this.emit("authorize",{client:null,result:"error page",description:e}),{type:"page",page:{status:400,tone:"error",title:e,message:t,details:r}}}clientList(){return[`Registered clients:
|
|
43
|
+
`+[...this.clients.values()].map(e=>" "+e.id+" ("+e.name+")").join(`
|
|
44
|
+
`)]}async token(e,t){this.prune();let{values:r,duplicates:n}=bo(e);if(n.length)return te("invalid_request",n.join(", ")+" sent more than once (RFC 6749 section 3.2)");let i=r.grant_type,o=this.takeTokenFault(i);if(o&&o.delay&&await new Promise(f=>setTimeout(f,o.delay)),o&&(o.error||o.html||o.status))return this.emit("token",{grant:i||null,result:"fault",fault:o.id}),o.html?{status:o.status||500,body:null,htmlError:!0}:te(o.error||"server_error",o.description||"Queued token fault "+o.id,o.status||400);let a=this.authenticateClient(r,t);if("status"in a)return a;let u=a.client,l;i?i==="authorization_code"?l=this.exchangeCode(u,r,o):i==="refresh_token"?l=this.refresh(u,r):l=te("unsupported_grant_type","Supported grant types: authorization_code, refresh_token"):l=te("invalid_request","grant_type is missing (RFC 6749 section 4.1.3)");let c=l.body;return this.emit("token",{grant:i||null,client:u.id,result:l.status===200?"ok":c.error,description:c.error_description}),l}authenticateClient(e,t){let r=e.client_id,n=e.client_secret,i=/^Basic +([A-Za-z0-9+/=]+)$/i.exec(t||"");if(t&&!i)return te("invalid_request","Only Basic authentication is supported in the Authorization header (RFC 6749 section 2.3.1)");if(i){if(n!==void 0)return te("invalid_request","The client used Basic authentication and client_secret, only one method is allowed (RFC 6749 section 2.3)");let u=b.Buffer.from(i[1],"base64").toString("utf-8"),l=u.indexOf(":"),c=y=>{try{return decodeURIComponent(y.replace(/\+/g," "))}catch{return null}},f=l<0?null:c(u.slice(0,l)),p=l<0?null:c(u.slice(l+1));if(f===null||p===null)return te("invalid_client","Malformed Basic credentials",401,{"WWW-Authenticate":'Basic realm="imapkit"'});if(r!==void 0&&r!==f)return te("invalid_request","client_id differs from the client of the Authorization header");r=f,n=p}let o=i?{"WWW-Authenticate":'Basic realm="imapkit"'}:void 0;if(!r)return te("invalid_client","No client authentication and no client_id (RFC 6749 section 4.1.3)",401,o);let a=this.clients.get(r);return a?a.secret===null?n!==void 0?te("invalid_client","Client "+r+" is a public client without a secret, leave client_secret out",401,o):{client:a}:n===void 0||!mr(n,a.secret)?te("invalid_client",n===void 0?"Client "+r+" is confidential, it must send its secret":"Wrong client secret",401,o):{client:a}:te("invalid_client","Unknown client "+JSON.stringify(r),401,o)}exchangeCode(e,t,r){if(!t.code)return te("invalid_request","code is missing (RFC 6749 section 4.1.3)");let n=this.codes.get(t.code);if(!n||n.expiresAt<=this.nowMs())return n&&this.codes.delete(t.code),te("invalid_grant",n?"The authorization code expired ("+this.codeTtl+" seconds, RFC 6749 section 4.1.2)":"Unknown authorization code");if(n.clientId!==e.id)return te("invalid_grant","The authorization code was issued to another client (RFC 6749 section 4.1.3)");if(n.used){let o=this.revokeGrant(n.grantId);return this.emit("revoke",{client:e.id,user:n.user,reason:"authorization code reused",tokens:o}),te("invalid_grant","The authorization code was used already, its tokens are revoked now (RFC 6749 section 4.1.2)")}if((n.redirectUriSent||t.redirect_uri!==void 0)&&t.redirect_uri!==n.redirectUri)return te("invalid_grant",(t.redirect_uri===void 0?"redirect_uri is missing":"redirect_uri differs from the authorization request")+", it must be identical (RFC 6749 section 4.1.3)");let i=t.code_verifier;if(n.challenge){if(!i)return te("invalid_grant","code_verifier is missing, the authorization request had a code_challenge (RFC 7636 section 4.5)");if(!ul.test(i))return te("invalid_grant","Invalid code_verifier, it must be 43 to 128 unreserved characters (RFC 7636 section 4.1)");let o=n.method==="S256"?ce.createHash("sha256").update(i).digest("base64url"):i;if(!mr(o,n.challenge))return te("invalid_grant","code_verifier does not match the code_challenge (RFC 7636 section 4.6)")}else if(i!==void 0)return te("invalid_grant","code_verifier without a code_challenge in the authorization request (RFC 9700 section 2.1.1)");return this.server.getUser(n.user)?(n.used=!0,{status:200,body:this.issueTokens(e,n.user,n.scope,n.grantId,{nonce:n.nonce,authTime:n.authTime,fault:r})}):te("invalid_grant","User "+n.user+" does not exist any more")}refresh(e,t){if(!t.refresh_token)return te("invalid_request","refresh_token is missing (RFC 6749 section 6)");let r=this.tokens.get(t.refresh_token);if(!r||r.type!=="refresh"||r.revoked)return te("invalid_grant",r&&r.revoked?"The refresh token was revoked":"Unknown refresh token");if(r.clientId!==e.id)return te("invalid_grant","The refresh token was issued to another client (RFC 6749 section 6)");if(r.rotated){let o=this.revokeGrant(r.grantId);return this.emit("revoke",{client:e.id,user:r.user,reason:"rotated refresh token reused",tokens:o}),te("invalid_grant","This refresh token was replaced by rotation, using it again revoked the grant (RFC 9700 section 4.14.2)")}if(!this.server.getUser(r.user))return te("invalid_grant","User "+r.user+" does not exist any more");let n=r.scope;if(t.scope){let o=[...new Set(t.scope.split(" ").filter(Boolean))],a=o.filter(u=>!r.scope.includes(u));if(a.length||!o.length)return te("invalid_scope","Scope beyond the original grant: "+(a.join(" ")||t.scope)+" (RFC 6749 section 6)");n=o}return{status:200,body:this.issueTokens(e,r.user,n,r.grantId,{refresh:r})}}issueTokens(e,t,r,n,i){let o=this.nowMs(),a=ts();this.tokens.set(a,{token:a,type:"access",clientId:e.id,user:t,scope:r,grantId:n,expiresAt:o+this.accessTokenTtl*1e3,revoked:!1,rotated:!1,endedAt:null});let u={access_token:a,token_type:"Bearer",expires_in:this.accessTokenTtl,scope:r.join(" ")};return i.refresh?this.options.rotateRefreshTokens&&(this.endToken(i.refresh,"rotated"),u.refresh_token=this.newRefreshToken(e,t,i.refresh.scope,n)):(this.options.refreshTokens==="always"||r.includes("offline_access"))&&(u.refresh_token=this.newRefreshToken(e,t,r,n)),!i.refresh&&r.includes("openid")&&(u.id_token=this.idToken(e,t,r,i.nonce,i.authTime,i.fault?i.fault.claims:void 0)),u}newRefreshToken(e,t,r,n){let i=ts();return this.tokens.set(i,{token:i,type:"refresh",clientId:e.id,user:t,scope:r,grantId:n,expiresAt:null,revoked:!1,rotated:!1,endedAt:null}),i}idToken(e,t,r,n,i,o){let a=Math.floor(this.nowMs()/1e3),u=Object.assign({iss:this.issuer,sub:t,aud:e.id,azp:e.id,iat:a,exp:a+this.accessTokenTtl,auth_time:i||a},n===void 0?{}:{nonce:n},this.userClaims(t,r));for(let[l,c]of Object.entries(o||{}))c===null?delete u[l]:u[l]=c;return ol(this.key||Ao(),u)}userClaims(e,t){let r={};t.includes("email")&&(r.email=e,r.email_verified=!0);let n=this.server.getUser(e);return t.includes("profile")&&n&&typeof n.displayName=="string"&&n.displayName&&(r.name=n.displayName),r}jwks(){return{keys:[(this.key||Ao()).jwk]}}takeTokenFault(e){let t=this.tokenFaults.find(r=>r.grant===void 0||r.grant===e);return t?(--t.remaining<=0&&this.tokenFaults.splice(this.tokenFaults.indexOf(t),1),t):null}revokeGrant(e){let t=0;return this.tokens.forEach(r=>{r.grantId===e&&!r.revoked&&(this.endToken(r,"revoked"),t++)}),t}revoke(e,t){let{values:r,duplicates:n}=bo(e);if(n.length)return te("invalid_request",n.join(", ")+" sent more than once");let i=this.authenticateClient(r,t);if("status"in i)return i;if(!r.token)return te("invalid_request","token is missing (RFC 7009 section 2.1)");let o=this.tokens.get(r.token);if(!o)return{status:200,body:{}};if(o.clientId!==i.client.id)return te("invalid_request","The token was issued to another client (RFC 7009 section 2.1)");let a=o.type==="refresh"?this.revokeGrant(o.grantId):+!o.revoked;return this.endToken(o,"revoked"),this.emit("revoke",{client:i.client.id,user:o.user,reason:o.type+" token revoked by the client",tokens:a}),{status:200,body:{}}}userinfo(e){let t=/^Bearer +([A-Za-z0-9\-._~+/]+=*)$/i.exec(e||""),r=(o,a,u)=>({status:u,body:{error:o,error_description:a},headers:{"WWW-Authenticate":"Bearer"+(o?' error="'+o+'", error_description="'+a+'"':"")}});if(!t)return r("invalid_request","Send the access token as Authorization: Bearer <token> (RFC 6750 section 2.1)",401);let n=this.tokens.get(t[1]),i=this.tokenProblem(n);return i||!n?r("invalid_token","The access token is "+(i||"unknown"),401):n.scope.includes("openid")?{status:200,body:Object.assign({sub:n.user},this.userClaims(n.user,n.scope))}:r("insufficient_scope","The access token has no openid scope",403)}tokenProblem(e){return!e||e.type!=="access"?e?"a refresh token, not an access token":"unknown":e.revoked?"revoked":e.expiresAt!==null&&e.expiresAt<=this.nowMs()?"expired":this.server.getUser(e.user)?null:"for a user that does not exist any more"}verifyAccessToken(e,t,r){let n=this.tokens.get(e);if(!n||n.type!=="access")return null;let i,o=this.tokenProblem(n);return o?i={error:"invalid_token",reason:"the access token is "+o}:t!==void 0&&t!==n.user?i={error:"invalid_token",reason:"the access token is for "+n.user+", not "+t}:n.scope.includes(this.mailScope)?i={user:n.user}:i={error:"insufficient_scope",reason:"the access token has no "+this.mailScope+" scope"},this.emit("access",{via:r,client:n.clientId,user:n.user,result:"user"in i?"ok":i.error,reason:"user"in i?null:i.reason}),i}metadata(){let e=["none","client_secret_basic","client_secret_post"];return{issuer:this.issuer,authorization_endpoint:this.issuer+"/authorize",token_endpoint:this.issuer+"/token",userinfo_endpoint:this.issuer+"/userinfo",jwks_uri:this.issuer+"/jwks",revocation_endpoint:this.issuer+"/revoke",scopes_supported:Object.keys(this.scopes),response_types_supported:["code"],response_modes_supported:["query"],grant_types_supported:["authorization_code","refresh_token"],subject_types_supported:["public"],id_token_signing_alg_values_supported:["RS256"],token_endpoint_auth_methods_supported:e,revocation_endpoint_auth_methods_supported:e,code_challenge_methods_supported:this.options.allowPlainPkce?["S256","plain"]:["S256"],claims_supported:["iss","sub","aud","azp","exp","iat","auth_time","nonce","email","email_verified","name"],prompt_values_supported:al,authorization_response_iss_parameter_supported:!0,request_parameter_supported:!1,request_uri_parameter_supported:!1}}describeClient(e){return{id:e.id,name:e.name,confidential:e.secret!==null,redirectUris:e.redirectUris.slice(),consent:e.consent}}describeToken(e){return{type:e.type,token:e.token,user:e.user,client:e.clientId,scope:e.scope.join(" "),expiresAt:e.expiresAt===null?null:new Date(e.expiresAt).toISOString(),expired:e.expiresAt!==null&&e.expiresAt<=this.nowMs(),revoked:e.revoked,rotated:e.rotated}}findTokens(e){let t=e||{};if(To(t,["user","client","token"]),t.type!==void 0&&t.type!=="access"&&t.type!=="refresh")throw new z('type must be "access" or "refresh"',"INVALID");return[...this.tokens.values()].filter(r=>(t.user===void 0||r.user===t.user)&&(t.client===void 0||r.clientId===t.client)&&(t.token===void 0||r.token===t.token)&&(t.type===void 0||r.type===t.type))}queueDecision(e){let t=e||{},r=$e(t.decision,"decision",!0);To(t,["client","user"]);let n=++this.queueCounter;return this.decisions.push({id:n,decision:r,client:t.client,user:t.user,remaining:fl(t.count)}),{id:n}}queueTokenFault(e){let t=e||{},{grant:r,error:n,status:i,html:o,delay:a,claims:u}=t;if(To(t,["description"]),r!==void 0&&r!=="authorization_code"&&r!=="refresh_token")throw new z('grant must be "authorization_code" or "refresh_token"',"INVALID");if(n!==void 0&&!ro(n))throw new z("error must be an OAuth error code","INVALID");if(i!==void 0&&(!Number.isInteger(i)||i<400||i>599))throw new z("status must be an HTTP error status, 400 to 599","INVALID");if(a!==void 0&&(typeof a!="number"||!(a>=0)||a>6e5))throw new z("delay must be milliseconds, at most 600000","INVALID");if(u!==void 0&&(!u||typeof u!="object"||Array.isArray(u)))throw new z("claims must be an object, null values remove claims","INVALID");if(n===void 0&&!o&&i===void 0&&a===void 0&&u===void 0)throw new z("A token fault needs error, status, html, delay or claims","INVALID");let l=++this.queueCounter;return this.tokenFaults.push({id:l,grant:r,error:n,description:t.description,status:i,html:!!o,delay:a||0,claims:u,remaining:fl(t.count)}),{id:l}}listClients(){return[...this.clients.values()].map(e=>this.describeClient(e))}setClient(e,t){let r=hl(e,t);return this.clients.set(r.id,r),this.describeClient(r)}deleteClient(e){if(!this.clients.delete(e))throw new z("OAuth client "+JSON.stringify(e)+" does not exist","NONEXISTENT")}setConsent(e){return this.consent=$e(e,"consent"),{consent:this.consent}}listTokens(e){return this.findTokens(e).map(t=>this.describeToken(t))}expireTokens(e){let t=this.findTokens(Object.assign({},e,{type:"access"})).filter(n=>!this.tokenProblem(n)),r=this.nowMs();return t.forEach(n=>n.expiresAt=r),{expired:t.length}}revokeTokens(e){let t=this.findTokens(e).filter(r=>!r.revoked);return t.forEach(r=>this.endToken(r,"revoked")),t.length&&this.emit("revoke",{reason:"control API",tokens:t.length}),{revoked:t.length}}info(){return{issuer:this.issuer,discovery:this.issuer?this.discoveryUrl():null,consent:this.consent,mailScope:this.mailScope,scopes:Object.keys(this.scopes),clients:this.listClients(),decisions:this.decisions.map(e=>Object.assign({},e)),tokenFaults:this.tokenFaults.map(e=>Object.assign({},e))}}registerControl(){let e=this.server.control,t=o=>({status:201,body:o}),r=()=>({deleted:!0}),n=o=>{let a={};for(let u of["user","client","type"]){let l=o.get(u);l!==null&&(a[u]=l)}return a},i=[["getOAuthInfo",()=>this.info(),"GET","/v1/oauth","OAuth provider: issuer, default consent, clients, queues",()=>e.getOAuthInfo()],["listOAuthClients",()=>this.listClients(),"GET","/v1/oauth/clients","Registered OAuth clients, without secrets",()=>e.listOAuthClients()],["setOAuthClient",(o,a)=>this.setClient(o,a),"PUT","/v1/oauth/clients/{id}","Registers or replaces an OAuth client ({ name, secret, redirectUris, consent })",({params:o,body:a})=>e.setOAuthClient(o.id,a)],["deleteOAuthClient",o=>this.deleteClient(o),"DELETE","/v1/oauth/clients/{id}","Removes an OAuth client",({params:o})=>(e.deleteOAuthClient(o.id),r())],["setOAuthConsent",o=>this.setConsent(o),"PUT","/v1/oauth/consent","Sets the default consent policy ({ consent }: prompt, approve, deny or { error, description })",({body:o})=>e.setOAuthConsent(o.consent)],["queueOAuthDecision",o=>this.queueDecision(o),"POST","/v1/oauth/decisions","Queues the decision of the next sign-ins ({ decision, client, user, count })",({body:o})=>t(e.queueOAuthDecision(o))],["listOAuthDecisions",()=>this.decisions.map(o=>Object.assign({},o)),"GET","/v1/oauth/decisions","Queued sign-in decisions",()=>e.listOAuthDecisions()],["clearOAuthDecisions",()=>{this.decisions=[]},"DELETE","/v1/oauth/decisions","Removes the queued sign-in decisions",()=>(e.clearOAuthDecisions(),r())],["queueOAuthTokenFault",o=>this.queueTokenFault(o),"POST","/v1/oauth/token-faults","Queues a fault of the token endpoint ({ grant, error, description, status, html, delay, claims, count })",({body:o})=>t(e.queueOAuthTokenFault(o))],["clearOAuthTokenFaults",()=>{this.tokenFaults=[]},"DELETE","/v1/oauth/token-faults","Removes the queued token endpoint faults",()=>(e.clearOAuthTokenFaults(),r())],["listOAuthTokens",o=>this.listTokens(o),"GET","/v1/oauth/tokens","Issued tokens (?user=&client=&type=access|refresh to choose)",({query:o})=>e.listOAuthTokens(n(o))],["expireOAuthTokens",o=>this.expireTokens(o),"POST","/v1/oauth/tokens/expire","Lets access tokens expire now ({ user, client, token })",({body:o})=>e.expireOAuthTokens(o)],["revokeOAuthTokens",o=>this.revokeTokens(o),"POST","/v1/oauth/tokens/revoke","Revokes access and refresh tokens ({ user, client, token, type })",({body:o})=>e.revokeOAuthTokens(o)]];for(let[o,a,u,l,c,f]of i)e.register(o,a,[{method:u,path:l,summary:c,handler:f}])}};function To(s,e){for(let t of e)if(s[t]!==void 0&&typeof s[t]!="string")throw new z(t+" must be a string","INVALID")}function fl(s){if(s===void 0)return 1;if(!Number.isInteger(s)||s<1)throw new z("count must be a positive integer","INVALID");return s}function te(s,e,t=400,r){return{status:t,body:{error:s,error_description:so(e)},headers:r}}g();g();var ie=s=>String(s).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e]),So=s=>s?Jt(s):"server default",kd=`
|
|
45
|
+
:root{color-scheme:light dark;--bg:#eef1f6;--card:#fff;--text:#1b2430;--muted:#5d6877;--line:#d9dfe8;--accent:#2457c5;--accent-text:#fff;--accent-soft:#e8eefc;--ok:#1a7f37;--ok-soft:#e6f4ea;--warn:#8a5a00;--warn-soft:#fff4d6;--bad:#b42318;--bad-soft:#fdecea;--code:#f0f2f5;--focus:#2457c5}
|
|
46
|
+
@media (prefers-color-scheme:dark){:root{--bg:#0d1117;--card:#161b22;--text:#e4e9f0;--muted:#9aa6b6;--line:#2b3440;--accent:#6e9bff;--accent-text:#0d1117;--accent-soft:#1b2640;--ok:#4cc06b;--ok-soft:#14281b;--warn:#e3b341;--warn-soft:#2d2411;--bad:#ff7b6e;--bad-soft:#331a18;--code:#1f252e;--focus:#8db0ff}}
|
|
47
|
+
*{box-sizing:border-box}
|
|
48
|
+
body{margin:0;min-height:100vh;background:var(--bg);color:var(--text);font:15px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif;display:flex;justify-content:center;align-items:flex-start;padding:32px 16px}
|
|
49
|
+
main{width:100%;max-width:480px;background:var(--card);border:1px solid var(--line);border-radius:14px;overflow:hidden;box-shadow:0 10px 30px rgba(16,32,64,.10)}
|
|
50
|
+
main.wide{max-width:760px}
|
|
51
|
+
.ribbon{background:repeating-linear-gradient(-45deg,#f5c542,#f5c542 10px,#efb429 10px,#efb429 20px);color:#3b2a00;font-weight:700;font-size:12px;letter-spacing:.05em;text-align:center;padding:5px 8px}
|
|
52
|
+
.body{padding:24px 26px 22px}
|
|
53
|
+
.brand{display:flex;align-items:center;gap:10px;color:var(--muted);font-size:13px;margin:0 0 16px}
|
|
54
|
+
.logo{width:26px;height:26px;border-radius:7px;background:linear-gradient(#3a6fd8,#1d4597);color:#fff;font-weight:800;font-size:12px;display:grid;place-items:center;flex:none}
|
|
55
|
+
h1{font-size:20px;line-height:1.3;margin:0 0 6px}
|
|
56
|
+
h2{font-size:14px;margin:20px 0 8px;color:var(--muted);text-transform:uppercase;letter-spacing:.05em}
|
|
57
|
+
p{margin:0 0 12px}
|
|
58
|
+
.muted{color:var(--muted)}
|
|
59
|
+
.small{font-size:13px}
|
|
60
|
+
code{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:12.5px;overflow-wrap:anywhere}
|
|
61
|
+
code{background:var(--code);padding:1px 5px;border-radius:4px}
|
|
62
|
+
fieldset{border:0;margin:0 0 14px;padding:0}
|
|
63
|
+
legend{font-weight:600;margin:0 0 8px;padding:0}
|
|
64
|
+
.acct{display:flex;align-items:center;gap:11px;padding:9px 12px;border:1px solid var(--line);border-radius:10px;margin-bottom:6px;cursor:pointer}
|
|
65
|
+
.acct:has(input:checked){border-color:var(--accent);background:var(--accent-soft)}
|
|
66
|
+
.acct input{accent-color:var(--accent);width:16px;height:16px;margin:0;flex:none}
|
|
67
|
+
.av{width:30px;height:30px;border-radius:50%;color:#fff;display:grid;place-items:center;font-weight:700;font-size:13px;flex:none}
|
|
68
|
+
.who{min-width:0;flex:1}
|
|
69
|
+
.nm{font-weight:600;line-height:1.25;overflow-wrap:anywhere}
|
|
70
|
+
.em{font-size:12.5px;color:var(--muted);overflow-wrap:anywhere}
|
|
71
|
+
.tag{display:inline-block;font-size:11.5px;font-weight:600;padding:1px 8px;border-radius:999px;white-space:nowrap}
|
|
72
|
+
.tag.ok{background:var(--ok-soft);color:var(--ok)}.tag.warn{background:var(--warn-soft);color:var(--warn)}.tag.bad{background:var(--bad-soft);color:var(--bad)}.tag.info{background:var(--accent-soft);color:var(--accent)}.tag.note{background:var(--code);color:var(--muted)}
|
|
73
|
+
ul.scopes{list-style:none;padding:0;margin:0 0 12px;border:1px solid var(--line);border-radius:10px}
|
|
74
|
+
ul.scopes li{display:flex;gap:10px;padding:8px 12px;border-top:1px solid var(--line);align-items:baseline}
|
|
75
|
+
ul.scopes li:first-child{border-top:0}
|
|
76
|
+
.ck{color:var(--ok);font-weight:700}
|
|
77
|
+
.raw{margin-left:auto;font-family:ui-monospace,Menlo,monospace;font-size:11.5px;color:var(--muted);text-align:right;overflow-wrap:anywhere}
|
|
78
|
+
.redir{font-size:13px;color:var(--muted);margin:0 0 16px;overflow-wrap:anywhere}
|
|
79
|
+
.btns{display:flex;flex-direction:row-reverse;gap:10px;margin:0 0 12px}
|
|
80
|
+
button{flex:1;font:inherit;font-weight:600;padding:10px 14px;border-radius:8px;border:1px solid var(--line);background:var(--card);color:var(--text);cursor:pointer;text-align:center;text-decoration:none}
|
|
81
|
+
button.primary{background:var(--accent);border-color:var(--accent);color:var(--accent-text)}
|
|
82
|
+
button:hover{filter:brightness(1.05)}
|
|
83
|
+
button:focus-visible,input:focus-visible,select:focus-visible,summary:focus-visible,a:focus-visible,.acct:has(input:focus-visible){outline:2px solid var(--focus);outline-offset:2px}
|
|
84
|
+
.remember{display:flex;gap:8px;align-items:center;font-size:13px;color:var(--muted);margin:0 0 4px}
|
|
85
|
+
.remember input{accent-color:var(--accent)}
|
|
86
|
+
details{border-top:1px solid var(--line);padding:10px 0 0;margin-top:12px;font-size:13.5px}
|
|
87
|
+
summary{cursor:pointer;color:var(--accent);font-weight:600}
|
|
88
|
+
ul.checks{list-style:none;padding:0;margin:10px 0 6px}
|
|
89
|
+
ul.checks li{display:flex;gap:8px;padding:3px 0;align-items:baseline}
|
|
90
|
+
.kv{font-family:ui-monospace,Menlo,monospace;font-size:12px;color:var(--muted);overflow-wrap:anywhere;margin:6px 0 0}
|
|
91
|
+
.row{display:flex;gap:8px;flex-wrap:wrap;margin:10px 0 0}
|
|
92
|
+
select,input[type=text]{font:inherit;font-size:13.5px;padding:7px 9px;border-radius:7px;border:1px solid var(--line);background:var(--card);color:var(--text);flex:1;min-width:0}
|
|
93
|
+
.row button{flex:none}
|
|
94
|
+
.mark{width:44px;height:44px;border-radius:50%;display:grid;place-items:center;font-size:22px;font-weight:700;margin:0 0 14px}
|
|
95
|
+
.mark.error{background:var(--bad-soft);color:var(--bad)}.mark.info{background:var(--accent-soft);color:var(--accent)}
|
|
96
|
+
pre{background:var(--code);border-radius:8px;padding:10px 12px;white-space:pre-wrap;overflow-wrap:anywhere;font-size:12.5px;margin:0 0 10px}
|
|
97
|
+
table{width:100%;border-collapse:collapse;font-size:13.5px;margin:0 0 6px}
|
|
98
|
+
th,td{text-align:left;padding:7px 8px;border-bottom:1px solid var(--line);vertical-align:top}
|
|
99
|
+
th{font-size:12px;color:var(--muted);text-transform:uppercase;letter-spacing:.04em}
|
|
100
|
+
footer{border-top:1px solid var(--line);padding:12px 26px;font-size:12.5px;color:var(--muted)}
|
|
101
|
+
@media (max-width:480px){body{padding:0}main{border-radius:0;border-left:0;border-right:0}.body{padding:20px 16px}footer{padding:12px 16px}}
|
|
102
|
+
`,dl=["#7c5cf6","#0e9f6e","#d9480f","#1c7ed6","#c2255c","#5c7cfa","#2b8a3e"];function Pd(s){let e=0;for(let r of s)e=e*31+(r.codePointAt(0)||0)>>>0;let t=(s.match(/[\p{L}\p{N}]/u)||["?"])[0].toUpperCase();return'<span class="av" aria-hidden="true" style="background:'+dl[e%dl.length]+'">'+ie(t)+"</span>"}function Io(s,e,t={}){return'<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex"><title>'+ie(s)+" - ImapKit</title><style>"+kd+"</style></head><body><main"+(t.wide?' class="wide"':"")+'><div class="ribbon" role="note">IMAPKIT TEST SERVER \xB7 NOT A REAL SIGN-IN</div><div class="body">'+e+"</div>"+(t.footer?"<footer>"+t.footer+"</footer>":"")+"</main></body></html>"}function Oo(s){let e=s;try{e=new URL(s).host}catch{}return'<div class="brand"><span class="logo" aria-hidden="true">IK</span><span>ImapKit sign-in \xB7 '+ie(e)+"</span></div>"}var Fd=s=>'<span class="tag '+s.level+'">'+s.level+"</span>",_d=[["error:access_denied","Return access_denied"],["error:invalid_scope","Return invalid_scope"],["error:server_error","Return server_error"],["error:temporarily_unavailable","Return temporarily_unavailable"],["error:consent_required","Return consent_required"],["error:login_required","Return login_required"],["wrong-state","Approve, but redirect with a wrong state"],["wrong-iss","Approve, but redirect with a wrong iss"],["no-redirect","Do not redirect (let the client time out)"]];function pl(s){let{request:e,users:t,scopes:r,issuer:n}=s,i=e.client,o=e.hintUser||t[0]&&t[0].name,a=e.checks.slice();o&&!o.includes("@")&&a.push({level:"note",text:"user name "+JSON.stringify(o)+" has no @: clients that take the email claim as an address may refuse it"}),e.prompt.length&&a.push({level:"note",text:"prompt="+e.prompt.join(" ")+": the consent page is shown because the policy is prompt ("+e.source+")"}),e.ignored.length&&a.push({level:"note",text:"ignored parameters: "+e.ignored.join(", ")});let u=a.filter(d=>d.level==="ok").length,l=a.length-u,c=a.some(d=>d.level==="warn"),f=e.redirectUri,p=!1;try{let d=new URL(e.redirectUri);f=d.origin!=="null"?d.origin+d.pathname:e.redirectUri,p=d.protocol==="http:"&&ke(d.hostname)}catch{}let y=t.length?t.map(d=>{let E=[d.name===e.hintUser?'<span class="tag info">login_hint</span>':"",d.consent?'<span class="tag '+(d.consent==="approve"?"ok":"bad")+'">auto: '+ie(So(d.consent))+"</span>":""].join("");return'<label class="acct"><input type="radio" name="user" value="'+ie(d.name)+'"'+(d.name===o?" checked":"")+" required>"+Pd(d.displayName||d.name)+'<span class="who"><span class="nm">'+ie(d.displayName||d.name)+"</span>"+(d.displayName?'<br><span class="em">'+ie(d.name)+"</span>":"")+"</span>"+E+"</label>"}).join(""):'<p class="muted">This server has no users, so only Deny is possible.</p>',A=e.scope.map(d=>'<li><span class="ck" aria-hidden="true">\u2713</span><span>'+ie(r[d]||d)+'</span><span class="raw">'+ie(d)+"</span></li>").join(""),m=["client_id="+i.id,"response_type=code","scope="+e.scope.join(" "),e.codeChallengeMethod?"code_challenge_method="+e.codeChallengeMethod:"",e.prompt.length?"prompt="+e.prompt.join(" "):"",e.loginHint!==void 0?"login_hint="+e.loginHint:""].filter(Boolean),h=Oo(n)+"<h1>"+ie(i.name)+' wants to access your mailbox</h1><p class="muted small">Choose the account to sign in as. No password needed.'+(i.name!==i.id?" Client ID <code>"+ie(i.id)+"</code>.":"")+'</p><form method="post" action="/authorize/decision"><input type="hidden" name="request" value="'+ie(e.id)+'"><fieldset><legend>Account</legend>'+y+'</fieldset><fieldset><legend>It will be able to</legend><ul class="scopes">'+A+'</ul></fieldset><p class="redir">Returns to <strong>'+ie(f)+"</strong> "+(p?'<span class="tag ok">loopback</span>':"")+'</p><div class="btns">'+(t.length?'<button class="primary" type="submit" name="action" value="allow">Allow</button>':"")+'<button type="submit" name="action" value="deny" formnovalidate>Deny</button></div><label class="remember"><input type="checkbox" name="remember" value="on"> Remember my choice for this app until the server restarts</label><details'+(c?" open":"")+"><summary>Request details ("+u+" passed"+(l?", "+l+" to look at":"")+')</summary><ul class="checks">'+a.map(d=>"<li>"+Fd(d)+"<span>"+ie(d.text)+"</span></li>").join("")+'</ul><p class="kv">'+ie(m.join(" \xB7 "))+'</p><p class="kv">redirect_uri='+ie(e.redirectUri)+'</p></details><details><summary>Other outcomes</summary><p class="muted small" style="margin:8px 0 0">Answer this sign-in with an error or a broken redirect, to test how the client handles it.</p><div class="row"><select id="outcome" name="outcome" aria-label="Outcome">'+_d.map(([d,E])=>'<option value="'+d+'">'+ie(E)+"</option>").join("")+'</select></div><div class="row"><input type="text" name="description" aria-label="error_description" placeholder="error_description (optional)" maxlength="300"><button type="submit" name="action" value="outcome" formnovalidate>Send</button></div></details></form>';return Io("Sign in to "+i.name,h,{footer:"Decision source if not answered here: "+ie(e.source)+". This request stays open for 10 minutes."})}function ml(s,e){let t=Oo(e)+'<div class="mark '+s.tone+'" aria-hidden="true">'+(s.tone==="error"?"!":"i")+"</div><h1>"+ie(s.title)+'</h1><p class="muted">'+ie(s.message)+"</p>"+(s.details||[]).map(r=>"<pre>"+ie(r)+"</pre>").join("");return Io(s.title,t,{footer:s.tone==="error"?"The client was not redirected: there was no safe place to send the answer to.":"You can close this tab."})}function gl(s){let{issuer:e,clients:t,users:r}=s,n=["/.well-known/openid-configuration","/authorize","/token","/userinfo","/jwks","/revoke"],i=Oo(e)+'<h1>ImapKit OAuth 2.0 / OpenID Connect provider</h1><p class="muted">A test identity provider for mail clients. Tokens it issues log in to this ImapKit server over IMAP (XOAUTH2, OAUTHBEARER) and SMTP (AUTH XOAUTH2) with the <code>'+ie(s.mailScope)+"</code> scope. Default consent policy: <strong>"+ie(So(s.consent))+"</strong>.</p><h2>Issuer</h2><pre>"+ie(e)+"</pre><h2>Clients</h2><table><thead><tr><th>Client ID</th><th>Name</th><th>Type</th><th>Consent</th></tr></thead><tbody>"+t.map(o=>"<tr><td><code>"+ie(o.id)+"</code></td><td>"+ie(o.name)+"</td><td>"+(o.secret===null?"public":"confidential")+"</td><td>"+ie(So(o.consent))+"</td></tr>").join("")+'</tbody></table><h2>Users</h2><p class="small">'+(r.length?r.map(o=>"<code>"+ie(o.name)+"</code>").join(" "):"none")+'</p><h2>Endpoints</h2><p class="small">'+n.map(o=>"<code>"+ie(o)+"</code>").join(" ")+"</p>";return Io("OAuth provider",i,{wide:!0,footer:"Documentation: https://imapkit.com/docs/guides/oauth"})}var Gd=64*1024,Je=class extends Error{constructor(e,t){super(t),this.status=e}};async function yr(s){if(!/^application\/x-www-form-urlencoded\b/i.test(s.headers["content-type"]||""))throw s.resume(),new Je(415,"The body must be application/x-www-form-urlencoded (RFC 6749 section 4.1.3)");let e=await mo(s,Gd,()=>new Je(413,"The body is larger than 64 KiB"));return new URLSearchParams(e.toString("utf-8"))}var xo={"Cache-Control":"no-store",Pragma:"no-cache","X-Content-Type-Options":"nosniff","Referrer-Policy":"no-referrer"},El={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"Authorization, Content-Type","Access-Control-Allow-Methods":"GET, POST, OPTIONS"};function Xd(s){try{let e=new URL(s.redirectUri);return"'self' "+(e.origin!=="null"?e.origin:e.protocol)}catch{return"'self'"}}function br(s,e,t,r="'none'"){s.writeHead(e,{...xo,"Content-Type":"text/html; charset=utf-8","Content-Length":b.Buffer.byteLength(t),"Content-Security-Policy":"default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; frame-ancestors 'none'; form-action "+r,"X-Frame-Options":"DENY"}),s.end(t)}function ft(s,e){if(e.htmlError){br(s,e.status,"<!doctype html><title>Error</title><h1>Something went wrong</h1>");return}let t=JSON.stringify(e.body);s.writeHead(e.status,{...xo,...El,...e.headers||{},"Content-Type":"application/json; charset=utf-8","Content-Length":b.Buffer.byteLength(t)}),s.end(t)}function jd(s,e,t){if(!s||s==="null"||s===new URL(e).origin)return!0;try{let r=new URL(s);return ke(r.hostname)&&r.host===t}catch{return!1}}function Al(s,e){let t=(o,a,u)=>{if(a.type==="redirect")o.writeHead(u,{...xo,Location:a.location,"Content-Type":"text/plain; charset=utf-8"}),o.end("Redirecting to "+a.location+`
|
|
103
|
+
`);else if(a.type==="page")br(o,a.page.status,ml(a.page,s.issuer));else{let l=pl({request:a.request,users:s.pageUsers(),scopes:s.scopes,issuer:s.issuer});br(o,200,l,Xd(a.request))}},r=o=>{if(!ke(e.host))return;let a=(o.headers.host||"").replace(/:\d+$/,""),u="";try{u=new URL(s.issuer).hostname}catch{}if(!ke(a)&&a.replace(/^\[|\]$/g,"")!==u.replace(/^\[|\]$/g,""))throw new Je(421,"Requests must use a loopback host name or the host of the issuer")},n=async(o,a)=>{r(o);let u=new URL(o.url||"/","http://localhost"),l=(o.method||"GET").toUpperCase(),c=l+" "+u.pathname;if(l==="OPTIONS")return a.writeHead(204,{...El,"Access-Control-Max-Age":"600"}),a.end();switch(c){case"GET /":return br(a,200,gl({issuer:s.issuer,consent:s.consent,clients:[...s.clients.values()],users:s.pageUsers(),mailScope:s.mailScope}));case"GET /.well-known/openid-configuration":case"GET /.well-known/oauth-authorization-server":return ft(a,{status:200,body:s.metadata()});case"GET /jwks":return ft(a,{status:200,body:s.jwks()});case"GET /authorize":return t(a,s.authorize(u.searchParams),302);case"POST /authorize":return t(a,s.authorize(await yr(o)),303);case"POST /authorize/decision":{if(!jd(o.headers.origin,s.issuer,o.headers.host))throw new Je(403,"The consent form must come from the consent page");return t(a,s.answerConsent(await yr(o)),303)}case"POST /token":return ft(a,await s.token(await yr(o),o.headers.authorization));case"POST /revoke":return ft(a,s.revoke(await yr(o),o.headers.authorization));case"GET /userinfo":return ft(a,s.userinfo(o.headers.authorization));case"POST /userinfo":return o.resume(),ft(a,s.userinfo(o.headers.authorization));default:{let f=["/","/authorize","/authorize/decision","/token","/revoke","/userinfo","/jwks"],p=u.pathname.startsWith("/.well-known/");throw new Je(f.includes(u.pathname)||p?405:404,f.includes(u.pathname)?"Method not allowed":"Not found")}}},i=(o,a)=>{n(o,a).catch(u=>{let l=u instanceof Je?u.status:500;a.headersSent||ft(a,{status:l,body:{error:l===500?"server_error":"invalid_request",error_description:u.message}})})};return e.secure?ce.createServer(e.credentials,i):ce.createServer(i)}g();var yl=`-----BEGIN PRIVATE KEY-----
|
|
40
104
|
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDN0THQ8qpf3mMo
|
|
41
105
|
NlVzVvjfsw/QHo22ojmmUO+3QjZDeB7mSmniyGOFw0M8f2g3FM0Kfa51rKMYXWQV
|
|
42
106
|
cqRTDFkk9zBnCagFIWCi2DI4VgArzWlu4TqOHfRIHcbAH1bTKVh5KnVmQA6j6leK
|
|
@@ -64,7 +128,7 @@ xB6r81uUHwy+XOq7A4OfgbEEuuKQ6tXOg72FX+38rF+Td6iA+6qIPoSoGtK0jANX
|
|
|
64
128
|
ykroFnXr4N3IL5TafDZVvMGNuWhWwS8JR3B0VDzPobt/jxPJKmGunZoCqwJC+nqT
|
|
65
129
|
ELanzRGdLk0G2chSGO7ZKGg=
|
|
66
130
|
-----END PRIVATE KEY-----
|
|
67
|
-
`,
|
|
131
|
+
`,bl=`-----BEGIN CERTIFICATE-----
|
|
68
132
|
MIIDOjCCAiKgAwIBAgIUad1YSlfC6YFAqn38plnziyvx1/YwDQYJKoZIhvcNAQEL
|
|
69
133
|
BQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MCAXDTI2MTAwNjA4NDU1OFoYDzIxMjYw
|
|
70
134
|
OTEyMDg0NTU4WjAUMRIwEAYDVQQDDAlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEB
|
|
@@ -84,12 +148,12 @@ ZG83/H0UYur8lN2JxV4ITRovftmtruiVNw3mXH5BZCIsoFAEtf3hssn6rekfEOfc
|
|
|
84
148
|
4vty2NskN112OLQzLK1Oq3dl0C6Ns1MdIoelAHrFdeM3O03Y0D2R+PlNw1cU55if
|
|
85
149
|
EF3engvuSVRtcV8eyxM=
|
|
86
150
|
-----END CERTIFICATE-----
|
|
87
|
-
`;E();E();var us=Ce(ir()),xb=us.default.once;var cs=class extends us.default{constructor(){super(),this.peer=null,this.destroyed=!1,this.encrypted=!1,this._paused=!1,this._ending=!1,this._encoding=null,this._received=[]}write(t,e,s){if(typeof e=="function"&&(s=e,e=void 0),this.destroyed||this._ending)return!1;let n=typeof t=="string"?I.Buffer.from(t,e||"utf8"):I.Buffer.from(t.buffer,t.byteOffset,t.byteLength);return ls(()=>{this.peer?.deliver(n),s?.()}),!0}end(t){return t!==void 0&&this.write(t),this.destroyed||this._ending?this:(this._ending=!0,ls(()=>{let e=this.peer;e&&!e.destroyed&&(e.emit("end"),e.close()),this.close()}),this)}destroy(t){if(this.destroyed)return this;let e=this.peer;return this.close(t),e&&!e.destroyed&&e.close(),this}resetAndDestroy(){let t=this.peer;if(this.destroy(),t){let e=new Error("read ECONNRESET");e.code="ECONNRESET",ls(()=>t.emit("error",e))}return this}startTls(t){this.encrypted=!0,this.peer&&(this.peer.encrypted=!0),t()}pause(){return this._paused=!0,this}resume(){for(this._paused=!1;this._received.length&&!this._paused&&!this.destroyed;)this.emitData(this._received.shift());return this}setEncoding(t){return this._encoding=t,this}deliver(t){if(!this.destroyed){if(this._paused){this._received.push(t);return}this.emitData(t)}}emitData(t){this.emit("data",this._encoding?t.toString(this._encoding):t)}close(t){this.destroyed||(this.destroyed=!0,this._received=[],ls(()=>{t&&this.emit("error",t),this.emit("close",!!t)}))}};function Du(){let r=new cs,t=new cs;return r.peer=t,t.peer=r,[r,t]}var fs=[];function ls(r){fs.push(r),fs.length===1&&L(_h)}function _h(){let r=fs.splice(0,fs.length);for(let t of r)t()}E();var ct=["greeting","command","input","response","continuation","quiet"],Wi=["greeting","response","continuation"],Lu={on:ct,command:["command","input","response","continuation","quiet"],tag:["command","input","response","continuation","quiet"],description:["response","continuation"],session:ct,user:ct,state:ct,mailbox:ct,untagged:["response"],match:ct,when:ct,nth:ct,times:ct,chance:ct,quietFor:["quiet"],mutate:["response","continuation"],literals:["response"],defer:["response"],send:ct,before:Wi,after:Wi,run:["command","input"],drop:["greeting","command","input","response","continuation"],delay:["greeting","command","response","continuation"],chunk:ct,chunkDelay:ct,truncate:ct,close:ct},Ru=["mutate","literals","defer","send","before","after","run","drop","delay","chunk","truncate","close"],kh=10,Uu=["command","description","session","state","user","mailbox"];function Ke(r,t){if(r===void 0)return null;let e=typeof r=="function"?r(t):r;if(I.Buffer.isBuffer(e))return e;let s=String(e).replace(/\$TAG/g,()=>t.tag||"*");return I.Buffer.from(s,/[\u0100-\uffff]/.test(s)?"utf-8":"binary")}function Bu(r){if(!r||typeof r!="object")throw new TypeError("A script rule must be an object");if(!ct.includes(r.on))throw new TypeError('Script rule "on" must be one of '+ct.join(", "));for(let t of Object.keys(r)){let e=Object.hasOwn(Lu,t)?Lu[t]:null;if(!e)throw new TypeError('Unknown script rule option "'+t+'"');if(!e.includes(r.on))throw new TypeError('Script rule option "'+t+'" can not be used with "on": "'+r.on+'"')}if(r.on==="quiet"&&!(Number.isInteger(r.quietFor)&&r.quietFor>0))throw new TypeError('A quiet rule needs "quietFor", a positive number of milliseconds');if(r.chance!==void 0&&!(typeof r.chance=="number"&&r.chance>=0&&r.chance<=1))throw new TypeError('Script rule option "chance" must be a number from 0 to 1');if(!Ru.some(t=>r[t]!==void 0&&r[t]!==!1))throw new TypeError("A script rule needs an action ("+Ru.join(", ")+")");if(r.drop&&(r.send!==void 0||r.run))throw new TypeError('Script rule option "drop" can not be combined with "send" or "run"');if(r.run&&(r.close||r.truncate!==void 0))throw new TypeError('Script rule option "run" can not be combined with "close" or "truncate"');if(r.chunkDelay!==void 0&&r.chunk===void 0)throw new TypeError('Script rule option "chunkDelay" needs "chunk"');if(!Wi.includes(r.on)&&r.send===void 0&&(r.chunk!==void 0||r.truncate!==void 0))throw new TypeError('Script rule options "chunk" and "truncate" need "send" with "on": "'+r.on+'"');for(let t of["nth","times","chunk"])if(r[t]!==void 0&&!(Number.isInteger(r[t])&&r[t]>0))throw new TypeError('Script rule option "'+t+'" must be a positive integer');for(let t of["delay","chunkDelay","truncate"])if(!(t==="chunkDelay"&&r[t]==="tick")&&r[t]!==void 0&&!(Number.isInteger(r[t])&&r[t]>=0))throw new TypeError('Script rule option "'+t+'" must be a non-negative integer');for(let t of["when","mutate"])if(r[t]!==void 0&&typeof r[t]!="function")throw new TypeError('Script rule option "'+t+'" must be a function');for(let t of["send","before","after"]){let e=r[t];if(e!==void 0&&typeof e!="string"&&typeof e!="function"&&!I.Buffer.isBuffer(e))throw new TypeError('Script rule option "'+t+'" must be a string, a Buffer or a function')}if(r.literals!==void 0&&typeof r.literals!="boolean")throw new TypeError('Script rule option "literals" must be true or false');if(r.defer!==void 0){if(r.defer!=="tagged"&&r.defer!=="next")throw new TypeError('Script rule option "defer" must be "tagged" or "next"');if(r.untagged!==!0)throw new TypeError('Script rule option "defer" needs "untagged": true');let t=["drop","delay","chunk","truncate","close"].find(e=>r[e]!==void 0&&r[e]!==!1);if(t)throw new TypeError('Script rule option "defer" can not be combined with "'+t+'"')}if(r.close!==void 0&&typeof r.close!="boolean"&&r.close!=="reset")throw new TypeError('Script rule option "close" must be true, false or "reset"');if(r.match===void 0)return null;if(r.match instanceof RegExp)return new RegExp(r.match.source,r.match.flags.replace(/[gy]/g,""));if(typeof r.match!="string")throw new TypeError('Script rule option "match" must be a string or a RegExp');try{return new RegExp(r.match)}catch(t){throw new TypeError('Script rule option "match" is not a valid regular expression: '+t.message,{cause:t})}}var hs=class{constructor(t,e){this.server=t,this.entries=[],this.ruleCounter=0;let s=t.options.scriptSeed,n=()=>{this.random=pr(typeof s=="number"?s:Math.floor(Math.random()*4294967295))};n(),t.on("reset",n),this.watched=new Set,e&&this.add(e)}get rules(){return this.entries.slice()}add(t){if(Array.isArray(t)){let e=t.map(Bu);return t.map((s,n)=>this.addEntry(s,e[n]))}return this.addEntry(t,Bu(t))}clear(){this.setEntries([])}watches(t){return this.watched.has(t)}check(t,e,s){if(!this.watched.has(e))return null;let n=jh(t,e,s),i=this.find(n);return i?{rule:i,context:n}:null}setEntries(t){this.entries=t,this.watched=new Set(t.map(e=>e.rule.on)),this.watched.has("quiet")&&this.server.connections?.forEach(e=>e.watchQuiet())}nextQuiet(t){let e=null;for(let s of this.entries){let n=s.rule.quietFor;s.rule.on==="quiet"&&n!==void 0&&n>t&&(e===null||n<e)&&(e=n)}return e}addEntry(t,e){let s=Object.freeze(Object.assign({},t)),n={};for(let a of Uu)if(s[a]!==void 0){let o=[].concat(s[a]);n[a]=new Set(a==="command"?o.map(u=>String(u).toUpperCase()):o)}let i={id:++this.ruleCounter,rule:s,match:e,sets:n,matched:0,hits:0,remove:()=>this.setEntries(this.entries.filter(a=>a!==i))};return this.setEntries(this.entries.concat(i)),i}find(t){for(let e of this.entries){let s=e.rule;if(!(s.on!==t.event||!this.matches(e,t))&&(e.matched++,!(e.matched<(s.nth||1)||s.times!==void 0&&e.hits>=s.times)&&!(s.chance!==void 0&&this.random()>=s.chance)))return e.hits++,this.server.emit("script",{rule:s,event:t.event,session:t.session,tag:t.tag,command:t.command}),s}return null}matches(t,e){let s=t.rule;for(let n of Uu){let i=t.sets[n],a=e[n];if(i&&(a==null||!i.has(a)))return!1}return s.tag!==void 0&&(e.tag===null||(s.tag instanceof RegExp?!s.tag.test(e.tag):s.tag!==e.tag))||s.untagged!==void 0&&s.untagged!==(!e.response||e.response.tag==="*")||s.quietFor!==void 0&&(e.quiet||0)<s.quietFor||t.match&&!t.match.test(e.data)?!1:!s.when||!!s.when(e)}};function jh(r,t,e){let s=r._runningCommand?r._runningCommand.parsed:r.inputHandler?r.inputCommand:null;return Object.assign({event:t,connection:r,session:r.sessionNumber,state:r.state,user:r.username||null,mailbox:r.selectedMailbox?r.selectedMailbox.path:null,tag:s?s.tag:null,command:s?String(s.command).toUpperCase():null},e)}function Hu(r,t,e,s){let n=t.drop?I.Buffer.alloc(0):Ke(t.send,e)||s,i=[Ke(t.before,e),n,Ke(t.after,e)].filter(a=>!!a);if(t.defer){(r._deferredOutput||=[]).push({mode:t.defer,tag:e.tag,data:I.Buffer.concat(i)});return}Zi(r,t,I.Buffer.concat(i),t.delay)}function Ji(r,t,e){let s=[],n=[];for(let i of r._deferredOutput)((e?i.mode==="tagged"&&(i.tag===null||i.tag===t):i.mode==="next"&&t!==null&&i.tag!==t)?s:n).push(i);s.length&&(r._deferredOutput=n.length?n:null,s.forEach(i=>r.write(i.data)))}function Gt(r){return typeof r=="string"?{type:"LITERAL",value:r}:Array.isArray(r)?r.map(Gt):r&&typeof r=="object"&&r.type==="STRING"?{type:"LITERAL",value:r.value}:r}var Ie=r=>String(typeof r=="string"?r:r&&typeof r=="object"?r.value:"").toUpperCase();function $i(r){if(!Array.isArray(r))return Gt(r);if(Array.isArray(r[0])){let s=r.findIndex(n=>!Array.isArray(n));return r.map((n,i)=>s<0||i<s?$i(n):Gt(n))}let t=Ie(r[0]),e=t==="MESSAGE"&&["RFC822","GLOBAL"].includes(Ie(r[1]));return r.map((s,n)=>n===0&&(t==="TEXT"||e)||n===1&&e?s:n===8&&e?$i(s):Gt(s))}var Vh=new Set(["INTERNALDATE","SAVEDATE"]);function vu(r){let t=Array.isArray(r.attributes)?r.attributes:null;if(!t)return r;let e=Ie(r.command),s=Ie(t[1]),n;if(s==="FETCH"||s==="UIDFETCH"){let i=Array.isArray(t[2])?t[2]:[],a=i.map((o,u)=>{if(u%2===0)return o;let l=i[u-1],c=l&&!l.section?Ie(l):"";return Vh.has(c)?o:c==="BODY"||c==="BODYSTRUCTURE"?$i(o):Gt(o)});n=t.map((o,u)=>u===2?a:o)}else e==="LIST"||e==="LSUB"?n=t.map((i,a)=>a===1?i:a===3&&Array.isArray(i)?i.map((o,u)=>u%2===1&&Ie(i[u-1])==="CHILDINFO"?o:Gt(o)):Gt(i)):e==="NAMESPACE"?n=t.map(i=>Array.isArray(i)?i.map(a=>Array.isArray(a)?a.map((o,u)=>u===1?o:Gt(o)):a):i):n=t.map(Gt);return Object.assign({},r,{attributes:n})}function Zi(r,t,e,s){r.queueOutput({data:t.truncate===void 0?e:e.subarray(0,t.truncate),delay:s,chunk:t.chunk,chunkDelay:t.chunkDelay===void 0?kh:t.chunkDelay,close:t.close||(t.truncate===void 0?void 0:!0)})}function Fu(r,t,e){Zi(r,t,Ke(t.send,e)||I.Buffer.alloc(0))}function ta(r,t,e,s){let n=Ke(t.send,e);(n||t.close)&&Zi(r,t,n||I.Buffer.alloc(0)),(t.run||!t.drop&&!n&&!t.close)&&s()}var ea=1024*1024,Qh=20,Yh=64*1024*1024,Kh=64*1024,_u="Literal too large",zh=new Set(["OK","NO","BAD","BYE","PREAUTH"]),ia=new RegExp("^["+lt.tag().replace(/[\\\]^-]/g,"\\$&")+"]+$"),sa="["+lt["ATOM-CHAR"]().replace(/[\\\]^-]/g,"\\$&")+"]+",Wh=new RegExp("^"+sa+"$"),$h=new RegExp("^"+sa+"( "+sa+")?$"),Jh=new Map(["\\Noinferiors","\\Noselect","\\Marked","\\Unmarked","\\HasChildren","\\HasNoChildren","\\NonExistent"].map(r=>[r.toLowerCase(),r]));function ie(r){let t=r.indexOf(" "),e=t>=0?r.substr(0,t):r;return e&&ia.test(e)?e:"*"}function ku(r,t){return r+" is not allowed in the "+t+" state"}function ju(r){return!!r.mailboxCopy||$(r.attributes&&r.attributes[1],"EXPUNGE")}function Vu(r){return!!r&&!r.command&&$(r.attributes&&r.attributes[1],"EXISTS")}var qu=new WeakMap,Zh=(r,t,e,s)=>{r.sendStatus(t,e,"NO","Unsupported authentication mechanism",!1,"UNKNOWN COMMAND"),s()};function aa(r){return new ze(r)}var ze=class extends ar{constructor(t){super(),this.options=Object.assign({},t),this.options.secureConnection?this.server=Kt.createServer(this.getCredentials(),this.createClient.bind(this)):this.server=Kt.createServer(this.createClient.bind(this)),this.setMaxListeners(0),this.connections=new Set,this.connectionHandlers=[],this.resetHandlers=[],this.outputHandlers=[],this.messageHandlers=[],this.fetchHandlers={},this.fetchFilters=[],this.searchHandlers={},this.storeHandlers={},this.storeFilters=[],this.notifyFilters=[],this.mailboxHandlers=[],this.appendChecks=[],this.copyHandlers=[],this.appendDataHandlers=Object.create(null),this.literalFilters=[Ja],this.urlAccessChecks=[],this.searchAccessChecks=[],this.commandChecks=[],this.rangeLimits=[],this.searchLimits=[],this.closedChecks=[],this.multiAppend=!1,this.commandHandlers=Object.assign(Object.create(null),yu),this.commandOptions=Object.create(null),this.capabilities={},this.allowedStatus=["MESSAGES","RECENT","UIDNEXT","UIDVALIDITY","UNSEEN"],this.statusHandlers={},this.literalPlus=!1,this.nonSyncLiteralLimit=1/0,this.parserOptions={allowSection:["BODY","BODY.PEEK"]},this.referenceNamespace=!1,this.activeConnection=null,this.sessionCounter=0,this.script=new hs(this,this.options.script);let e=bu(this.options.quirks);e.rules.length&&this.script.add(e.rules),this.loadUsers(),this.control=new ns(this),du(this,this.options.plugins,e.removePlugins),this.options.storage&&Yi(this.options.storage),this.systemFlags=[].concat(this.options.systemFlags||["\\Answered","\\Flagged","\\Draft","\\Deleted","\\Seen"]),this.loadStorage(),this.smtpServer=null,this.restServer=null}loadUsers(){this.users=Object.assign(Object.create(null),this.options.users?structuredClone(this.options.users):{testuser:{password:"testpass",xoauth2:{accessToken:"testtoken",sessionTimeout:Er}}})}loadStorage(){this.storage=this.options.storage?structuredClone(this.options.storage):{INBOX:{},"":{}},this.referenceNamespace=!1,this.uidvalidityCounter=0,this.subscriptions=new Set,this.folderCache=Object.create(null),this.indexFolders(!0)}async start(t,e){let s=await Qu(this.server,t,e);return await Promise.all([this.options.smtp?this.startSmtp():null,this.options.rest?this.startRest():null]),s}async startRest(){let{port:t,host:e,token:s}=this.options.rest||{};return this.restServer=xu(this,{host:e,token:s}),Qu(this.restServer,t,e||"127.0.0.1")}startSmtp(){let{port:t,host:e}=this.options.smtp||{};return this.loadSmtpListener().then(({startSMTPServer:s})=>new Promise((n,i)=>{let a=s(t||0,this,o=>{a.removeListener("error",i),n(o)},e);a.once("error",i),this.smtpServer=a}))}loadSmtpListener(){return Promise.resolve().then(()=>(Gu(),Xu)).catch(t=>{throw new Error("The smtp option needs the smtp-server package, install it with: npm install smtp-server ("+t.message+")")})}stop(){return this.control.shutdown({graceful:!1})}listen(...t){this.server.listen.apply(this.server,t)}close(t){this.closeListeners(!0),this.server.close(t),this.connections.forEach(e=>{e.socket&&e.socket.destroy()})}closeListeners(t){this.smtpServer&&(this.smtpServer.close(()=>!1),this.smtpServer=null),this.restServer&&(this.restServer.endStreams?.(),this.restServer.close(),t?this.restServer.closeAllConnections?.():this.restServer.closeIdleConnections?.(),this.restServer=null)}getCredentials(){return this.options.credentials||(this.options.credentials={key:Mu,cert:wu}),this.options.credentials}address(){return this.server.address()}createClient(t){let e=new We(this,t);this.connectionHandlers.forEach(s=>{s(e)})}connect(t){let[e,s]=Du();return e.encrypted=s.encrypted=!t||t.secure!==!1,this.createClient(e),s}registerCapability(t,e){this.capabilities[t]=e||function(){return!0}}setCommandHandler(t,e,s){t=(t||"").toString().toUpperCase(),this.commandHandlers[t]=e,s&&(this.commandOptions[t]=et(s))}getCommandOptions(t){return t=(t||"").toString().toUpperCase(),this.commandOptions[t]||Ya(t)||et()}getCommandStates(t){return this.getCommandOptions(t).states}getUser(t){return typeof t=="string"&&this.users[t]||!1}getMailbox(t){return t.toUpperCase()==="INBOX"?this.folderCache.INBOX:this.folderCache[t]}notify(t,e,s,n){t.notification=!0;let i={command:t,mailbox:e,ignoreConnection:s,filter:n,origin:this.activeConnection};this.emit("notify",i)}mailboxChanged(t,e,s){let n=Object.assign({type:t,path:e,oldPath:null,mailbox:null},s,{origin:this.activeConnection});this.emit("mailbox",n)}withOrigin(t,e){let s=this.activeConnection;this.activeConnection=t;try{return e()}finally{this.activeConnection=s}}getCommandHandler(t){return this.commandHandlers[(t||"").toString().toUpperCase()]||!1}getStatus(t){let e=typeof t=="string"?this.getMailbox(t):t;if(!e)return!1;let s={},n=0,i=0,a=this.permanentFlagList(e),o=0,u=[];return this.connections.forEach(l=>{l.selectedMailbox===e&&l.recent&&u.push(l.recent)}),e.messages.forEach(l=>{l.flags.indexOf("\\Seen")<0?i++:n++,(l.recent||u.some(c=>c.has(l)))&&o++,l.flags.forEach(c=>{s[c]?s[c]++:s[c]=1,a.indexOf(c)<0&&a.push(c)})}),{flags:s,seen:n,unseen:i,recent:o,permanentFlags:a}}validateInternalDate(t){return wr(t)}formatInternalDate(t){let e=t.getDate(),s=me[t.getMonth()],n=t.getFullYear(),i=t.getHours(),a=t.getMinutes(),o=t.getSeconds(),u=t.getTimezoneOffset(),l=Math.floor(Math.abs(u)/60),c=Math.abs(u)%60;return(e<10?"0":"")+e+"-"+s+"-"+n+" "+(i<10?"0":"")+i+":"+(a<10?"0":"")+a+":"+(o<10?"0":"")+o+" "+(u>0?"-":"+")+(l<10?"0":"")+l+(c<10?"0":"")+c}createMailbox(t,e){if(!t)throw K("Invalid mailbox name","CANNOT");if(t.toUpperCase()==="INBOX")throw K("INBOX can not be modified","ALREADYEXISTS");let{namespace:s,storage:n}=this.getPersonalNamespace(t);if(t=this.stripSeparator(t,n.separator),this.folderCache[t]&&this.folderCache[t].flags.indexOf("\\Noselect")<0)throw K("Mailbox already exists","ALREADYEXISTS");let i=t.substr(s.length).split(n.separator);if(i.some(u=>!u))throw K("Mailbox names can not have empty hierarchy levels","CANNOT");let a=n,o=s;return o&&(o=o.substr(0,o.length-n.separator.length)),i.forEach(u=>{o+=(o.length?n.separator:"")+u;let l=this.getMailbox(o)||!1;if(l&&l.flags&&l.flags.indexOf("\\Noinferiors")>=0)throw K("Can not create subfolders for "+l.path,"CANNOT");let c=o===t,h=c&&e;if(!l||h||c&&l.flags.indexOf("\\Noselect")>=0){let m=l&&l.folders,T=h?e:{uidvalidity:++this.uidvalidityCounter};m&&(T.folders=Object.assign({},m,T.folders)),this.trackSubscription(T),this.processMailbox(o,T,s),a.folders=a.folders||{},a.folders[u]=T,this.folderCache[o]=T,l=T}a!==n?this.setChildrenFlags(a,!0):l.namespace===this.referenceNamespace&&this.inboxHoldsNamespace()&&this.setChildrenFlags(this.storage.INBOX,!0),a=l}),this.folderCache[t]}deleteMailbox(t,e){if(t.toUpperCase()==="INBOX")throw K("INBOX can not be modified","CANNOT");let{namespace:s,storage:n}=this.getPersonalNamespace(t),i=this.folderCache[this.stripSeparator(t,n.separator)];if(!i)throw K("Mailbox does not exist","NONEXISTENT");if(i.flags.indexOf("\\Noselect")>=0&&Object.keys(i.folders||{}).length)throw K("Mailbox has children, delete them first","HASCHILDREN");let a=i.path.split(n.separator),o=a.pop(),u=a.join(n.separator),l=u!=="INBOX"&&this.folderCache[u]||n;if(i.folders&&Object.keys(i.folders).length&&!e){let c={flags:["\\Noselect"],folders:i.folders};this.trackSubscription(c),this.processMailbox(i.path,c,i.namespace),l.folders[o]=c,this.folderCache[i.path]=c;return}delete this.folderCache[i.path],delete l.folders[o],l!==n?l.flags.indexOf("\\Noselect")>=0&&!Object.keys(l.folders||{}).length?this.deleteMailbox(l.path):this.setChildrenFlags(l,Object.keys(l.folders||{}).length>0):s===this.referenceNamespace&&this.inboxHoldsNamespace()&&this.setChildrenFlags(this.storage.INBOX,Object.keys(n.folders||{}).length>0)}getPersonalNamespace(t){let e="";Object.keys(this.storage).forEach(n=>{if(n==="INBOX")return;let i=n.length?n.substr(0,n.length-this.storage[n].separator.length):n;if(n.length&&(t===i||t.substr(0,n.length)===n)){if(t===i)throw K("Used mailbox name is a namespace value","CANNOT");e=n}else!e&&!n&&this.storage[n].type==="personal"&&(e=n)});let s=this.storage[e];if(!s)throw K("Unknown namespace","CANNOT");if(s.type!=="personal")throw K("Permission denied","NOPERM");return{namespace:e,storage:s}}stripSeparator(t,e){return t.substr(-e.length)===e?t.substr(0,t.length-e.length):t}inboxHoldsNamespace(){let t=this.referenceNamespace;if(t===!1)return!1;let e=this.storage[t];return!!e&&t.substr(0,t.length-e.separator.length).toUpperCase()==="INBOX"}indexFolders(t){let e=Object.create(null),s=(n,i,a,o)=>{Object.keys(a).forEach(u=>{let l=a[u],c=(n?n+(n.substr(-1)!==i?i:""):"")+u;this.processMailbox(c,l,o),e[c]=l,t&&this.processMessages(l),l.folders&&Object.keys(l.folders).length&&s(c,i,l.folders,o)})};this.storage.INBOX||(this.storage.INBOX={}),Object.keys(this.storage).forEach(n=>{n!=="INBOX"&&(this.storage[n].folders=this.storage[n].folders||{},this.storage[n].separator=this.storage[n].separator||(/[^a-z0-9]$/i.test(n)?n.substr(-1):"/"),this.storage[n].type=this.storage[n].type||"personal",this.storage[n].type==="personal"&&this.referenceNamespace===!1&&(this.referenceNamespace=n),s(n,this.storage[n].separator,this.storage[n].folders,n))}),this.referenceNamespace||(this.storage[""]=this.storage[""]||{},this.storage[""].folders=this.storage[""].folders||{},this.storage[""].separator=this.storage[""].separator||"/",this.storage[""].type="personal",this.referenceNamespace=""),this.storage.INBOX.separator||(this.storage.INBOX.separator=this.storage[this.referenceNamespace].separator),e.INBOX=this.storage.INBOX,this.processMailbox("INBOX",this.storage.INBOX,"INBOX"),t&&this.processMessages(this.storage.INBOX),this.storage.INBOX.folders&&Object.keys(this.storage.INBOX.folders).length&&s("INBOX",this.storage.INBOX.separator,this.storage.INBOX.folders,this.referenceNamespace),this.inboxHoldsNamespace()&&this.setChildrenFlags(this.storage.INBOX,Object.keys(this.storage[this.referenceNamespace].folders||{}).length>0),this.folderCache=e}processMessages(t){let e=new Set,s=t.messages;s.forEach((n,i)=>{let a=typeof n=="string"?s[i]={raw:n}:n;if(this.processMessage(a,t),e.has(a.uid))throw new Error("Duplicate UID "+a.uid+" in mailbox "+t.path);e.add(a.uid)}),t.messages.sort((n,i)=>n.uid-i.uid)}processMailbox(t,e,s){e.path=t,e.namespace=s,e.uid=e.uid||1,e.uidvalidity=e.uidvalidity||1,this.uidvalidityCounter=Math.max(this.uidvalidityCounter,e.uidvalidity),e.flags=[].concat(e.flags||[]).map(a=>Jh.get(String(a).toLowerCase())||a),e.allowPermanentFlags="allowPermanentFlags"in e?e.allowPermanentFlags:!0,e.permanentFlags=[].concat(e.permanentFlags||this.systemFlags),this.trackSubscription(e,!0);let n=[].concat(e.messages||[]);e.messages=n,e.uidnext=Math.max(...[e.uidnext||1].concat(n.map(a=>((typeof a=="string"?0:a.uid)||0)+1)));let i=e;this.setChildrenFlags(i,Object.keys(i.folders||{}).length>0),this.mailboxHandlers.forEach(a=>{a(this,i)})}trackSubscription(t,e){let s=Object.getOwnPropertyDescriptor(t,"subscribed");if(s&&s.get)return;let n=s?!!s.value:e;Object.defineProperty(t,"subscribed",{enumerable:!0,configurable:!0,get:()=>this.subscriptions.has(t.path),set:i=>{i?this.subscriptions.add(t.path):this.subscriptions.delete(t.path)}}),typeof n=="boolean"&&(t.subscribed=n)}setChildrenFlags(t,e){this.removeFlag(t.flags,"\\HasChildren"),this.removeFlag(t.flags,"\\HasNoChildren"),t.flags.indexOf("\\Noinferiors")<0&&t.flags.push(e?"\\HasChildren":"\\HasNoChildren")}ensureFlag(t,e){t.indexOf(e)<0&&t.push(e)}removeFlag(t,e){let s;if(t.indexOf(e)>=0)for(s=t.length-1;s>=0;s--)t[s]===e&&t.splice(s,1)}rememberFlags(t,e){let s=t.knownFlags=t.knownFlags||[];e.forEach(n=>this.ensureFlag(s,n))}isPermanentFlag(t,e){return t.allowPermanentFlags||(t.permanentFlags||[]).indexOf(e)>=0||!!t.knownFlags&&t.knownFlags.indexOf(e)>=0}permanentFlagList(t){let e=[].concat(t.permanentFlags||[]);return(t.knownFlags||[]).forEach(s=>this.ensureFlag(e,s)),e}now(){let t=this.options.now,e=typeof t=="function"?t():t;return e==null?new Date:new Date(e)}normalizeDateTime(t){return t instanceof Date?this.formatInternalDate(t):typeof t=="string"?t.replace(/-([a-z]{3})-/i,(e,s)=>"-"+(me[Vt(s)]||s)+"-"):t}processMessage(t,e){t.internaldate=this.normalizeDateTime(t.internaldate||this.now()),t.flags=[].concat(t.flags||[]),t.flags.indexOf("\\Recent")>=0&&(this.removeFlag(t.flags,"\\Recent"),t.recent=!0),this.rememberFlags(e,t.flags),t.uid=t.uid||e.uidnext++,t.uid>=e.uidnext&&(e.uidnext=t.uid+1),t.raw instanceof Uint8Array?t.raw=I.Buffer.from(t.raw).toString("binary"):typeof t.raw!="string"&&(t.raw=t.raw?String(t.raw):""),/[\u0100-\uffff]/.test(t.raw)&&(t.raw=I.Buffer.from(t.raw,"utf-8").toString("binary"));let s=t;this.messageHandlers.forEach(n=>{n(this,s,e)})}appendMessage(t,e,s,n,i,a){let o=typeof t=="string"?this.getMailbox(t):t,u=Object.assign({},a,{flags:e.filter(l=>this.isPermanentFlag(o,l)),internaldate:s,raw:n,recent:!0});o.messages.push(u),this.processMessage(u,o);for(let l of this.connections)if(l.selectedMailbox===o&&!l.readOnly&&l.recent){l.recent.add(u),delete u.recent;break}return this.notify({tag:"*",attributes:[o.messages.length,{type:"ATOM",value:"EXISTS"}],message:u},o,i),{mailbox:o,message:u}}copyMessage(t,e){let s={};return this.copyHandlers.forEach(n=>{n(this,e,s,t)}),this.appendMessage(t,[].concat(e.flags||[]),e.internaldate,e.raw,!1,s)}getNamespace(t){let e=!1;return Object.keys(this.storage).forEach(s=>{s!=="INBOX"&&t.substr(0,s.length)===s&&(e===!1||s.length>e.length)&&(e=s)}),e}targetRefusal(t){let e=this.getMailbox(t);return e?e.flags.indexOf("\\Noselect")>=0?{command:"NO",code:"TRYCREATE",text:"Target mailbox is not selectable"}:!1:{command:"NO",code:"TRYCREATE",text:"Target mailbox does not exist"}}getMailboxNamespace(t){if(t&&typeof t=="object")return t.namespace;if(t.toUpperCase()==="INBOX")return"INBOX";let e=this.getMailbox(t);return e?e.namespace:this.getNamespace(t)}isPersonal(t){let e=this.getMailboxNamespace(t);return e==="INBOX"||e!==!1&&!!this.storage[e]&&this.storage[e].type==="personal"}getSeparator(t){let e=this.getMailboxNamespace(t),s=e===!1?void 0:this.storage[e];return s&&s.separator||this.storage.INBOX.separator||"/"}getParentPath(t){let e=this.getSeparator(t);t=this.stripSeparator(t,e);let s=t.lastIndexOf(e);if(s<=0)return!1;let n=t.substr(0,s);return n.toUpperCase()==="INBOX"?"INBOX":this.storage[n+e]?!1:n}getDescendants(t,e){let s=e||this.folderCache,n=t+this.getSeparator(t);return Object.keys(s).filter(i=>i.substr(0,n.length)===n).map(i=>s[i])}hasDescendant(t,e){let s=t+this.getSeparator(t);for(let n of Object.keys(this.folderCache))if(n.substr(0,s.length)===s&&e(this.folderCache[n]))return!0;return!1}listAttributes(t,e){let s=e.exists!==!1,n=(t&&t.flags||[]).filter(i=>i!=="\\HasChildren"&&i!=="\\HasNoChildren"&&(s||i!=="\\Noselect"));return s||n.push("\\NonExistent"),e.subscribed&&n.push("\\Subscribed"),n.push(...e.extra||[]),n.indexOf("\\Noinferiors")<0&&n.push(e.hasChildren?"\\HasChildren":"\\HasNoChildren"),n}matchFolders(t,e,s,n){let i=n||this.folderCache,a=s||(m=>m),o=e.charAt(0)==="#"?e:(t||"")+e,u=(m,T="")=>new RegExp("^"+o.replace(/([\\^$+?!.():=[\]{}|,-])/g,"\\$1").replace(/[*]/g,".*").replace(/[%]/g,"[^"+m.replace(/([\\^$+*?!.():=[\]{}|,-])/g,"\\$1")+"]*")+"$",T),l=o.replace(/[*%].*$/,""),c=new Map;Object.keys(this.storage).forEach(m=>{let T=a(m),A=m===this.referenceNamespace||l.substr(0,T.length)===T;c.set(m,A?u(this.storage[m].separator):null)});let h=[];return i.INBOX&&u(this.storage.INBOX&&this.storage.INBOX.separator||"/","i").test("INBOX")&&h.push(i.INBOX),Object.keys(i).forEach(m=>{let T=i[m],A=m!=="INBOX"&&T.namespace!==!1&&T.namespace!=="INBOX"?c.get(T.namespace):null;if(!A)return;let p=a(m);A.test(p)&&(T.flags.indexOf("\\NonExistent")<0||p===o)&&h.push(T)}),h}getSubscriptionTree(){let t=Object.create(null),e=(n,i)=>{t[n]=t[n]||this.getMailbox(n)||{path:n,namespace:this.getNamespace(n),flags:["\\Noselect"],subscribed:i}},s=[...this.subscriptions].filter(n=>n==="INBOX"||this.getNamespace(n)!==!1);return s.forEach(n=>e(n,!0)),s.forEach(n=>{for(let i=this.getParentPath(n);i;i=this.getParentPath(i))e(i,!1)}),t}getMessageRange(t,e,s){let n=(e||"").toString(),i=typeof t=="string"?this.getMailbox(t):t;if(!mr(n)){let T=new Error("Invalid sequence set");throw T.imapResponse="BAD",T}let a=[],o=n.split(","),u=Array.isArray(i)?i:i.messages,l,c=u.length,h=0,m=function(T,A,p){for(let f=0,d=A.length;f<d;f++){let g=A[f].split(":"),b=g.shift(),C=Number(b==="*"?p:b)||1,v=g.pop()||C,M=Number(v==="*"&&p||v)||C;if(T>=Math.min(C,M)&&T<=Math.max(C,M))return!0}return!1};u.forEach(T=>{T.uid>h&&(h=T.uid)});for(let T=0,A=u.length;T<A;T++)l=u[T].uid||1,m(s?l:T+1,o,s?h:c)&&a.push([T+1,u[T]]);return a}},We=class{constructor(t,e){this.server=t,this.socket=e,this.options=this.server.options,this.state="Not Authenticated",this.sessionNumber=++this.server.sessionCounter,this._outputQueue=null,this._outputTimer=null,this._deferredOutput=null,this.secureConnection=!!this.options.secureConnection||e.encrypted===!0,this._remainder="",this._command="",this._literalRemaining=0,this.inputHandler=!1,this.transport=null,this.parserOptions={},this.compilerOptions={},this.messageGlobal=!1,this._commandQueue=[],this._processing=!1,this.options.debug&&typeof this.socket.pipe=="function"&&this.socket.pipe(U.stdout),this.socket.on("data",this.receive.bind(this)),this.socket.on("close",this.onClose.bind(this)),this.socket.on("error",this.onError.bind(this)),this.directNotifications=!1,this._notificationCallback=this.onNotify.bind(this),this.notificationQueue=[],this.server.on("notify",this._notificationCallback),this.server.connections.add(this),this.emitSession("open"),this.scriptOutput("greeting",`* OK ImapKit ready for rumble\r
|
|
88
|
-
`,{})}write(
|
|
89
|
-
`;if(!this.server.script.watches("continuation")){this.write(n);return}let i=
|
|
90
|
-
`);if(i<0)return;let
|
|
91
|
-
`}sendStatus(t,
|
|
92
|
-
`,l.stack),this.send({tag:
|
|
151
|
+
`;g();g();var Tr=Ut(ds()),tI=Tr.default.once;var Ir=class extends Tr.default{constructor(){super(),this.peer=null,this.destroyed=!1,this.encrypted=!1,this._paused=!1,this._ending=!1,this._encoding=null,this._received=[]}write(e,t,r){if(typeof t=="function"&&(r=t,t=void 0),this.destroyed||this._ending)return!1;let n=typeof e=="string"?b.Buffer.from(e,t||"utf8"):b.Buffer.from(e.buffer,e.byteOffset,e.byteLength);return Sr(()=>{this.peer?.deliver(n),r?.()}),!0}end(e){return e!==void 0&&this.write(e),this.destroyed||this._ending?this:(this._ending=!0,Sr(()=>{let t=this.peer;t&&!t.destroyed&&(t.emit("end"),t.close()),this.close()}),this)}destroy(e){if(this.destroyed)return this;let t=this.peer;return this.close(e),t&&!t.destroyed&&t.close(),this}resetAndDestroy(){let e=this.peer;if(this.destroy(),e){let t=new Error("read ECONNRESET");t.code="ECONNRESET",Sr(()=>e.emit("error",t))}return this}startTls(e){this.encrypted=!0,this.peer&&(this.peer.encrypted=!0),e()}pause(){return this._paused=!0,this}resume(){for(this._paused=!1;this._received.length&&!this._paused&&!this.destroyed;)this.emitData(this._received.shift());return this}setEncoding(e){return this._encoding=e,this}deliver(e){if(!this.destroyed){if(this._paused){this._received.push(e);return}this.emitData(e)}}emitData(e){this.emit("data",this._encoding?e.toString(this._encoding):e)}close(e){this.destroyed||(this.destroyed=!0,this._received=[],Sr(()=>{e&&this.emit("error",e),this.emit("close",!!e)}))}};function Tl(){let s=new Ir,e=new Ir;return s.peer=e,e.peer=s,[s,e]}var Or=[];function Sr(s){Or.push(s),Or.length===1&&R(qd)}function qd(){let s=Or.splice(0,Or.length);for(let e of s)e()}g();var de=["greeting","command","input","response","continuation","quiet"],Co=["greeting","response","continuation"],Sl={on:de,command:["command","input","response","continuation","quiet"],tag:["command","input","response","continuation","quiet"],description:["response","continuation"],session:de,user:de,state:de,mailbox:de,untagged:["response"],match:de,when:de,nth:de,times:de,chance:de,quietFor:["quiet"],mutate:["response","continuation"],literals:["response"],defer:["response"],send:de,before:Co,after:Co,run:["command","input"],drop:["greeting","command","input","response","continuation"],delay:["greeting","command","response","continuation"],chunk:de,chunkDelay:de,truncate:de,close:de},Il=["mutate","literals","defer","send","before","after","run","drop","delay","chunk","truncate","close"],Qd=10,Ol=["command","description","session","state","user","mailbox"];function ss(s,e){if(s===void 0)return null;let t=typeof s=="function"?s(e):s;if(b.Buffer.isBuffer(t))return t;let r=String(t).replace(/\$TAG/g,()=>e.tag||"*");return b.Buffer.from(r,/[\u0100-\uffff]/.test(r)?"utf-8":"binary")}function xl(s){if(!s||typeof s!="object")throw new TypeError("A script rule must be an object");if(!de.includes(s.on))throw new TypeError('Script rule "on" must be one of '+de.join(", "));for(let e of Object.keys(s)){let t=Object.hasOwn(Sl,e)?Sl[e]:null;if(!t)throw new TypeError('Unknown script rule option "'+e+'"');if(!t.includes(s.on))throw new TypeError('Script rule option "'+e+'" can not be used with "on": "'+s.on+'"')}if(s.on==="quiet"&&!(Number.isInteger(s.quietFor)&&s.quietFor>0))throw new TypeError('A quiet rule needs "quietFor", a positive number of milliseconds');if(s.chance!==void 0&&!(typeof s.chance=="number"&&s.chance>=0&&s.chance<=1))throw new TypeError('Script rule option "chance" must be a number from 0 to 1');if(!Il.some(e=>s[e]!==void 0&&s[e]!==!1))throw new TypeError("A script rule needs an action ("+Il.join(", ")+")");if(s.drop&&(s.send!==void 0||s.run))throw new TypeError('Script rule option "drop" can not be combined with "send" or "run"');if(s.run&&(s.close||s.truncate!==void 0))throw new TypeError('Script rule option "run" can not be combined with "close" or "truncate"');if(s.chunkDelay!==void 0&&s.chunk===void 0)throw new TypeError('Script rule option "chunkDelay" needs "chunk"');if(!Co.includes(s.on)&&s.send===void 0&&(s.chunk!==void 0||s.truncate!==void 0))throw new TypeError('Script rule options "chunk" and "truncate" need "send" with "on": "'+s.on+'"');for(let e of["nth","times","chunk"])if(s[e]!==void 0&&!(Number.isInteger(s[e])&&s[e]>0))throw new TypeError('Script rule option "'+e+'" must be a positive integer');for(let e of["delay","chunkDelay","truncate"])if(!(e==="chunkDelay"&&s[e]==="tick")&&s[e]!==void 0&&!(Number.isInteger(s[e])&&s[e]>=0))throw new TypeError('Script rule option "'+e+'" must be a non-negative integer');for(let e of["when","mutate"])if(s[e]!==void 0&&typeof s[e]!="function")throw new TypeError('Script rule option "'+e+'" must be a function');for(let e of["send","before","after"]){let t=s[e];if(t!==void 0&&typeof t!="string"&&typeof t!="function"&&!b.Buffer.isBuffer(t))throw new TypeError('Script rule option "'+e+'" must be a string, a Buffer or a function')}if(s.literals!==void 0&&typeof s.literals!="boolean")throw new TypeError('Script rule option "literals" must be true or false');if(s.defer!==void 0){if(s.defer!=="tagged"&&s.defer!=="next")throw new TypeError('Script rule option "defer" must be "tagged" or "next"');if(s.untagged!==!0)throw new TypeError('Script rule option "defer" needs "untagged": true');let e=["drop","delay","chunk","truncate","close"].find(t=>s[t]!==void 0&&s[t]!==!1);if(e)throw new TypeError('Script rule option "defer" can not be combined with "'+e+'"')}if(s.close!==void 0&&typeof s.close!="boolean"&&s.close!=="reset")throw new TypeError('Script rule option "close" must be true, false or "reset"');if(s.match===void 0)return null;if(s.match instanceof RegExp)return new RegExp(s.match.source,s.match.flags.replace(/[gy]/g,""));if(typeof s.match!="string")throw new TypeError('Script rule option "match" must be a string or a RegExp');try{return new RegExp(s.match)}catch(e){throw new TypeError('Script rule option "match" is not a valid regular expression: '+e.message,{cause:e})}}var xr=class{constructor(e,t){this.server=e,this.entries=[],this.ruleCounter=0;let r=e.options.scriptSeed,n=()=>{this.random=Ss(typeof r=="number"?r:Math.floor(Math.random()*4294967295))};n(),e.on("reset",n),this.watched=new Set,t&&this.add(t)}get rules(){return this.entries.slice()}add(e){if(Array.isArray(e)){let t=e.map(xl);return e.map((r,n)=>this.addEntry(r,t[n]))}return this.addEntry(e,xl(e))}clear(){this.setEntries([])}watches(e){return this.watched.has(e)}check(e,t,r){if(!this.watched.has(t))return null;let n=Yd(e,t,r),i=this.find(n);return i?{rule:i,context:n}:null}setEntries(e){this.entries=e,this.watched=new Set(e.map(t=>t.rule.on)),this.watched.has("quiet")&&this.server.connections?.forEach(t=>t.watchQuiet())}nextQuiet(e){let t=null;for(let r of this.entries){let n=r.rule.quietFor;r.rule.on==="quiet"&&n!==void 0&&n>e&&(t===null||n<t)&&(t=n)}return t}addEntry(e,t){let r=Object.freeze(Object.assign({},e)),n={};for(let o of Ol)if(r[o]!==void 0){let a=[].concat(r[o]);n[o]=new Set(o==="command"?a.map(u=>String(u).toUpperCase()):a)}let i={id:++this.ruleCounter,rule:r,match:t,sets:n,matched:0,hits:0,remove:()=>this.setEntries(this.entries.filter(o=>o!==i))};return this.setEntries(this.entries.concat(i)),i}find(e){for(let t of this.entries){let r=t.rule;if(!(r.on!==e.event||!this.matches(t,e))&&(t.matched++,!(t.matched<(r.nth||1)||r.times!==void 0&&t.hits>=r.times)&&!(r.chance!==void 0&&this.random()>=r.chance)))return t.hits++,this.server.emit("script",{rule:r,event:e.event,session:e.session,tag:e.tag,command:e.command}),r}return null}matches(e,t){let r=e.rule;for(let n of Ol){let i=e.sets[n],o=t[n];if(i&&(o==null||!i.has(o)))return!1}return r.tag!==void 0&&(t.tag===null||(r.tag instanceof RegExp?!r.tag.test(t.tag):r.tag!==t.tag))||r.untagged!==void 0&&r.untagged!==(!t.response||t.response.tag==="*")||r.quietFor!==void 0&&(t.quiet||0)<r.quietFor||e.match&&!e.match.test(t.data)?!1:!r.when||!!r.when(t)}};function Yd(s,e,t){let r=s._runningCommand?s._runningCommand.parsed:s.inputHandler?s.inputCommand:null;return Object.assign({event:e,connection:s,session:s.sessionNumber,state:s.state,user:s.username||null,mailbox:s.selectedMailbox?s.selectedMailbox.path:null,tag:r?r.tag:null,command:r?String(r.command).toUpperCase():null},t)}function Cl(s,e,t,r){let n=e.drop?b.Buffer.alloc(0):ss(e.send,t)||r,i=[ss(e.before,t),n,ss(e.after,t)].filter(o=>!!o);if(e.defer){(s._deferredOutput||=[]).push({mode:e.defer,tag:t.tag,data:b.Buffer.concat(i)});return}Mo(s,e,b.Buffer.concat(i),e.delay)}function No(s,e,t){let r=[],n=[];for(let i of s._deferredOutput)((t?i.mode==="tagged"&&(i.tag===null||i.tag===e):i.mode==="next"&&e!==null&&i.tag!==e)?r:n).push(i);r.length&&(s._deferredOutput=n.length?n:null,r.forEach(i=>s.write(i.data)))}function Ve(s){return typeof s=="string"?{type:"LITERAL",value:s}:Array.isArray(s)?s.map(Ve):s&&typeof s=="object"&&s.type==="STRING"?{type:"LITERAL",value:s.value}:s}var Rt=s=>String(typeof s=="string"?s:s&&typeof s=="object"?s.value:"").toUpperCase();function wo(s){if(!Array.isArray(s))return Ve(s);if(Array.isArray(s[0])){let r=s.findIndex(n=>!Array.isArray(n));return s.map((n,i)=>r<0||i<r?wo(n):Ve(n))}let e=Rt(s[0]),t=e==="MESSAGE"&&["RFC822","GLOBAL"].includes(Rt(s[1]));return s.map((r,n)=>n===0&&(e==="TEXT"||t)||n===1&&t?r:n===8&&t?wo(r):Ve(r))}var Kd=new Set(["INTERNALDATE","SAVEDATE"]);function wl(s){let e=Array.isArray(s.attributes)?s.attributes:null;if(!e)return s;let t=Rt(s.command),r=Rt(e[1]),n;if(r==="FETCH"||r==="UIDFETCH"){let i=Array.isArray(e[2])?e[2]:[],o=i.map((a,u)=>{if(u%2===0)return a;let l=i[u-1],c=l&&!l.section?Rt(l):"";return Kd.has(c)?a:c==="BODY"||c==="BODYSTRUCTURE"?wo(a):Ve(a)});n=e.map((a,u)=>u===2?o:a)}else t==="LIST"||t==="LSUB"?n=e.map((i,o)=>o===1?i:o===3&&Array.isArray(i)?i.map((a,u)=>u%2===1&&Rt(i[u-1])==="CHILDINFO"?a:Ve(a)):Ve(i)):t==="NAMESPACE"?n=e.map(i=>Array.isArray(i)?i.map(o=>Array.isArray(o)?o.map((a,u)=>u===1?a:Ve(a)):o):i):n=e.map(Ve);return Object.assign({},s,{attributes:n})}function Mo(s,e,t,r){s.queueOutput({data:e.truncate===void 0?t:t.subarray(0,e.truncate),delay:r,chunk:e.chunk,chunkDelay:e.chunkDelay===void 0?Qd:e.chunkDelay,close:e.close||(e.truncate===void 0?void 0:!0)})}function Nl(s,e,t){Mo(s,e,ss(e.send,t)||b.Buffer.alloc(0))}function Ro(s,e,t,r){let n=ss(e.send,t);(n||e.close)&&Mo(s,e,n||b.Buffer.alloc(0)),(e.run||!e.drop&&!n&&!e.close)&&r()}var Lo=1024*1024,Wd=20,$d=64*1024*1024,Jd=64*1024,Dl="Literal too large",Zd=new Set(["OK","NO","BAD","BYE","PREAUTH"]),Bo=new RegExp("^["+he.tag().replace(/[\\\]^-]/g,"\\$&")+"]+$"),Uo="["+he["ATOM-CHAR"]().replace(/[\\\]^-]/g,"\\$&")+"]+",ep=new RegExp("^"+Uo+"$"),tp=new RegExp("^"+Uo+"( "+Uo+")?$"),sp=new Map(["\\Noinferiors","\\Noselect","\\Marked","\\Unmarked","\\HasChildren","\\HasNoChildren","\\NonExistent"].map(s=>[s.toLowerCase(),s]));function ht(s){let e=s.indexOf(" "),t=e>=0?s.substr(0,e):s;return t&&Bo.test(t)?t:"*"}function Ul(s,e){return s+" is not allowed in the "+e+" state"}function vl(s){return!!s.mailboxCopy||J(s.attributes&&s.attributes[1],"EXPUNGE")}function Bl(s){return!!s&&!s.command&&J(s.attributes&&s.attributes[1],"EXISTS")}var Hl=new WeakMap,rp=(s,e,t,r)=>{s.sendStatus(e,t,"NO","Unsupported authentication mechanism",!1,"UNKNOWN COMMAND"),r()};function Ho(s){return new rs(s)}var rs=class extends ps{constructor(e){super(),this.options=Object.assign({},e),this.options.secureConnection?this.server=Qe.createServer(this.getCredentials(),this.createClient.bind(this)):this.server=Qe.createServer(this.createClient.bind(this)),this.setMaxListeners(0),this.connections=new Set,this.connectionHandlers=[],this.resetHandlers=[],this.outputHandlers=[],this.messageHandlers=[],this.fetchHandlers={},this.fetchFilters=[],this.searchHandlers={},this.storeHandlers={},this.storeFilters=[],this.notifyFilters=[],this.mailboxHandlers=[],this.appendChecks=[],this.copyHandlers=[],this.appendDataHandlers=Object.create(null),this.literalFilters=[Na],this.urlAccessChecks=[],this.searchAccessChecks=[],this.commandChecks=[],this.rangeLimits=[],this.searchLimits=[],this.closedChecks=[],this.multiAppend=!1,this.commandHandlers=Object.assign(Object.create(null),zu),this.commandOptions=Object.create(null),this.capabilities={},this.allowedStatus=["MESSAGES","RECENT","UIDNEXT","UIDVALIDITY","UNSEEN"],this.statusHandlers={},this.literalPlus=!1,this.nonSyncLiteralLimit=1/0,this.parserOptions={allowSection:["BODY","BODY.PEEK"]},this.referenceNamespace=!1,this.activeConnection=null,this.sessionCounter=0,this.script=new xr(this,this.options.script);let t=el(this.options.quirks);t.rules.length&&this.script.add(t.rules),this.loadUsers(),this.control=new hr(this),this.oauth=this.options.oauth?new Ar(this,this.options.oauth):null,this.oauthServer=null,Xu(this,this.options.plugins,t.removePlugins),this.options.storage&&co(this.options.storage),this.systemFlags=[].concat(this.options.systemFlags||["\\Answered","\\Flagged","\\Draft","\\Deleted","\\Seen"]),this.loadStorage(),this.tlsServer=null,this.smtpServer=null,this.restServer=null}loadUsers(){this.users=Object.assign(Object.create(null),this.options.users?structuredClone(this.options.users):{testuser:{password:"testpass",xoauth2:{accessToken:"testtoken",sessionTimeout:Os}}});for(let e of Object.keys(this.users)){let t=this.users[e];t&&t.oauth!==void 0&&(t.oauth=io(t.oauth,"users["+JSON.stringify(e)+"].oauth"))}}loadStorage(){this.storage=this.options.storage?structuredClone(this.options.storage):{INBOX:{},"":{}},this.referenceNamespace=!1,this.uidvalidityCounter=0,this.subscriptions=new Set,this.folderCache=Object.create(null),this.indexFolders(!0)}async start(e,t){let r=await wr(this.server,e,t);return await Promise.all([this.options.tls?this.startTlsListener(t):null,this.options.smtp?this.startSmtp():null,this.options.rest?this.startRest():null,this.oauth?this.startOAuth():null]),r}startTlsListener(e){let{port:t,host:r}=this.options.tls||{};return this.tlsServer=Qe.createServer(this.getCredentials(),this.createClient.bind(this)),wr(this.tlsServer,t,r||e)}async startRest(){let{port:e,host:t,token:r}=this.options.rest||{};return this.restServer=il(this,{host:t,token:r}),wr(this.restServer,e,t||"127.0.0.1")}async startOAuth(){let e=this.oauth,{port:t,host:r="127.0.0.1",secure:n}=e.options;this.oauthServer=Al(e,{secure:n,host:r,credentials:this.getCredentials()});let i=await wr(this.oauthServer,t,r);return e.listening(r,i),i}checkAccessToken(e,t,r="imap"){let n=this.oauth&&this.oauth.verifyAccessToken(e,t,r);if(n)return n;let i=a=>{let u=this.users[a];return!!(u&&u.xoauth2&&u.xoauth2.accessToken===e)},o=t===void 0?Object.keys(this.users).find(i):i(t)?t:void 0;return o===void 0?{error:"invalid_token",reason:"unknown access token"}:{user:o}}startSmtp(){let{port:e,host:t}=this.options.smtp||{};return this.loadSmtpListener().then(({startSMTPServer:r})=>new Promise((n,i)=>{let o=r(e||0,this,a=>{o.removeListener("error",i),n(a)},t);o.once("error",i),this.smtpServer=o}))}loadSmtpListener(){return Promise.resolve().then(()=>(Ll(),Rl)).catch(e=>{throw new Error("The smtp option needs the smtp-server package, install it with: npm install smtp-server ("+e.message+")")})}stop(){return this.control.shutdown({graceful:!1})}listen(...e){this.server.listen.apply(this.server,e)}close(e){this.closeListeners(!0),this.closeImapListeners(e),this.connections.forEach(t=>{t.socket&&t.socket.destroy()})}closeImapListeners(e){let t=this.tlsServer?[this.server,this.tlsServer]:[this.server];this.tlsServer=null;let r=t.length,n;t.forEach(i=>i.close(o=>{n=n||o,--r===0&&e?.(n)}))}closeListeners(e){this.smtpServer&&(this.smtpServer.close(()=>!1),this.smtpServer=null),this.restServer&&(this.restServer.endStreams?.(),kl(this.restServer,e),this.restServer=null),this.oauthServer&&(kl(this.oauthServer,e),this.oauthServer=null)}getCredentials(){return this.options.credentials||(this.options.credentials={key:yl,cert:bl}),this.options.credentials}address(){return this.server.address()}createClient(e){let t=new ns(this,e);this.connectionHandlers.forEach(r=>{r(t)})}connect(e){let[t,r]=Tl();return t.encrypted=r.encrypted=!e||e.secure!==!1,this.createClient(t),r}registerCapability(e,t){this.capabilities[e]=t||function(){return!0}}setCommandHandler(e,t,r){e=(e||"").toString().toUpperCase(),this.commandHandlers[e]=t,r&&(this.commandOptions[e]=re(r))}getCommandOptions(e){return e=(e||"").toString().toUpperCase(),this.commandOptions[e]||Ia(e)||re()}getCommandStates(e){return this.getCommandOptions(e).states}getUser(e){return typeof e=="string"&&Object.hasOwn(this.users,e)&&this.users[e]||!1}getMailbox(e){return e.toUpperCase()==="INBOX"?this.folderCache.INBOX:this.folderCache[e]}notify(e,t,r,n){e.notification=!0;let i={command:e,mailbox:t,ignoreConnection:r,filter:n,origin:this.activeConnection};this.emit("notify",i)}mailboxChanged(e,t,r){let n=Object.assign({type:e,path:t,oldPath:null,mailbox:null},r,{origin:this.activeConnection});this.emit("mailbox",n)}withOrigin(e,t){let r=this.activeConnection;this.activeConnection=e;try{return t()}finally{this.activeConnection=r}}getCommandHandler(e){return this.commandHandlers[(e||"").toString().toUpperCase()]||!1}getStatus(e){let t=typeof e=="string"?this.getMailbox(e):e;if(!t)return!1;let r={},n=0,i=0,o=this.permanentFlagList(t),a=0,u=[];return this.connections.forEach(l=>{l.selectedMailbox===t&&l.recent&&u.push(l.recent)}),t.messages.forEach(l=>{l.flags.indexOf("\\Seen")<0?i++:n++,(l.recent||u.some(c=>c.has(l)))&&a++,l.flags.forEach(c=>{r[c]?r[c]++:r[c]=1,o.indexOf(c)<0&&o.push(c)})}),{flags:r,seen:n,unseen:i,recent:a,permanentFlags:o}}validateInternalDate(e){return ks(e)}formatInternalDate(e){let t=e.getDate(),r=St[e.getMonth()],n=e.getFullYear(),i=e.getHours(),o=e.getMinutes(),a=e.getSeconds(),u=e.getTimezoneOffset(),l=Math.floor(Math.abs(u)/60),c=Math.abs(u)%60;return(t<10?"0":"")+t+"-"+r+"-"+n+" "+(i<10?"0":"")+i+":"+(o<10?"0":"")+o+":"+(a<10?"0":"")+a+" "+(u>0?"-":"+")+(l<10?"0":"")+l+(c<10?"0":"")+c}createMailbox(e,t){if(!e)throw K("Invalid mailbox name","CANNOT");if(e.toUpperCase()==="INBOX")throw K("INBOX can not be modified","ALREADYEXISTS");let{namespace:r,storage:n}=this.getPersonalNamespace(e);if(e=this.stripSeparator(e,n.separator),this.folderCache[e]&&this.folderCache[e].flags.indexOf("\\Noselect")<0)throw K("Mailbox already exists","ALREADYEXISTS");let i=e.substr(r.length).split(n.separator);if(i.some(u=>!u))throw K("Mailbox names can not have empty hierarchy levels","CANNOT");let o=n,a=r;return a&&(a=a.substr(0,a.length-n.separator.length)),i.forEach(u=>{a+=(a.length?n.separator:"")+u;let l=this.getMailbox(a)||!1;if(l&&l.flags&&l.flags.indexOf("\\Noinferiors")>=0)throw K("Can not create subfolders for "+l.path,"CANNOT");let c=a===e,f=c&&t;if(!l||f||c&&l.flags.indexOf("\\Noselect")>=0){let p=l&&l.folders,y=f?t:{uidvalidity:++this.uidvalidityCounter};p&&(y.folders=Object.assign({},p,y.folders)),this.trackSubscription(y),this.processMailbox(a,y,r),o.folders=o.folders||{},o.folders[u]=y,this.folderCache[a]=y,l=y}o!==n?this.setChildrenFlags(o,!0):l.namespace===this.referenceNamespace&&this.inboxHoldsNamespace()&&this.setChildrenFlags(this.storage.INBOX,!0),o=l}),this.folderCache[e]}deleteMailbox(e,t){if(e.toUpperCase()==="INBOX")throw K("INBOX can not be modified","CANNOT");let{namespace:r,storage:n}=this.getPersonalNamespace(e),i=this.folderCache[this.stripSeparator(e,n.separator)];if(!i)throw K("Mailbox does not exist","NONEXISTENT");if(i.flags.indexOf("\\Noselect")>=0&&Object.keys(i.folders||{}).length)throw K("Mailbox has children, delete them first","HASCHILDREN");let o=i.path.split(n.separator),a=o.pop(),u=o.join(n.separator),l=u!=="INBOX"&&this.folderCache[u]||n;if(i.folders&&Object.keys(i.folders).length&&!t){let c={flags:["\\Noselect"],folders:i.folders};this.trackSubscription(c),this.processMailbox(i.path,c,i.namespace),l.folders[a]=c,this.folderCache[i.path]=c;return}delete this.folderCache[i.path],delete l.folders[a],l!==n?l.flags.indexOf("\\Noselect")>=0&&!Object.keys(l.folders||{}).length?this.deleteMailbox(l.path):this.setChildrenFlags(l,Object.keys(l.folders||{}).length>0):r===this.referenceNamespace&&this.inboxHoldsNamespace()&&this.setChildrenFlags(this.storage.INBOX,Object.keys(n.folders||{}).length>0)}getPersonalNamespace(e){let t="";Object.keys(this.storage).forEach(n=>{if(n==="INBOX")return;let i=n.length?n.substr(0,n.length-this.storage[n].separator.length):n;if(n.length&&(e===i||e.substr(0,n.length)===n)){if(e===i)throw K("Used mailbox name is a namespace value","CANNOT");t=n}else!t&&!n&&this.storage[n].type==="personal"&&(t=n)});let r=this.storage[t];if(!r)throw K("Unknown namespace","CANNOT");if(r.type!=="personal")throw K("Permission denied","NOPERM");return{namespace:t,storage:r}}stripSeparator(e,t){return e.substr(-t.length)===t?e.substr(0,e.length-t.length):e}inboxHoldsNamespace(){let e=this.referenceNamespace;if(e===!1)return!1;let t=this.storage[e];return!!t&&e.substr(0,e.length-t.separator.length).toUpperCase()==="INBOX"}indexFolders(e){let t=Object.create(null),r=(n,i,o,a)=>{Object.keys(o).forEach(u=>{let l=o[u],c=(n?n+(n.substr(-1)!==i?i:""):"")+u;this.processMailbox(c,l,a),t[c]=l,e&&this.processMessages(l),l.folders&&Object.keys(l.folders).length&&r(c,i,l.folders,a)})};this.storage.INBOX||(this.storage.INBOX={}),Object.keys(this.storage).forEach(n=>{n!=="INBOX"&&(this.storage[n].folders=this.storage[n].folders||{},this.storage[n].separator=this.storage[n].separator||(/[^a-z0-9]$/i.test(n)?n.substr(-1):"/"),this.storage[n].type=this.storage[n].type||"personal",this.storage[n].type==="personal"&&this.referenceNamespace===!1&&(this.referenceNamespace=n),r(n,this.storage[n].separator,this.storage[n].folders,n))}),this.referenceNamespace||(this.storage[""]=this.storage[""]||{},this.storage[""].folders=this.storage[""].folders||{},this.storage[""].separator=this.storage[""].separator||"/",this.storage[""].type="personal",this.referenceNamespace=""),this.storage.INBOX.separator||(this.storage.INBOX.separator=this.storage[this.referenceNamespace].separator),t.INBOX=this.storage.INBOX,this.processMailbox("INBOX",this.storage.INBOX,"INBOX"),e&&this.processMessages(this.storage.INBOX),this.storage.INBOX.folders&&Object.keys(this.storage.INBOX.folders).length&&r("INBOX",this.storage.INBOX.separator,this.storage.INBOX.folders,this.referenceNamespace),this.inboxHoldsNamespace()&&this.setChildrenFlags(this.storage.INBOX,Object.keys(this.storage[this.referenceNamespace].folders||{}).length>0),this.folderCache=t}processMessages(e){let t=new Set,r=e.messages;r.forEach((n,i)=>{let o=typeof n=="string"?r[i]={raw:n}:n;if(this.processMessage(o,e),t.has(o.uid))throw new Error("Duplicate UID "+o.uid+" in mailbox "+e.path);t.add(o.uid)}),e.messages.sort((n,i)=>n.uid-i.uid)}processMailbox(e,t,r){t.path=e,t.namespace=r,t.uid=t.uid||1,t.uidvalidity=t.uidvalidity||1,this.uidvalidityCounter=Math.max(this.uidvalidityCounter,t.uidvalidity),t.flags=[].concat(t.flags||[]).map(o=>sp.get(String(o).toLowerCase())||o),t.allowPermanentFlags="allowPermanentFlags"in t?t.allowPermanentFlags:!0,t.permanentFlags=[].concat(t.permanentFlags||this.systemFlags),this.trackSubscription(t,!0);let n=[].concat(t.messages||[]);t.messages=n,t.uidnext=Math.max(...[t.uidnext||1].concat(n.map(o=>((typeof o=="string"?0:o.uid)||0)+1)));let i=t;this.setChildrenFlags(i,Object.keys(i.folders||{}).length>0),this.mailboxHandlers.forEach(o=>{o(this,i)})}trackSubscription(e,t){let r=Object.getOwnPropertyDescriptor(e,"subscribed");if(r&&r.get)return;let n=r?!!r.value:t;Object.defineProperty(e,"subscribed",{enumerable:!0,configurable:!0,get:()=>this.subscriptions.has(e.path),set:i=>{i?this.subscriptions.add(e.path):this.subscriptions.delete(e.path)}}),typeof n=="boolean"&&(e.subscribed=n)}setChildrenFlags(e,t){this.removeFlag(e.flags,"\\HasChildren"),this.removeFlag(e.flags,"\\HasNoChildren"),e.flags.indexOf("\\Noinferiors")<0&&e.flags.push(t?"\\HasChildren":"\\HasNoChildren")}ensureFlag(e,t){e.indexOf(t)<0&&e.push(t)}removeFlag(e,t){let r;if(e.indexOf(t)>=0)for(r=e.length-1;r>=0;r--)e[r]===t&&e.splice(r,1)}rememberFlags(e,t){let r=e.knownFlags=e.knownFlags||[];t.forEach(n=>this.ensureFlag(r,n))}isPermanentFlag(e,t){return e.allowPermanentFlags||(e.permanentFlags||[]).indexOf(t)>=0||!!e.knownFlags&&e.knownFlags.indexOf(t)>=0}permanentFlagList(e){let t=[].concat(e.permanentFlags||[]);return(e.knownFlags||[]).forEach(r=>this.ensureFlag(t,r)),t}now(){let e=this.options.now,t=typeof e=="function"?e():e;return t==null?new Date:new Date(t)}normalizeDateTime(e){return e instanceof Date?this.formatInternalDate(e):typeof e=="string"?e.replace(/-([a-z]{3})-/i,(t,r)=>"-"+(St[ze(r)]||r)+"-"):e}processMessage(e,t){e.internaldate=this.normalizeDateTime(e.internaldate||this.now()),e.flags=[].concat(e.flags||[]),e.flags.indexOf("\\Recent")>=0&&(this.removeFlag(e.flags,"\\Recent"),e.recent=!0),this.rememberFlags(t,e.flags),e.uid=e.uid||t.uidnext++,e.uid>=t.uidnext&&(t.uidnext=e.uid+1),e.raw instanceof Uint8Array?e.raw=b.Buffer.from(e.raw).toString("binary"):typeof e.raw!="string"&&(e.raw=e.raw?String(e.raw):""),/[\u0100-\uffff]/.test(e.raw)&&(e.raw=b.Buffer.from(e.raw,"utf-8").toString("binary"));let r=e;this.messageHandlers.forEach(n=>{n(this,r,t)})}appendMessage(e,t,r,n,i,o){let a=typeof e=="string"?this.getMailbox(e):e,u=Object.assign({},o,{flags:t.filter(l=>this.isPermanentFlag(a,l)),internaldate:r,raw:n,recent:!0});a.messages.push(u),this.processMessage(u,a);for(let l of this.connections)if(l.selectedMailbox===a&&!l.readOnly&&l.recent){l.recent.add(u),delete u.recent;break}return this.emit("append",a,[u],this.activeConnection),this.notify({tag:"*",attributes:[a.messages.length,{type:"ATOM",value:"EXISTS"}],message:u},a,i),{mailbox:a,message:u}}copyMessage(e,t){let r={};return this.copyHandlers.forEach(n=>{n(this,t,r,e)}),this.appendMessage(e,[].concat(t.flags||[]),t.internaldate,t.raw,!1,r)}getNamespace(e){let t=!1;return Object.keys(this.storage).forEach(r=>{r!=="INBOX"&&e.substr(0,r.length)===r&&(t===!1||r.length>t.length)&&(t=r)}),t}targetRefusal(e){let t=this.getMailbox(e);return t?t.flags.indexOf("\\Noselect")>=0?{command:"NO",code:"TRYCREATE",text:"Target mailbox is not selectable"}:!1:{command:"NO",code:"TRYCREATE",text:"Target mailbox does not exist"}}getMailboxNamespace(e){if(e&&typeof e=="object")return e.namespace;if(e.toUpperCase()==="INBOX")return"INBOX";let t=this.getMailbox(e);return t?t.namespace:this.getNamespace(e)}isPersonal(e){let t=this.getMailboxNamespace(e);return t==="INBOX"||t!==!1&&!!this.storage[t]&&this.storage[t].type==="personal"}getSeparator(e){let t=this.getMailboxNamespace(e),r=t===!1?void 0:this.storage[t];return r&&r.separator||this.storage.INBOX.separator||"/"}getParentPath(e){let t=this.getSeparator(e);e=this.stripSeparator(e,t);let r=e.lastIndexOf(t);if(r<=0)return!1;let n=e.substr(0,r);return n.toUpperCase()==="INBOX"?"INBOX":this.storage[n+t]?!1:n}getDescendants(e,t){let r=t||this.folderCache,n=e+this.getSeparator(e);return Object.keys(r).filter(i=>i.substr(0,n.length)===n).map(i=>r[i])}hasDescendant(e,t){let r=e+this.getSeparator(e);for(let n of Object.keys(this.folderCache))if(n.substr(0,r.length)===r&&t(this.folderCache[n]))return!0;return!1}listAttributes(e,t){let r=t.exists!==!1,n=(e&&e.flags||[]).filter(i=>i!=="\\HasChildren"&&i!=="\\HasNoChildren"&&(r||i!=="\\Noselect"));return r||n.push("\\NonExistent"),t.subscribed&&n.push("\\Subscribed"),n.push(...t.extra||[]),n.indexOf("\\Noinferiors")<0&&n.push(t.hasChildren?"\\HasChildren":"\\HasNoChildren"),n}matchFolders(e,t,r,n){let i=n||this.folderCache,o=r||(p=>p),a=t.charAt(0)==="#"?t:(e||"")+t,u=(p,y="")=>new RegExp("^"+a.replace(/([\\^$+?!.():=[\]{}|,-])/g,"\\$1").replace(/[*]/g,".*").replace(/[%]/g,"[^"+p.replace(/([\\^$+*?!.():=[\]{}|,-])/g,"\\$1")+"]*")+"$",y),l=a.replace(/[*%].*$/,""),c=new Map;Object.keys(this.storage).forEach(p=>{let y=o(p),A=p===this.referenceNamespace||l.substr(0,y.length)===y;c.set(p,A?u(this.storage[p].separator):null)});let f=[];return i.INBOX&&u(this.storage.INBOX&&this.storage.INBOX.separator||"/","i").test("INBOX")&&f.push(i.INBOX),Object.keys(i).forEach(p=>{let y=i[p],A=p!=="INBOX"&&y.namespace!==!1&&y.namespace!=="INBOX"?c.get(y.namespace):null;if(!A)return;let m=o(p);A.test(m)&&(y.flags.indexOf("\\NonExistent")<0||m===a)&&f.push(y)}),f}getSubscriptionTree(){let e=Object.create(null),t=(n,i)=>{e[n]=e[n]||this.getMailbox(n)||{path:n,namespace:this.getNamespace(n),flags:["\\Noselect"],subscribed:i}},r=[...this.subscriptions].filter(n=>n==="INBOX"||this.getNamespace(n)!==!1);return r.forEach(n=>t(n,!0)),r.forEach(n=>{for(let i=this.getParentPath(n);i;i=this.getParentPath(i))t(i,!1)}),e}getMessageRange(e,t,r){let n=(t||"").toString(),i=typeof e=="string"?this.getMailbox(e):e;if(!Is(n)){let y=new Error("Invalid sequence set");throw y.imapResponse="BAD",y}let o=[],a=n.split(","),u=Array.isArray(i)?i:i.messages,l,c=u.length,f=0,p=function(y,A,m){for(let h=0,d=A.length;h<d;h++){let E=A[h].split(":"),I=E.shift(),C=Number(I==="*"?m:I)||1,H=E.pop()||C,N=Number(H==="*"&&m||H)||C;if(y>=Math.min(C,N)&&y<=Math.max(C,N))return!0}return!1};u.forEach(y=>{y.uid>f&&(f=y.uid)});for(let y=0,A=u.length;y<A;y++)l=u[y].uid||1,p(r?l:y+1,a,r?f:c)&&o.push([y+1,u[y]]);return o}},ns=class{constructor(e,t){this.server=e,this.socket=t,this.options=this.server.options,this.state="Not Authenticated",this.sessionNumber=++this.server.sessionCounter,this._outputQueue=null,this._outputTimer=null,this._deferredOutput=null,this.secureConnection=!!this.options.secureConnection||t.encrypted===!0,this._remainder="",this._command="",this._literalRemaining=0,this.inputHandler=!1,this.transport=null,this.parserOptions={},this.compilerOptions={},this.messageGlobal=!1,this._commandQueue=[],this._processing=!1,this.options.debug&&typeof this.socket.pipe=="function"&&this.socket.pipe(U.stdout),this.socket.on("data",this.receive.bind(this)),this.socket.on("close",this.onClose.bind(this)),this.socket.on("error",this.onError.bind(this)),this.directNotifications=!1,this._notificationCallback=this.onNotify.bind(this),this.notificationQueue=[],this.server.on("notify",this._notificationCallback),this.server.connections.add(this),this.emitSession("open"),this.scriptOutput("greeting",`* OK ImapKit ready for rumble\r
|
|
152
|
+
`,{})}write(e){let t=typeof e=="string"?b.Buffer.from(e,"binary"):e;this._outputQueue?this._outputQueue.push({data:t,transport:this.transport}):this.writeLayer(t,this.transport)}queueOutput(e){if(!this._outputQueue&&!e.delay&&!e.chunk){e.data&&this.writeLayer(e.data,this.transport),e.close&&this.closeNow(e.close);return}this._outputQueue=this._outputQueue||[],this._outputQueue.push(Object.assign({},e,{transport:this.transport})),!this._outputTimer&&!this._outputWaiting&&this.flushOutput()}flushOutput(){let e=this._outputQueue||[];for(;e.length;){let t=e[0];if(t.delay){let r=t.delay;t.delay=0,this._outputTimer=setTimeout(()=>{this._outputTimer=null,this.flushOutput()},r);return}if(t.data&&t.chunk&&t.data.length>t.chunk){let r=t.data.subarray(0,t.chunk);if(t.data=t.data.subarray(t.chunk),!t.chunkDelay||t.chunkDelay==="tick"){this.socket?.setNoDelay?.(!0),this._outputWaiting=!0,this.writeLayer(r,t.transport||null,()=>{this._outputWaiting&&this._outputQueue===e&&(this._outputTimer=ip(()=>{this._outputTimer=null,this._outputWaiting=!1,this.flushOutput()}))});return}t.delay=t.chunkDelay,this.writeLayer(r,t.transport||null);continue}if(t.data&&this.writeLayer(t.data,t.transport||null),e.shift(),t.close){this.closeNow(t.close);return}}this._outputQueue=null}clearOutputQueue(){this._outputTimer&&(clearTimeout(this._outputTimer),D(this._outputTimer),this._outputTimer=null),this._outputWaiting=!1,this._outputQueue=null,this._deferredOutput=null}writeLayer(e,t,r){this.trace("out",e),t?(t.write(e),r&&R(r)):this.writeRaw(e,r)}trace(e,t){this.server.listenerCount("trace")&&this.server.emit("trace",{session:this.sessionNumber,direction:e,data:t})}scriptOutput(e,t,r,n){let i=this.server.script.check(this,e,Object.assign({},r,{data:t}));if(!i){this.write(t);return}let{rule:o,context:a}=i;if((o.mutate||o.literals)&&n&&a.response){let u=a.response;if(o.mutate){let c=vo(u);u=o.mutate(c,a)||c}let l=n(o.literals?wl(u):u);if(l===null)return;a.data=l}Cl(this,o,a,b.Buffer.from(a.data,"binary"))}sendContinuation(e,t,r){let n="+ "+e+`\r
|
|
153
|
+
`;if(!this.server.script.watches("continuation")){this.write(n);return}let i=r?r():null;this.scriptOutput("continuation",n,i===null?{description:t}:{description:t,tag:ht(i),command:Do(i)})}writeRaw(e,t){this.socket&&!this.socket.destroyed&&(this.socket.write(e,t),this.touch())}touch(){if(!this.server.script.watches("quiet")){this._lastActivity=void 0;return}this._lastActivity=Date.now(),this._quietTimer||this.watchQuiet()}watchQuiet(e=0){if(this._quietTimer||!this.socket||this._closing)return;let t=this._lastActivity||Date.now();this._lastActivity=t;let r=this.server.script.nextQuiet(e);r!==null&&(this._quietTimer=setTimeout(()=>{if(this._quietTimer=null,!this.isOpen()||this._lastActivity!==t)return this.watchQuiet();let n=Math.max(Date.now()-t,r),i=this.server.script.check(this,"quiet",{data:"",quiet:n});i&&Nl(this,i.rule,i.context),this._lastActivity===t&&this.watchQuiet(n)},Math.max(0,r-(Date.now()-t))),this._quietTimer.unref?.())}receive(e){this.touch(),this.transport?this.transport.receive(e):this.onData(e)}end(){if(this._outputQueue&&this.socket){this._closing=!0,this._outputQueue.push({close:!0});return}this.closeNow(!0)}closeNow(e){let t=this.socket;if(t)if(this._closing=!0,this.clearOutputQueue(),e==="reset"){this.discardInput(),this._resetting=!0,t.pause();let r=this.tcpSocket;setTimeout(()=>{t.destroyed||op(t,r)},Wd)}else this.transport?this.transport.end(()=>t.end()):t.end()}bye(e,t){this.sendStatus({tag:"*"},null,"BYE",e,!1,t||"BYE"),this.closeMailbox(),this.state="Logout",this.discardInput(),this.end()}hasPendingInput(){return!!(this._remainder||this._command||this._literalRemaining||this._commandQueue.length)}isBusy(){return!!(this._processing||this._commandQueue.length)}isPipelinedAfterRefusal(){return!!this._pipelinedAfter&&this._pipelinedAfter.read===this._readCount}refusePipelined(e,t){this.sendStatus(e,t,"BAD","Commands must not be pipelined after "+this._pipelinedAfter?.command,!1,"INVALID COMMAND")}discardInput(){this._commandQueue=[],this._remainder="",this._command="",this._literalRemaining=0,this._skipCommand=!1,this._earlyLiteral=!1}resetSession(){this.closeMailbox(),this.state="Not Authenticated",this.username=!1,this.everSelected=!1,this.directNotifications=!1,this.server.resetHandlers.forEach(e=>e(this))}closeMailbox(){let e=!!this.selectedMailbox;this.state="Authenticated",this.selectedMailbox=!1,this.readOnly=!1,this.recent=null,this.notificationQueue=[],e&&this.emitSession("unselect")}onClose(){this.socket&&(this.socket.removeAllListeners(),this.socket=null),this.transport&&(this.transport.destroy(),this.transport=null),this.clearOutputQueue(),this._quietTimer&&(clearTimeout(this._quietTimer),this._quietTimer=null),this.server.removeListener("notify",this._notificationCallback),this.server.connections.delete(this)&&this.emitSession("close")}onError(e){this.options.debug&&(console.log("Socket error event emitted, %s",Date()),console.log(e.stack));try{this.socket?.end()}catch{}}handleInput(e){let t=this.inputHandler,r=this.server.script.check(this,"input",{data:e});r?Ro(this,r.rule,r.context,()=>t(e)):t(e)}onData(e){let t,r;if(this._resetting)return;if(e&&e.length&&this.trace("in",e),this._readCount=(this._readCount||0)+1,r=(e||"").toString("binary"),this._discardLine){let i=r.indexOf(`
|
|
154
|
+
`);if(i<0)return;let o=this._discardLine;this._discardLine=!1,r=r.substr(i+1),this.sendBad(o,"Command line too long","LINE TOO LONG")}if(this._literalRemaining&&(r=this.readLiteral(r),this._literalRemaining))return;let n=this.server.literalPlus?/(?<marker>(?<tilde>~)?\{(?<size>\d+)(?<plus>\+)?\})?(?<cr>\r?)\n/:/(?<marker>(?<tilde>~)?\{(?<size>\d+)\})?(?<cr>\r?)\n/;for(this._remainder=r=this._remainder+r;t=n.exec(r);){let{marker:i,tilde:o,size:a,plus:u,cr:l}=t.groups;if(t.index>Lo){let f=ht(this._command||r);this.sendBad("*","Command line too long","LINE TOO LONG"),this.sendBad(f,"Command line too long","LINE TOO LONG"),this._remainder=r=r.substr(t.index+t[0].length),this._command="",this._skipCommand=!1;continue}if(!l){let f=this._command+r.substr(0,t.index+t[0].length-1);this._remainder=r=r.substr(t.index+t[0].length),this._command="",this._skipCommand?this._skipCommand=!1:this.sendBad(this.inputHandler?"*":ht(f),"Lines must end with CRLF","INVALID LINE ENDING",f);continue}if(!a||this._skipCommand&&!u){let f=this._command+r.substr(0,t.index);if(this._remainder=r.substr(t.index+t[0].length),this._command="",this._skipCommand?this._skipCommand=!1:this._earlyLiteral?(this._earlyLiteral=!1,this.sendBad(ht(f),"Literal data must wait for the continuation request","LITERAL TOO EARLY",f)):this.inputHandler?this.handleInput(f):this.scheduleCommand(f),this.upgrading)return;r=this._remainder;continue}let c=Number(a);if(!this._skipCommand){let f=this._command+r.substr(0,t.index),p=ht(f+i),y=this.checkLiteral(f,c,!u,!!o);if(y){if(u){this.sendStatus({tag:"*"},f,"BYE",y.text,y.text===Dl&&"TOOBIG","LITERAL REFUSED"),this._remainder=this._command="",this.end();return}this.sendStatus({tag:p},f,y.command,y.text,y.code||!1,"LITERAL REFUSED"),this._remainder=r=r.substr(t.index+t[0].length),this._command="";continue}u&&c>this.server.nonSyncLiteralLimit&&(this.sendStatus({tag:p},f,"BAD","Non-synchronizing literals are limited to "+this.server.nonSyncLiteralLimit+" octets","TOOBIG","LITERAL TOO BIG"),this._skipCommand=!0,this._command="")}if(!u){if(r.length>t.index+t[0].length)this._earlyLiteral=!0;else if(!this._earlyLiteral){let f=r.substr(0,t.index)+i;this.sendContinuation("Go ahead","LITERAL",()=>this._command+f)}}if(this._remainder="",this._skipCommand||(this._command+=r.substr(0,t.index+t[0].length)),this._literalRemaining=c,r=this.readLiteral(r.substr(t.index+t[0].length)),this._literalRemaining)return;this._remainder=r}if(this._remainder.length>Lo){this.sendBad("*","Command line too long","LINE TOO LONG");let i=ht(this._command||this._remainder);this._remainder="",this._command="",this._skipCommand=!1,this._discardLine=i}}readLiteral(e){let t=Math.min(this._literalRemaining,e.length);return this._skipCommand||(this._command+=e.substr(0,t)),this._literalRemaining-=t,e.substr(t)}sendBad(e,t,r,n){this.sendStatus({tag:e},n,"BAD",t,!1,r)}checkLiteral(e,t,r,n){let i=l=>({command:"BAD",text:l}),o=this.getMaxLiteralSize();if(t>o||e.length+t>o+Lo)return i(Dl);if(this.isPipelinedAfterRefusal())return i("Commands must not be pipelined after "+this._pipelinedAfter?.command);if(this.inputHandler)return n?i("Literal8 is not allowed here"):!1;let a=Do(e);if(!tp.test(a)||!this.server.getCommandHandler(a))return i("Unknown command");let u=this.server.getCommandOptions(a);if(u.states&&u.states.indexOf(this.state)<0)return i(Ul(a,this.state));if(n&&!(u.literal8===!0||u.literal8&&Object.hasOwn(this.server.capabilities,u.literal8)))return i("Literal8 is not allowed in "+a);if(r)for(let l of this.server.literalFilters){let c=l(this,a,e,t);if(c)return c}return!1}getMaxLiteralSize(){return this.state==="Not Authenticated"?Jd:Number(this.options.maxLiteralSize)||$d}getSessionMessages(){for(let e=0,t=this.notificationQueue.length;e<t;e++){let r=this.notificationQueue[e].mailboxCopy;if(r)return r}return this.selectedMailbox?this.selectedMailbox.messages:[]}getMessageRange(e,t){return this.server.getMessageRange(this.getSessionMessages(),e,t)}limitRange(e,t){return this.server.rangeLimits.reduce((r,n)=>n(this,e,r)||r,t)}getCommandRange(e,t){let r=this.getMessageRange(e,t);if(t)return r;let n=this.getSessionMessages().length;return String(e).split(/[,:]/).forEach(i=>{if(i==="*"?!n:Number(i)>n){let o=new Error(n?"Message sequence number "+i+" is greater than the number of messages ("+n+")":"The mailbox is empty");throw o.imapResponse="BAD",o}}),r}hasPendingExpunge(){return this.notificationQueue.some(vl)}notifyFlagChanges(e){this.selectedMailbox&&fn(this.server,this.selectedMailbox,e,this)}sendFlagUpdate(e,t,r){let n=this.server.fetchHandlers.FLAGS||Te.FLAGS;e.forEach(i=>{if(!(!t.has(i)||i.ghost)){if(r){if(r.has(i))return;r.add(i)}this.send({tag:"*",notification:!0,attributes:[t.get(i),{type:"ATOM",value:"FETCH"},[{type:"ATOM",value:"UID"},i.uid,{type:"ATOM",value:"FLAGS"},n(this,i,{type:"ATOM",value:"FLAGS"})]]},"FLAG NOTIFICATION",null,null,i)}})}isRecent(e){return!!(this.recent&&this.recent.has(e))}getFlags(e){return this.isRecent(e)?e.flags.concat("\\Recent"):e.flags}canSetSeen(){return!this.readOnly}readOnlyRefusal(){return this.readOnly?{command:"NO",code:"CLIENTBUG",text:"Mailbox is read-only"}:!1}refuseReadOnly(e,t,r){let n=this.readOnlyRefusal();return n&&this.sendStatus(e,t,n.command,n.text,n.code,r),!!n}canExpunge(){return!this.readOnly}onNotify(e){if(e.ignoreConnection===this||e.filter&&!e.filter(this)||!this.server.notifyFilters.every(r=>r(this,e)))return;let t=typeof e.mailbox=="string"?this.server.getMailbox(e.mailbox):e.mailbox;if(!e.mailbox||this.selectedMailbox&&this.selectedMailbox===t){let r=e.command;r.mailboxCopy&&this.notificationQueue.some(n=>n.mailboxCopy)&&(r=Object.assign({},r),delete r.mailboxCopy),this.queueNotification(r,e)}}queueNotification(e,t){this.notificationQueue.push(e),this.directNotifications&&this.processNotifications()}upgradeConnection(e){this.upgrading=!0,this.discardInput();let t=this.socket;if(typeof t.startTls=="function")return t.startTls(()=>{this.secureConnection=!0,this.upgrading=!1,e()});let r=Qe.createSecureContext(this.server.getCredentials()),n={secureContext:r,isServer:!0,server:this.server.server,SNICallback:function(a,u){u(null,r)}};this.tcpSocket=t,t.removeAllListeners(),t.on("error",this.onError.bind(this));let i=new Qe.TLSSocket(t,n),o=a=>{this.options.debug&&console.log("TLS error: %s",a.message),i.destroy()};i.on("close",this.onClose.bind(this)),i.on("error",o),i.on("clientError",o),i.on("secure",()=>{this.secureConnection=!0,this.socket=i,this.upgrading=!1,i.on("data",this.receive.bind(this)),e()})}prepareNotifications(e){return e}holdsExpunge(e){let t=this.server.getCommandOptions(e.command);return t.noExpunge||t.searchCriteria!==!1&&this.usesSequenceNumbers(e)}processNotifications(e,t){if(!this.notificationQueue.length)return;let r=this.notificationQueue,n=r.find(A=>A.mailboxCopy),i=[];if(e&&(this.holdsExpunge(e)||t&&this.usesSequenceNumbers(e))){let A=r.findIndex(vl);if(A>=0&&(i=r.slice(A),r=r.slice(0,A)),!r.length)return}this.notificationQueue=i,r=this.prepareNotifications(r);let o=r.findIndex(A=>A.mailboxCopy),a=new Map,u=A=>{let m=a.get(A);return m||(m=new Map(A.map((h,d)=>[h,d+1])),a.set(A,m)),m},l=this.selectedMailbox?this.selectedMailbox.messages:[],c=new Set,f=A=>n&&(o<0||A<o)?n.mailboxCopy:l,p=-1,y=!1;r.forEach((A,m)=>{A.flagUpdate?this.sendFlagUpdate(A.flagUpdate,u(f(m)),c):this.send(A),Bl(A)&&(p=m,y=y||!!A.message);let h=r[m+1];p<0||Bl(h)||h&&h.fetchedMessage||(y&&this.sendRecent(Number(r[p].attributes[0]),u(f(p))),p=-1,y=!1)})}sendRecent(e,t){let r=0;(this.recent||new Set).forEach(n=>{let i=t.get(n);i&&i<=e&&r++}),this.send({tag:"*",notification:!0,attributes:[r,{type:"ATOM",value:"RECENT"}]},"RECENT NOTIFICATION")}send(e,t,r,n,...i){if(!this.isOpen()||(!e.notification&&e.tag!=="*"&&this.processNotifications(r),this.server.outputHandlers.forEach(c=>{c(this,e,t,r,n,...i)}),this._commandStart&&r&&e.tag===this._commandStart.tag&&r.tag===e.tag&&this.commandCompleted(String(e.command||"").toUpperCase()),e.skipResponse))return;this.notificationQueue.length&&r&&e.tag===r.tag&&e.command==="OK"&&this.hasPendingExpunge()&&this.holdsExpunge(r)&&!(Array.isArray(e.attributes)&&e.attributes.some(c=>c&&c.type==="SECTION"))&&(e.attributes=[{type:"SECTION",section:[{type:"ATOM",value:"EXPUNGEISSUED"}]}].concat(e.attributes||[]));let o=c=>c&&c.type==="MAILBOX",a=c=>c.some(f=>o(f)||Array.isArray(f)&&a(f)),u=c=>c.map(f=>o(f)?ap(this.exportMailboxName(f.value)):Array.isArray(f)?u(f):f);if(Array.isArray(e.attributes)&&a(e.attributes)&&(e=Object.assign({},e,{attributes:u(e.attributes)})),Zd.has((e.command||"").toString().toUpperCase())&&Array.isArray(e.attributes)){let c=f=>f&&f.type==="TEXT"&&typeof f.value=="string"&&/[^\x20-\x7e]/.test(f.value);e.attributes.some(c)&&(e=Object.assign({},e,{attributes:e.attributes.map(f=>c(f)?Object.assign({},f,{value:f.value.replace(/[^\x20-\x7e]/g,"?")}):f)}))}let l=this.compileResponse(e);l!==null&&(this._deferredOutput&&No(this,r&&r.command&&r.tag&&r.tag!=="*"?r.tag:null,!1),this.scriptResponse(e,l,t,r),this._deferredOutput&&e.tag!=="*"&&e.tag!=="+"&&No(this,e.tag,!0))}scriptResponse(e,t,r,n){let i=e.tag==="+"?"continuation":"response";if(!this.server.script.watches(i)){this.write(t);return}this.scriptOutput(i,t,Object.assign({description:r||null,response:e},n&&n.command?{tag:n.tag||null,command:String(n.command).toUpperCase()}:{}),o=>this.compileResponse(o))}compileResponse(e){let t;try{t=st.compiler(e,this.compilerOptions)}catch(r){if(this.options.debug&&console.log("Failed to compile response: %s",r.message),e.tag==="*")return null;t=e.tag+" NO [SERVERBUG] Failed to compile response"}return this.options.debug&&console.log("SEND: %s",t),t+`\r
|
|
155
|
+
`}sendStatus(e,t,r,n,i,o){let a=[];i&&a.push({type:"SECTION",section:[].concat(i).map(u=>({type:"ATOM",value:String(u)}))}),a.push({type:"TEXT",value:n}),o||(o=(e.command||"").toString().toUpperCase()+(r==="OK"?"":" FAILED")),this.send({tag:e.tag,command:r,attributes:a},o,e,t)}isAmbiguous(e){if(!this.usesSequenceNumbers(e))return!1;if(this._unsafeCompletedRead===this._readCount)return!0;let t=r=>!!r&&!this.server.getCommandOptions(r.parsed.command).noExpunge;return t(this._runningCommand)||this._commandQueue.some(t)}usesSequenceNumbers(e){let t=Hl.get(e);return t===void 0&&(t=this.findSequenceNumbers(e),Hl.set(e,t)),t}findSequenceNumbers(e){let{sequenceSet:t,searchCriteria:r}=this.server.getCommandOptions(e.command);if(t!==!1){let n=e.attributes&&e.attributes[t];return!n||/^[\d*]/.test(String(n.value))}return r!==!1?Za(this.server,(e.attributes||[]).slice(r)):!1}decodeSaslResponse(e){return e==="="?b.Buffer.alloc(0):typeof e!="string"||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)?!1:b.Buffer.from(e,"base64")}getTargetMailbox(e,t,r,n){let i=this.server.targetRefusal(e);return i?(this.sendStatus(t,r,i.command,i.text,i.code,n),!1):this.server.getMailbox(e)}checkAppend(e,t,r,n,i,o){return this.applyChecks(this.server.appendChecks.map(a=>a(this,e,t,o||{})),r,n,i)}applyChecks(e,t,r,n){let i=e.filter(a=>!!a),o=i.find(a=>!a.soft);return o?(this.sendStatus(t,r,"NO",o.text,o.code,n),!1):(i.forEach(a=>{this.send({tag:"*",command:"NO",attributes:[{type:"SECTION",section:[{type:"ATOM",value:a.code}]},{type:"TEXT",value:a.text}]},"CHECK WARNING",t,r)}),!0)}importMailboxName(e){let t=Tt(e);if(t){let r=new Error(t);throw r.imapResponse="BAD",r}return e}exportMailboxName(e){return e}scheduleCommand(e,t){let r,n=ht(e),i=!t&&this.server.script.watches("command")?this.server.script.check(this,"command",{data:e,tag:n,command:Do(e)}):null;if(i){this._commandQueue.push({parsed:{tag:n,command:i.context.command||""},data:e,script:i}),this.processQueue();return}try{r=st.parser(e,Object.assign({literalPlus:this.server.literalPlus},this.server.parserOptions,this.parserOptions))}catch(a){let u=a;this.send({tag:"*",command:"BAD",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"SYNTAX"}]},{type:"TEXT",value:u.message}]},"ERROR MESSAGE",null,e,u),this.send({tag:n,command:"BAD",attributes:[{type:"TEXT",value:"Error parsing command"}]},"ERROR RESPONSE",null,e,u);return}if(this.isPipelinedAfterRefusal()){this.refusePipelined(r,e);return}let o=/^AUTHENTICATE /i.test(r.command)&&!this.server.getCommandHandler(r.command)?rp:void 0;if(o||this.server.getCommandHandler(r.command)){if(this.isAmbiguous(r)){this.sendStatus(r,e,"BAD","Commands with message sequence numbers must wait for the completion of earlier commands");return}let a={parsed:r,data:e,handler:o};t?this._commandQueue.unshift(a):this._commandQueue.push(a),this.processQueue()}else this.send({tag:r.tag,command:"BAD",attributes:[{type:"TEXT",value:"Invalid command "+r.command}]},"UNKNOWN COMMAND",r,e)}commandCompleted(e){let t=this._commandStart;this._commandStart=null;let r=this.server;if(!r.listenerCount("command")&&!r.listenerCount("session"))return;r.emit("command",{session:this.sessionNumber,tag:t.tag,command:t.command,status:e,user:this.username||null});let n=i=>i==="Authenticated"||i==="Selected";n(t.state)!==n(this.state)&&this.state!=="Logout"&&this.emitSession(n(this.state)?"login":"logout")}emitSession(e,t){this.server.listenerCount("session")&&this.server.emit("session",Object.assign({type:e,session:this.describe()},t))}describe(){return{session:this.sessionNumber,user:this.username||null,state:this.state,mailbox:this.selectedMailbox?this.selectedMailbox.path:null,readOnly:!!this.selectedMailbox&&!!this.readOnly,enabled:Array.isArray(this.enabled)?this.enabled.slice():[],secure:!!this.secureConnection,compressed:!!this.transport,remoteAddress:this.socket&&this.socket.remoteAddress||null}}isOpen(){return!!this.socket&&!this.socket.destroyed&&!this._closing}runScriptedCommand(e,t){let{rule:r,context:n}=e.script,i=()=>{if(!this.socket||this._closing)return t();Ro(this,r,n,()=>{this._runningCommand=null,this.scheduleCommand(e.data,!0)}),t()};r.delay?setTimeout(i,r.delay):i()}processQueue(e){if(!e&&this._processing)return;if(!this._commandQueue.length){this._processing=!1;return}this._processing=!0;let t=this._commandQueue.shift(),r=t.parsed.command.toUpperCase();this._runningCommand=t;let n=this.server.getCommandOptions(r);this._commandStart={tag:t.parsed.tag,command:r,state:this.state};let i=!1,o=()=>{i||(i=!0,this._runningCommand=null,n.noExpunge||(this._unsafeCompletedRead=this._readCount),this._commandQueue.length?this.processQueue(!0):this._processing=!1)};if(t.script){this.runScriptedCommand(t,o);return}if(n.states&&n.states.indexOf(this.state)<0)return this.sendStatus(t.parsed,t.data,"BAD",Ul(r,this.state)),o();if(t.parsed.attributes&&n.noArguments)return this.sendStatus(t.parsed,t.data,"BAD",r+" does not take any arguments"),o();if(n.noPipelining&&this.hasPendingInput())return this.sendStatus(t.parsed,t.data,"BAD","Commands must not be pipelined after "+r),this._pipelinedAfter={command:r,read:this._readCount},this._commandQueue.splice(0).forEach(u=>this.refusePipelined(u.parsed,u.data)),o();yt(t.parsed,t.data,u=>u.length===1&&(n.mailboxArguments.includes(u[0])||n.astringArguments.includes(u[0]))||n.searchCriteria!==!1&&u[0]>=n.searchCriteria);let a=up(this,t.parsed,n.mailboxArguments);if(a)return this.sendStatus(t.parsed,t.data,"BAD",a),o();for(let u of this.server.commandChecks){let l=u(this,t.parsed);if(l)return this.sendStatus(t.parsed,t.data,l.command||"BAD",l.text,l.code),o()}this.state==="Selected"&&(r.startsWith("UID ")||n.noExpunge||n.sequenceSet!==!1||n.searchCriteria!==!1)&&this.processNotifications(t.parsed,!0),this.server.withOrigin(this,()=>{try{let u=this.inputHandler;(t.handler||this.server.getCommandHandler(t.parsed.command))(this,t.parsed,t.data,o),this.inputHandler&&this.inputHandler!==u&&(this.inputCommand={tag:t.parsed.tag,command:t.parsed.command},this.emitSession("waiting",{command:r}))}catch(u){let l=u,c=l.imapResponse==="BAD";!c&&this.options.debug&&console.error("Error processing command:",l,`
|
|
156
|
+
`,l.stack),this.send({tag:t.parsed.tag,command:c?"BAD":"NO",attributes:[].concat(c?[]:{type:"SECTION",section:[{type:"ATOM",value:"SERVERBUG"}]},{type:"TEXT",value:c?l.message:"Server error: "+l.message})},c?"INVALID COMMAND":"SERVER ERROR",t.parsed,t.data),o()}})}expungeDeleted(e,t,r){this.expungeSpecificMessages(e,n=>n.flags.indexOf("\\Deleted")>=0,t,r)}expungeSpecificMessages(e,t,r,n,i){it(this.server,e,t,{origin:this,skip:r?this:null,skipExists:n?this:null,highestFirst:!!i})}},np="Deno"in globalThis;function ip(s){return np?setTimeout(s,0):R(s)}function kl(s,e){s.close(),e?s.closeAllConnections?.():s.closeIdleConnections?.()}function wr(s,e,t){return new Promise((r,n)=>{s.once("error",n),s.listen({port:e||0,host:t},()=>{s.removeListener("error",n),r(s.address().port)})})}function op(s,e){let t=s._parent,r=[e,t instanceof Qe.Socket?t:null,s];for(let n of r)if(n&&!n.destroyed&&typeof n.resetAndDestroy=="function")try{n.resetAndDestroy();break}catch{}s.destroy()}function vo(s){if(Array.isArray(s))return s.map(vo);if(s&&typeof s=="object"&&Object.getPrototypeOf(s)===Object.prototype){let e={};for(let t of Object.keys(s))e[t]=vo(s[t]);return e}return s}function Do(s){let e=s.match(/^[^ ]* ([^ ]*)(?: ([^ ]*))?/),t=(e&&e[1]||"").toUpperCase();return(t==="UID"||t==="AUTHENTICATE")&&(t+=" "+(e&&e[2]||"").toUpperCase()),t}function ap(s){return{type:ep.test(s)&&!/^NIL$/i.test(s)?"ATOM":"STRING",value:s}}function up(s,e,t){for(let r of t){let n=(e.attributes||[])[r];if(n&&["STRING","ATOM","LITERAL"].indexOf(n.type)>=0)try{n.value=s.importMailboxName(n.value)}catch(i){return i.message}}return!1}var lp=Object.assign(Ho,{TAG_REGEX:Bo,IMAPServer:rs,IMAPConnection:ns,ImapKitError:z,quirks:Zt}),qI=lp;export{ns as IMAPConnection,rs as IMAPServer,z as ImapKitError,Bo as TAG_REGEX,qI as default,Zt as quirks,lo as storageSchema,co as validateStorage};
|
|
93
157
|
/*! Bundled license information:
|
|
94
158
|
|
|
95
159
|
ieee754/index.js:
|