imapkit 5.0.0 → 5.1.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 +51 -29
- package/bin/help.txt +3 -2
- package/bin/imapkit.js +15 -5
- package/dist/browser/imapkit.js +105 -0
- package/dist/cjs/commands/handlers/fetch.js +2 -1
- package/dist/cjs/commands/handlers/store.js +4 -4
- package/dist/cjs/commands/list.js +17 -3
- package/dist/cjs/control.d.ts +4 -9
- package/dist/cjs/control.js +1 -1
- package/dist/cjs/dates.d.ts +9 -1
- package/dist/cjs/dates.js +20 -0
- package/dist/cjs/envelope.d.ts +1 -1
- package/dist/cjs/envelope.js +26 -1
- package/dist/cjs/index.d.ts +3 -1
- package/dist/cjs/load-plugins.d.ts +3 -1
- package/dist/cjs/load-plugins.js +25 -6
- package/dist/cjs/memory-socket.d.ts +69 -0
- package/dist/cjs/memory-socket.js +187 -0
- package/dist/cjs/plugins/binary.js +2 -1
- package/dist/cjs/plugins/context-search.js +2 -2
- package/dist/cjs/plugins/create-special-use.d.ts +0 -5
- package/dist/cjs/plugins/create-special-use.js +11 -1
- package/dist/cjs/plugins/idle.js +2 -2
- package/dist/cjs/plugins/imap4rev2.js +5 -0
- package/dist/cjs/plugins/metadata-server.d.ts +6 -2
- package/dist/cjs/plugins/metadata-server.js +3 -1
- package/dist/cjs/plugins/metadata.d.ts +5 -1
- package/dist/cjs/plugins/metadata.js +3 -0
- package/dist/cjs/quirks.d.ts +2 -2
- package/dist/cjs/quirks.js +5 -4
- package/dist/cjs/rest.d.ts +7 -3
- package/dist/cjs/rest.js +11 -5
- package/dist/cjs/server.d.ts +67 -3
- package/dist/cjs/server.js +241 -93
- package/dist/cjs/storage-schema.js +12 -5
- package/dist/cjs/store-operations.d.ts +5 -2
- package/dist/cjs/store-operations.js +6 -3
- package/dist/cjs/types.d.ts +4 -0
- package/dist/esm/commands/handlers/fetch.js +2 -1
- package/dist/esm/commands/handlers/store.js +4 -4
- package/dist/esm/commands/list.js +17 -3
- package/dist/esm/control.d.ts +4 -9
- package/dist/esm/control.js +1 -1
- package/dist/esm/dates.d.ts +9 -1
- package/dist/esm/dates.js +20 -1
- package/dist/esm/envelope.d.ts +1 -1
- package/dist/esm/envelope.js +26 -1
- package/dist/esm/index.d.ts +3 -1
- package/dist/esm/load-plugins.d.ts +3 -1
- package/dist/esm/load-plugins.js +25 -6
- package/dist/esm/memory-socket.d.ts +69 -0
- package/dist/esm/memory-socket.js +182 -0
- package/dist/esm/plugins/binary.js +2 -1
- package/dist/esm/plugins/context-search.js +2 -2
- package/dist/esm/plugins/create-special-use.d.ts +0 -5
- package/dist/esm/plugins/create-special-use.js +8 -1
- package/dist/esm/plugins/idle.js +2 -2
- package/dist/esm/plugins/imap4rev2.js +5 -0
- package/dist/esm/plugins/metadata-server.d.ts +6 -2
- package/dist/esm/plugins/metadata-server.js +3 -1
- package/dist/esm/plugins/metadata.d.ts +5 -1
- package/dist/esm/plugins/metadata.js +3 -0
- package/dist/esm/quirks.d.ts +2 -2
- package/dist/esm/quirks.js +5 -4
- package/dist/esm/rest.d.ts +7 -3
- package/dist/esm/rest.js +11 -5
- package/dist/esm/server.d.ts +67 -3
- package/dist/esm/server.js +243 -95
- package/dist/esm/storage-schema.js +12 -5
- package/dist/esm/store-operations.d.ts +5 -2
- package/dist/esm/store-operations.js +6 -3
- package/dist/esm/types.d.ts +4 -0
- package/dist/plugin-help.json +3 -2
- package/package.json +8 -1
|
@@ -0,0 +1,105 @@
|
|
|
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":bt(()=>"(){"+ht.SP()+ht.CTL()+ht["list-wildcards"]()+ht["quoted-specials"]()+ht["resp-specials"]()),"list-wildcards":()=>"%*","quoted-specials":()=>ht.DQUOTE()+"\\","resp-specials":()=>"]",tag:bt(()=>lr(ht["ASTRING-CHAR"](),"+")),command:bt(()=>ht["ATOM-CHAR"]()),_expandRange:zt,_excludeChars:lr,isAtomChar(r){return Ql().has(r)},isSequenceSet(r){return!!r&&r.split(",").every(t=>/^(?:\d+|\*)(?::(?:\d+|\*))?$/.test(t))},verify(r,t){for(let e=0,s=r.length;e<s;e++)if(t.indexOf(r.charAt(e))<0)return e;return-1}},lt=ht;var Yl=4294967295,Kl=Number.MAX_SAFE_INTEGER,zl=25,Wl=r=>lt.isAtomChar(r),Bs=r=>r>=48&&r<=57,$l=r=>lt.isSequenceSet(r),it=(r,t,e)=>{let s=new Error(r+" at position "+t);return s.code=e||"ParserError",s.pos=t,s};function Fs(r,t){let e={...t,allowSection:t?.allowSection||["BODY","BODY.PEEK"],multiWords:t?.multiWords||["UID","AUTHENTICATE"],allowUntagged:!!t?.allowUntagged},s=new Hs(r,e),n=s.getTag();s.getSpace();let i={tag:n,command:s.getCommand()};return e.multiWords.indexOf((i.command||"").toUpperCase())>=0&&(s.getSpace(),i.command+=" "+s.getElement(lt.command())),s.remainder.length&&(s.getSpace(),i.attributes=s.getAttributes()),i}var Hs=class{constructor(t,e){this.input=(t||"").toString(),this.options=e,this.remainder=this.input,this.pos=0}getTag(){return this.tag||(this.tag=this.getElement(lt.tag()+(this.options.allowUntagged?"*":""))),this.tag}getCommand(){return this.command||(this.command=this.getElement(lt.command())),this.command}getElement(t){let e;if(this.remainder.match(/^\s/))throw it("Unexpected whitespace",this.pos);let s=this.remainder.match(/^[^\s]+(?=\s|$)/);if(!s)throw it("Unexpected end of input",this.pos);let n=s[0];if((e=lt.verify(n,t))>=0)throw it("Unexpected char",this.pos+e);return this.pos+=n.length,this.remainder=this.remainder.substring(n.length),n}getSpace(){if(!this.remainder.length)throw it("Unexpected end of input",this.pos);if(lt.verify(this.remainder.charAt(0),lt.SP())>=0)throw it("Unexpected char",this.pos);this.pos++,this.remainder=this.remainder.substring(1)}getAttributes(){if(!this.remainder.length)throw it("Unexpected end of input",this.pos);if(this.remainder.match(/^\s/))throw it("Unexpected whitespace",this.pos);return new vs(this.pos,this.remainder,this.options).getAttributes()}},vs=class{constructor(t,e,s){this.str=(e||"").toString(),this.options=s,this.pos=t||0,this.maxSectionName=Math.max(0,...this.options.allowSection.map(n=>n.length)),this.maxNumber=this.options.number64?Kl:Yl,this.tree=this.currentNode=this.createNode(),this.currentNode.type="TREE",this.processString()}getAttributes(){let t=[],e=t,s=()=>e[e.length-1],n=i=>{let a,o=e;if(!i.closed)throw it("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"){e.push(null);break}a={type:i.type,value:i.value},e.push(a);break;case"SECTION":e=s().section=[];break;case"LIST":a=[],e.push(a),e=a;break;case"PARTIAL":s().partial=i.value.split(".").map(Number);break}i.childNodes.forEach(n),e=o};return n(this.tree),t}createNode(t,e){let s={childNodes:[],type:!1,value:"",closed:!0,depth:t?t.depth+1:0};if(s.depth>zl)throw it("Too much nesting",e,"MaxNestingReached");return t&&(s.parentNode=t,t.childNodes.push(s)),typeof e=="number"&&(s.startPos=e),s}addValue(t,e,s,n){let i=this.createNode(this.currentNode,this.pos+s);return i.type=t,i.value=e,i.endPos=this.pos+n-1,i}closeNode(t){this.currentNode.closed=!0,this.currentNode.endPos=this.pos+t,this.currentNode=this.currentNode.parentNode}unexpected(t){return it(t>=this.str.length?"Unexpected end of input":"Unexpected char",this.pos+t)}afterValue(t){let e=this.str;if(t>=e.length)return t;let s=e.charAt(t);if(s===" "){let n=e.charAt(t+1);if(t+1>=e.length||n===" "||n===")"||n==="]"&&this.currentNode.type==="SECTION")throw it("Unexpected whitespace",this.pos+t);return t+1}if(s===")"&&this.currentNode.type==="LIST"||s==="]"&&this.currentNode.type==="SECTION")return t;throw it("Unexpected char",this.pos+t)}processString(){let t=this.str,e=t.length,s=0;for(;s<e;)switch(t.charAt(s)){case" ":throw it("Unexpected whitespace",this.pos+s);case'"':s=this.readString(s);break;case"(":this.currentNode=this.createNode(this.currentNode,this.pos+s),this.currentNode.type="LIST",this.currentNode.closed=!1,s++;break;case")":if(this.currentNode.type!=="LIST")throw it("Unexpected list terminator )",this.pos+s);this.closeNode(s),s=this.afterValue(s+1);break;case"]":if(this.currentNode.type!=="SECTION"){s=this.readAtom(s);break}this.closeNode(s),s=this.str.charAt(s+1)==="<"?this.readPartial(s+1):this.afterValue(s+1);break;case"{":s=this.readLiteral(s,!1);break;case"~":s=this.options.literal8&&t.charAt(s+1)==="{"?this.readLiteral(s,!0):this.readAtom(s);break;default:s=this.readAtom(s);break}}readAtom(t){let e=this.str,s=e.length,n=this.currentNode.type,i=!0,a=!0,o;for(o=t;o<s;o++){let c=e.charAt(o),h=e.charCodeAt(o);if(c===" "||c===")"&&n==="LIST"||c==="]"&&n==="SECTION")break;if(c==="["&&o>t&&o-t<=this.maxSectionName&&this.options.allowSection.indexOf(e.slice(t,o).toUpperCase())>=0)return this.addValue("ATOM",e.slice(t,o),t,o),this.currentNode=this.createNode(this.currentNode,this.pos+o),this.currentNode.type="SECTION",this.currentNode.closed=!1,o+1;if(!Wl(c)&&c!=="%"&&c!=="*"&&c!=="]"&&!(c==="\\"&&o===t))throw it("Unexpected char",this.pos+o);Bs(h)||(a=!1,c!==":"&&c!==","&&c!=="*"&&(i=!1))}if(o===t)throw it("Unexpected char",this.pos+o);let u=e.slice(t,o),l="ATOM";return i&&!a&&u!=="*"&&$l(u)&&(l="SEQUENCE"),this.addValue(l,u,t,o),this.afterValue(o)}readString(t){let e=this.str,s=e.length,n=!!this.options.utf8,i=!1,a="",o=t+1;for(let u=t+1;u<s;u++){let l=e.charCodeAt(u);if(l===34){if(i&&!kt(I.Buffer.from(e.slice(t+1,u),"binary")))throw it("Invalid UTF-8",this.pos+t+1);return a+=e.slice(o,u),this.addValue("STRING",a,t,u+1),this.afterValue(u+1)}if(l===92){if(u+1>=s)throw it("Unexpected end of input",this.pos+u+1);let c=e.charAt(u+1);if(c!=='"'&&c!=="\\")throw it("Unexpected escaped char",this.pos+u+1);a+=e.slice(o,u)+c,u++,o=u+1;continue}if(n&&l>127&&l<=255){i=!0;continue}if(l===0||l===10||l===13||l>127)throw it("Unexpected char",this.pos+u)}throw it("Unexpected end of input",this.pos+s)}readLiteral(t,e){let s=this.str,n=s.length,i=t+(e?2:1),a=i;for(;a<n&&Bs(s.charCodeAt(a));)a++;if(a===i)throw this.unexpected(a);let o=Number(s.slice(i,a));if(s.charAt(a)==="+"&&this.options.literalPlus&&a++,s.charAt(a)!=="}")throw this.unexpected(a);if(a++,s.charAt(a)===`
|
|
3
|
+
`)a++;else if(s.charAt(a)==="\r"&&s.charAt(a+1)===`
|
|
4
|
+
`)a+=2;else throw this.unexpected(a);if(o>this.maxNumber||a+o>n)throw it("Unexpected end of input",this.pos+n);let u=s.substring(a,a+o);if(!e){let l=u.indexOf("\0");if(l>=0)throw it("Unexpected \\x00",this.pos+a+l)}return this.addValue(e?"LITERAL8":"LITERAL",u,t,a+o),this.afterValue(a+o)}readPartial(t){let e=this.str,s=e.length,n=t+1,i=a=>{let o=n;for(;n<s&&Bs(e.charCodeAt(n));)n++;if(n===o)throw this.unexpected(n);if(a&&e.charAt(o)==="0")throw it("Invalid partial",this.pos+o);if(Number(e.slice(o,n))>this.maxNumber)throw it("Invalid partial",this.pos+o)};if(i(!1),e.charAt(n)==="."&&(n++,i(!0)),e.charAt(n)!==">")throw this.unexpected(n);return this.addValue("PARTIAL",e.slice(t+1,n),t,n+1),this.afterValue(n+1)}};E();var ja=/[\x00\r\n\x80-\uffff]/,Va=/[\x00\r\n\u0100-\uffff]/,Jl=r=>{for(let t=0,e=r.length;t<e;t++)if(!lt.isAtomChar(r.charAt(t)))return!1;return!!r.length},Zl=r=>r==="\\*"||Jl(r.charAt(0)==="\\"?r.slice(1):r),tc=r=>r==="$"||lt.isSequenceSet(r),Ps=r=>{let t=Math.round(Number(r));return Number.isSafeInteger(t)&&t>=0?t:0},Ht=r=>I.Buffer.isBuffer(r)?r.toString("binary"):r==null?"":String(r),cr=r=>"{"+r.length+`}\r
|
|
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
|
+
`):t}function oo(r,t){let e=[],s="",n=!1,i=0;for(let a=0;a<r.length;a++){let o=r.charAt(a);if(n){s+=o,o==="\\"&&a+1<r.length?s+=r.charAt(++a):o==='"'&&(n=!1);continue}if(i){o==="\\"?a++:o==="("?i++:o===")"&&i--;continue}o==='"'?(n=!0,s+=o):o==="("?i=1:t&&o===t?(e.push(s),s=""):s+=o}return e.push(s),e}function uo(r,t){let e=t.replace(/%([0-9a-fA-F]{2})/g,(s,n)=>String.fromCharCode(parseInt(n,16)));switch((r||"").trim().toLowerCase()){case"":case"utf-8":case"utf8":case"us-ascii":case"ascii":return e;case"iso-8859-1":case"latin1":return I.Buffer.from(e,"utf-8").toString("binary");default:return"=?"+r.toUpperCase()+"?Q?"+t.replace(/%/g,"=")+"?="}}var nn=class{constructor(t,e){this.rfc822=t||"",this.depth=e||0,this._br="",this._pos=0,this.tree={childNodes:[]},this._node=this.createNode(this.tree)}parse(){let t,e="";for(;typeof this._br=="string";){t=this.readLine();let s=this.matchDelimiter(t);if(s)this.endPart(s,e);else switch(this._node.state){case"header":t?this._node.header.push(t):this.endHeader();break;case"body":this._node.body.push((this._node.body.length?e:"")+t);break;case"epilogue":this._node.epilogue||(this._node.epilogue=[]),this._node.epilogue.push(e+t);break;default:throw new Error("Unexpected state")}e=this._br}}readLine(){let t=this.rfc822.indexOf(`
|
|
7
|
+
`,this._pos);if(t<0){let n=this.rfc822.slice(this._pos);return this._pos=this.rfc822.length,this._br=!1,n}let e=t;e>this._pos&&this.rfc822.charCodeAt(e-1)===13&&e--;let s=this.rfc822.slice(this._pos,e);return this._br=this.rfc822.slice(e,t+1),this._pos=t+1,s}endHeader(){this.processNodeHeader(),this.processContentType(),this._node.state="body"}matchDelimiter(t){if(!t.startsWith("--"))return!1;let e=this._node,s=e.boundary?e:e.parentNode;for(let n=s;n.boundary;n=n.parentNode){let i="--"+n.boundary;if(!t.startsWith(i))continue;let a=t.slice(i.length),o=a.startsWith("--");if(o&&(a=a.slice(2)),!/[^ \t]/.test(a))return n.state==="epilogue"?!1:{multipart:n,close:o,pad:a}}return!1}endPart(t,e){let s=this._node,n=t.multipart;if(s!==n){if(s.state==="header"){this.endHeader();for(let i=s;i!==n;i=i.parentNode)i.bare=!0}}else s.body.length&&(s.body[s.body.length-1]+=e);if(t.close)t.pad&&(n.closePad=t.pad),delete n.unterminated,n.state="epilogue",this._node=n;else{let i=this.createNode(n);t.pad&&(i.pad=t.pad),this._node=i}}parseEmbeddedMessage(t){let e=t.parsedHeader["content-type"],s=(e&&e.value||"").toLowerCase();if(s!=="message/rfc822"&&s!=="message/global"||this.depth>=Ec)return;let n=(t.parsedHeader["content-transfer-encoding"]||"").toString().trim().toLowerCase();n&&!Ir.includes(n)||(t[s==="message/rfc822"?"message":"globalMessage"]=Be(t.body,this.depth+1))}finalizeTree(){this._node.state==="header"&&(this.endHeader(),this._node.header.length&&!this.rfc822.endsWith(`
|
|
8
|
+
`)&&(this._node.headerUnterminated=!0));let t=[...this.tree.childNodes];for(;t.length;){let e=t.pop(),s=e,n=e.body,i=s.boundary&&!s.unterminated;n.length||e.childNodes.length||i||(s.hasBody=!1),s.lineCount=n.length?n.length-1:0,s.body=n.join(""),s.size=s.body.length,this.parseEmbeddedMessage(s),e.epilogue&&(s.epilogue=e.epilogue.join("")),e.childNodes.forEach(a=>t.push(a)),delete e.parentNode,delete e.state,s.childNodes.length||delete s.childNodes}}createNode(t){let e={state:"header",childNodes:[],header:[],parsedHeader:Object.create(null),body:[],multipart:!1,boundary:!1,parentNode:t};return t.childNodes.push(e),e}processNodeHeader(){let t=this._node,e=t.parsedHeader,s=[];for(let n of t.header)s.length&&/^\s/.test(n)?s[s.length-1]+=`\r
|
|
9
|
+
`+n:s.push(n);t.header=s;for(let n of s){let i=n.split(":"),a=(i.shift()||"").trim().toLowerCase(),o=i.join(":").trim();ao.test(a)&&(a in e?Array.isArray(e[a])?e[a].push(o):e[a]=[e[a],o]:e[a]=o.replace(/\s*\r?\n\s*/g," "))}if(!e["content-type"]){let n=(t.parentNode&&t.parentNode.multipart||"").toString().toLowerCase();e["content-type"]=n==="digest"?"message/rfc822":"text/plain"}["content-type","content-disposition"].forEach(n=>{e[n]&&(e[n]=this.parseValueParams([].concat(e[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(e[n])&&(e[n]=e[n].pop().replace(/\s*\r?\n\s*/g," "))}),e["content-transfer-encoding"]&&(e["content-transfer-encoding"]=oo(e["content-transfer-encoding"])[0].trim()),["from","sender","reply-to","to","cc","bcc"].forEach(n=>{e[n]&&(e[n]=[].concat(e[n]).flatMap(i=>i&&br(i.replace(/\s*\r?\n\s*/g," "))||[]))})}parseValueParams(t){let e={value:"",type:"",subtype:"",params:Object.create(null)},s=Object.create(null);return oo(t||"",";").forEach((n,i)=>{if(!i){e.value=n.trim();let c=e.value.split("/");e.type=(c.shift()||"").toLowerCase(),e.subtype=c.join("/");return}let a=n.split("="),o=(a.shift()||"").trim().toLowerCase(),u=a.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,""),!ao.test(o))return;let l=o.match(/^([^*]+)(?:\*(\d{1,3}))?(\*)?$/);if(l&&(l[2]!==void 0||l[3])){let c=l[1];s[c]||(s[c]=[]),s[c][Number(l[2])||0]={value:u,extended:!!l[3]}}else e.params[o]=u;e.hasParams=!0}),Object.keys(s).forEach(n=>{let i="",a="",o=!1;s[n].forEach((u,l)=>{if(!u)return;let c=u.value;if(u.extended&&!l){let h=c.split("'");h.length>=3&&(i=h.shift(),h.shift(),c=h.join("'"))}u.extended?(o=!0,a+=c):a+=c.replace(/[^\x21-\x24\x26-\x7e]/g,h=>"%"+("0"+h.charCodeAt(0).toString(16)).substr(-2))}),e.params[n]=uo(o?i:"",a)}),e}processContentType(){let t=this._node,e=t.parsedHeader["content-type"];e.type==="multipart"&&e.params.boundary&&(t.multipart=e.subtype,t.boundary=e.params.boundary,t.unterminated=!0)}};function Be(r,t){let e=new nn(r,t);return e.parse(),e.finalizeTree(),e.tree.childNodes[0]}var gc=Be(`Content-Type: text/plain\r
|
|
10
|
+
\r
|
|
11
|
+
`);function te(r){return r.childNodes?r.childNodes:r.boundary?[gc]:void 0}function ee(r,t){return r.message||(t?r.globalMessage:void 0)}function de(r,t,e){let s=r,n=r;for(let i of(t||"").toString().split(".")){let a=Number(i)-1;if(!s||!(a>=0))return!1;let o=te(s);if(n=o?o[a]:a===0?s:void 0,!n)return!1;s=ee(n,e)||(te(n)?n:!1)}return n}function Or(r){let t=r.header||[];return r.hasBody===!1?t.length?t.join(`\r
|
|
12
|
+
`)+(r.headerUnterminated?"":`\r
|
|
13
|
+
`):"":t.length?t.join(`\r
|
|
14
|
+
`)+`\r
|
|
15
|
+
\r
|
|
16
|
+
`:`\r
|
|
17
|
+
`}function Rt(r,t){let e=[],s=(n,i)=>{if(i){let o=n.header||[];o.length&&e.push(o.join(`\r
|
|
18
|
+
`)+(n.headerUnterminated?"":`\r
|
|
19
|
+
`))}if(n.hasBody===!1||(i&&e.push(`\r
|
|
20
|
+
`),e.push(n.body||""),!n.boundary))return;let a=n.childNodes||[];for(let o=0;o<a.length;o++){let u=a[o];e.push("--"+n.boundary+(u.pad||"")+`\r
|
|
21
|
+
`),s(u,!0),(!n.unterminated||o<a.length-1)&&!u.bare&&e.push(`\r
|
|
22
|
+
`)}n.unterminated||(e.push("--"+n.boundary+"--"+(n.closePad||"")),e.push(n.epilogue||""))};return s(r,!t),e.join("")}var lo=new WeakMap;function rt(r){let t=lo.get(r);if(!t||t.source!==r.raw){let e=Ue(r.raw);t={source:r.raw,raw:e,tree:Be(e)},lo.set(r,t)}return t}E();E();E();var Ac=/^[\s,]*(@(?:[^:[]|\[[^\]]*\])*):/;function Tc(r){let t=r.match(Ac);return t?[t[1].split(",").map(s=>s.trim()).filter(s=>s).join(","),r.substr(t[0].length).trim()]:[null,r]}function He(r){let t=r.subject;return[r.date||null,typeof t=="string"?t:null,Pt(r.from),Pt(r.sender,r.from),Pt(r["reply-to"],r.from),Pt(r.to),Pt(r.cc),Pt(r.bcc),r["in-reply-to"]||null,r["message-id"]||null]}function Pt(r,t){let e=[].concat(r||[]);if(e.length||(e=[].concat(t||[])),!e.length)return null;let s=[];return e.forEach(n=>{if(n.group){s.push([null,null,n.name||"",null]),s=s.concat(Pt(n.group)||[]),s.push([null,null,null,null]);return}let i=n.name||null,a=n.address||"";if(!a&&i&&(a=i,i=null),!a)return;let[o,u]=Tc(a);a=u;let l=a.lastIndexOf("@"),c=l>=0?a.substr(0,l):a,h=(l>=0?a.substr(l+1):"")||"MISSING_DOMAIN";s.push([i,o,c||null,h])}),Object.defineProperty(s,"adjacentLists",{value:!0}),s.length?s:null}var an=yc;function yc(r,t){t=t||{};let e=l=>t.upperCaseKeys&&typeof l=="string"?l.toUpperCase():l,s=l=>{if(!l||!l.hasParams)return null;let c=[],h=l.params;return Object.keys(h).forEach(m=>{c.push(e(m),h[m])}),c.length?c:null},n=l=>{let c=l.parsedHeader["content-type"]||{},h=c.type||null,m=c.subtype||null;return(!h||!m)&&(h==="text"||m==="plain"?(h="text",m="plain"):(h="application",m="octet-stream")),[e(h),e(m),s(c),l.parsedHeader["content-id"]||null,l.parsedHeader["content-description"]||null,e(l.parsedHeader["content-transfer-encoding"]||"7bit"),l.size]},i=l=>{let c=l.parsedHeader["content-language"]&&l.parsedHeader["content-language"].replace(/[ ,]+/g,",").replace(/^,+|,+$/g,""),h=c&&c.split(",")||null,m=l.parsedHeader["content-disposition"],T=[m&&[e(m.value),s(m)]||null,h];return t.skipContentLocation||T.push(l.parsedHeader["content-location"]||null),T},a=(l,c)=>{let h=n(l).concat(c);return t.body||(h=h.concat([l.parsedHeader["content-md5"]||null],i(l))),h},o=l=>{let c=te(l).map(u).concat([e(l.multipart)]);return t.body||(c=c.concat([s(l.parsedHeader["content-type"])],i(l))),Object.defineProperty(c,"adjacentLists",{value:!0}),c},u=l=>{switch((l.parsedHeader["content-type"]||{}).type){case"multipart":return te(l)?o(l):a(l,[]);case"text":return a(l,[l.lineCount]);case"message":{let h=ee(l,t.messageGlobal);return h?a(l,[He(h.parsedHeader),u(h),l.lineCount]):a(l,[])}default:return a(l,[])}};return u(r)}var ft={},At=ft;Object.defineProperty(ft,"applyPartial",{value:Nr});ft.UID=function(r,t){return t.uid};ft.FLAGS=function(r,t){return r.getFlags(t).map(e=>({type:"ATOM",value:e}))};ft.BODYSTRUCTURE=function(r,t){return an(rt(t).tree,{upperCaseKeys:!0,skipContentLocation:!0,messageGlobal:r.messageGlobal})};ft.ENVELOPE=function(r,t){return He(rt(t).tree.parsedHeader)};ft["BODY.PEEK"]=function(r,t,e){if(!e.section)throw new Error("BODY.PEEK requires ans argument list");return ft.BODY(r,t,e)};function Sc(r,t){if(r.section.length!==2||!Array.isArray(r.section[1])||!r.section[1].length)throw new Error(t+" expects a list of header fields");return r.section[1].map(e=>{if(["ATOM","STRING","LITERAL"].indexOf(e.type)<0)throw new Error("Invalid header field name in list");return e.type="ATOM",e.value.toUpperCase()})}function bc(r,t,e){if(!t.section.length)return r.raw;if(t.section[0].type!=="ATOM")throw new Error("Invalid BODY[<section>] identifier"+(t.section[0].value?" "+t.section[0].type:""));let s=(t.section[0].value||"").toUpperCase().match(/^((?:[1-9]\d*)(?:\.[1-9]\d*)*)?(?:(?:^|\.)(HEADER|HEADER\.FIELDS|HEADER\.FIELDS\.NOT|TEXT|MIME))?$/);if(!s||s[2]==="MIME"&&!s[1])throw new Error("Invalid BODY[<section>] identifier "+t.section[0].value);let n=s[1]||"",i=s[2]||"",a=[];if(["HEADER.FIELDS","HEADER.FIELDS.NOT"].indexOf(i)>=0)a=Sc(t,i);else if(t.section.length>1)throw new Error((i||"Part number")+" does not take any arguments");let o=n?de(r.tree,n,e):r.tree;if(!o)return"";let u=n?ee(o,e):o;switch(i){case"":return Rt(o,!0);case"MIME":return Or(o);case"TEXT":return u?Rt(u,!0):"";case"HEADER":return u?Or(u):"";default:{if(!u)return"";let l=i==="HEADER.FIELDS",c="";return(u.header||[]).forEach(h=>{let m=h.split(":")[0].toUpperCase().trim();a.indexOf(m)>=0===l&&(c+=h+`\r
|
|
23
|
+
`)}),c+`\r
|
|
24
|
+
`}}}function Nr(r,t){if(!t)return r;if(t.length!==2||!(t[1]>0))throw new Error("Invalid partial range, expecting <start.length>");return r.substr(t[0],t[1])}ft.BODY=function(r,t,e){let s=rt(t);if(!e.section){if(e.partial)throw new Error("BODY without a section does not take a partial range");return an(s.tree,{body:!0,upperCaseKeys:!0,messageGlobal:r.messageGlobal})}return{type:"LITERAL",value:Nr(bc(s,e,r.messageGlobal),e.partial)}};ft.INTERNALDATE=function(r,t){return t.internaldate};ft.RFC822=function(r,t){return{type:"LITERAL",value:rt(t).raw}};ft.RFC822.setsSeen=!0;ft["RFC822.SIZE"]=function(r,t){return rt(t).raw.length};ft["RFC822.HEADER"]=function(r,t){return{type:"LITERAL",value:Or(rt(t).tree)}};ft["RFC822.TEXT"]=function(r,t){return{type:"LITERAL",value:Rt(rt(t).tree,!0)}};ft["RFC822.TEXT"].setsSeen=!0;var Ic=/^[1-9]\d*(?:\.[1-9]\d*)*$/,on=new WeakMap;function co(r){let t=new Error(r);return t.imapResponse="NO",t.code="UNKNOWN-CTE",t}function fo(r){let t=r.parsedHeader["content-type"];return(t&&t.value||"").toLowerCase()}function ho(r){return(r.parsedHeader["content-transfer-encoding"]||"7bit").toString().trim().toLowerCase()}function po(r,t){let e=fo(r);return!r.boundary&&!/^multipart\//.test(e)&&e!=="message/rfc822"&&(!t||e!=="message/global")}function Oc(r){let t=r.replace(/[^A-Za-z0-9+/=]/g,"").split("=")[0];return t.length%4===1&&(t=t.slice(0,-1)),I.Buffer.from(t,"base64").toString("binary")}function Nc(r){return r.replace(/[ \t]+(?=\r\n|$)/g,"").replace(/=(?:\r\n|$)/g,"").replace(/=([0-9A-Fa-f]{2})/g,(t,e)=>String.fromCharCode(parseInt(e,16)))}function mo(r,t,e){let s=e.value.toUpperCase(),n=e.section;if(!n)throw new Error(s+" requires a section");if(!n.length)throw new Error(s+"[] is not allowed, BINARY applies to leaf body parts only (RFC 9051 section 6.4.5)");if(n.length!==1||n[0].type!=="ATOM"||!Ic.test(n[0].value))throw new Error("Invalid "+s+" section, expecting a part number (RFC 3516 section 7)");let i=de(rt(t).tree,n[0].value,r.messageGlobal);if(!i)return"";if(!po(i,r.messageGlobal))throw new Error(s+"["+n[0].value+"] is not a leaf body part (RFC 9051 section 6.4.5)");return on.has(i)||on.set(i,Cc(i)),on.get(i)}function Cc(r){let t=Rt(r,!0),e=ho(r),s;if(Ir.includes(e))s=t;else if(e==="base64")s=Oc(t);else if(e==="quoted-printable")s=Nc(t);else throw co("Unknown Content-Transfer-Encoding "+JSON.stringify(e).replace(/[^\x20-\x7e]/g,"?"));return/^text\//.test(fo(r))?Ue(s):s}function un(r,t,e){let s=Nr(mo(r,t,e),e.partial);return{type:s.indexOf("\0")>=0?"LITERAL8":"LITERAL",value:s}}un.setsSeen=!0;function xc(r,t,e){if(e.partial)throw new Error("BINARY.SIZE does not take a partial range");return mo(r,t,e).length}function Mc(r){let t=Be(r),e=n=>{if(n.childNodes)return n.childNodes.map(e).includes(!0);let i=ee(n,!0);if(i)return e(i)?(n.body=Rt(i),!0):!1;let a=ho(n);return!po(n,!0)||!n.body||!(a==="binary"||Ir.includes(a)&&n.body.indexOf("\0")>=0)?!1:(n.body=I.Buffer.from(n.body,"binary").toString("base64").match(/.{1,76}/g).join(`\r
|
|
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
|
|
26
|
+
\r
|
|
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(e=>{let s=e.length;for(;s>0&&(e[s-1]===" "||e[s-1]===" ");)s--;return e.slice(0,s)}).join(`\r
|
|
30
|
+
`).replace(/=\r\n/g,"").replace(/=([0-9A-Fa-f]{2})/g,(e,s)=>String.fromCharCode(parseInt(s,16)));return I.Buffer.from(t,"binary")}function Ff(r){let t=r.split(/\r?\n/).filter(e=>!/^>/.test(e)).join(`
|
|
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 bu(r){let t=[],e=new Map;return[].concat(r||[]).forEach(s=>{let n=String(s).toLowerCase(),i=Object.hasOwn(qe,n)?qe[n]:null;if(!i)throw new Error('Unknown quirk "'+s+'". Available quirks: '+Object.keys(qe).join(", "));t.push(...i.rules||[]),(i.removePlugins||[]).forEach(a=>e.set(a,n))}),{rules:t,removePlugins:e}}E();var bh=["acl","metadata","special-use","MAILBOXID","HIGHESTMODSEQ","qresyncExpunged","appendLimit","SAVEDATE","MODSEQ","EMAILID","THREADID","X-GM-LABELS","X-GM-MSGID","X-GM-THRID"],is={type:"array",items:{type:"string"}},Vi={type:"integer",minimum:1,maximum:4294967295},Qi={$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:Vi,flags:{oneOf:[{type:"string"},is]},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:Vi,uidnext:Vi,flags:is,permanentFlags:is,allowPermanentFlags:{type:"boolean"},subscribed:{type:"boolean"},knownFlags:is,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"}}}}}},qi=Object.keys(Qi.$defs.mailbox.properties),Ih=["separator","type"],Oh=Object.keys(Qi.$defs.message.oneOf[1].properties);function Nh(r,t){return t.includes(r)||bh.includes(r)?null:t.find(e=>e.toLowerCase()===r.toLowerCase()||r.length>3&&Ch(e,r)===1)||null}function Ch(r,t){let e=Array.from({length:t.length+1},(s,n)=>n);for(let s=1;s<=r.length;s++){let n=e[0];e[0]=s;for(let i=1;i<=t.length;i++){let a=e[i];e[i]=Math.min(e[i]+1,e[i-1]+1,n+(r[s-1]===t[i-1]?0:1)),n=a}}return e[t.length]}var as=r=>!!r&&typeof r=="object"&&!Array.isArray(r),Iu=r=>Array.isArray(r)&&r.every(t=>typeof t=="string"),Ou=r=>Number.isSafeInteger(r)&&r>=1&&r<=4294967295;function Yi(r){let t=(i,a)=>{throw new Error("Invalid storage at "+i+": "+a)},e=(i,a,o)=>{Object.keys(i).forEach(u=>{let l=Nh(u,o);l&&t(a,"unknown key "+JSON.stringify(u)+", did you mean "+JSON.stringify(l)+"?")})},s=(i,a)=>{if(!(typeof i=="string"||i instanceof Uint8Array)){if(!as(i))return t(a,"a message is a string or an object");e(i,a,Oh),i.raw!==void 0&&typeof i.raw!="string"&&!(i.raw instanceof Uint8Array)&&t(a+".raw","must be a string"),i.uid!==void 0&&!Ou(i.uid)&&t(a+".uid","must be an integer from 1 to "+4294967295),i.flags!==void 0&&typeof i.flags!="string"&&!Iu(i.flags)&&t(a+".flags","must be a flag or a list of flags");for(let o of["internaldate","SAVEDATE"]){let u=i[o];u===void 0||u===!1||o==="SAVEDATE"&&u===null||(u instanceof Date?isNaN(u.getTime()):!wr(u))&&t(a+"."+o,'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"&&t(a+".recent","must be true or false")}},n=(i,a,o)=>{if(!as(i))return t(a,"a mailbox is an object");e(i,a,o);for(let u of["uidvalidity","uidnext"])i[u]!==void 0&&!Ou(i[u])&&t(a+"."+u,"must be an integer from 1 to "+4294967295);for(let u of["flags","permanentFlags","knownFlags"])i[u]!==void 0&&!Iu(i[u])&&t(a+"."+u,"must be a list of strings");for(let u of["allowPermanentFlags","subscribed"])i[u]!==void 0&&typeof i[u]!="boolean"&&t(a+"."+u,"must be true or false");i.messages!==void 0&&(Array.isArray(i.messages)||t(a+".messages","must be a list of messages"),i.messages.forEach((u,l)=>s(u,a+".messages["+l+"]"))),i.folders!==void 0&&(as(i.folders)||t(a+".folders","must be an object of mailboxes by name"),Object.keys(i.folders).forEach(u=>n(i.folders[u],a+".folders["+JSON.stringify(u)+"]",qi)))};as(r)||t("the top level","storage is an object of namespaces"),Object.keys(r).forEach(i=>{let a=r[i],o=JSON.stringify(i);if(i==="INBOX")return n(a,o,qi.concat("separator"));n(a,o,qi.concat(Ih));let u=a;u.separator!==void 0&&(typeof u.separator!="string"||u.separator.length!==1)&&t(o+".separator","must be a single character"),u.type!==void 0&&!["personal","user","shared"].includes(u.type)&&t(o+".type",'must be "personal", "user" or "shared"')})}E();E();var Ki=r=>()=>{throw new Error(r+" is not available in the browser")},xh=Ki("The REST API"),Mh=Ki("The REST API"),wh=Ki("The REST API"),Qe={createServer:xh,createHash:Mh,timingSafeEqual:wh};var Dh=64*1024*1024,Lh={NONEXISTENT:404,NOTFOUND:404,ALREADYEXISTS:409,INVALID:400,UNAUTHORIZED:401,METHOD:405,TOOBIG:413,UNSUPPORTED:415};function Nu(r){let t=r.replace(/^\[|\]$/g,"").toLowerCase();return t==="localhost"||t==="::1"||/^(::ffff:)?127\.\d+\.\d+\.\d+$/.test(t)}var Ye=r=>/^\d+$/.test(r)?Number(r):NaN;function Cu(r){let{raw:t,...e}=r;return t?Object.assign(e,{raw:t.toString("base64"),encoding:"base64"}):e}function Rh(r,t){if(t!==void 0&&t!=="base64"&&t!=="utf-8")throw K('encoding must be "utf-8" or "base64"',"INVALID");return t==="base64"&&typeof r=="string"?I.Buffer.from(r,"base64"):r}var os=["session","command","mailbox","expunge","flags","acl","script","reset"],zi=r=>r?r.sessionNumber:null;function Uh(r,t){switch(r){case"mailbox":{let{type:e,path:s,oldPath:n,origin:i}=t[0];return{type:e,path:s,oldPath:n,origin:zi(i)}}case"expunge":return{path:t[0].path,uids:t[1].map(e=>e.uid),origin:zi(t[2])};case"flags":return{path:t[0].path,messages:t[1].map(e=>({uid:e.uid,flags:e.flags.slice()})),origin:zi(t[2])};case"acl":return{path:t[0].path};default:return t[0]||{}}}function Bh(r,t,e){return(s,n)=>{e.add(s),s.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-store"}),s.write(`: connected
|
|
33
|
+
|
|
34
|
+
`);let i=t.map(o=>{let u=(...l)=>s.write("event: "+o+`
|
|
35
|
+
data: `+JSON.stringify(Uh(o,l))+`
|
|
36
|
+
|
|
37
|
+
`);return r.on(o,u),{type:o,listener:u}}),a=setInterval(()=>s.write(`: ping
|
|
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-----
|
|
40
|
+
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDN0THQ8qpf3mMo
|
|
41
|
+
NlVzVvjfsw/QHo22ojmmUO+3QjZDeB7mSmniyGOFw0M8f2g3FM0Kfa51rKMYXWQV
|
|
42
|
+
cqRTDFkk9zBnCagFIWCi2DI4VgArzWlu4TqOHfRIHcbAH1bTKVh5KnVmQA6j6leK
|
|
43
|
+
jvSW2021Ntp8VX+KV5nXM3rRUWaPUSGj1+n6Pcj8ZrMdm2bd6Q4UscCvKrCi1dBP
|
|
44
|
+
TPt9BNVO0CXL8zsiQfNOveN4nTBmF4T1+P/vvzSqHr199XDkjlhd8j3Pm2LKNS5O
|
|
45
|
+
nPERgwZhgIg15G7Y/vz9N0vZGmIU7ApunyrgOhV1o4AlOzdo31xbVYIVn7/fv44D
|
|
46
|
+
G7hvX8DVAgMBAAECggEABIVNSlEiM+PfGrGC0/s7kTJOLRyWsUXD7WbGtShDp9y6
|
|
47
|
+
FQXaaIxNP1FoJyqHP/p5fHsBO310waK/gYcYm+hgBuNVEVZRdfdjN4B3LeyZqVyk
|
|
48
|
+
LbbNwfRferwIswydLBsy4cpwdLQAflI15Qm5zpx3ivzu9J8uI3xEGUl8r59RmOE9
|
|
49
|
+
tXb+sA9YtWRXUR4mhqApGxMI5ZP1/WbmhlDvLUnartyBNilfS3RTWY7nWMKk3U0N
|
|
50
|
+
yFmYX17WZYnXbJtXQmOX/LHd1nM2NFS2B6yJ6JKY0/jPOGCaTBcVmFgO3x/aDgiJ
|
|
51
|
+
m0XL1mpGBIUugQTio5N1Ewznrg6SA7rzsOzN1g3ZqwKBgQD48+lGyQmFAaaXzf+9
|
|
52
|
+
WiG6F6hQtsiWDwhQ3C1m1fOMk2Fgi/eVPEWxIRbf18XBwgvt4Q7PoyojzR730YZl
|
|
53
|
+
5WsEpliGyaBdrR4ZRh92t3y0fQ6Q/AMhsIEIu62lZbLlLenW5/OZLyVsuctAUZCg
|
|
54
|
+
HBNgwR1wuvBBXrc+TIXjUYgsfwKBgQDTpLEqsjh8ZrCvubH0mlTCHkSS/A3ifk27
|
|
55
|
+
suLZhps0J0JMM1drxpNHcfySZ31sVrMZog1cf5W6z55pYlEDCrlEjK2gjyzJnmUA
|
|
56
|
+
KE+ramKMH1/hfxdVZLY1F1zL2oLuprQEE6AUMDdZiv4JMcNfHA05Ii5VpsGe/sVe
|
|
57
|
+
aCiudjH4qwKBgFEFiMk5ynhYJjDHoVCt0cYvxt6l7jgwIkO2tKwAO6hnmsyCIQyX
|
|
58
|
+
thLEsx4cqka58Yn0sg5Pivpl2otKzJPDC4ZS4QLVAfUaz23oTXskklhnTuNOsXI4
|
|
59
|
+
cHY4JnZq18MQo0cG7FfRaTuuaADByvDg0kmt7/ftTx3nRnnnC7gEo+3fAoGAX4WG
|
|
60
|
+
fNnBSsxiVH2ARwDc3lwg4SIn9iDBXsTnQ/xP0mMhthi6DSer02Qr9bwFzL74yMnu
|
|
61
|
+
M+BVqOIKAlBgdfoCEmFYAA5+zWTS+xY2lwxF/C4w7SqaUm1JG3823774t1PADdL5
|
|
62
|
+
vgLhCGYGMAoovqV/hljaBshjvSoJ1Ik4Sz2HYk8CgYEAnSqiwlpYZKQX7jBo7yWA
|
|
63
|
+
xB6r81uUHwy+XOq7A4OfgbEEuuKQ6tXOg72FX+38rF+Td6iA+6qIPoSoGtK0jANX
|
|
64
|
+
ykroFnXr4N3IL5TafDZVvMGNuWhWwS8JR3B0VDzPobt/jxPJKmGunZoCqwJC+nqT
|
|
65
|
+
ELanzRGdLk0G2chSGO7ZKGg=
|
|
66
|
+
-----END PRIVATE KEY-----
|
|
67
|
+
`,wu=`-----BEGIN CERTIFICATE-----
|
|
68
|
+
MIIDOjCCAiKgAwIBAgIUad1YSlfC6YFAqn38plnziyvx1/YwDQYJKoZIhvcNAQEL
|
|
69
|
+
BQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MCAXDTI2MTAwNjA4NDU1OFoYDzIxMjYw
|
|
70
|
+
OTEyMDg0NTU4WjAUMRIwEAYDVQQDDAlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEB
|
|
71
|
+
AQUAA4IBDwAwggEKAoIBAQDN0THQ8qpf3mMoNlVzVvjfsw/QHo22ojmmUO+3QjZD
|
|
72
|
+
eB7mSmniyGOFw0M8f2g3FM0Kfa51rKMYXWQVcqRTDFkk9zBnCagFIWCi2DI4VgAr
|
|
73
|
+
zWlu4TqOHfRIHcbAH1bTKVh5KnVmQA6j6leKjvSW2021Ntp8VX+KV5nXM3rRUWaP
|
|
74
|
+
USGj1+n6Pcj8ZrMdm2bd6Q4UscCvKrCi1dBPTPt9BNVO0CXL8zsiQfNOveN4nTBm
|
|
75
|
+
F4T1+P/vvzSqHr199XDkjlhd8j3Pm2LKNS5OnPERgwZhgIg15G7Y/vz9N0vZGmIU
|
|
76
|
+
7ApunyrgOhV1o4AlOzdo31xbVYIVn7/fv44DG7hvX8DVAgMBAAGjgYEwfzAdBgNV
|
|
77
|
+
HQ4EFgQUzO7Y5K1NaU+/GXZJi2C47uK0+tQwHwYDVR0jBBgwFoAUzO7Y5K1NaU+/
|
|
78
|
+
GXZJi2C47uK0+tQwDwYDVR0TAQH/BAUwAwEB/zAsBgNVHREEJTAjgglsb2NhbGhv
|
|
79
|
+
c3SHBH8AAAGHEAAAAAAAAAAAAAAAAAAAAAEwDQYJKoZIhvcNAQELBQADggEBAL/P
|
|
80
|
+
p3lI83Fcw8EpVyzr9QPYA7JZVmy8YlJ7vouOmEUi6X7BnK5Eits1uHGZ6rtLGBCY
|
|
81
|
+
Eu4Z4DnCPXnyXuo4Bzaqabs5qUro3Ztf0FXeatGCmTLx06JSapKVyoXkJpzLzX0u
|
|
82
|
+
pj0WfWUkwD3rGQozn0FOUOrZyjYgPgsqr6doWd5emAWl1L8ZGDFJEWPRvrS0dw7Z
|
|
83
|
+
ZG83/H0UYur8lN2JxV4ITRovftmtruiVNw3mXH5BZCIsoFAEtf3hssn6rekfEOfc
|
|
84
|
+
4vty2NskN112OLQzLK1Oq3dl0C6Ns1MdIoelAHrFdeM3O03Y0D2R+PlNw1cU55if
|
|
85
|
+
EF3engvuSVRtcV8eyxM=
|
|
86
|
+
-----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(t){let e=typeof t=="string"?I.Buffer.from(t,"binary"):t;this._outputQueue?this._outputQueue.push({data:e,transport:this.transport}):this.writeLayer(e,this.transport)}queueOutput(t){if(!this._outputQueue&&!t.delay&&!t.chunk){t.data&&this.writeLayer(t.data,this.transport),t.close&&this.closeNow(t.close);return}this._outputQueue=this._outputQueue||[],this._outputQueue.push(Object.assign({},t,{transport:this.transport})),!this._outputTimer&&!this._outputWaiting&&this.flushOutput()}flushOutput(){let t=this._outputQueue||[];for(;t.length;){let e=t[0];if(e.delay){let s=e.delay;e.delay=0,this._outputTimer=setTimeout(()=>{this._outputTimer=null,this.flushOutput()},s);return}if(e.data&&e.chunk&&e.data.length>e.chunk){let s=e.data.subarray(0,e.chunk);if(e.data=e.data.subarray(e.chunk),!e.chunkDelay||e.chunkDelay==="tick"){this.socket?.setNoDelay?.(!0),this._outputWaiting=!0,this.writeLayer(s,e.transport||null,()=>{this._outputWaiting&&this._outputQueue===t&&(this._outputTimer=ed(()=>{this._outputTimer=null,this._outputWaiting=!1,this.flushOutput()}))});return}e.delay=e.chunkDelay,this.writeLayer(s,e.transport||null);continue}if(e.data&&this.writeLayer(e.data,e.transport||null),t.shift(),e.close){this.closeNow(e.close);return}}this._outputQueue=null}clearOutputQueue(){this._outputTimer&&(clearTimeout(this._outputTimer),R(this._outputTimer),this._outputTimer=null),this._outputWaiting=!1,this._outputQueue=null,this._deferredOutput=null}writeLayer(t,e,s){e?(e.write(t),s&&L(s)):this.writeRaw(t,s)}scriptOutput(t,e,s,n){let i=this.server.script.check(this,t,Object.assign({},s,{data:e}));if(!i){this.write(e);return}let{rule:a,context:o}=i;if((a.mutate||a.literals)&&n&&o.response){let u=o.response;if(a.mutate){let c=na(u);u=a.mutate(c,o)||c}let l=n(a.literals?vu(u):u);if(l===null)return;o.data=l}Hu(this,a,o,I.Buffer.from(o.data,"binary"))}sendContinuation(t,e,s){let n="+ "+t+`\r
|
|
89
|
+
`;if(!this.server.script.watches("continuation")){this.write(n);return}let i=s?s():null;this.scriptOutput("continuation",n,i===null?{description:e}:{description:e,tag:ie(i),command:ra(i)})}writeRaw(t,e){this.socket&&!this.socket.destroyed&&(this.socket.write(t,e),this.touch())}touch(){if(!this.server.script.watches("quiet")){this._lastActivity=void 0;return}this._lastActivity=Date.now(),this._quietTimer||this.watchQuiet()}watchQuiet(t=0){if(this._quietTimer||!this.socket||this._closing)return;let e=this._lastActivity||Date.now();this._lastActivity=e;let s=this.server.script.nextQuiet(t);s!==null&&(this._quietTimer=setTimeout(()=>{if(this._quietTimer=null,!this.isOpen()||this._lastActivity!==e)return this.watchQuiet();let n=Math.max(Date.now()-e,s),i=this.server.script.check(this,"quiet",{data:"",quiet:n});i&&Fu(this,i.rule,i.context),this._lastActivity===e&&this.watchQuiet(n)},Math.max(0,s-(Date.now()-e))),this._quietTimer.unref?.())}receive(t){this.touch(),this.transport?this.transport.receive(t):this.onData(t)}end(){if(this._outputQueue&&this.socket){this._closing=!0,this._outputQueue.push({close:!0});return}this.closeNow(!0)}closeNow(t){let e=this.socket;if(e)if(this._closing=!0,this.clearOutputQueue(),t==="reset"){this.discardInput(),this._resetting=!0,e.pause();let s=this.tcpSocket;setTimeout(()=>{e.destroyed||rd(e,s)},Qh)}else this.transport?this.transport.end(()=>e.end()):e.end()}bye(t,e){this.sendStatus({tag:"*"},null,"BYE",t,!1,e||"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(t,e){this.sendStatus(t,e,"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(t=>t(this))}closeMailbox(){let t=!!this.selectedMailbox;this.state="Authenticated",this.selectedMailbox=!1,this.readOnly=!1,this.recent=null,this.notificationQueue=[],t&&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(t){this.options.debug&&(console.log("Socket error event emitted, %s",Date()),console.log(t.stack));try{this.socket?.end()}catch{}}handleInput(t){let e=this.inputHandler,s=this.server.script.check(this,"input",{data:t});s?ta(this,s.rule,s.context,()=>e(t)):e(t)}onData(t){let e,s;if(this._resetting)return;if(this._readCount=(this._readCount||0)+1,s=(t||"").toString("binary"),this._discardLine){let i=s.indexOf(`
|
|
90
|
+
`);if(i<0)return;let a=this._discardLine;this._discardLine=!1,s=s.substr(i+1),this.sendBad(a,"Command line too long","LINE TOO LONG")}if(this._literalRemaining&&(s=this.readLiteral(s),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=s=this._remainder+s;e=n.exec(s);){let{marker:i,tilde:a,size:o,plus:u,cr:l}=e.groups;if(e.index>ea){let h=ie(this._command||s);this.sendBad("*","Command line too long","LINE TOO LONG"),this.sendBad(h,"Command line too long","LINE TOO LONG"),this._remainder=s=s.substr(e.index+e[0].length),this._command="",this._skipCommand=!1;continue}if(!l){let h=this._command+s.substr(0,e.index+e[0].length-1);this._remainder=s=s.substr(e.index+e[0].length),this._command="",this._skipCommand?this._skipCommand=!1:this.sendBad(this.inputHandler?"*":ie(h),"Lines must end with CRLF","INVALID LINE ENDING",h);continue}if(!o||this._skipCommand&&!u){let h=this._command+s.substr(0,e.index);if(this._remainder=s.substr(e.index+e[0].length),this._command="",this._skipCommand?this._skipCommand=!1:this._earlyLiteral?(this._earlyLiteral=!1,this.sendBad(ie(h),"Literal data must wait for the continuation request","LITERAL TOO EARLY",h)):this.inputHandler?this.handleInput(h):this.scheduleCommand(h),this.upgrading)return;s=this._remainder;continue}let c=Number(o);if(!this._skipCommand){let h=this._command+s.substr(0,e.index),m=ie(h+i),T=this.checkLiteral(h,c,!u,!!a);if(T){if(u){this.sendStatus({tag:"*"},h,"BYE",T.text,T.text===_u&&"TOOBIG","LITERAL REFUSED"),this._remainder=this._command="",this.end();return}this.sendStatus({tag:m},h,T.command,T.text,T.code||!1,"LITERAL REFUSED"),this._remainder=s=s.substr(e.index+e[0].length),this._command="";continue}u&&c>this.server.nonSyncLiteralLimit&&(this.sendStatus({tag:m},h,"BAD","Non-synchronizing literals are limited to "+this.server.nonSyncLiteralLimit+" octets","TOOBIG","LITERAL TOO BIG"),this._skipCommand=!0,this._command="")}if(!u){if(s.length>e.index+e[0].length)this._earlyLiteral=!0;else if(!this._earlyLiteral){let h=s.substr(0,e.index)+i;this.sendContinuation("Go ahead","LITERAL",()=>this._command+h)}}if(this._remainder="",this._skipCommand||(this._command+=s.substr(0,e.index+e[0].length)),this._literalRemaining=c,s=this.readLiteral(s.substr(e.index+e[0].length)),this._literalRemaining)return;this._remainder=s}if(this._remainder.length>ea){this.sendBad("*","Command line too long","LINE TOO LONG");let i=ie(this._command||this._remainder);this._remainder="",this._command="",this._skipCommand=!1,this._discardLine=i}}readLiteral(t){let e=Math.min(this._literalRemaining,t.length);return this._skipCommand||(this._command+=t.substr(0,e)),this._literalRemaining-=e,t.substr(e)}sendBad(t,e,s,n){this.sendStatus({tag:t},n,"BAD",e,!1,s)}checkLiteral(t,e,s,n){let i=l=>({command:"BAD",text:l}),a=this.getMaxLiteralSize();if(e>a||t.length+e>a+ea)return i(_u);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 o=ra(t);if(!$h.test(o)||!this.server.getCommandHandler(o))return i("Unknown command");let u=this.server.getCommandOptions(o);if(u.states&&u.states.indexOf(this.state)<0)return i(ku(o,this.state));if(n&&!(u.literal8===!0||u.literal8&&Object.hasOwn(this.server.capabilities,u.literal8)))return i("Literal8 is not allowed in "+o);if(s)for(let l of this.server.literalFilters){let c=l(this,o,t,e);if(c)return c}return!1}getMaxLiteralSize(){return this.state==="Not Authenticated"?Kh:Number(this.options.maxLiteralSize)||Yh}getSessionMessages(){for(let t=0,e=this.notificationQueue.length;t<e;t++){let s=this.notificationQueue[t].mailboxCopy;if(s)return s}return this.selectedMailbox?this.selectedMailbox.messages:[]}getMessageRange(t,e){return this.server.getMessageRange(this.getSessionMessages(),t,e)}limitRange(t,e){return this.server.rangeLimits.reduce((s,n)=>n(this,t,s)||s,e)}getCommandRange(t,e){let s=this.getMessageRange(t,e);if(e)return s;let n=this.getSessionMessages().length;return String(t).split(/[,:]/).forEach(i=>{if(i==="*"?!n:Number(i)>n){let a=new Error(n?"Message sequence number "+i+" is greater than the number of messages ("+n+")":"The mailbox is empty");throw a.imapResponse="BAD",a}}),s}hasPendingExpunge(){return this.notificationQueue.some(ju)}notifyFlagChanges(t){this.selectedMailbox&&Ws(this.server,this.selectedMailbox,t,this)}sendFlagUpdate(t,e,s){let n=this.server.fetchHandlers.FLAGS||At.FLAGS;t.forEach(i=>{if(!(!e.has(i)||i.ghost)){if(s){if(s.has(i))return;s.add(i)}this.send({tag:"*",notification:!0,attributes:[e.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(t){return!!(this.recent&&this.recent.has(t))}getFlags(t){return this.isRecent(t)?t.flags.concat("\\Recent"):t.flags}canSetSeen(){return!this.readOnly}readOnlyRefusal(){return this.readOnly?{command:"NO",code:"CLIENTBUG",text:"Mailbox is read-only"}:!1}refuseReadOnly(t,e,s){let n=this.readOnlyRefusal();return n&&this.sendStatus(t,e,n.command,n.text,n.code,s),!!n}canExpunge(){return!this.readOnly}onNotify(t){if(t.ignoreConnection===this||t.filter&&!t.filter(this)||!this.server.notifyFilters.every(s=>s(this,t)))return;let e=typeof t.mailbox=="string"?this.server.getMailbox(t.mailbox):t.mailbox;if(!t.mailbox||this.selectedMailbox&&this.selectedMailbox===e){let s=t.command;s.mailboxCopy&&this.notificationQueue.some(n=>n.mailboxCopy)&&(s=Object.assign({},s),delete s.mailboxCopy),this.queueNotification(s,t)}}queueNotification(t,e){this.notificationQueue.push(t),this.directNotifications&&this.processNotifications()}upgradeConnection(t){this.upgrading=!0,this.discardInput();let e=this.socket;if(typeof e.startTls=="function")return e.startTls(()=>{this.secureConnection=!0,this.upgrading=!1,t()});let s=Kt.createSecureContext(this.server.getCredentials()),n={secureContext:s,isServer:!0,server:this.server.server,SNICallback:function(o,u){u(null,s)}};this.tcpSocket=e,e.removeAllListeners(),e.on("error",this.onError.bind(this));let i=new Kt.TLSSocket(e,n),a=o=>{this.options.debug&&console.log("TLS error: %s",o.message),i.destroy()};i.on("close",this.onClose.bind(this)),i.on("error",a),i.on("clientError",a),i.on("secure",()=>{this.secureConnection=!0,this.socket=i,this.upgrading=!1,i.on("data",this.receive.bind(this)),t()})}prepareNotifications(t){return t}holdsExpunge(t){let e=this.server.getCommandOptions(t.command);return e.noExpunge||e.searchCriteria!==!1&&this.usesSequenceNumbers(t)}processNotifications(t,e){if(!this.notificationQueue.length)return;let s=this.notificationQueue,n=s.find(A=>A.mailboxCopy),i=[];if(t&&(this.holdsExpunge(t)||e&&this.usesSequenceNumbers(t))){let A=s.findIndex(ju);if(A>=0&&(i=s.slice(A),s=s.slice(0,A)),!s.length)return}this.notificationQueue=i,s=this.prepareNotifications(s);let a=s.findIndex(A=>A.mailboxCopy),o=new Map,u=A=>{let p=o.get(A);return p||(p=new Map(A.map((f,d)=>[f,d+1])),o.set(A,p)),p},l=this.selectedMailbox?this.selectedMailbox.messages:[],c=new Set,h=A=>n&&(a<0||A<a)?n.mailboxCopy:l,m=-1,T=!1;s.forEach((A,p)=>{A.flagUpdate?this.sendFlagUpdate(A.flagUpdate,u(h(p)),c):this.send(A),Vu(A)&&(m=p,T=T||!!A.message);let f=s[p+1];m<0||Vu(f)||f&&f.fetchedMessage||(T&&this.sendRecent(Number(s[m].attributes[0]),u(h(m))),m=-1,T=!1)})}sendRecent(t,e){let s=0;(this.recent||new Set).forEach(n=>{let i=e.get(n);i&&i<=t&&s++}),this.send({tag:"*",notification:!0,attributes:[s,{type:"ATOM",value:"RECENT"}]},"RECENT NOTIFICATION")}send(t,e,s,n,...i){if(!this.isOpen()||(!t.notification&&t.tag!=="*"&&this.processNotifications(s),this.server.outputHandlers.forEach(c=>{c(this,t,e,s,n,...i)}),this._commandStart&&s&&t.tag===this._commandStart.tag&&s.tag===t.tag&&this.commandCompleted(String(t.command||"").toUpperCase()),t.skipResponse))return;this.notificationQueue.length&&s&&t.tag===s.tag&&t.command==="OK"&&this.hasPendingExpunge()&&this.holdsExpunge(s)&&!(Array.isArray(t.attributes)&&t.attributes.some(c=>c&&c.type==="SECTION"))&&(t.attributes=[{type:"SECTION",section:[{type:"ATOM",value:"EXPUNGEISSUED"}]}].concat(t.attributes||[]));let a=c=>c&&c.type==="MAILBOX",o=c=>c.some(h=>a(h)||Array.isArray(h)&&o(h)),u=c=>c.map(h=>a(h)?sd(this.exportMailboxName(h.value)):Array.isArray(h)?u(h):h);if(Array.isArray(t.attributes)&&o(t.attributes)&&(t=Object.assign({},t,{attributes:u(t.attributes)})),zh.has((t.command||"").toString().toUpperCase())&&Array.isArray(t.attributes)){let c=h=>h&&h.type==="TEXT"&&typeof h.value=="string"&&/[^\x20-\x7e]/.test(h.value);t.attributes.some(c)&&(t=Object.assign({},t,{attributes:t.attributes.map(h=>c(h)?Object.assign({},h,{value:h.value.replace(/[^\x20-\x7e]/g,"?")}):h)}))}let l=this.compileResponse(t);l!==null&&(this._deferredOutput&&Ji(this,s&&s.command&&s.tag&&s.tag!=="*"?s.tag:null,!1),this.scriptResponse(t,l,e,s),this._deferredOutput&&t.tag!=="*"&&t.tag!=="+"&&Ji(this,t.tag,!0))}scriptResponse(t,e,s,n){let i=t.tag==="+"?"continuation":"response";if(!this.server.script.watches(i)){this.write(e);return}this.scriptOutput(i,e,Object.assign({description:s||null,response:t},n&&n.command?{tag:n.tag||null,command:String(n.command).toUpperCase()}:{}),a=>this.compileResponse(a))}compileResponse(t){let e;try{e=Wt.compiler(t,this.compilerOptions)}catch(s){if(this.options.debug&&console.log("Failed to compile response: %s",s.message),t.tag==="*")return null;e=t.tag+" NO [SERVERBUG] Failed to compile response"}return this.options.debug&&console.log("SEND: %s",e),e+`\r
|
|
91
|
+
`}sendStatus(t,e,s,n,i,a){let o=[];i&&o.push({type:"SECTION",section:[].concat(i).map(u=>({type:"ATOM",value:String(u)}))}),o.push({type:"TEXT",value:n}),a||(a=(t.command||"").toString().toUpperCase()+(s==="OK"?"":" FAILED")),this.send({tag:t.tag,command:s,attributes:o},a,t,e)}isAmbiguous(t){if(!this.usesSequenceNumbers(t))return!1;if(this._unsafeCompletedRead===this._readCount)return!0;let e=s=>!!s&&!this.server.getCommandOptions(s.parsed.command).noExpunge;return e(this._runningCommand)||this._commandQueue.some(e)}usesSequenceNumbers(t){let e=qu.get(t);return e===void 0&&(e=this.findSequenceNumbers(t),qu.set(t,e)),e}findSequenceNumbers(t){let{sequenceSet:e,searchCriteria:s}=this.server.getCommandOptions(t.command);if(e!==!1){let n=t.attributes&&t.attributes[e];return!n||/^[\d*]/.test(String(n.value))}return s!==!1?Oo(this.server,(t.attributes||[]).slice(s)):!1}decodeSaslResponse(t){return t==="="?I.Buffer.alloc(0):typeof t!="string"||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t)?!1:I.Buffer.from(t,"base64")}getTargetMailbox(t,e,s,n){let i=this.server.targetRefusal(t);return i?(this.sendStatus(e,s,i.command,i.text,i.code,n),!1):this.server.getMailbox(t)}checkAppend(t,e,s,n,i,a){return this.applyChecks(this.server.appendChecks.map(o=>o(this,t,e,a||{})),s,n,i)}applyChecks(t,e,s,n){let i=t.filter(o=>!!o),a=i.find(o=>!o.soft);return a?(this.sendStatus(e,s,"NO",a.text,a.code,n),!1):(i.forEach(o=>{this.send({tag:"*",command:"NO",attributes:[{type:"SECTION",section:[{type:"ATOM",value:o.code}]},{type:"TEXT",value:o.text}]},"CHECK WARNING",e,s)}),!0)}importMailboxName(t){let e=pe(t);if(e){let s=new Error(e);throw s.imapResponse="BAD",s}return t}exportMailboxName(t){return t}scheduleCommand(t,e){let s,n=ie(t),i=!e&&this.server.script.watches("command")?this.server.script.check(this,"command",{data:t,tag:n,command:ra(t)}):null;if(i){this._commandQueue.push({parsed:{tag:n,command:i.context.command||""},data:t,script:i}),this.processQueue();return}try{s=Wt.parser(t,Object.assign({literalPlus:this.server.literalPlus},this.server.parserOptions,this.parserOptions))}catch(o){let u=o;this.send({tag:"*",command:"BAD",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"SYNTAX"}]},{type:"TEXT",value:u.message}]},"ERROR MESSAGE",null,t,u),this.send({tag:n,command:"BAD",attributes:[{type:"TEXT",value:"Error parsing command"}]},"ERROR RESPONSE",null,t,u);return}if(this.isPipelinedAfterRefusal()){this.refusePipelined(s,t);return}let a=/^AUTHENTICATE /i.test(s.command)&&!this.server.getCommandHandler(s.command)?Zh:void 0;if(a||this.server.getCommandHandler(s.command)){if(this.isAmbiguous(s)){this.sendStatus(s,t,"BAD","Commands with message sequence numbers must wait for the completion of earlier commands");return}let o={parsed:s,data:t,handler:a};e?this._commandQueue.unshift(o):this._commandQueue.push(o),this.processQueue()}else this.send({tag:s.tag,command:"BAD",attributes:[{type:"TEXT",value:"Invalid command "+s.command}]},"UNKNOWN COMMAND",s,t)}commandCompleted(t){let e=this._commandStart;this._commandStart=null;let s=this.server;if(!s.listenerCount("command")&&!s.listenerCount("session"))return;s.emit("command",{session:this.sessionNumber,tag:e.tag,command:e.command,status:t,user:this.username||null});let n=i=>i==="Authenticated"||i==="Selected";n(e.state)!==n(this.state)&&this.state!=="Logout"&&this.emitSession(n(this.state)?"login":"logout")}emitSession(t,e){this.server.listenerCount("session")&&this.server.emit("session",Object.assign({type:t,session:this.describe()},e))}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(t,e){let{rule:s,context:n}=t.script,i=()=>{if(!this.socket||this._closing)return e();ta(this,s,n,()=>{this._runningCommand=null,this.scheduleCommand(t.data,!0)}),e()};s.delay?setTimeout(i,s.delay):i()}processQueue(t){if(!t&&this._processing)return;if(!this._commandQueue.length){this._processing=!1;return}this._processing=!0;let e=this._commandQueue.shift(),s=e.parsed.command.toUpperCase();this._runningCommand=e;let n=this.server.getCommandOptions(s);this._commandStart={tag:e.parsed.tag,command:s,state:this.state};let i=!1,a=()=>{i||(i=!0,this._runningCommand=null,n.noExpunge||(this._unsafeCompletedRead=this._readCount),this._commandQueue.length?this.processQueue(!0):this._processing=!1)};if(e.script){this.runScriptedCommand(e,a);return}if(n.states&&n.states.indexOf(this.state)<0)return this.sendStatus(e.parsed,e.data,"BAD",ku(s,this.state)),a();if(e.parsed.attributes&&n.noArguments)return this.sendStatus(e.parsed,e.data,"BAD",s+" does not take any arguments"),a();if(n.noPipelining&&this.hasPendingInput())return this.sendStatus(e.parsed,e.data,"BAD","Commands must not be pipelined after "+s),this._pipelinedAfter={command:s,read:this._readCount},this._commandQueue.splice(0).forEach(u=>this.refusePipelined(u.parsed,u.data)),a();he(e.parsed,e.data,u=>u.length===1&&(n.mailboxArguments.includes(u[0])||n.astringArguments.includes(u[0]))||n.searchCriteria!==!1&&u[0]>=n.searchCriteria);let o=nd(this,e.parsed,n.mailboxArguments);if(o)return this.sendStatus(e.parsed,e.data,"BAD",o),a();for(let u of this.server.commandChecks){let l=u(this,e.parsed);if(l)return this.sendStatus(e.parsed,e.data,l.command||"BAD",l.text,l.code),a()}this.state==="Selected"&&(s.startsWith("UID ")||n.noExpunge||n.sequenceSet!==!1||n.searchCriteria!==!1)&&this.processNotifications(e.parsed,!0),this.server.withOrigin(this,()=>{try{let u=this.inputHandler;(e.handler||this.server.getCommandHandler(e.parsed.command))(this,e.parsed,e.data,a),this.inputHandler&&this.inputHandler!==u&&(this.inputCommand={tag:e.parsed.tag,command:e.parsed.command},this.emitSession("waiting",{command:s}))}catch(u){let l=u,c=l.imapResponse==="BAD";!c&&this.options.debug&&console.error("Error processing command:",l,`
|
|
92
|
+
`,l.stack),this.send({tag:e.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",e.parsed,e.data),a()}})}expungeDeleted(t,e,s){this.expungeSpecificMessages(t,n=>n.flags.indexOf("\\Deleted")>=0,e,s)}expungeSpecificMessages(t,e,s,n,i){Zt(this.server,t,e,{origin:this,skip:s?this:null,skipExists:n?this:null,highestFirst:!!i})}},td="Deno"in globalThis;function ed(r){return td?setTimeout(r,0):L(r)}function Qu(r,t,e){return new Promise((s,n)=>{r.once("error",n),r.listen({port:t||0,host:e},()=>{r.removeListener("error",n),s(r.address().port)})})}function rd(r,t){let e=r._parent,s=[t,e instanceof Kt.Socket?e:null,r];for(let n of s)if(n&&!n.destroyed&&typeof n.resetAndDestroy=="function")try{n.resetAndDestroy();break}catch{}r.destroy()}function na(r){if(Array.isArray(r))return r.map(na);if(r&&typeof r=="object"&&Object.getPrototypeOf(r)===Object.prototype){let t={};for(let e of Object.keys(r))t[e]=na(r[e]);return t}return r}function ra(r){let t=r.match(/^[^ ]* ([^ ]*)(?: ([^ ]*))?/),e=(t&&t[1]||"").toUpperCase();return(e==="UID"||e==="AUTHENTICATE")&&(e+=" "+(t&&t[2]||"").toUpperCase()),e}function sd(r){return{type:Wh.test(r)&&!/^NIL$/i.test(r)?"ATOM":"STRING",value:r}}function nd(r,t,e){for(let s of e){let n=(t.attributes||[])[s];if(n&&["STRING","ATOM","LITERAL"].indexOf(n.type)>=0)try{n.value=r.importMailboxName(n.value)}catch(i){return i.message}}return!1}var id=Object.assign(aa,{TAG_REGEX:ia,IMAPServer:ze,IMAPConnection:We,ImapKitError:nt,quirks:qe}),mI=id;export{We as IMAPConnection,ze as IMAPServer,nt as ImapKitError,ia as TAG_REGEX,mI as default,qe as quirks,Qi as storageSchema,Yi as validateStorage};
|
|
93
|
+
/*! Bundled license information:
|
|
94
|
+
|
|
95
|
+
ieee754/index.js:
|
|
96
|
+
(*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> *)
|
|
97
|
+
|
|
98
|
+
buffer/index.js:
|
|
99
|
+
(*!
|
|
100
|
+
* The buffer module from node.js, for the browser.
|
|
101
|
+
*
|
|
102
|
+
* @author Feross Aboukhadijeh <https://feross.org>
|
|
103
|
+
* @license MIT
|
|
104
|
+
*)
|
|
105
|
+
*/
|