quickblox-react-ui-kit 0.3.1 → 0.4.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 +0 -324
- package/dist/CommonTypes/CommonTypes.d.ts +1 -0
- package/dist/Data/source/remote/IRemoteDataSource.d.ts +3 -0
- package/dist/Data/source/remote/RemoteDataSource.d.ts +3 -0
- package/dist/Domain/use_cases/ai/AIAnswerAssistWithSDKUseCase.d.ts +11 -0
- package/dist/Domain/use_cases/ai/AITranslateWithSDKUseCase.d.ts +12 -0
- package/dist/Presentation/Views/Dialog/AIWidgets/UseDefaultAIAssistAnswerWidgetWithSDK.d.ts +3 -0
- package/dist/Presentation/Views/Dialog/AIWidgets/UseDefaultAITranslateWidgetWithSDK.d.ts +3 -0
- package/dist/Presentation/ui-components/TextField/TextField.d.ts +1 -1
- package/dist/index-ui.js +500 -3
- package/dist/index-ui.js.map +1 -1
- package/dist/qb-api-calls/index.d.ts +3 -1
- package/package.json +3 -5
- package/src/CommonTypes/CommonTypes.ts +1 -0
- package/src/Data/DefaultConfigurations.ts +3 -0
- package/src/Data/repository/ConnectionRepository.ts +2 -1
- package/src/Data/source/remote/IRemoteDataSource.ts +13 -0
- package/src/Data/source/remote/RemoteDataSource.ts +22 -0
- package/src/Domain/use_cases/ai/AIAnswerAssistWithSDKUseCase.ts +50 -0
- package/src/Domain/use_cases/ai/AITranslateWithSDKUseCase.ts +107 -0
- package/src/Presentation/Views/Dialog/AIWidgets/UseDefaultAIAssistAnswerWidgetWithSDK.tsx +74 -0
- package/src/Presentation/Views/Dialog/AIWidgets/UseDefaultAITranslateWidgetWithSDK.tsx +70 -0
- package/src/Presentation/layouts/Desktop/QuickBloxUIKitDesktopLayout.tsx +14 -2
- package/src/QBconfig.ts +3 -0
- package/src/package_artan_react_ui.json +91 -0
- package/src/package_original.json +115 -0
- package/src/qb-api-calls/index.ts +49 -0
- package/storybook-static/{703.776b9f13.iframe.bundle.js → 703.f12f2e71.iframe.bundle.js} +2 -2
- package/storybook-static/{703.776b9f13.iframe.bundle.js.map → 703.f12f2e71.iframe.bundle.js.map} +1 -1
- package/storybook-static/docs-Introduction-mdx.9dc275f1.iframe.bundle.js +10 -0
- package/storybook-static/{docs-Introduction-mdx.bcb06844.iframe.bundle.js.map → docs-Introduction-mdx.9dc275f1.iframe.bundle.js.map} +1 -1
- package/storybook-static/docs-Styling-mdx.72149f36.iframe.bundle.js +10 -0
- package/storybook-static/{docs-Styling-mdx.1d6c1212.iframe.bundle.js.map → docs-Styling-mdx.72149f36.iframe.bundle.js.map} +1 -1
- package/storybook-static/iframe.html +1 -1
- package/storybook-static/index.html +4 -8
- package/storybook-static/project.json +1 -1
- package/storybook-static/{runtime~main.3464b25a.iframe.bundle.js → runtime~main.72d6302b.iframe.bundle.js} +1 -1
- package/tsconfig.buildlib.json +33 -0
- package/storybook-static/docs-Introduction-mdx.bcb06844.iframe.bundle.js +0 -10
- package/storybook-static/docs-Styling-mdx.1d6c1212.iframe.bundle.js +0 -10
- package/storybook-static/sb-addons/onboarding-7/manager-bundle.js +0 -503
- package/storybook-static/sb-addons/onboarding-7/manager-bundle.js.LEGAL.txt +0 -48
- /package/storybook-static/sb-addons/{interactions-8 → interactions-7}/manager-bundle.js +0 -0
- /package/storybook-static/sb-addons/{interactions-8 → interactions-7}/manager-bundle.js.LEGAL.txt +0 -0
- /package/storybook-static/sb-addons/{viewport-9 → viewport-8}/manager-bundle.js +0 -0
- /package/storybook-static/sb-addons/{viewport-9 → viewport-8}/manager-bundle.js.LEGAL.txt +0 -0
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
object-assign
|
|
22
22
|
(c) Sindre Sorhus
|
|
23
23
|
@license MIT
|
|
24
|
-
*/"use strict";var getOwnPropertySymbols=Object.getOwnPropertySymbols,hasOwnProperty=Object.prototype.hasOwnProperty,propIsEnumerable=Object.prototype.propertyIsEnumerable;function toObject(val){if(null==val)throw TypeError("Object.assign cannot be called with null or undefined");return Object(val)}function shouldUseNative(){try{if(!Object.assign)return!1;var test1=new String("abc");if(test1[5]="de","5"===Object.getOwnPropertyNames(test1)[0])return!1;for(var test2={},i=0;i<10;i++)test2["_"+String.fromCharCode(i)]=i;var order2=Object.getOwnPropertyNames(test2).map(function(n){return test2[n]});if("0123456789"!==order2.join(""))return!1;var test3={};if("abcdefghijklmnopqrst".split("").forEach(function(letter){test3[letter]=letter}),"abcdefghijklmnopqrst"!==Object.keys(Object.assign({},test3)).join(""))return!1;return!0}catch(err){return!1}}module.exports=shouldUseNative()?Object.assign:function(target,source){for(var from,symbols,to=toObject(target),s=1;s<arguments.length;s++){for(var key in from=Object(arguments[s]))hasOwnProperty.call(from,key)&&(to[key]=from[key]);if(getOwnPropertySymbols){symbols=getOwnPropertySymbols(from);for(var i=0;i<symbols.length;i++)propIsEnumerable.call(from,symbols[i])&&(to[symbols[i]]=from[symbols[i]])}}return to}},{}],139:[function(require1,module,exports){exports.endianness=function(){return"LE"},exports.hostname=function(){return"undefined"!=typeof location?location.hostname:""},exports.loadavg=function(){return[]},exports.uptime=function(){return 0},exports.freemem=function(){return Number.MAX_VALUE},exports.totalmem=function(){return Number.MAX_VALUE},exports.cpus=function(){return[]},exports.type=function(){return"Browser"},exports.release=function(){return"undefined"!=typeof navigator?navigator.appVersion:""},exports.networkInterfaces=exports.getNetworkInterfaces=function(){return{}},exports.arch=function(){return"javascript"},exports.platform=function(){return"browser"},exports.tmpdir=exports.tmpDir=function(){return"/tmp"},exports.EOL="\n"},{}],140:[function(require1,module,exports){"use strict";var TYPED_OK="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;exports.assign=function(obj){for(var sources=Array.prototype.slice.call(arguments,1);sources.length;){var source=sources.shift();if(source){if("object"!=typeof source)throw TypeError(source+"must be non-object");for(var p in source)source.hasOwnProperty(p)&&(obj[p]=source[p])}}return obj},exports.shrinkBuf=function(buf,size){return buf.length===size?buf:buf.subarray?buf.subarray(0,size):(buf.length=size,buf)};var fnTyped={arraySet:function(dest,src,src_offs,len,dest_offs){if(src.subarray&&dest.subarray){dest.set(src.subarray(src_offs,src_offs+len),dest_offs);return}for(var i=0;i<len;i++)dest[dest_offs+i]=src[src_offs+i]},flattenChunks:function(chunks){var i,l,len,pos,chunk,result;for(i=0,len=0,l=chunks.length;i<l;i++)len+=chunks[i].length;for(i=0,result=new Uint8Array(len),pos=0,l=chunks.length;i<l;i++)chunk=chunks[i],result.set(chunk,pos),pos+=chunk.length;return result}},fnUntyped={arraySet:function(dest,src,src_offs,len,dest_offs){for(var i=0;i<len;i++)dest[dest_offs+i]=src[src_offs+i]},flattenChunks:function(chunks){return[].concat.apply([],chunks)}};exports.setTyped=function(on){on?(exports.Buf8=Uint8Array,exports.Buf16=Uint16Array,exports.Buf32=Int32Array,exports.assign(exports,fnTyped)):(exports.Buf8=Array,exports.Buf16=Array,exports.Buf32=Array,exports.assign(exports,fnUntyped))},exports.setTyped(TYPED_OK)},{}],141:[function(require1,module,exports){"use strict";function adler32(adler,buf,len,pos){for(var s1=65535&adler|0,s2=adler>>>16&65535|0,n=0;0!==len;){n=len>2e3?2e3:len,len-=n;do s2=s2+(s1=s1+buf[pos++]|0)|0;while(--n)s1%=65521,s2%=65521}return s1|s2<<16|0}module.exports=adler32},{}],142:[function(require1,module,exports){"use strict";module.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],143:[function(require1,module,exports){"use strict";var crcTable=function makeTable(){for(var c,table=[],n=0;n<256;n++){c=n;for(var k=0;k<8;k++)c=1&c?3988292384^c>>>1:c>>>1;table[n]=c}return table}();function crc32(crc,buf,len,pos){var end=pos+len;crc^=-1;for(var i=pos;i<end;i++)crc=crc>>>8^crcTable[(crc^buf[i])&255];return -1^crc}module.exports=crc32},{}],144:[function(require1,module,exports){"use strict";var configuration_table,utils=require1("../utils/common"),trees=require1("./trees"),adler32=require1("./adler32"),crc32=require1("./crc32"),msg=require1("./messages");function err(strm,errorCode){return strm.msg=msg[errorCode],errorCode}function rank(f){return(f<<1)-(f>4?9:0)}function zero(buf){for(var len=buf.length;--len>=0;)buf[len]=0}function flush_pending(strm){var s=strm.state,len=s.pending;len>strm.avail_out&&(len=strm.avail_out),0!==len&&(utils.arraySet(strm.output,s.pending_buf,s.pending_out,len,strm.next_out),strm.next_out+=len,s.pending_out+=len,strm.total_out+=len,strm.avail_out-=len,s.pending-=len,0===s.pending&&(s.pending_out=0))}function flush_block_only(s,last){trees._tr_flush_block(s,s.block_start>=0?s.block_start:-1,s.strstart-s.block_start,last),s.block_start=s.strstart,flush_pending(s.strm)}function put_byte(s,b){s.pending_buf[s.pending++]=b}function putShortMSB(s,b){s.pending_buf[s.pending++]=b>>>8&255,s.pending_buf[s.pending++]=255&b}function read_buf(strm,buf,start,size){var len=strm.avail_in;return(len>size&&(len=size),0===len)?0:(strm.avail_in-=len,utils.arraySet(buf,strm.input,strm.next_in,len,start),1===strm.state.wrap?strm.adler=adler32(strm.adler,buf,len,start):2===strm.state.wrap&&(strm.adler=crc32(strm.adler,buf,len,start)),strm.next_in+=len,strm.total_in+=len,len)}function longest_match(s,cur_match){var match,len,chain_length=s.max_chain_length,scan=s.strstart,best_len=s.prev_length,nice_match=s.nice_match,limit=s.strstart>s.w_size-262?s.strstart-(s.w_size-262):0,_win=s.window,wmask=s.w_mask,prev=s.prev,strend=s.strstart+258,scan_end1=_win[scan+best_len-1],scan_end=_win[scan+best_len];s.prev_length>=s.good_match&&(chain_length>>=2),nice_match>s.lookahead&&(nice_match=s.lookahead);do{if(_win[(match=cur_match)+best_len]!==scan_end||_win[match+best_len-1]!==scan_end1||_win[match]!==_win[scan]||_win[++match]!==_win[scan+1])continue;scan+=2,match++;do;while(_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&scan<strend)if(len=258-(strend-scan),scan=strend-258,len>best_len){if(s.match_start=cur_match,best_len=len,len>=nice_match)break;scan_end1=_win[scan+best_len-1],scan_end=_win[scan+best_len]}}while((cur_match=prev[cur_match&wmask])>limit&&0!=--chain_length)return best_len<=s.lookahead?best_len:s.lookahead}function fill_window(s){var p,n,m,more,str,_w_size=s.w_size;do{if(more=s.window_size-s.lookahead-s.strstart,s.strstart>=_w_size+(_w_size-262)){utils.arraySet(s.window,s.window,_w_size,_w_size,0),s.match_start-=_w_size,s.strstart-=_w_size,s.block_start-=_w_size,p=n=s.hash_size;do m=s.head[--p],s.head[p]=m>=_w_size?m-_w_size:0;while(--n)p=n=_w_size;do m=s.prev[--p],s.prev[p]=m>=_w_size?m-_w_size:0;while(--n)more+=_w_size}if(0===s.strm.avail_in)break;if(n=read_buf(s.strm,s.window,s.strstart+s.lookahead,more),s.lookahead+=n,s.lookahead+s.insert>=3)for(str=s.strstart-s.insert,s.ins_h=s.window[str],s.ins_h=(s.ins_h<<s.hash_shift^s.window[str+1])&s.hash_mask;s.insert&&(s.ins_h=(s.ins_h<<s.hash_shift^s.window[str+3-1])&s.hash_mask,s.prev[str&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=str,str++,s.insert--,!(s.lookahead+s.insert<3)););}while(s.lookahead<262&&0!==s.strm.avail_in)}function deflate_fast(s,flush){for(var hash_head,bflush;;){if(s.lookahead<262){if(fill_window(s),s.lookahead<262&&0===flush)return 1;if(0===s.lookahead)break}if(hash_head=0,s.lookahead>=3&&(s.ins_h=(s.ins_h<<s.hash_shift^s.window[s.strstart+3-1])&s.hash_mask,hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=s.strstart),0!==hash_head&&s.strstart-hash_head<=s.w_size-262&&(s.match_length=longest_match(s,hash_head)),s.match_length>=3){if(bflush=trees._tr_tally(s,s.strstart-s.match_start,s.match_length-3),s.lookahead-=s.match_length,s.match_length<=s.max_lazy_match&&s.lookahead>=3){s.match_length--;do s.strstart++,s.ins_h=(s.ins_h<<s.hash_shift^s.window[s.strstart+3-1])&s.hash_mask,hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=s.strstart;while(0!=--s.match_length)s.strstart++}else s.strstart+=s.match_length,s.match_length=0,s.ins_h=s.window[s.strstart],s.ins_h=(s.ins_h<<s.hash_shift^s.window[s.strstart+1])&s.hash_mask}else bflush=trees._tr_tally(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++;if(bflush&&(flush_block_only(s,!1),0===s.strm.avail_out))return 1}return(s.insert=s.strstart<2?s.strstart:2,4===flush)?(flush_block_only(s,!0),0===s.strm.avail_out)?3:4:s.last_lit&&(flush_block_only(s,!1),0===s.strm.avail_out)?1:2}function deflate_slow(s,flush){for(var hash_head,bflush,max_insert;;){if(s.lookahead<262){if(fill_window(s),s.lookahead<262&&0===flush)return 1;if(0===s.lookahead)break}if(hash_head=0,s.lookahead>=3&&(s.ins_h=(s.ins_h<<s.hash_shift^s.window[s.strstart+3-1])&s.hash_mask,hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=s.strstart),s.prev_length=s.match_length,s.prev_match=s.match_start,s.match_length=2,0!==hash_head&&s.prev_length<s.max_lazy_match&&s.strstart-hash_head<=s.w_size-262&&(s.match_length=longest_match(s,hash_head),s.match_length<=5&&(1===s.strategy||3===s.match_length&&s.strstart-s.match_start>4096)&&(s.match_length=2)),s.prev_length>=3&&s.match_length<=s.prev_length){max_insert=s.strstart+s.lookahead-3,bflush=trees._tr_tally(s,s.strstart-1-s.prev_match,s.prev_length-3),s.lookahead-=s.prev_length-1,s.prev_length-=2;do++s.strstart<=max_insert&&(s.ins_h=(s.ins_h<<s.hash_shift^s.window[s.strstart+3-1])&s.hash_mask,hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=s.strstart);while(0!=--s.prev_length)if(s.match_available=0,s.match_length=2,s.strstart++,bflush&&(flush_block_only(s,!1),0===s.strm.avail_out))return 1}else if(s.match_available){if((bflush=trees._tr_tally(s,0,s.window[s.strstart-1]))&&flush_block_only(s,!1),s.strstart++,s.lookahead--,0===s.strm.avail_out)return 1}else s.match_available=1,s.strstart++,s.lookahead--}return(s.match_available&&(bflush=trees._tr_tally(s,0,s.window[s.strstart-1]),s.match_available=0),s.insert=s.strstart<2?s.strstart:2,4===flush)?(flush_block_only(s,!0),0===s.strm.avail_out)?3:4:s.last_lit&&(flush_block_only(s,!1),0===s.strm.avail_out)?1:2}function deflate_rle(s,flush){for(var bflush,prev,scan,strend,_win=s.window;;){if(s.lookahead<=258){if(fill_window(s),s.lookahead<=258&&0===flush)return 1;if(0===s.lookahead)break}if(s.match_length=0,s.lookahead>=3&&s.strstart>0&&(prev=_win[scan=s.strstart-1])===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]){strend=s.strstart+258;do;while(prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&scan<strend)s.match_length=258-(strend-scan),s.match_length>s.lookahead&&(s.match_length=s.lookahead)}if(s.match_length>=3?(bflush=trees._tr_tally(s,1,s.match_length-3),s.lookahead-=s.match_length,s.strstart+=s.match_length,s.match_length=0):(bflush=trees._tr_tally(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++),bflush&&(flush_block_only(s,!1),0===s.strm.avail_out))return 1}return(s.insert=0,4===flush)?(flush_block_only(s,!0),0===s.strm.avail_out)?3:4:s.last_lit&&(flush_block_only(s,!1),0===s.strm.avail_out)?1:2}function deflate_huff(s,flush){for(var bflush;;){if(0===s.lookahead&&(fill_window(s),0===s.lookahead)){if(0===flush)return 1;break}if(s.match_length=0,bflush=trees._tr_tally(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++,bflush&&(flush_block_only(s,!1),0===s.strm.avail_out))return 1}return(s.insert=0,4===flush)?(flush_block_only(s,!0),0===s.strm.avail_out)?3:4:s.last_lit&&(flush_block_only(s,!1),0===s.strm.avail_out)?1:2}function Config(good_length,max_lazy,nice_length,max_chain,func){this.good_length=good_length,this.max_lazy=max_lazy,this.nice_length=nice_length,this.max_chain=max_chain,this.func=func}function lm_init(s){s.window_size=2*s.w_size,zero(s.head),s.max_lazy_match=configuration_table[s.level].max_lazy,s.good_match=configuration_table[s.level].good_length,s.nice_match=configuration_table[s.level].nice_length,s.max_chain_length=configuration_table[s.level].max_chain,s.strstart=0,s.block_start=0,s.lookahead=0,s.insert=0,s.match_length=s.prev_length=2,s.match_available=0,s.ins_h=0}function DeflateState(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=8,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new utils.Buf16(1146),this.dyn_dtree=new utils.Buf16(122),this.bl_tree=new utils.Buf16(78),zero(this.dyn_ltree),zero(this.dyn_dtree),zero(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new utils.Buf16(16),this.heap=new utils.Buf16(573),zero(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new utils.Buf16(573),zero(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function deflateResetKeep(strm){var s;return strm&&strm.state?(strm.total_in=strm.total_out=0,strm.data_type=2,(s=strm.state).pending=0,s.pending_out=0,s.wrap<0&&(s.wrap=-s.wrap),s.status=s.wrap?42:113,strm.adler=2===s.wrap?0:1,s.last_flush=0,trees._tr_init(s),0):err(strm,-2)}function deflateReset(strm){var ret=deflateResetKeep(strm);return 0===ret&&lm_init(strm.state),ret}function deflateSetHeader(strm,head){return strm&&strm.state&&2===strm.state.wrap?(strm.state.gzhead=head,0):-2}function deflateInit2(strm,level,method,windowBits,memLevel,strategy){if(!strm)return -2;var wrap=1;if(-1===level&&(level=6),windowBits<0?(wrap=0,windowBits=-windowBits):windowBits>15&&(wrap=2,windowBits-=16),memLevel<1||memLevel>9||8!==method||windowBits<8||windowBits>15||level<0||level>9||strategy<0||strategy>4)return err(strm,-2);8===windowBits&&(windowBits=9);var s=new DeflateState;return strm.state=s,s.strm=strm,s.wrap=wrap,s.gzhead=null,s.w_bits=windowBits,s.w_size=1<<s.w_bits,s.w_mask=s.w_size-1,s.hash_bits=memLevel+7,s.hash_size=1<<s.hash_bits,s.hash_mask=s.hash_size-1,s.hash_shift=~~((s.hash_bits+3-1)/3),s.window=new utils.Buf8(2*s.w_size),s.head=new utils.Buf16(s.hash_size),s.prev=new utils.Buf16(s.w_size),s.lit_bufsize=1<<memLevel+6,s.pending_buf_size=4*s.lit_bufsize,s.pending_buf=new utils.Buf8(s.pending_buf_size),s.d_buf=1*s.lit_bufsize,s.l_buf=3*s.lit_bufsize,s.level=level,s.strategy=strategy,s.method=method,deflateReset(strm)}function deflateInit(strm,level){return deflateInit2(strm,level,8,15,8,0)}function deflate(strm,flush){if(!strm||!strm.state||flush>5||flush<0)return strm?err(strm,-2):-2;if(s=strm.state,!strm.output||!strm.input&&0!==strm.avail_in||666===s.status&&4!==flush)return err(strm,0===strm.avail_out?-5:-2);if(s.strm=strm,old_flush=s.last_flush,s.last_flush=flush,42===s.status){if(2===s.wrap)strm.adler=0,put_byte(s,31),put_byte(s,139),put_byte(s,8),s.gzhead?(put_byte(s,(s.gzhead.text?1:0)+(s.gzhead.hcrc?2:0)+(s.gzhead.extra?4:0)+(s.gzhead.name?8:0)+(s.gzhead.comment?16:0)),put_byte(s,255&s.gzhead.time),put_byte(s,s.gzhead.time>>8&255),put_byte(s,s.gzhead.time>>16&255),put_byte(s,s.gzhead.time>>24&255),put_byte(s,9===s.level?2:s.strategy>=2||s.level<2?4:0),put_byte(s,255&s.gzhead.os),s.gzhead.extra&&s.gzhead.extra.length&&(put_byte(s,255&s.gzhead.extra.length),put_byte(s,s.gzhead.extra.length>>8&255)),s.gzhead.hcrc&&(strm.adler=crc32(strm.adler,s.pending_buf,s.pending,0)),s.gzindex=0,s.status=69):(put_byte(s,0),put_byte(s,0),put_byte(s,0),put_byte(s,0),put_byte(s,0),put_byte(s,9===s.level?2:s.strategy>=2||s.level<2?4:0),put_byte(s,3),s.status=113);else{var old_flush,s,beg,val,header=8+(s.w_bits-8<<4)<<8;header|=(s.strategy>=2||s.level<2?0:s.level<6?1:6===s.level?2:3)<<6,0!==s.strstart&&(header|=32),header+=31-header%31,s.status=113,putShortMSB(s,header),0!==s.strstart&&(putShortMSB(s,strm.adler>>>16),putShortMSB(s,65535&strm.adler)),strm.adler=1}}if(69===s.status){if(s.gzhead.extra){for(beg=s.pending;s.gzindex<(65535&s.gzhead.extra.length)&&(s.pending!==s.pending_buf_size||(s.gzhead.hcrc&&s.pending>beg&&(strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)),flush_pending(strm),beg=s.pending,s.pending!==s.pending_buf_size));)put_byte(s,255&s.gzhead.extra[s.gzindex]),s.gzindex++;s.gzhead.hcrc&&s.pending>beg&&(strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)),s.gzindex===s.gzhead.extra.length&&(s.gzindex=0,s.status=73)}else s.status=73}if(73===s.status){if(s.gzhead.name){beg=s.pending;do{if(s.pending===s.pending_buf_size&&(s.gzhead.hcrc&&s.pending>beg&&(strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)),flush_pending(strm),beg=s.pending,s.pending===s.pending_buf_size)){val=1;break}val=s.gzindex<s.gzhead.name.length?255&s.gzhead.name.charCodeAt(s.gzindex++):0,put_byte(s,val)}while(0!==val)s.gzhead.hcrc&&s.pending>beg&&(strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)),0===val&&(s.gzindex=0,s.status=91)}else s.status=91}if(91===s.status){if(s.gzhead.comment){beg=s.pending;do{if(s.pending===s.pending_buf_size&&(s.gzhead.hcrc&&s.pending>beg&&(strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)),flush_pending(strm),beg=s.pending,s.pending===s.pending_buf_size)){val=1;break}val=s.gzindex<s.gzhead.comment.length?255&s.gzhead.comment.charCodeAt(s.gzindex++):0,put_byte(s,val)}while(0!==val)s.gzhead.hcrc&&s.pending>beg&&(strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)),0===val&&(s.status=103)}else s.status=103}if(103===s.status&&(s.gzhead.hcrc?(s.pending+2>s.pending_buf_size&&flush_pending(strm),s.pending+2<=s.pending_buf_size&&(put_byte(s,255&strm.adler),put_byte(s,strm.adler>>8&255),strm.adler=0,s.status=113)):s.status=113),0!==s.pending){if(flush_pending(strm),0===strm.avail_out)return s.last_flush=-1,0}else if(0===strm.avail_in&&rank(flush)<=rank(old_flush)&&4!==flush)return err(strm,-5);if(666===s.status&&0!==strm.avail_in)return err(strm,-5);if(0!==strm.avail_in||0!==s.lookahead||0!==flush&&666!==s.status){var bstate=2===s.strategy?deflate_huff(s,flush):3===s.strategy?deflate_rle(s,flush):configuration_table[s.level].func(s,flush);if((3===bstate||4===bstate)&&(s.status=666),1===bstate||3===bstate)return 0===strm.avail_out&&(s.last_flush=-1),0;if(2===bstate&&(1===flush?trees._tr_align(s):5!==flush&&(trees._tr_stored_block(s,0,0,!1),3===flush&&(zero(s.head),0===s.lookahead&&(s.strstart=0,s.block_start=0,s.insert=0))),flush_pending(strm),0===strm.avail_out))return s.last_flush=-1,0}return 4!==flush?0:s.wrap<=0?1:(2===s.wrap?(put_byte(s,255&strm.adler),put_byte(s,strm.adler>>8&255),put_byte(s,strm.adler>>16&255),put_byte(s,strm.adler>>24&255),put_byte(s,255&strm.total_in),put_byte(s,strm.total_in>>8&255),put_byte(s,strm.total_in>>16&255),put_byte(s,strm.total_in>>24&255)):(putShortMSB(s,strm.adler>>>16),putShortMSB(s,65535&strm.adler)),flush_pending(strm),s.wrap>0&&(s.wrap=-s.wrap),0!==s.pending?0:1)}function deflateEnd(strm){var status;return strm&&strm.state?42!==(status=strm.state.status)&&69!==status&&73!==status&&91!==status&&103!==status&&113!==status&&666!==status?err(strm,-2):(strm.state=null,113===status?err(strm,-3):0):-2}function deflateSetDictionary(strm,dictionary){var s,str,n,wrap,avail,next,input,tmpDict,dictLength=dictionary.length;if(!strm||!strm.state||2===(wrap=(s=strm.state).wrap)||1===wrap&&42!==s.status||s.lookahead)return -2;for(1===wrap&&(strm.adler=adler32(strm.adler,dictionary,dictLength,0)),s.wrap=0,dictLength>=s.w_size&&(0===wrap&&(zero(s.head),s.strstart=0,s.block_start=0,s.insert=0),tmpDict=new utils.Buf8(s.w_size),utils.arraySet(tmpDict,dictionary,dictLength-s.w_size,s.w_size,0),dictionary=tmpDict,dictLength=s.w_size),avail=strm.avail_in,next=strm.next_in,input=strm.input,strm.avail_in=dictLength,strm.next_in=0,strm.input=dictionary,fill_window(s);s.lookahead>=3;){str=s.strstart,n=s.lookahead-2;do s.ins_h=(s.ins_h<<s.hash_shift^s.window[str+3-1])&s.hash_mask,s.prev[str&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=str,str++;while(--n)s.strstart=str,s.lookahead=2,fill_window(s)}return s.strstart+=s.lookahead,s.block_start=s.strstart,s.insert=s.lookahead,s.lookahead=0,s.match_length=s.prev_length=2,s.match_available=0,strm.next_in=next,strm.input=input,strm.avail_in=avail,s.wrap=wrap,0}configuration_table=[new Config(0,0,0,0,function deflate_stored(s,flush){var max_block_size=65535;for(65535>s.pending_buf_size-5&&(max_block_size=s.pending_buf_size-5);;){if(s.lookahead<=1){if(fill_window(s),0===s.lookahead&&0===flush)return 1;if(0===s.lookahead)break}s.strstart+=s.lookahead,s.lookahead=0;var max_start=s.block_start+max_block_size;if((0===s.strstart||s.strstart>=max_start)&&(s.lookahead=s.strstart-max_start,s.strstart=max_start,flush_block_only(s,!1),0===s.strm.avail_out)||s.strstart-s.block_start>=s.w_size-262&&(flush_block_only(s,!1),0===s.strm.avail_out))return 1}return(s.insert=0,4===flush)?(flush_block_only(s,!0),0===s.strm.avail_out)?3:4:(s.strstart>s.block_start&&(flush_block_only(s,!1),s.strm.avail_out),1)}),new Config(4,4,8,4,deflate_fast),new Config(4,5,16,8,deflate_fast),new Config(4,6,32,32,deflate_fast),new Config(4,4,16,16,deflate_slow),new Config(8,16,32,32,deflate_slow),new Config(8,16,128,128,deflate_slow),new Config(8,32,128,256,deflate_slow),new Config(32,128,258,1024,deflate_slow),new Config(32,258,258,4096,deflate_slow)],exports.deflateInit=deflateInit,exports.deflateInit2=deflateInit2,exports.deflateReset=deflateReset,exports.deflateResetKeep=deflateResetKeep,exports.deflateSetHeader=deflateSetHeader,exports.deflate=deflate,exports.deflateEnd=deflateEnd,exports.deflateSetDictionary=deflateSetDictionary,exports.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":140,"./adler32":141,"./crc32":143,"./messages":148,"./trees":149}],145:[function(require1,module,exports){"use strict";module.exports=function inflate_fast(strm,start){var state,_in,last,_out,beg,end,dmax,wsize,whave,wnext,s_window,hold,bits,lcode,dcode,lmask,dmask,here,op,len,dist,from,from_source,input,output;state=strm.state,_in=strm.next_in,input=strm.input,last=_in+(strm.avail_in-5),_out=strm.next_out,output=strm.output,beg=_out-(start-strm.avail_out),end=_out+(strm.avail_out-257),dmax=state.dmax,wsize=state.wsize,whave=state.whave,wnext=state.wnext,s_window=state.window,hold=state.hold,bits=state.bits,lcode=state.lencode,dcode=state.distcode,lmask=(1<<state.lenbits)-1,dmask=(1<<state.distbits)-1;top:do for(bits<15&&(hold+=input[_in++]<<bits,bits+=8,hold+=input[_in++]<<bits,bits+=8),here=lcode[hold&lmask];;){if(hold>>>=op=here>>>24,bits-=op,0==(op=here>>>16&255))output[_out++]=65535&here;else if(16&op)for(len=65535&here,(op&=15)&&(bits<op&&(hold+=input[_in++]<<bits,bits+=8),len+=hold&(1<<op)-1,hold>>>=op,bits-=op),bits<15&&(hold+=input[_in++]<<bits,bits+=8,hold+=input[_in++]<<bits,bits+=8),here=dcode[hold&dmask];;){if(hold>>>=op=here>>>24,bits-=op,16&(op=here>>>16&255)){if(dist=65535&here,bits<(op&=15)&&(hold+=input[_in++]<<bits,(bits+=8)<op&&(hold+=input[_in++]<<bits,bits+=8)),(dist+=hold&(1<<op)-1)>dmax){strm.msg="invalid distance too far back",state.mode=30;break top}if(hold>>>=op,bits-=op,dist>(op=_out-beg)){if((op=dist-op)>whave&&state.sane){strm.msg="invalid distance too far back",state.mode=30;break top}if(from=0,from_source=s_window,0===wnext){if(from+=wsize-op,op<len){len-=op;do output[_out++]=s_window[from++];while(--op)from=_out-dist,from_source=output}}else if(wnext<op){if(from+=wsize+wnext-op,(op-=wnext)<len){len-=op;do output[_out++]=s_window[from++];while(--op)if(from=0,wnext<len){len-=op=wnext;do output[_out++]=s_window[from++];while(--op)from=_out-dist,from_source=output}}}else if(from+=wnext-op,op<len){len-=op;do output[_out++]=s_window[from++];while(--op)from=_out-dist,from_source=output}for(;len>2;)output[_out++]=from_source[from++],output[_out++]=from_source[from++],output[_out++]=from_source[from++],len-=3;len&&(output[_out++]=from_source[from++],len>1&&(output[_out++]=from_source[from++]))}else{from=_out-dist;do output[_out++]=output[from++],output[_out++]=output[from++],output[_out++]=output[from++],len-=3;while(len>2)len&&(output[_out++]=output[from++],len>1&&(output[_out++]=output[from++]))}}else if((64&op)==0){here=dcode[(65535&here)+(hold&(1<<op)-1)];continue}else{strm.msg="invalid distance code",state.mode=30;break top}break}else if((64&op)==0){here=lcode[(65535&here)+(hold&(1<<op)-1)];continue}else if(32&op){state.mode=12;break top}else{strm.msg="invalid literal/length code",state.mode=30;break top}break}while(_in<last&&_out<end)_in-=len=bits>>3,bits-=len<<3,hold&=(1<<bits)-1,strm.next_in=_in,strm.next_out=_out,strm.avail_in=_in<last?5+(last-_in):5-(_in-last),strm.avail_out=_out<end?257+(end-_out):257-(_out-end),state.hold=hold,state.bits=bits}},{}],146:[function(require1,module,exports){"use strict";var lenfix,distfix,utils=require1("../utils/common"),adler32=require1("./adler32"),crc32=require1("./crc32"),inflate_fast=require1("./inffast"),inflate_table=require1("./inftrees");function zswap32(q){return(q>>>24&255)+(q>>>8&65280)+((65280&q)<<8)+((255&q)<<24)}function InflateState(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new utils.Buf16(320),this.work=new utils.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function inflateResetKeep(strm){var state;return strm&&strm.state?(state=strm.state,strm.total_in=strm.total_out=state.total=0,strm.msg="",state.wrap&&(strm.adler=1&state.wrap),state.mode=1,state.last=0,state.havedict=0,state.dmax=32768,state.head=null,state.hold=0,state.bits=0,state.lencode=state.lendyn=new utils.Buf32(852),state.distcode=state.distdyn=new utils.Buf32(592),state.sane=1,state.back=-1,0):-2}function inflateReset(strm){var state;return strm&&strm.state?((state=strm.state).wsize=0,state.whave=0,state.wnext=0,inflateResetKeep(strm)):-2}function inflateReset2(strm,windowBits){var wrap,state;return strm&&strm.state?(state=strm.state,windowBits<0?(wrap=0,windowBits=-windowBits):(wrap=(windowBits>>4)+1,windowBits<48&&(windowBits&=15)),windowBits&&(windowBits<8||windowBits>15))?-2:(null!==state.window&&state.wbits!==windowBits&&(state.window=null),state.wrap=wrap,state.wbits=windowBits,inflateReset(strm)):-2}function inflateInit2(strm,windowBits){var ret,state;return strm?(state=new InflateState,strm.state=state,state.window=null,0!==(ret=inflateReset2(strm,windowBits))&&(strm.state=null),ret):-2}function inflateInit(strm){return inflateInit2(strm,15)}var virgin=!0;function fixedtables(state){if(virgin){var sym;for(lenfix=new utils.Buf32(512),distfix=new utils.Buf32(32),sym=0;sym<144;)state.lens[sym++]=8;for(;sym<256;)state.lens[sym++]=9;for(;sym<280;)state.lens[sym++]=7;for(;sym<288;)state.lens[sym++]=8;for(inflate_table(1,state.lens,0,288,lenfix,0,state.work,{bits:9}),sym=0;sym<32;)state.lens[sym++]=5;inflate_table(2,state.lens,0,32,distfix,0,state.work,{bits:5}),virgin=!1}state.lencode=lenfix,state.lenbits=9,state.distcode=distfix,state.distbits=5}function updatewindow(strm,src,end,copy){var dist,state=strm.state;return null===state.window&&(state.wsize=1<<state.wbits,state.wnext=0,state.whave=0,state.window=new utils.Buf8(state.wsize)),copy>=state.wsize?(utils.arraySet(state.window,src,end-state.wsize,state.wsize,0),state.wnext=0,state.whave=state.wsize):((dist=state.wsize-state.wnext)>copy&&(dist=copy),utils.arraySet(state.window,src,end-copy,dist,state.wnext),(copy-=dist)?(utils.arraySet(state.window,src,end-copy,copy,0),state.wnext=copy,state.whave=state.wsize):(state.wnext+=dist,state.wnext===state.wsize&&(state.wnext=0),state.whave<state.wsize&&(state.whave+=dist))),0}function inflate(strm,flush){var state,input,output,next,put,have,left,hold,bits,_in,_out,copy,from,from_source,here_bits,here_op,here_val,last_bits,last_op,last_val,len,ret,opts,n,here=0,hbuf=new utils.Buf8(4),order=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!strm||!strm.state||!strm.output||!strm.input&&0!==strm.avail_in)return -2;12===(state=strm.state).mode&&(state.mode=13),put=strm.next_out,output=strm.output,left=strm.avail_out,next=strm.next_in,input=strm.input,have=strm.avail_in,hold=state.hold,bits=state.bits,_in=have,_out=left,ret=0;inf_leave:for(;;)switch(state.mode){case 1:if(0===state.wrap){state.mode=13;break}for(;bits<16;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(2&state.wrap&&35615===hold){state.check=0,hbuf[0]=255&hold,hbuf[1]=hold>>>8&255,state.check=crc32(state.check,hbuf,2,0),hold=0,bits=0,state.mode=2;break}if(state.flags=0,state.head&&(state.head.done=!1),!(1&state.wrap)||(((255&hold)<<8)+(hold>>8))%31){strm.msg="incorrect header check",state.mode=30;break}if((15&hold)!=8){strm.msg="unknown compression method",state.mode=30;break}if(hold>>>=4,bits-=4,len=(15&hold)+8,0===state.wbits)state.wbits=len;else if(len>state.wbits){strm.msg="invalid window size",state.mode=30;break}state.dmax=1<<len,strm.adler=state.check=1,state.mode=512&hold?10:12,hold=0,bits=0;break;case 2:for(;bits<16;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(state.flags=hold,(255&state.flags)!=8){strm.msg="unknown compression method",state.mode=30;break}if(57344&state.flags){strm.msg="unknown header flags set",state.mode=30;break}state.head&&(state.head.text=hold>>8&1),512&state.flags&&(hbuf[0]=255&hold,hbuf[1]=hold>>>8&255,state.check=crc32(state.check,hbuf,2,0)),hold=0,bits=0,state.mode=3;case 3:for(;bits<32;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}state.head&&(state.head.time=hold),512&state.flags&&(hbuf[0]=255&hold,hbuf[1]=hold>>>8&255,hbuf[2]=hold>>>16&255,hbuf[3]=hold>>>24&255,state.check=crc32(state.check,hbuf,4,0)),hold=0,bits=0,state.mode=4;case 4:for(;bits<16;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}state.head&&(state.head.xflags=255&hold,state.head.os=hold>>8),512&state.flags&&(hbuf[0]=255&hold,hbuf[1]=hold>>>8&255,state.check=crc32(state.check,hbuf,2,0)),hold=0,bits=0,state.mode=5;case 5:if(1024&state.flags){for(;bits<16;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}state.length=hold,state.head&&(state.head.extra_len=hold),512&state.flags&&(hbuf[0]=255&hold,hbuf[1]=hold>>>8&255,state.check=crc32(state.check,hbuf,2,0)),hold=0,bits=0}else state.head&&(state.head.extra=null);state.mode=6;case 6:if(1024&state.flags&&((copy=state.length)>have&&(copy=have),copy&&(state.head&&(len=state.head.extra_len-state.length,state.head.extra||(state.head.extra=Array(state.head.extra_len)),utils.arraySet(state.head.extra,input,next,copy,len)),512&state.flags&&(state.check=crc32(state.check,input,copy,next)),have-=copy,next+=copy,state.length-=copy),state.length))break inf_leave;state.length=0,state.mode=7;case 7:if(2048&state.flags){if(0===have)break inf_leave;copy=0;do len=input[next+copy++],state.head&&len&&state.length<65536&&(state.head.name+=String.fromCharCode(len));while(len&©<have)if(512&state.flags&&(state.check=crc32(state.check,input,copy,next)),have-=copy,next+=copy,len)break inf_leave}else state.head&&(state.head.name=null);state.length=0,state.mode=8;case 8:if(4096&state.flags){if(0===have)break inf_leave;copy=0;do len=input[next+copy++],state.head&&len&&state.length<65536&&(state.head.comment+=String.fromCharCode(len));while(len&©<have)if(512&state.flags&&(state.check=crc32(state.check,input,copy,next)),have-=copy,next+=copy,len)break inf_leave}else state.head&&(state.head.comment=null);state.mode=9;case 9:if(512&state.flags){for(;bits<16;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(hold!==(65535&state.check)){strm.msg="header crc mismatch",state.mode=30;break}hold=0,bits=0}state.head&&(state.head.hcrc=state.flags>>9&1,state.head.done=!0),strm.adler=state.check=0,state.mode=12;break;case 10:for(;bits<32;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}strm.adler=state.check=zswap32(hold),hold=0,bits=0,state.mode=11;case 11:if(0===state.havedict)return strm.next_out=put,strm.avail_out=left,strm.next_in=next,strm.avail_in=have,state.hold=hold,state.bits=bits,2;strm.adler=state.check=1,state.mode=12;case 12:if(5===flush||6===flush)break inf_leave;case 13:if(state.last){hold>>>=7&bits,bits-=7&bits,state.mode=27;break}for(;bits<3;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}switch(state.last=1&hold,bits-=1,3&(hold>>>=1)){case 0:state.mode=14;break;case 1:if(fixedtables(state),state.mode=20,6===flush){hold>>>=2,bits-=2;break inf_leave}break;case 2:state.mode=17;break;case 3:strm.msg="invalid block type",state.mode=30}hold>>>=2,bits-=2;break;case 14:for(hold>>>=7&bits,bits-=7&bits;bits<32;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if((65535&hold)!=(hold>>>16^65535)){strm.msg="invalid stored block lengths",state.mode=30;break}if(state.length=65535&hold,hold=0,bits=0,state.mode=15,6===flush)break inf_leave;case 15:state.mode=16;case 16:if(copy=state.length){if(copy>have&&(copy=have),copy>left&&(copy=left),0===copy)break inf_leave;utils.arraySet(output,input,next,copy,put),have-=copy,next+=copy,left-=copy,put+=copy,state.length-=copy;break}state.mode=12;break;case 17:for(;bits<14;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(state.nlen=(31&hold)+257,hold>>>=5,bits-=5,state.ndist=(31&hold)+1,hold>>>=5,bits-=5,state.ncode=(15&hold)+4,hold>>>=4,bits-=4,state.nlen>286||state.ndist>30){strm.msg="too many length or distance symbols",state.mode=30;break}state.have=0,state.mode=18;case 18:for(;state.have<state.ncode;){for(;bits<3;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}state.lens[order[state.have++]]=7&hold,hold>>>=3,bits-=3}for(;state.have<19;)state.lens[order[state.have++]]=0;if(state.lencode=state.lendyn,state.lenbits=7,opts={bits:state.lenbits},ret=inflate_table(0,state.lens,0,19,state.lencode,0,state.work,opts),state.lenbits=opts.bits,ret){strm.msg="invalid code lengths set",state.mode=30;break}state.have=0,state.mode=19;case 19:for(;state.have<state.nlen+state.ndist;){for(;here_bits=(here=state.lencode[hold&(1<<state.lenbits)-1])>>>24,here_op=here>>>16&255,here_val=65535&here,!(here_bits<=bits);){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(here_val<16)hold>>>=here_bits,bits-=here_bits,state.lens[state.have++]=here_val;else{if(16===here_val){for(n=here_bits+2;bits<n;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(hold>>>=here_bits,bits-=here_bits,0===state.have){strm.msg="invalid bit length repeat",state.mode=30;break}len=state.lens[state.have-1],copy=3+(3&hold),hold>>>=2,bits-=2}else if(17===here_val){for(n=here_bits+3;bits<n;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}hold>>>=here_bits,bits-=here_bits,len=0,copy=3+(7&hold),hold>>>=3,bits-=3}else{for(n=here_bits+7;bits<n;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}hold>>>=here_bits,bits-=here_bits,len=0,copy=11+(127&hold),hold>>>=7,bits-=7}if(state.have+copy>state.nlen+state.ndist){strm.msg="invalid bit length repeat",state.mode=30;break}for(;copy--;)state.lens[state.have++]=len}}if(30===state.mode)break;if(0===state.lens[256]){strm.msg="invalid code -- missing end-of-block",state.mode=30;break}if(state.lenbits=9,opts={bits:state.lenbits},ret=inflate_table(1,state.lens,0,state.nlen,state.lencode,0,state.work,opts),state.lenbits=opts.bits,ret){strm.msg="invalid literal/lengths set",state.mode=30;break}if(state.distbits=6,state.distcode=state.distdyn,opts={bits:state.distbits},ret=inflate_table(2,state.lens,state.nlen,state.ndist,state.distcode,0,state.work,opts),state.distbits=opts.bits,ret){strm.msg="invalid distances set",state.mode=30;break}if(state.mode=20,6===flush)break inf_leave;case 20:state.mode=21;case 21:if(have>=6&&left>=258){strm.next_out=put,strm.avail_out=left,strm.next_in=next,strm.avail_in=have,state.hold=hold,state.bits=bits,inflate_fast(strm,_out),put=strm.next_out,output=strm.output,left=strm.avail_out,next=strm.next_in,input=strm.input,have=strm.avail_in,hold=state.hold,bits=state.bits,12===state.mode&&(state.back=-1);break}for(state.back=0;here_bits=(here=state.lencode[hold&(1<<state.lenbits)-1])>>>24,here_op=here>>>16&255,here_val=65535&here,!(here_bits<=bits);){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(here_op&&(240&here_op)==0){for(last_bits=here_bits,last_op=here_op,last_val=here_val;here_bits=(here=state.lencode[last_val+((hold&(1<<last_bits+last_op)-1)>>last_bits)])>>>24,here_op=here>>>16&255,here_val=65535&here,!(last_bits+here_bits<=bits);){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}hold>>>=last_bits,bits-=last_bits,state.back+=last_bits}if(hold>>>=here_bits,bits-=here_bits,state.back+=here_bits,state.length=here_val,0===here_op){state.mode=26;break}if(32&here_op){state.back=-1,state.mode=12;break}if(64&here_op){strm.msg="invalid literal/length code",state.mode=30;break}state.extra=15&here_op,state.mode=22;case 22:if(state.extra){for(n=state.extra;bits<n;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}state.length+=hold&(1<<state.extra)-1,hold>>>=state.extra,bits-=state.extra,state.back+=state.extra}state.was=state.length,state.mode=23;case 23:for(;here_bits=(here=state.distcode[hold&(1<<state.distbits)-1])>>>24,here_op=here>>>16&255,here_val=65535&here,!(here_bits<=bits);){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if((240&here_op)==0){for(last_bits=here_bits,last_op=here_op,last_val=here_val;here_bits=(here=state.distcode[last_val+((hold&(1<<last_bits+last_op)-1)>>last_bits)])>>>24,here_op=here>>>16&255,here_val=65535&here,!(last_bits+here_bits<=bits);){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}hold>>>=last_bits,bits-=last_bits,state.back+=last_bits}if(hold>>>=here_bits,bits-=here_bits,state.back+=here_bits,64&here_op){strm.msg="invalid distance code",state.mode=30;break}state.offset=here_val,state.extra=15&here_op,state.mode=24;case 24:if(state.extra){for(n=state.extra;bits<n;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}state.offset+=hold&(1<<state.extra)-1,hold>>>=state.extra,bits-=state.extra,state.back+=state.extra}if(state.offset>state.dmax){strm.msg="invalid distance too far back",state.mode=30;break}state.mode=25;case 25:if(0===left)break inf_leave;if(copy=_out-left,state.offset>copy){if((copy=state.offset-copy)>state.whave&&state.sane){strm.msg="invalid distance too far back",state.mode=30;break}copy>state.wnext?(copy-=state.wnext,from=state.wsize-copy):from=state.wnext-copy,copy>state.length&&(copy=state.length),from_source=state.window}else from_source=output,from=put-state.offset,copy=state.length;copy>left&&(copy=left),left-=copy,state.length-=copy;do output[put++]=from_source[from++];while(--copy)0===state.length&&(state.mode=21);break;case 26:if(0===left)break inf_leave;output[put++]=state.length,left--,state.mode=21;break;case 27:if(state.wrap){for(;bits<32;){if(0===have)break inf_leave;have--,hold|=input[next++]<<bits,bits+=8}if(_out-=left,strm.total_out+=_out,state.total+=_out,_out&&(strm.adler=state.check=state.flags?crc32(state.check,output,_out,put-_out):adler32(state.check,output,_out,put-_out)),_out=left,(state.flags?hold:zswap32(hold))!==state.check){strm.msg="incorrect data check",state.mode=30;break}hold=0,bits=0}state.mode=28;case 28:if(state.wrap&&state.flags){for(;bits<32;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(hold!==(4294967295&state.total)){strm.msg="incorrect length check",state.mode=30;break}hold=0,bits=0}state.mode=29;case 29:ret=1;break inf_leave;case 30:ret=-3;break inf_leave;case 31:return -4;default:return -2}return(strm.next_out=put,strm.avail_out=left,strm.next_in=next,strm.avail_in=have,state.hold=hold,state.bits=bits,(state.wsize||_out!==strm.avail_out&&state.mode<30&&(state.mode<27||4!==flush))&&updatewindow(strm,strm.output,strm.next_out,_out-strm.avail_out))?(state.mode=31,-4):(_in-=strm.avail_in,_out-=strm.avail_out,strm.total_in+=_in,strm.total_out+=_out,state.total+=_out,state.wrap&&_out&&(strm.adler=state.check=state.flags?crc32(state.check,output,_out,strm.next_out-_out):adler32(state.check,output,_out,strm.next_out-_out)),strm.data_type=state.bits+(state.last?64:0)+(12===state.mode?128:0)+(20===state.mode||15===state.mode?256:0),(0===_in&&0===_out||4===flush)&&0===ret&&(ret=-5),ret)}function inflateEnd(strm){if(!strm||!strm.state)return -2;var state=strm.state;return state.window&&(state.window=null),strm.state=null,0}function inflateGetHeader(strm,head){var state;return strm&&strm.state&&(2&(state=strm.state).wrap)!=0?(state.head=head,head.done=!1,0):-2}function inflateSetDictionary(strm,dictionary){var state,dictLength=dictionary.length;return strm&&strm.state&&(0===(state=strm.state).wrap||11===state.mode)?11===state.mode&&adler32(1,dictionary,dictLength,0)!==state.check?-3:updatewindow(strm,dictionary,dictLength,dictLength)?(state.mode=31,-4):(state.havedict=1,0):-2}exports.inflateReset=inflateReset,exports.inflateReset2=inflateReset2,exports.inflateResetKeep=inflateResetKeep,exports.inflateInit=inflateInit,exports.inflateInit2=inflateInit2,exports.inflate=inflate,exports.inflateEnd=inflateEnd,exports.inflateGetHeader=inflateGetHeader,exports.inflateSetDictionary=inflateSetDictionary,exports.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":140,"./adler32":141,"./crc32":143,"./inffast":145,"./inftrees":147}],147:[function(require1,module,exports){"use strict";var utils=require1("../utils/common"),lbase=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],lext=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],dbase=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],dext=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];module.exports=function inflate_table(type,lens,lens_index,codes,table,table_index,work,opts){var incr,fill,low,mask,next,end,here_bits,here_op,here_val,bits=opts.bits,len=0,sym=0,min=0,max=0,root=0,curr=0,drop=0,left=0,used=0,huff=0,base=null,base_index=0,count=new utils.Buf16(16),offs=new utils.Buf16(16),extra=null,extra_index=0;for(len=0;len<=15;len++)count[len]=0;for(sym=0;sym<codes;sym++)count[lens[lens_index+sym]]++;for(max=15,root=bits;max>=1&&0===count[max];max--);if(root>max&&(root=max),0===max)return table[table_index++]=20971520,table[table_index++]=20971520,opts.bits=1,0;for(min=1;min<max&&0===count[min];min++);for(root<min&&(root=min),left=1,len=1;len<=15;len++)if(left<<=1,(left-=count[len])<0)return -1;if(left>0&&(0===type||1!==max))return -1;for(len=1,offs[1]=0;len<15;len++)offs[len+1]=offs[len]+count[len];for(sym=0;sym<codes;sym++)0!==lens[lens_index+sym]&&(work[offs[lens[lens_index+sym]]++]=sym);if(0===type?(base=extra=work,end=19):1===type?(base=lbase,base_index-=257,extra=lext,extra_index-=257,end=256):(base=dbase,extra=dext,end=-1),huff=0,sym=0,len=min,next=table_index,curr=root,drop=0,low=-1,mask=(used=1<<root)-1,1===type&&used>852||2===type&&used>592)return 1;for(;;){here_bits=len-drop,work[sym]<end?(here_op=0,here_val=work[sym]):work[sym]>end?(here_op=extra[extra_index+work[sym]],here_val=base[base_index+work[sym]]):(here_op=96,here_val=0),incr=1<<len-drop,min=fill=1<<curr;do table[next+(huff>>drop)+(fill-=incr)]=here_bits<<24|here_op<<16|here_val|0;while(0!==fill)for(incr=1<<len-1;huff&incr;)incr>>=1;if(0!==incr?(huff&=incr-1,huff+=incr):huff=0,sym++,0==--count[len]){if(len===max)break;len=lens[lens_index+work[sym]]}if(len>root&&(huff&mask)!==low){for(0===drop&&(drop=root),next+=min,left=1<<(curr=len-drop);curr+drop<max&&!((left-=count[curr+drop])<=0);)curr++,left<<=1;if(used+=1<<curr,1===type&&used>852||2===type&&used>592)return 1;table[low=huff&mask]=root<<24|curr<<16|next-table_index|0}}return 0!==huff&&(table[next+huff]=len-drop<<24|4194304),opts.bits=root,0}},{"../utils/common":140}],148:[function(require1,module,exports){"use strict";module.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],149:[function(require1,module,exports){"use strict";var static_l_desc,static_d_desc,static_bl_desc,utils=require1("../utils/common");function zero(buf){for(var len=buf.length;--len>=0;)buf[len]=0}var extra_lbits=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],extra_dbits=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],extra_blbits=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],bl_order=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],static_ltree=Array(576);zero(static_ltree);var static_dtree=Array(60);zero(static_dtree);var _dist_code=Array(512);zero(_dist_code);var _length_code=Array(256);zero(_length_code);var base_length=Array(29);zero(base_length);var base_dist=Array(30);function StaticTreeDesc(static_tree,extra_bits,extra_base,elems,max_length){this.static_tree=static_tree,this.extra_bits=extra_bits,this.extra_base=extra_base,this.elems=elems,this.max_length=max_length,this.has_stree=static_tree&&static_tree.length}function TreeDesc(dyn_tree,stat_desc){this.dyn_tree=dyn_tree,this.max_code=0,this.stat_desc=stat_desc}function d_code(dist){return dist<256?_dist_code[dist]:_dist_code[256+(dist>>>7)]}function put_short(s,w){s.pending_buf[s.pending++]=255&w,s.pending_buf[s.pending++]=w>>>8&255}function send_bits(s,value,length){s.bi_valid>16-length?(s.bi_buf|=value<<s.bi_valid&65535,put_short(s,s.bi_buf),s.bi_buf=value>>16-s.bi_valid,s.bi_valid+=length-16):(s.bi_buf|=value<<s.bi_valid&65535,s.bi_valid+=length)}function send_code(s,c,tree){send_bits(s,tree[2*c],tree[2*c+1])}function bi_reverse(code,len){var res=0;do res|=1&code,code>>>=1,res<<=1;while(--len>0)return res>>>1}function bi_flush(s){16===s.bi_valid?(put_short(s,s.bi_buf),s.bi_buf=0,s.bi_valid=0):s.bi_valid>=8&&(s.pending_buf[s.pending++]=255&s.bi_buf,s.bi_buf>>=8,s.bi_valid-=8)}function gen_bitlen(s,desc){var h,n,m,bits,xbits,f,tree=desc.dyn_tree,max_code=desc.max_code,stree=desc.stat_desc.static_tree,has_stree=desc.stat_desc.has_stree,extra=desc.stat_desc.extra_bits,base=desc.stat_desc.extra_base,max_length=desc.stat_desc.max_length,overflow=0;for(bits=0;bits<=15;bits++)s.bl_count[bits]=0;for(tree[2*s.heap[s.heap_max]+1]=0,h=s.heap_max+1;h<573;h++)(bits=tree[2*tree[2*(n=s.heap[h])+1]+1]+1)>max_length&&(bits=max_length,overflow++),tree[2*n+1]=bits,!(n>max_code)&&(s.bl_count[bits]++,xbits=0,n>=base&&(xbits=extra[n-base]),f=tree[2*n],s.opt_len+=f*(bits+xbits),has_stree&&(s.static_len+=f*(stree[2*n+1]+xbits)));if(0!==overflow){do{for(bits=max_length-1;0===s.bl_count[bits];)bits--;s.bl_count[bits]--,s.bl_count[bits+1]+=2,s.bl_count[max_length]--,overflow-=2}while(overflow>0)for(bits=max_length;0!==bits;bits--)for(n=s.bl_count[bits];0!==n;)!((m=s.heap[--h])>max_code)&&(tree[2*m+1]!==bits&&(s.opt_len+=(bits-tree[2*m+1])*tree[2*m],tree[2*m+1]=bits),n--)}}function gen_codes(tree,max_code,bl_count){var bits,n,next_code=Array(16),code=0;for(bits=1;bits<=15;bits++)next_code[bits]=code=code+bl_count[bits-1]<<1;for(n=0;n<=max_code;n++){var len=tree[2*n+1];0!==len&&(tree[2*n]=bi_reverse(next_code[len]++,len))}}function tr_static_init(){var n,bits,length,code,dist,bl_count=Array(16);for(code=0,length=0;code<28;code++)for(n=0,base_length[code]=length;n<1<<extra_lbits[code];n++)_length_code[length++]=code;for(_length_code[length-1]=code,dist=0,code=0;code<16;code++)for(n=0,base_dist[code]=dist;n<1<<extra_dbits[code];n++)_dist_code[dist++]=code;for(dist>>=7;code<30;code++)for(n=0,base_dist[code]=dist<<7;n<1<<extra_dbits[code]-7;n++)_dist_code[256+dist++]=code;for(bits=0;bits<=15;bits++)bl_count[bits]=0;for(n=0;n<=143;)static_ltree[2*n+1]=8,n++,bl_count[8]++;for(;n<=255;)static_ltree[2*n+1]=9,n++,bl_count[9]++;for(;n<=279;)static_ltree[2*n+1]=7,n++,bl_count[7]++;for(;n<=287;)static_ltree[2*n+1]=8,n++,bl_count[8]++;for(gen_codes(static_ltree,287,bl_count),n=0;n<30;n++)static_dtree[2*n+1]=5,static_dtree[2*n]=bi_reverse(n,5);static_l_desc=new StaticTreeDesc(static_ltree,extra_lbits,257,286,15),static_d_desc=new StaticTreeDesc(static_dtree,extra_dbits,0,30,15),static_bl_desc=new StaticTreeDesc([],extra_blbits,0,19,7)}function init_block(s){var n;for(n=0;n<286;n++)s.dyn_ltree[2*n]=0;for(n=0;n<30;n++)s.dyn_dtree[2*n]=0;for(n=0;n<19;n++)s.bl_tree[2*n]=0;s.dyn_ltree[512]=1,s.opt_len=s.static_len=0,s.last_lit=s.matches=0}function bi_windup(s){s.bi_valid>8?put_short(s,s.bi_buf):s.bi_valid>0&&(s.pending_buf[s.pending++]=s.bi_buf),s.bi_buf=0,s.bi_valid=0}function copy_block(s,buf,len,header){bi_windup(s),header&&(put_short(s,len),put_short(s,~len)),utils.arraySet(s.pending_buf,s.window,buf,len,s.pending),s.pending+=len}function smaller(tree,n,m,depth){var _n2=2*n,_m2=2*m;return tree[_n2]<tree[_m2]||tree[_n2]===tree[_m2]&&depth[n]<=depth[m]}function pqdownheap(s,tree,k){for(var v=s.heap[k],j=k<<1;j<=s.heap_len&&(j<s.heap_len&&smaller(tree,s.heap[j+1],s.heap[j],s.depth)&&j++,!smaller(tree,v,s.heap[j],s.depth));)s.heap[k]=s.heap[j],k=j,j<<=1;s.heap[k]=v}function compress_block(s,ltree,dtree){var dist,lc,code,extra,lx=0;if(0!==s.last_lit)do dist=s.pending_buf[s.d_buf+2*lx]<<8|s.pending_buf[s.d_buf+2*lx+1],lc=s.pending_buf[s.l_buf+lx],lx++,0===dist?send_code(s,lc,ltree):(send_code(s,(code=_length_code[lc])+256+1,ltree),0!==(extra=extra_lbits[code])&&send_bits(s,lc-=base_length[code],extra),send_code(s,code=d_code(--dist),dtree),0!==(extra=extra_dbits[code])&&send_bits(s,dist-=base_dist[code],extra));while(lx<s.last_lit)send_code(s,256,ltree)}function build_tree(s,desc){var n,m,node,tree=desc.dyn_tree,stree=desc.stat_desc.static_tree,has_stree=desc.stat_desc.has_stree,elems=desc.stat_desc.elems,max_code=-1;for(n=0,s.heap_len=0,s.heap_max=573;n<elems;n++)0!==tree[2*n]?(s.heap[++s.heap_len]=max_code=n,s.depth[n]=0):tree[2*n+1]=0;for(;s.heap_len<2;)tree[2*(node=s.heap[++s.heap_len]=max_code<2?++max_code:0)]=1,s.depth[node]=0,s.opt_len--,has_stree&&(s.static_len-=stree[2*node+1]);for(desc.max_code=max_code,n=s.heap_len>>1;n>=1;n--)pqdownheap(s,tree,n);node=elems;do n=s.heap[1],s.heap[1]=s.heap[s.heap_len--],pqdownheap(s,tree,1),m=s.heap[1],s.heap[--s.heap_max]=n,s.heap[--s.heap_max]=m,tree[2*node]=tree[2*n]+tree[2*m],s.depth[node]=(s.depth[n]>=s.depth[m]?s.depth[n]:s.depth[m])+1,tree[2*n+1]=tree[2*m+1]=node,s.heap[1]=node++,pqdownheap(s,tree,1);while(s.heap_len>=2)s.heap[--s.heap_max]=s.heap[1],gen_bitlen(s,desc),gen_codes(tree,max_code,s.bl_count)}function scan_tree(s,tree,max_code){var n,curlen,prevlen=-1,nextlen=tree[1],count=0,max_count=7,min_count=4;for(0===nextlen&&(max_count=138,min_count=3),tree[(max_code+1)*2+1]=65535,n=0;n<=max_code;n++)curlen=nextlen,nextlen=tree[(n+1)*2+1],++count<max_count&&curlen===nextlen||(count<min_count?s.bl_tree[2*curlen]+=count:0!==curlen?(curlen!==prevlen&&s.bl_tree[2*curlen]++,s.bl_tree[32]++):count<=10?s.bl_tree[34]++:s.bl_tree[36]++,count=0,prevlen=curlen,0===nextlen?(max_count=138,min_count=3):curlen===nextlen?(max_count=6,min_count=3):(max_count=7,min_count=4))}function send_tree(s,tree,max_code){var n,curlen,prevlen=-1,nextlen=tree[1],count=0,max_count=7,min_count=4;for(0===nextlen&&(max_count=138,min_count=3),n=0;n<=max_code;n++)if(curlen=nextlen,nextlen=tree[(n+1)*2+1],!(++count<max_count)||curlen!==nextlen){if(count<min_count)do send_code(s,curlen,s.bl_tree);while(0!=--count)else 0!==curlen?(curlen!==prevlen&&(send_code(s,curlen,s.bl_tree),count--),send_code(s,16,s.bl_tree),send_bits(s,count-3,2)):count<=10?(send_code(s,17,s.bl_tree),send_bits(s,count-3,3)):(send_code(s,18,s.bl_tree),send_bits(s,count-11,7));count=0,prevlen=curlen,0===nextlen?(max_count=138,min_count=3):curlen===nextlen?(max_count=6,min_count=3):(max_count=7,min_count=4)}}function build_bl_tree(s){var max_blindex;for(scan_tree(s,s.dyn_ltree,s.l_desc.max_code),scan_tree(s,s.dyn_dtree,s.d_desc.max_code),build_tree(s,s.bl_desc),max_blindex=18;max_blindex>=3&&0===s.bl_tree[2*bl_order[max_blindex]+1];max_blindex--);return s.opt_len+=3*(max_blindex+1)+5+5+4,max_blindex}function send_all_trees(s,lcodes,dcodes,blcodes){var rank;for(send_bits(s,lcodes-257,5),send_bits(s,dcodes-1,5),send_bits(s,blcodes-4,4),rank=0;rank<blcodes;rank++)send_bits(s,s.bl_tree[2*bl_order[rank]+1],3);send_tree(s,s.dyn_ltree,lcodes-1),send_tree(s,s.dyn_dtree,dcodes-1)}function detect_data_type(s){var n,black_mask=4093624447;for(n=0;n<=31;n++,black_mask>>>=1)if(1&black_mask&&0!==s.dyn_ltree[2*n])return 0;if(0!==s.dyn_ltree[18]||0!==s.dyn_ltree[20]||0!==s.dyn_ltree[26])return 1;for(n=32;n<256;n++)if(0!==s.dyn_ltree[2*n])return 1;return 0}zero(base_dist);var static_init_done=!1;function _tr_init(s){static_init_done||(tr_static_init(),static_init_done=!0),s.l_desc=new TreeDesc(s.dyn_ltree,static_l_desc),s.d_desc=new TreeDesc(s.dyn_dtree,static_d_desc),s.bl_desc=new TreeDesc(s.bl_tree,static_bl_desc),s.bi_buf=0,s.bi_valid=0,init_block(s)}function _tr_stored_block(s,buf,stored_len,last){send_bits(s,0+(last?1:0),3),copy_block(s,buf,stored_len,!0)}function _tr_align(s){send_bits(s,2,3),send_code(s,256,static_ltree),bi_flush(s)}function _tr_flush_block(s,buf,stored_len,last){var opt_lenb,static_lenb,max_blindex=0;s.level>0?(2===s.strm.data_type&&(s.strm.data_type=detect_data_type(s)),build_tree(s,s.l_desc),build_tree(s,s.d_desc),max_blindex=build_bl_tree(s),opt_lenb=s.opt_len+3+7>>>3,(static_lenb=s.static_len+3+7>>>3)<=opt_lenb&&(opt_lenb=static_lenb)):opt_lenb=static_lenb=stored_len+5,stored_len+4<=opt_lenb&&-1!==buf?_tr_stored_block(s,buf,stored_len,last):4===s.strategy||static_lenb===opt_lenb?(send_bits(s,2+(last?1:0),3),compress_block(s,static_ltree,static_dtree)):(send_bits(s,4+(last?1:0),3),send_all_trees(s,s.l_desc.max_code+1,s.d_desc.max_code+1,max_blindex+1),compress_block(s,s.dyn_ltree,s.dyn_dtree)),init_block(s),last&&bi_windup(s)}function _tr_tally(s,dist,lc){return s.pending_buf[s.d_buf+2*s.last_lit]=dist>>>8&255,s.pending_buf[s.d_buf+2*s.last_lit+1]=255&dist,s.pending_buf[s.l_buf+s.last_lit]=255&lc,s.last_lit++,0===dist?s.dyn_ltree[2*lc]++:(s.matches++,dist--,s.dyn_ltree[(_length_code[lc]+256+1)*2]++,s.dyn_dtree[2*d_code(dist)]++),s.last_lit===s.lit_bufsize-1}exports._tr_init=_tr_init,exports._tr_stored_block=_tr_stored_block,exports._tr_flush_block=_tr_flush_block,exports._tr_tally=_tr_tally,exports._tr_align=_tr_align},{"../utils/common":140}],150:[function(require1,module,exports){"use strict";function ZStream(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}module.exports=ZStream},{}],151:[function(require1,module,exports){(function(process){(function(){"use strict";function nextTick(fn,arg1,arg2,arg3){if("function"!=typeof fn)throw TypeError('"callback" argument must be a function');var args,i,len=arguments.length;switch(len){case 0:case 1:return process.nextTick(fn);case 2:return process.nextTick(function afterTickOne(){fn.call(null,arg1)});case 3:return process.nextTick(function afterTickTwo(){fn.call(null,arg1,arg2)});case 4:return process.nextTick(function afterTickThree(){fn.call(null,arg1,arg2,arg3)});default:for(args=Array(len-1),i=0;i<args.length;)args[i++]=arguments[i];return process.nextTick(function afterTick(){fn.apply(null,args)})}}void 0!==process&&process.version&&0!==process.version.indexOf("v0.")&&(0!==process.version.indexOf("v1.")||0===process.version.indexOf("v1.8."))?module.exports=process:module.exports={nextTick:nextTick}}).call(this)}).call(this,require1("_process"))},{_process:152}],152:[function(require1,module,exports){var cachedSetTimeout,cachedClearTimeout,currentQueue,process=module.exports={};function defaultSetTimout(){throw Error("setTimeout has not been defined")}function defaultClearTimeout(){throw Error("clearTimeout has not been defined")}function runTimeout(fun){if(cachedSetTimeout===setTimeout)return setTimeout(fun,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(fun,0);try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout)return clearTimeout(marker);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(marker);try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}!function(){try{cachedSetTimeout="function"==typeof setTimeout?setTimeout:defaultSetTimout}catch(e){cachedSetTimeout=defaultSetTimout}try{cachedClearTimeout="function"==typeof clearTimeout?clearTimeout:defaultClearTimeout}catch(e){cachedClearTimeout=defaultClearTimeout}}();var queue=[],draining=!1,queueIndex=-1;function cleanUpNextTick(){draining&¤tQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var timeout=runTimeout(cleanUpNextTick);draining=!0;for(var len=queue.length;len;){for(currentQueue=queue,queue=[];++queueIndex<len;)currentQueue&¤tQueue[queueIndex].run();queueIndex=-1,len=queue.length}currentQueue=null,draining=!1,runClearTimeout(timeout)}}function Item(fun,array){this.fun=fun,this.array=array}function noop(){}process.nextTick=function(fun){var args=Array(arguments.length-1);if(arguments.length>1)for(var i=1;i<arguments.length;i++)args[i-1]=arguments[i];queue.push(new Item(fun,args)),1!==queue.length||draining||runTimeout(drainQueue)},Item.prototype.run=function(){this.fun.apply(null,this.array)},process.title="browser",process.browser=!0,process.env={},process.argv=[],process.version="",process.versions={},process.on=noop,process.addListener=noop,process.once=noop,process.off=noop,process.removeListener=noop,process.removeAllListeners=noop,process.emit=noop,process.prependListener=noop,process.prependOnceListener=noop,process.listeners=function(name){return[]},process.binding=function(name){throw Error("process.binding is not supported")},process.cwd=function(){return"/"},process.chdir=function(dir){throw Error("process.chdir is not supported")},process.umask=function(){return 0}},{}],153:[function(require1,module,exports){"use strict";function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}module.exports=function(qs,sep,eq,options){sep=sep||"&",eq=eq||"=";var obj={};if("string"!=typeof qs||0===qs.length)return obj;var regexp=/\+/g;qs=qs.split(sep);var maxKeys=1e3;options&&"number"==typeof options.maxKeys&&(maxKeys=options.maxKeys);var len=qs.length;maxKeys>0&&len>maxKeys&&(len=maxKeys);for(var i=0;i<len;++i){var kstr,vstr,k,v,x=qs[i].replace(regexp,"%20"),idx=x.indexOf(eq);idx>=0?(kstr=x.substr(0,idx),vstr=x.substr(idx+1)):(kstr=x,vstr=""),k=decodeURIComponent(kstr),v=decodeURIComponent(vstr),hasOwnProperty(obj,k)?isArray(obj[k])?obj[k].push(v):obj[k]=[obj[k],v]:obj[k]=v}return obj};var isArray=Array.isArray||function(xs){return"[object Array]"===Object.prototype.toString.call(xs)}},{}],154:[function(require1,module,exports){"use strict";var stringifyPrimitive=function(v){switch(typeof v){case"string":return v;case"boolean":return v?"true":"false";case"number":return isFinite(v)?v:"";default:return""}};module.exports=function(obj,sep,eq,name){return(sep=sep||"&",eq=eq||"=",null===obj&&(obj=void 0),"object"==typeof obj)?map(objectKeys(obj),function(k){var ks=encodeURIComponent(stringifyPrimitive(k))+eq;return isArray(obj[k])?map(obj[k],function(v){return ks+encodeURIComponent(stringifyPrimitive(v))}).join(sep):ks+encodeURIComponent(stringifyPrimitive(obj[k]))}).join(sep):name?encodeURIComponent(stringifyPrimitive(name))+eq+encodeURIComponent(stringifyPrimitive(obj)):""};var isArray=Array.isArray||function(xs){return"[object Array]"===Object.prototype.toString.call(xs)};function map(xs,f){if(xs.map)return xs.map(f);for(var res=[],i=0;i<xs.length;i++)res.push(f(xs[i],i));return res}var objectKeys=Object.keys||function(obj){var res=[];for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&res.push(key);return res}},{}],155:[function(require1,module,exports){"use strict";exports.decode=exports.parse=require1("./decode"),exports.encode=exports.stringify=require1("./encode")},{"./decode":153,"./encode":154}],156:[function(require1,module,exports){"use strict";function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype),subClass.prototype.constructor=subClass,subClass.__proto__=superClass}var codes={};function createErrorType(code,message,Base){function getMessage(arg1,arg2,arg3){return"string"==typeof message?message:message(arg1,arg2,arg3)}Base||(Base=Error);var NodeError=function(_Base){function NodeError(arg1,arg2,arg3){return _Base.call(this,getMessage(arg1,arg2,arg3))||this}return _inheritsLoose(NodeError,_Base),NodeError}(Base);NodeError.prototype.name=Base.name,NodeError.prototype.code=code,codes[code]=NodeError}function oneOf(expected,thing){if(!Array.isArray(expected))return"of ".concat(thing," ").concat(String(expected));var len=expected.length;return(expected=expected.map(function(i){return String(i)}),len>2)?"one of ".concat(thing," ").concat(expected.slice(0,len-1).join(", "),", or ")+expected[len-1]:2===len?"one of ".concat(thing," ").concat(expected[0]," or ").concat(expected[1]):"of ".concat(thing," ").concat(expected[0])}function startsWith(str,search,pos){return str.substr(!pos||pos<0?0:+pos,search.length)===search}function endsWith(str,search,this_len){return(void 0===this_len||this_len>str.length)&&(this_len=str.length),str.substring(this_len-search.length,this_len)===search}function includes(str,search,start){return"number"!=typeof start&&(start=0),!(start+search.length>str.length)&&-1!==str.indexOf(search,start)}createErrorType("ERR_INVALID_OPT_VALUE",function(name,value){return'The value "'+value+'" is invalid for option "'+name+'"'},TypeError),createErrorType("ERR_INVALID_ARG_TYPE",function(name,expected,actual){if("string"==typeof expected&&startsWith(expected,"not ")?(determiner="must not be",expected=expected.replace(/^not /,"")):determiner="must be",endsWith(name," argument"))msg="The ".concat(name," ").concat(determiner," ").concat(oneOf(expected,"type"));else{var determiner,msg,type=includes(name,".")?"property":"argument";msg='The "'.concat(name,'" ').concat(type," ").concat(determiner," ").concat(oneOf(expected,"type"))}return msg+". Received type ".concat(typeof actual)},TypeError),createErrorType("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),createErrorType("ERR_METHOD_NOT_IMPLEMENTED",function(name){return"The "+name+" method is not implemented"}),createErrorType("ERR_STREAM_PREMATURE_CLOSE","Premature close"),createErrorType("ERR_STREAM_DESTROYED",function(name){return"Cannot call "+name+" after a stream was destroyed"}),createErrorType("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),createErrorType("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),createErrorType("ERR_STREAM_WRITE_AFTER_END","write after end"),createErrorType("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),createErrorType("ERR_UNKNOWN_ENCODING",function(arg){return"Unknown encoding: "+arg},TypeError),createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),module.exports.codes=codes},{}],157:[function(require1,module,exports){(function(process){(function(){"use strict";var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys};module.exports=Duplex;var Readable=require1("./_stream_readable"),Writable=require1("./_stream_writable");require1("inherits")(Duplex,Readable);for(var keys=objectKeys(Writable.prototype),v=0;v<keys.length;v++){var method=keys[v];Duplex.prototype[method]||(Duplex.prototype[method]=Writable.prototype[method])}function Duplex(options){if(!(this instanceof Duplex))return new Duplex(options);Readable.call(this,options),Writable.call(this,options),this.allowHalfOpen=!0,options&&(!1===options.readable&&(this.readable=!1),!1===options.writable&&(this.writable=!1),!1===options.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",onend)))}function onend(){this._writableState.ended||process.nextTick(onEndNT,this)}function onEndNT(self1){self1.end()}Object.defineProperty(Duplex.prototype,"writableHighWaterMark",{enumerable:!1,get:function get(){return this._writableState.highWaterMark}}),Object.defineProperty(Duplex.prototype,"writableBuffer",{enumerable:!1,get:function get(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(Duplex.prototype,"writableLength",{enumerable:!1,get:function get(){return this._writableState.length}}),Object.defineProperty(Duplex.prototype,"destroyed",{enumerable:!1,get:function get(){return void 0!==this._readableState&&void 0!==this._writableState&&this._readableState.destroyed&&this._writableState.destroyed},set:function set(value){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=value,this._writableState.destroyed=value)}})}).call(this)}).call(this,require1("_process"))},{"./_stream_readable":159,"./_stream_writable":161,_process:152,inherits:85}],158:[function(require1,module,exports){"use strict";module.exports=PassThrough;var Transform=require1("./_stream_transform");function PassThrough(options){if(!(this instanceof PassThrough))return new PassThrough(options);Transform.call(this,options)}require1("inherits")(PassThrough,Transform),PassThrough.prototype._transform=function(chunk,encoding,cb){cb(null,chunk)}},{"./_stream_transform":160,inherits:85}],159:[function(require1,module,exports){(function(process,global){(function(){"use strict";module.exports=Readable,Readable.ReadableState=ReadableState,require1("events").EventEmitter;var Duplex,debug,StringDecoder,createReadableStreamAsyncIterator,from,EElistenerCount=function(emitter,type){return emitter.listeners(type).length},Stream=require1("./internal/streams/stream"),Buffer=require1("buffer").Buffer,OurUint8Array=global.Uint8Array||function(){};function _uint8ArrayToBuffer(chunk){return Buffer.from(chunk)}function _isUint8Array(obj){return Buffer.isBuffer(obj)||obj instanceof OurUint8Array}var debugUtil=require1("util");debug=debugUtil&&debugUtil.debuglog?debugUtil.debuglog("stream"):function debug(){};var BufferList=require1("./internal/streams/buffer_list"),destroyImpl=require1("./internal/streams/destroy"),getHighWaterMark=require1("./internal/streams/state").getHighWaterMark,_require$codes=require1("../errors").codes,ERR_INVALID_ARG_TYPE=_require$codes.ERR_INVALID_ARG_TYPE,ERR_STREAM_PUSH_AFTER_EOF=_require$codes.ERR_STREAM_PUSH_AFTER_EOF,ERR_METHOD_NOT_IMPLEMENTED=_require$codes.ERR_METHOD_NOT_IMPLEMENTED,ERR_STREAM_UNSHIFT_AFTER_END_EVENT=_require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;require1("inherits")(Readable,Stream);var errorOrDestroy=destroyImpl.errorOrDestroy,kProxyEvents=["error","close","destroy","pause","resume"];function prependListener(emitter,event,fn){if("function"==typeof emitter.prependListener)return emitter.prependListener(event,fn);emitter._events&&emitter._events[event]?Array.isArray(emitter._events[event])?emitter._events[event].unshift(fn):emitter._events[event]=[fn,emitter._events[event]]:emitter.on(event,fn)}function ReadableState(options,stream,isDuplex){Duplex=Duplex||require1("./_stream_duplex"),options=options||{},"boolean"!=typeof isDuplex&&(isDuplex=stream instanceof Duplex),this.objectMode=!!options.objectMode,isDuplex&&(this.objectMode=this.objectMode||!!options.readableObjectMode),this.highWaterMark=getHighWaterMark(this,options,"readableHighWaterMark",isDuplex),this.buffer=new BufferList,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=!1!==options.emitClose,this.autoDestroy=!!options.autoDestroy,this.destroyed=!1,this.defaultEncoding=options.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,options.encoding&&(StringDecoder||(StringDecoder=require1("string_decoder/").StringDecoder),this.decoder=new StringDecoder(options.encoding),this.encoding=options.encoding)}function Readable(options){if(Duplex=Duplex||require1("./_stream_duplex"),!(this instanceof Readable))return new Readable(options);var isDuplex=this instanceof Duplex;this._readableState=new ReadableState(options,this,isDuplex),this.readable=!0,options&&("function"==typeof options.read&&(this._read=options.read),"function"==typeof options.destroy&&(this._destroy=options.destroy)),Stream.call(this)}function readableAddChunk(stream,chunk,encoding,addToFront,skipChunkCheck){debug("readableAddChunk",chunk);var er,state=stream._readableState;if(null===chunk)state.reading=!1,onEofChunk(stream,state);else if(skipChunkCheck||(er=chunkInvalid(state,chunk)),er)errorOrDestroy(stream,er);else if(state.objectMode||chunk&&chunk.length>0){if("string"==typeof chunk||state.objectMode||Object.getPrototypeOf(chunk)===Buffer.prototype||(chunk=_uint8ArrayToBuffer(chunk)),addToFront)state.endEmitted?errorOrDestroy(stream,new ERR_STREAM_UNSHIFT_AFTER_END_EVENT):addChunk(stream,state,chunk,!0);else if(state.ended)errorOrDestroy(stream,new ERR_STREAM_PUSH_AFTER_EOF);else{if(state.destroyed)return!1;state.reading=!1,state.decoder&&!encoding?(chunk=state.decoder.write(chunk),state.objectMode||0!==chunk.length?addChunk(stream,state,chunk,!1):maybeReadMore(stream,state)):addChunk(stream,state,chunk,!1)}}else addToFront||(state.reading=!1,maybeReadMore(stream,state));return!state.ended&&(state.length<state.highWaterMark||0===state.length)}function addChunk(stream,state,chunk,addToFront){state.flowing&&0===state.length&&!state.sync?(state.awaitDrain=0,stream.emit("data",chunk)):(state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):state.buffer.push(chunk),state.needReadable&&emitReadable(stream)),maybeReadMore(stream,state)}function chunkInvalid(state,chunk){var er;return _isUint8Array(chunk)||"string"==typeof chunk||void 0===chunk||state.objectMode||(er=new ERR_INVALID_ARG_TYPE("chunk",["string","Buffer","Uint8Array"],chunk)),er}function computeNewHighWaterMark(n){return n>=1073741824?n=1073741824:(n--,n|=n>>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n++),n}function howMuchToRead(n,state){return n<=0||0===state.length&&state.ended?0:state.objectMode?1:n!=n?state.flowing&&state.length?state.buffer.head.data.length:state.length:(n>state.highWaterMark&&(state.highWaterMark=computeNewHighWaterMark(n)),n<=state.length)?n:state.ended?state.length:(state.needReadable=!0,0)}function onEofChunk(stream,state){if(debug("onEofChunk"),!state.ended){if(state.decoder){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,state.sync?emitReadable(stream):(state.needReadable=!1,state.emittedReadable||(state.emittedReadable=!0,emitReadable_(stream)))}}function emitReadable(stream){var state=stream._readableState;debug("emitReadable",state.needReadable,state.emittedReadable),state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,process.nextTick(emitReadable_,stream))}function emitReadable_(stream){var state=stream._readableState;debug("emitReadable_",state.destroyed,state.length,state.ended),!state.destroyed&&(state.length||state.ended)&&(stream.emit("readable"),state.emittedReadable=!1),state.needReadable=!state.flowing&&!state.ended&&state.length<=state.highWaterMark,flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,process.nextTick(maybeReadMore_,stream,state))}function maybeReadMore_(stream,state){for(;!state.reading&&!state.ended&&(state.length<state.highWaterMark||state.flowing&&0===state.length);){var len=state.length;if(debug("maybeReadMore read 0"),stream.read(0),len===state.length)break}state.readingMore=!1}function pipeOnDrain(src){return function pipeOnDrainFunctionResult(){var state=src._readableState;debug("pipeOnDrain",state.awaitDrain),state.awaitDrain&&state.awaitDrain--,0===state.awaitDrain&&EElistenerCount(src,"data")&&(state.flowing=!0,flow(src))}}function updateReadableListening(self1){var state=self1._readableState;state.readableListening=self1.listenerCount("readable")>0,state.resumeScheduled&&!state.paused?state.flowing=!0:self1.listenerCount("data")>0&&self1.resume()}function nReadingNextTick(self1){debug("readable nexttick read 0"),self1.read(0)}function resume(stream,state){state.resumeScheduled||(state.resumeScheduled=!0,process.nextTick(resume_,stream,state))}function resume_(stream,state){debug("resume",state.reading),state.reading||stream.read(0),state.resumeScheduled=!1,stream.emit("resume"),flow(stream),state.flowing&&!state.reading&&stream.read(0)}function flow(stream){var state=stream._readableState;for(debug("flow",state.flowing);state.flowing&&null!==stream.read(););}function fromList(n,state){var ret;return 0===state.length?null:(state.objectMode?ret=state.buffer.shift():!n||n>=state.length?(ret=state.decoder?state.buffer.join(""):1===state.buffer.length?state.buffer.first():state.buffer.concat(state.length),state.buffer.clear()):ret=state.buffer.consume(n,state.decoder),ret)}function endReadable(stream){var state=stream._readableState;debug("endReadable",state.endEmitted),state.endEmitted||(state.ended=!0,process.nextTick(endReadableNT,state,stream))}function endReadableNT(state,stream){if(debug("endReadableNT",state.endEmitted,state.length),!state.endEmitted&&0===state.length&&(state.endEmitted=!0,stream.readable=!1,stream.emit("end"),state.autoDestroy)){var wState=stream._writableState;(!wState||wState.autoDestroy&&wState.finished)&&stream.destroy()}}function indexOf(xs,x){for(var i=0,l=xs.length;i<l;i++)if(xs[i]===x)return i;return -1}Object.defineProperty(Readable.prototype,"destroyed",{enumerable:!1,get:function get(){return void 0!==this._readableState&&this._readableState.destroyed},set:function set(value){this._readableState&&(this._readableState.destroyed=value)}}),Readable.prototype.destroy=destroyImpl.destroy,Readable.prototype._undestroy=destroyImpl.undestroy,Readable.prototype._destroy=function(err,cb){cb(err)},Readable.prototype.push=function(chunk,encoding){var skipChunkCheck,state=this._readableState;return state.objectMode?skipChunkCheck=!0:"string"==typeof chunk&&((encoding=encoding||state.defaultEncoding)!==state.encoding&&(chunk=Buffer.from(chunk,encoding),encoding=""),skipChunkCheck=!0),readableAddChunk(this,chunk,encoding,!1,skipChunkCheck)},Readable.prototype.unshift=function(chunk){return readableAddChunk(this,chunk,null,!0,!1)},Readable.prototype.isPaused=function(){return!1===this._readableState.flowing},Readable.prototype.setEncoding=function(enc){StringDecoder||(StringDecoder=require1("string_decoder/").StringDecoder);var decoder=new StringDecoder(enc);this._readableState.decoder=decoder,this._readableState.encoding=this._readableState.decoder.encoding;for(var p=this._readableState.buffer.head,content="";null!==p;)content+=decoder.write(p.data),p=p.next;return this._readableState.buffer.clear(),""!==content&&this._readableState.buffer.push(content),this._readableState.length=content.length,this},Readable.prototype.read=function(n){debug("read",n),n=parseInt(n,10);var ret,state=this._readableState,nOrig=n;if(0!==n&&(state.emittedReadable=!1),0===n&&state.needReadable&&((0!==state.highWaterMark?state.length>=state.highWaterMark:state.length>0)||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(0===(n=howMuchToRead(n,state))&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;return debug("need readable",doRead),(0===state.length||state.length-n<state.highWaterMark)&&debug("length less than watermark",doRead=!0),state.ended||state.reading?debug("reading or ended",doRead=!1):doRead&&(debug("do read"),state.reading=!0,state.sync=!0,0===state.length&&(state.needReadable=!0),this._read(state.highWaterMark),state.sync=!1,state.reading||(n=howMuchToRead(nOrig,state))),null===(ret=n>0?fromList(n,state):null)?(state.needReadable=state.length<=state.highWaterMark,n=0):(state.length-=n,state.awaitDrain=0),0===state.length&&(state.ended||(state.needReadable=!0),nOrig!==n&&state.ended&&endReadable(this)),null!==ret&&this.emit("data",ret),ret},Readable.prototype._read=function(n){errorOrDestroy(this,new ERR_METHOD_NOT_IMPLEMENTED("_read()"))},Readable.prototype.pipe=function(dest,pipeOpts){var src=this,state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest)}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var endFn=pipeOpts&&!1===pipeOpts.end||dest===process.stdout||dest===process.stderr?unpipe:onend;function onunpipe(readable,unpipeInfo){debug("onunpipe"),readable===src&&unpipeInfo&&!1===unpipeInfo.hasUnpiped&&(unpipeInfo.hasUnpiped=!0,cleanup())}function onend(){debug("onend"),dest.end()}state.endEmitted?process.nextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);var cleanedUp=!1;function cleanup(){debug("cleanup"),dest.removeListener("close",onclose),dest.removeListener("finish",onfinish),dest.removeListener("drain",ondrain),dest.removeListener("error",onerror),dest.removeListener("unpipe",onunpipe),src.removeListener("end",onend),src.removeListener("end",unpipe),src.removeListener("data",ondata),cleanedUp=!0,state.awaitDrain&&(!dest._writableState||dest._writableState.needDrain)&&ondrain()}function ondata(chunk){debug("ondata");var ret=dest.write(chunk);debug("dest.write",ret),!1===ret&&((1===state.pipesCount&&state.pipes===dest||state.pipesCount>1&&-1!==indexOf(state.pipes,dest))&&!cleanedUp&&(debug("false write response, pause",state.awaitDrain),state.awaitDrain++),src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EElistenerCount(dest,"error")&&errorOrDestroy(dest,er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}return src.on("data",ondata),prependListener(dest,"error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState,unpipeInfo={hasUnpiped:!1};if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes||(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this,unpipeInfo)),this;if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var i=0;i<len;i++)dests[i].emit("unpipe",this,{hasUnpiped:!1});return this}var index=indexOf(state.pipes,dest);return -1===index||(state.pipes.splice(index,1),state.pipesCount-=1,1===state.pipesCount&&(state.pipes=state.pipes[0]),dest.emit("unpipe",this,unpipeInfo)),this},Readable.prototype.on=function(ev,fn){var res=Stream.prototype.on.call(this,ev,fn),state=this._readableState;return"data"===ev?(state.readableListening=this.listenerCount("readable")>0,!1!==state.flowing&&this.resume()):"readable"!==ev||state.endEmitted||state.readableListening||(state.readableListening=state.needReadable=!0,state.flowing=!1,state.emittedReadable=!1,debug("on readable",state.length,state.reading),state.length?emitReadable(this):state.reading||process.nextTick(nReadingNextTick,this)),res},Readable.prototype.addListener=Readable.prototype.on,Readable.prototype.removeListener=function(ev,fn){var res=Stream.prototype.removeListener.call(this,ev,fn);return"readable"===ev&&process.nextTick(updateReadableListening,this),res},Readable.prototype.removeAllListeners=function(ev){var res=Stream.prototype.removeAllListeners.apply(this,arguments);return("readable"===ev||void 0===ev)&&process.nextTick(updateReadableListening,this),res},Readable.prototype.resume=function(){var state=this._readableState;return state.flowing||(debug("resume"),state.flowing=!state.readableListening,resume(this,state)),state.paused=!1,this},Readable.prototype.pause=function(){return debug("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(debug("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},Readable.prototype.wrap=function(stream){var _this=this,state=this._readableState,paused=!1;for(var i in stream.on("end",function(){if(debug("wrapped end"),state.decoder&&!state.ended){var chunk=state.decoder.end();chunk&&chunk.length&&_this.push(chunk)}_this.push(null)}),stream.on("data",function(chunk){debug("wrapped data"),state.decoder&&(chunk=state.decoder.write(chunk)),(!state.objectMode||null!=chunk)&&(state.objectMode||chunk&&chunk.length)&&(_this.push(chunk)||(paused=!0,stream.pause()))}),stream)void 0===this[i]&&"function"==typeof stream[i]&&(this[i]=function methodWrap(method){return function methodWrapReturnFunction(){return stream[method].apply(stream,arguments)}}(i));for(var n=0;n<kProxyEvents.length;n++)stream.on(kProxyEvents[n],this.emit.bind(this,kProxyEvents[n]));return this._read=function(n){debug("wrapped _read",n),paused&&(paused=!1,stream.resume())},this},"function"==typeof Symbol&&(Readable.prototype[Symbol.asyncIterator]=function(){return void 0===createReadableStreamAsyncIterator&&(createReadableStreamAsyncIterator=require1("./internal/streams/async_iterator")),createReadableStreamAsyncIterator(this)}),Object.defineProperty(Readable.prototype,"readableHighWaterMark",{enumerable:!1,get:function get(){return this._readableState.highWaterMark}}),Object.defineProperty(Readable.prototype,"readableBuffer",{enumerable:!1,get:function get(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(Readable.prototype,"readableFlowing",{enumerable:!1,get:function get(){return this._readableState.flowing},set:function set(state){this._readableState&&(this._readableState.flowing=state)}}),Readable._fromList=fromList,Object.defineProperty(Readable.prototype,"readableLength",{enumerable:!1,get:function get(){return this._readableState.length}}),"function"==typeof Symbol&&(Readable.from=function(iterable,opts){return void 0===from&&(from=require1("./internal/streams/from")),from(Readable,iterable,opts)})}).call(this)}).call(this,require1("_process"),void 0!==__webpack_require__.g?__webpack_require__.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../errors":156,"./_stream_duplex":157,"./internal/streams/async_iterator":162,"./internal/streams/buffer_list":163,"./internal/streams/destroy":164,"./internal/streams/from":166,"./internal/streams/state":168,"./internal/streams/stream":169,_process:152,buffer:47,events:80,inherits:85,"string_decoder/":207,util:29}],160:[function(require1,module,exports){"use strict";module.exports=Transform;var _require$codes=require1("../errors").codes,ERR_METHOD_NOT_IMPLEMENTED=_require$codes.ERR_METHOD_NOT_IMPLEMENTED,ERR_MULTIPLE_CALLBACK=_require$codes.ERR_MULTIPLE_CALLBACK,ERR_TRANSFORM_ALREADY_TRANSFORMING=_require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,ERR_TRANSFORM_WITH_LENGTH_0=_require$codes.ERR_TRANSFORM_WITH_LENGTH_0,Duplex=require1("./_stream_duplex");function afterTransform(er,data){var ts=this._transformState;ts.transforming=!1;var cb=ts.writecb;if(null===cb)return this.emit("error",new ERR_MULTIPLE_CALLBACK);ts.writechunk=null,ts.writecb=null,null!=data&&this.push(data),cb(er);var rs=this._readableState;rs.reading=!1,(rs.needReadable||rs.length<rs.highWaterMark)&&this._read(rs.highWaterMark)}function Transform(options){if(!(this instanceof Transform))return new Transform(options);Duplex.call(this,options),this._transformState={afterTransform:afterTransform.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,options&&("function"==typeof options.transform&&(this._transform=options.transform),"function"==typeof options.flush&&(this._flush=options.flush)),this.on("prefinish",prefinish)}function prefinish(){var _this=this;"function"!=typeof this._flush||this._readableState.destroyed?done(this,null,null):this._flush(function(er,data){done(_this,er,data)})}function done(stream,er,data){if(er)return stream.emit("error",er);if(null!=data&&stream.push(data),stream._writableState.length)throw new ERR_TRANSFORM_WITH_LENGTH_0;if(stream._transformState.transforming)throw new ERR_TRANSFORM_ALREADY_TRANSFORMING;return stream.push(null)}require1("inherits")(Transform,Duplex),Transform.prototype.push=function(chunk,encoding){return this._transformState.needTransform=!1,Duplex.prototype.push.call(this,chunk,encoding)},Transform.prototype._transform=function(chunk,encoding,cb){cb(new ERR_METHOD_NOT_IMPLEMENTED("_transform()"))},Transform.prototype._write=function(chunk,encoding,cb){var ts=this._transformState;if(ts.writecb=cb,ts.writechunk=chunk,ts.writeencoding=encoding,!ts.transforming){var rs=this._readableState;(ts.needTransform||rs.needReadable||rs.length<rs.highWaterMark)&&this._read(rs.highWaterMark)}},Transform.prototype._read=function(n){var ts=this._transformState;null===ts.writechunk||ts.transforming?ts.needTransform=!0:(ts.transforming=!0,this._transform(ts.writechunk,ts.writeencoding,ts.afterTransform))},Transform.prototype._destroy=function(err,cb){Duplex.prototype._destroy.call(this,err,function(err2){cb(err2)})}},{"../errors":156,"./_stream_duplex":157,inherits:85}],161:[function(require1,module,exports){(function(process,global){(function(){"use strict";function CorkedRequest(state){var _this=this;this.next=null,this.entry=null,this.finish=function(){onCorkedFinish(_this,state)}}module.exports=Writable,Writable.WritableState=WritableState;var Duplex,realHasInstance,internalUtil={deprecate:require1("util-deprecate")},Stream=require1("./internal/streams/stream"),Buffer=require1("buffer").Buffer,OurUint8Array=global.Uint8Array||function(){};function _uint8ArrayToBuffer(chunk){return Buffer.from(chunk)}function _isUint8Array(obj){return Buffer.isBuffer(obj)||obj instanceof OurUint8Array}var destroyImpl=require1("./internal/streams/destroy"),getHighWaterMark=require1("./internal/streams/state").getHighWaterMark,_require$codes=require1("../errors").codes,ERR_INVALID_ARG_TYPE=_require$codes.ERR_INVALID_ARG_TYPE,ERR_METHOD_NOT_IMPLEMENTED=_require$codes.ERR_METHOD_NOT_IMPLEMENTED,ERR_MULTIPLE_CALLBACK=_require$codes.ERR_MULTIPLE_CALLBACK,ERR_STREAM_CANNOT_PIPE=_require$codes.ERR_STREAM_CANNOT_PIPE,ERR_STREAM_DESTROYED=_require$codes.ERR_STREAM_DESTROYED,ERR_STREAM_NULL_VALUES=_require$codes.ERR_STREAM_NULL_VALUES,ERR_STREAM_WRITE_AFTER_END=_require$codes.ERR_STREAM_WRITE_AFTER_END,ERR_UNKNOWN_ENCODING=_require$codes.ERR_UNKNOWN_ENCODING,errorOrDestroy=destroyImpl.errorOrDestroy;function nop(){}function WritableState(options,stream,isDuplex){Duplex=Duplex||require1("./_stream_duplex"),options=options||{},"boolean"!=typeof isDuplex&&(isDuplex=stream instanceof Duplex),this.objectMode=!!options.objectMode,isDuplex&&(this.objectMode=this.objectMode||!!options.writableObjectMode),this.highWaterMark=getHighWaterMark(this,options,"writableHighWaterMark",isDuplex),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var noDecode=!1===options.decodeStrings;this.decodeStrings=!noDecode,this.defaultEncoding=options.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(er){onwrite(stream,er)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==options.emitClose,this.autoDestroy=!!options.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new CorkedRequest(this)}function Writable(options){var isDuplex=this instanceof(Duplex=Duplex||require1("./_stream_duplex"));if(!isDuplex&&!realHasInstance.call(Writable,this))return new Writable(options);this._writableState=new WritableState(options,this,isDuplex),this.writable=!0,options&&("function"==typeof options.write&&(this._write=options.write),"function"==typeof options.writev&&(this._writev=options.writev),"function"==typeof options.destroy&&(this._destroy=options.destroy),"function"==typeof options.final&&(this._final=options.final)),Stream.call(this)}function writeAfterEnd(stream,cb){var er=new ERR_STREAM_WRITE_AFTER_END;errorOrDestroy(stream,er),process.nextTick(cb,er)}function validChunk(stream,state,chunk,cb){var er;return null===chunk?er=new ERR_STREAM_NULL_VALUES:"string"==typeof chunk||state.objectMode||(er=new ERR_INVALID_ARG_TYPE("chunk",["string","Buffer"],chunk)),!er||(errorOrDestroy(stream,er),process.nextTick(cb,er),!1)}function decodeChunk(state,chunk,encoding){return state.objectMode||!1===state.decodeStrings||"string"!=typeof chunk||(chunk=Buffer.from(chunk,encoding)),chunk}function writeOrBuffer(stream,state,isBuf,chunk,encoding,cb){if(!isBuf){var newChunk=decodeChunk(state,chunk,encoding);chunk!==newChunk&&(isBuf=!0,encoding="buffer",chunk=newChunk)}var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length<state.highWaterMark;if(ret||(state.needDrain=!0),state.writing||state.corked){var last=state.lastBufferedRequest;state.lastBufferedRequest={chunk:chunk,encoding:encoding,isBuf:isBuf,callback:cb,next:null},last?last.next=state.lastBufferedRequest:state.bufferedRequest=state.lastBufferedRequest,state.bufferedRequestCount+=1}else doWrite(stream,state,!1,len,chunk,encoding,cb);return ret}function doWrite(stream,state,writev,len,chunk,encoding,cb){state.writelen=len,state.writecb=cb,state.writing=!0,state.sync=!0,state.destroyed?state.onwrite(new ERR_STREAM_DESTROYED("write")):writev?stream._writev(chunk,state.onwrite):stream._write(chunk,encoding,state.onwrite),state.sync=!1}function onwriteError(stream,state,sync,er,cb){--state.pendingcb,sync?(process.nextTick(cb,er),process.nextTick(finishMaybe,stream,state),stream._writableState.errorEmitted=!0,errorOrDestroy(stream,er)):(cb(er),stream._writableState.errorEmitted=!0,errorOrDestroy(stream,er),finishMaybe(stream,state))}function onwriteStateUpdate(state){state.writing=!1,state.writecb=null,state.length-=state.writelen,state.writelen=0}function onwrite(stream,er){var state=stream._writableState,sync=state.sync,cb=state.writecb;if("function"!=typeof cb)throw new ERR_MULTIPLE_CALLBACK;if(onwriteStateUpdate(state),er)onwriteError(stream,state,sync,er,cb);else{var finished=needFinish(state)||stream.destroyed;finished||state.corked||state.bufferProcessing||!state.bufferedRequest||clearBuffer(stream,state),sync?process.nextTick(afterWrite,stream,state,finished,cb):afterWrite(stream,state,finished,cb)}}function afterWrite(stream,state,finished,cb){finished||onwriteDrain(stream,state),state.pendingcb--,cb(),finishMaybe(stream,state)}function onwriteDrain(stream,state){0===state.length&&state.needDrain&&(state.needDrain=!1,stream.emit("drain"))}function clearBuffer(stream,state){state.bufferProcessing=!0;var entry=state.bufferedRequest;if(stream._writev&&entry&&entry.next){var buffer=Array(state.bufferedRequestCount),holder=state.corkedRequestsFree;holder.entry=entry;for(var count=0,allBuffers=!0;entry;)buffer[count]=entry,entry.isBuf||(allBuffers=!1),entry=entry.next,count+=1;buffer.allBuffers=allBuffers,doWrite(stream,state,!0,state.length,buffer,"",holder.finish),state.pendingcb++,state.lastBufferedRequest=null,holder.next?(state.corkedRequestsFree=holder.next,holder.next=null):state.corkedRequestsFree=new CorkedRequest(state),state.bufferedRequestCount=0}else{for(;entry;){var chunk=entry.chunk,encoding=entry.encoding,cb=entry.callback,len=state.objectMode?1:chunk.length;if(doWrite(stream,state,!1,len,chunk,encoding,cb),entry=entry.next,state.bufferedRequestCount--,state.writing)break}null===entry&&(state.lastBufferedRequest=null)}state.bufferedRequest=entry,state.bufferProcessing=!1}function needFinish(state){return state.ending&&0===state.length&&null===state.bufferedRequest&&!state.finished&&!state.writing}function callFinal(stream,state){stream._final(function(err){state.pendingcb--,err&&errorOrDestroy(stream,err),state.prefinished=!0,stream.emit("prefinish"),finishMaybe(stream,state)})}function prefinish(stream,state){state.prefinished||state.finalCalled||("function"!=typeof stream._final||state.destroyed?(state.prefinished=!0,stream.emit("prefinish")):(state.pendingcb++,state.finalCalled=!0,process.nextTick(callFinal,stream,state)))}function finishMaybe(stream,state){var need=needFinish(state);if(need&&(prefinish(stream,state),0===state.pendingcb&&(state.finished=!0,stream.emit("finish"),state.autoDestroy))){var rState=stream._readableState;(!rState||rState.autoDestroy&&rState.endEmitted)&&stream.destroy()}return need}function endWritable(stream,state,cb){state.ending=!0,finishMaybe(stream,state),cb&&(state.finished?process.nextTick(cb):stream.once("finish",cb)),state.ended=!0,stream.writable=!1}function onCorkedFinish(corkReq,state,err){var entry=corkReq.entry;for(corkReq.entry=null;entry;){var cb=entry.callback;state.pendingcb--,cb(err),entry=entry.next}state.corkedRequestsFree.next=corkReq}require1("inherits")(Writable,Stream),WritableState.prototype.getBuffer=function getBuffer(){for(var current=this.bufferedRequest,out=[];current;)out.push(current),current=current.next;return out},function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate(function writableStateBufferGetter(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(_){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(realHasInstance=Function.prototype[Symbol.hasInstance],Object.defineProperty(Writable,Symbol.hasInstance,{value:function value(object){return!!realHasInstance.call(this,object)||this===Writable&&object&&object._writableState instanceof WritableState}})):realHasInstance=function realHasInstance(object){return object instanceof this},Writable.prototype.pipe=function(){errorOrDestroy(this,new ERR_STREAM_CANNOT_PIPE)},Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState,ret=!1,isBuf=!state.objectMode&&_isUint8Array(chunk);return isBuf&&!Buffer.isBuffer(chunk)&&(chunk=_uint8ArrayToBuffer(chunk)),"function"==typeof encoding&&(cb=encoding,encoding=null),isBuf?encoding="buffer":encoding||(encoding=state.defaultEncoding),"function"!=typeof cb&&(cb=nop),state.ending?writeAfterEnd(this,cb):(isBuf||validChunk(this,state,chunk,cb))&&(state.pendingcb++,ret=writeOrBuffer(this,state,isBuf,chunk,encoding,cb)),ret},Writable.prototype.cork=function(){this._writableState.corked++},Writable.prototype.uncork=function(){var state=this._writableState;!state.corked||(state.corked--,state.writing||state.corked||state.bufferProcessing||!state.bufferedRequest||clearBuffer(this,state))},Writable.prototype.setDefaultEncoding=function setDefaultEncoding(encoding){if("string"==typeof encoding&&(encoding=encoding.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())>-1))throw new ERR_UNKNOWN_ENCODING(encoding);return this._writableState.defaultEncoding=encoding,this},Object.defineProperty(Writable.prototype,"writableBuffer",{enumerable:!1,get:function get(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(Writable.prototype,"writableHighWaterMark",{enumerable:!1,get:function get(){return this._writableState.highWaterMark}}),Writable.prototype._write=function(chunk,encoding,cb){cb(new ERR_METHOD_NOT_IMPLEMENTED("_write()"))},Writable.prototype._writev=null,Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;return"function"==typeof chunk?(cb=chunk,chunk=null,encoding=null):"function"==typeof encoding&&(cb=encoding,encoding=null),null!=chunk&&this.write(chunk,encoding),state.corked&&(state.corked=1,this.uncork()),state.ending||endWritable(this,state,cb),this},Object.defineProperty(Writable.prototype,"writableLength",{enumerable:!1,get:function get(){return this._writableState.length}}),Object.defineProperty(Writable.prototype,"destroyed",{enumerable:!1,get:function get(){return void 0!==this._writableState&&this._writableState.destroyed},set:function set(value){this._writableState&&(this._writableState.destroyed=value)}}),Writable.prototype.destroy=destroyImpl.destroy,Writable.prototype._undestroy=destroyImpl.undestroy,Writable.prototype._destroy=function(err,cb){cb(err)}}).call(this)}).call(this,require1("_process"),void 0!==__webpack_require__.g?__webpack_require__.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../errors":156,"./_stream_duplex":157,"./internal/streams/destroy":164,"./internal/streams/state":168,"./internal/streams/stream":169,_process:152,buffer:47,inherits:85,"util-deprecate":214}],162:[function(require1,module,exports){(function(process){(function(){"use strict";function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}var _Object$setPrototypeO,finished=require1("./end-of-stream"),kLastResolve=Symbol("lastResolve"),kLastReject=Symbol("lastReject"),kError=Symbol("error"),kEnded=Symbol("ended"),kLastPromise=Symbol("lastPromise"),kHandlePromise=Symbol("handlePromise"),kStream=Symbol("stream");function createIterResult(value,done){return{value:value,done:done}}function readAndResolve(iter){var resolve=iter[kLastResolve];if(null!==resolve){var data=iter[kStream].read();null!==data&&(iter[kLastPromise]=null,iter[kLastResolve]=null,iter[kLastReject]=null,resolve(createIterResult(data,!1)))}}function onReadable(iter){process.nextTick(readAndResolve,iter)}function wrapForNext(lastPromise,iter){return function(resolve,reject){lastPromise.then(function(){if(iter[kEnded]){resolve(createIterResult(void 0,!0));return}iter[kHandlePromise](resolve,reject)},reject)}}var AsyncIteratorPrototype=Object.getPrototypeOf(function(){}),ReadableStreamAsyncIteratorPrototype=Object.setPrototypeOf((_defineProperty(_Object$setPrototypeO={get stream(){return this[kStream]},next:function next(){var promise,_this=this,error=this[kError];if(null!==error)return Promise.reject(error);if(this[kEnded])return Promise.resolve(createIterResult(void 0,!0));if(this[kStream].destroyed)return new Promise(function(resolve,reject){process.nextTick(function(){_this[kError]?reject(_this[kError]):resolve(createIterResult(void 0,!0))})});var lastPromise=this[kLastPromise];if(lastPromise)promise=new Promise(wrapForNext(lastPromise,this));else{var data=this[kStream].read();if(null!==data)return Promise.resolve(createIterResult(data,!1));promise=new Promise(this[kHandlePromise])}return this[kLastPromise]=promise,promise}},Symbol.asyncIterator,function(){return this}),_defineProperty(_Object$setPrototypeO,"return",function _return(){var _this2=this;return new Promise(function(resolve,reject){_this2[kStream].destroy(null,function(err){if(err){reject(err);return}resolve(createIterResult(void 0,!0))})})}),_Object$setPrototypeO),AsyncIteratorPrototype);module.exports=function(stream){var _Object$create,iterator=Object.create(ReadableStreamAsyncIteratorPrototype,(_defineProperty(_Object$create={},kStream,{value:stream,writable:!0}),_defineProperty(_Object$create,kLastResolve,{value:null,writable:!0}),_defineProperty(_Object$create,kLastReject,{value:null,writable:!0}),_defineProperty(_Object$create,kError,{value:null,writable:!0}),_defineProperty(_Object$create,kEnded,{value:stream._readableState.endEmitted,writable:!0}),_defineProperty(_Object$create,kHandlePromise,{value:function value(resolve,reject){var data=iterator[kStream].read();data?(iterator[kLastPromise]=null,iterator[kLastResolve]=null,iterator[kLastReject]=null,resolve(createIterResult(data,!1))):(iterator[kLastResolve]=resolve,iterator[kLastReject]=reject)},writable:!0}),_Object$create));return iterator[kLastPromise]=null,finished(stream,function(err){if(err&&"ERR_STREAM_PREMATURE_CLOSE"!==err.code){var reject=iterator[kLastReject];null!==reject&&(iterator[kLastPromise]=null,iterator[kLastResolve]=null,iterator[kLastReject]=null,reject(err)),iterator[kError]=err;return}var resolve=iterator[kLastResolve];null!==resolve&&(iterator[kLastPromise]=null,iterator[kLastResolve]=null,iterator[kLastReject]=null,resolve(createIterResult(void 0,!0))),iterator[kEnded]=!0}),stream.on("readable",onReadable.bind(null,iterator)),iterator}}).call(this)}).call(this,require1("_process"))},{"./end-of-stream":165,_process:152}],163:[function(require1,module,exports){"use strict";function ownKeys(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);enumerableOnly&&(symbols=symbols.filter(function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable})),keys.push.apply(keys,symbols)}return keys}function _objectSpread(target){for(var i=1;i<arguments.length;i++){var source=null!=arguments[i]?arguments[i]:{};i%2?ownKeys(Object(source),!0).forEach(function(key){_defineProperty(target,key,source[key])}):Object.getOwnPropertyDescriptors?Object.defineProperties(target,Object.getOwnPropertyDescriptors(source)):ownKeys(Object(source)).forEach(function(key){Object.defineProperty(target,key,Object.getOwnPropertyDescriptor(source,key))})}return target}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw TypeError("Cannot call a class as a function")}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){return protoProps&&_defineProperties(Constructor.prototype,protoProps),staticProps&&_defineProperties(Constructor,staticProps),Constructor}var Buffer=require1("buffer").Buffer,inspect=require1("util").inspect,custom=inspect&&inspect.custom||"inspect";function copyBuffer(src,target,offset){Buffer.prototype.copy.call(src,target,offset)}module.exports=function(){function BufferList(){_classCallCheck(this,BufferList),this.head=null,this.tail=null,this.length=0}return _createClass(BufferList,[{key:"push",value:function push(v){var entry={data:v,next:null};this.length>0?this.tail.next=entry:this.head=entry,this.tail=entry,++this.length}},{key:"unshift",value:function unshift(v){var entry={data:v,next:this.head};0===this.length&&(this.tail=entry),this.head=entry,++this.length}},{key:"shift",value:function shift(){if(0!==this.length){var ret=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,ret}}},{key:"clear",value:function clear(){this.head=this.tail=null,this.length=0}},{key:"join",value:function join(s){if(0===this.length)return"";for(var p=this.head,ret=""+p.data;p=p.next;)ret+=s+p.data;return ret}},{key:"concat",value:function concat(n){if(0===this.length)return Buffer.alloc(0);for(var ret=Buffer.allocUnsafe(n>>>0),p=this.head,i=0;p;)copyBuffer(p.data,ret,i),i+=p.data.length,p=p.next;return ret}},{key:"consume",value:function consume(n,hasStrings){var ret;return n<this.head.data.length?(ret=this.head.data.slice(0,n),this.head.data=this.head.data.slice(n)):ret=n===this.head.data.length?this.shift():hasStrings?this._getString(n):this._getBuffer(n),ret}},{key:"first",value:function first(){return this.head.data}},{key:"_getString",value:function _getString(n){var p=this.head,c=1,ret=p.data;for(n-=ret.length;p=p.next;){var str=p.data,nb=n>str.length?str.length:n;if(nb===str.length?ret+=str:ret+=str.slice(0,n),0==(n-=nb)){nb===str.length?(++c,p.next?this.head=p.next:this.head=this.tail=null):(this.head=p,p.data=str.slice(nb));break}++c}return this.length-=c,ret}},{key:"_getBuffer",value:function _getBuffer(n){var ret=Buffer.allocUnsafe(n),p=this.head,c=1;for(p.data.copy(ret),n-=p.data.length;p=p.next;){var buf=p.data,nb=n>buf.length?buf.length:n;if(buf.copy(ret,ret.length-n,0,nb),0==(n-=nb)){nb===buf.length?(++c,p.next?this.head=p.next:this.head=this.tail=null):(this.head=p,p.data=buf.slice(nb));break}++c}return this.length-=c,ret}},{key:custom,value:function value(_,options){return inspect(this,_objectSpread({},options,{depth:0,customInspect:!1}))}}]),BufferList}()},{buffer:47,util:29}],164:[function(require1,module,exports){(function(process){(function(){"use strict";function destroy(err,cb){var _this=this,readableDestroyed=this._readableState&&this._readableState.destroyed,writableDestroyed=this._writableState&&this._writableState.destroyed;return readableDestroyed||writableDestroyed?cb?cb(err):err&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process.nextTick(emitErrorNT,this,err)):process.nextTick(emitErrorNT,this,err)):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(err||null,function(err){!cb&&err?_this._writableState?_this._writableState.errorEmitted?process.nextTick(emitCloseNT,_this):(_this._writableState.errorEmitted=!0,process.nextTick(emitErrorAndCloseNT,_this,err)):process.nextTick(emitErrorAndCloseNT,_this,err):cb?(process.nextTick(emitCloseNT,_this),cb(err)):process.nextTick(emitCloseNT,_this)})),this}function emitErrorAndCloseNT(self1,err){emitErrorNT(self1,err),emitCloseNT(self1)}function emitCloseNT(self1){(!self1._writableState||self1._writableState.emitClose)&&(!self1._readableState||self1._readableState.emitClose)&&self1.emit("close")}function undestroy(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function emitErrorNT(self1,err){self1.emit("error",err)}function errorOrDestroy(stream,err){var rState=stream._readableState,wState=stream._writableState;rState&&rState.autoDestroy||wState&&wState.autoDestroy?stream.destroy(err):stream.emit("error",err)}module.exports={destroy:destroy,undestroy:undestroy,errorOrDestroy:errorOrDestroy}}).call(this)}).call(this,require1("_process"))},{_process:152}],165:[function(require1,module,exports){"use strict";var ERR_STREAM_PREMATURE_CLOSE=require1("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;function once(callback){var called=!1;return function(){if(!called){called=!0;for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];callback.apply(this,args)}}}function noop(){}function isRequest(stream){return stream.setHeader&&"function"==typeof stream.abort}function eos(stream,opts,callback){if("function"==typeof opts)return eos(stream,null,opts);opts||(opts={}),callback=once(callback||noop);var readable=opts.readable||!1!==opts.readable&&stream.readable,writable=opts.writable||!1!==opts.writable&&stream.writable,onlegacyfinish=function(){stream.writable||onfinish()},writableEnded=stream._writableState&&stream._writableState.finished,onfinish=function(){writable=!1,writableEnded=!0,readable||callback.call(stream)},readableEnded=stream._readableState&&stream._readableState.endEmitted,onend=function(){readable=!1,readableEnded=!0,writable||callback.call(stream)},onerror=function(err){callback.call(stream,err)},onclose=function(){var err;return readable&&!readableEnded?(stream._readableState&&stream._readableState.ended||(err=new ERR_STREAM_PREMATURE_CLOSE),callback.call(stream,err)):writable&&!writableEnded?(stream._writableState&&stream._writableState.ended||(err=new ERR_STREAM_PREMATURE_CLOSE),callback.call(stream,err)):void 0},onrequest=function(){stream.req.on("finish",onfinish)};return isRequest(stream)?(stream.on("complete",onfinish),stream.on("abort",onclose),stream.req?onrequest():stream.on("request",onrequest)):writable&&!stream._writableState&&(stream.on("end",onlegacyfinish),stream.on("close",onlegacyfinish)),stream.on("end",onend),stream.on("finish",onfinish),!1!==opts.error&&stream.on("error",onerror),stream.on("close",onclose),function(){stream.removeListener("complete",onfinish),stream.removeListener("abort",onclose),stream.removeListener("request",onrequest),stream.req&&stream.req.removeListener("finish",onfinish),stream.removeListener("end",onlegacyfinish),stream.removeListener("close",onlegacyfinish),stream.removeListener("finish",onfinish),stream.removeListener("end",onend),stream.removeListener("error",onerror),stream.removeListener("close",onclose)}}module.exports=eos},{"../../../errors":156}],166:[function(require1,module,exports){module.exports=function(){throw Error("Readable.from is not available in the browser")}},{}],167:[function(require1,module,exports){"use strict";function once(callback){var called=!1;return function(){called||(called=!0,callback.apply(void 0,arguments))}}var eos,_require$codes=require1("../../../errors").codes,ERR_MISSING_ARGS=_require$codes.ERR_MISSING_ARGS,ERR_STREAM_DESTROYED=_require$codes.ERR_STREAM_DESTROYED;function noop(err){if(err)throw err}function isRequest(stream){return stream.setHeader&&"function"==typeof stream.abort}function destroyer(stream,reading,writing,callback){callback=once(callback);var closed=!1;stream.on("close",function(){closed=!0}),void 0===eos&&(eos=require1("./end-of-stream")),eos(stream,{readable:reading,writable:writing},function(err){if(err)return callback(err);closed=!0,callback()});var destroyed=!1;return function(err){if(!closed&&!destroyed){if(destroyed=!0,isRequest(stream))return stream.abort();if("function"==typeof stream.destroy)return stream.destroy();callback(err||new ERR_STREAM_DESTROYED("pipe"))}}}function call(fn){fn()}function pipe(from,to){return from.pipe(to)}function popCallback(streams){return streams.length&&"function"==typeof streams[streams.length-1]?streams.pop():noop}function pipeline(){for(var error,_len=arguments.length,streams=Array(_len),_key=0;_key<_len;_key++)streams[_key]=arguments[_key];var callback=popCallback(streams);if(Array.isArray(streams[0])&&(streams=streams[0]),streams.length<2)throw new ERR_MISSING_ARGS("streams");var destroys=streams.map(function(stream,i){var reading=i<streams.length-1;return destroyer(stream,reading,i>0,function(err){error||(error=err),err&&destroys.forEach(call),reading||(destroys.forEach(call),callback(error))})});return streams.reduce(pipe)}module.exports=pipeline},{"../../../errors":156,"./end-of-stream":165}],168:[function(require1,module,exports){"use strict";var ERR_INVALID_OPT_VALUE=require1("../../../errors").codes.ERR_INVALID_OPT_VALUE;function highWaterMarkFrom(options,isDuplex,duplexKey){return null!=options.highWaterMark?options.highWaterMark:isDuplex?options[duplexKey]:null}function getHighWaterMark(state,options,duplexKey,isDuplex){var hwm=highWaterMarkFrom(options,isDuplex,duplexKey);if(null!=hwm){if(!(isFinite(hwm)&&Math.floor(hwm)===hwm)||hwm<0)throw new ERR_INVALID_OPT_VALUE(isDuplex?duplexKey:"highWaterMark",hwm);return Math.floor(hwm)}return state.objectMode?16:16384}module.exports={getHighWaterMark:getHighWaterMark}},{"../../../errors":156}],169:[function(require1,module,exports){arguments[4][41][0].apply(exports,arguments)},{dup:41,events:80}],170:[function(require1,module,exports){(exports=module.exports=require1("./lib/_stream_readable.js")).Stream=exports,exports.Readable=exports,exports.Writable=require1("./lib/_stream_writable.js"),exports.Duplex=require1("./lib/_stream_duplex.js"),exports.Transform=require1("./lib/_stream_transform.js"),exports.PassThrough=require1("./lib/_stream_passthrough.js"),exports.finished=require1("./lib/internal/streams/end-of-stream.js"),exports.pipeline=require1("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":157,"./lib/_stream_passthrough.js":158,"./lib/_stream_readable.js":159,"./lib/_stream_transform.js":160,"./lib/_stream_writable.js":161,"./lib/internal/streams/end-of-stream.js":165,"./lib/internal/streams/pipeline.js":167}],171:[function(require1,module,exports){var EventEmitter=require1("events").EventEmitter,backoff=require1("backoff"),noop=function(){};module.exports=function(createConnection){return function(opts,onConnect){onConnect="function"==typeof opts?opts:onConnect,opts="object"==typeof opts?opts:{initialDelay:1e3,maxDelay:3e4},onConnect||(onConnect=opts.onConnect);var args,emitter=opts.emitter||new EventEmitter;emitter.connected=!1,emitter.reconnect=!0,onConnect&&emitter.on("connect",onConnect);var backoffMethod=(backoff[opts.type]||backoff.fibonacci)(opts);backoffMethod.on("backoff",function(n,d){emitter.emit("backoff",n,d)});var cleanup=noop;function attempt(n,delay){if(emitter.reconnect){cleanup(),emitter.emit("reconnect",n,delay);var con=createConnection.apply(null,args);con!==emitter._connection&&emitter.emit("connection",con),emitter._connection=con,cleanup=onCleanup,con.on("error",onDisconnect).on("close",onDisconnect).on("end",onDisconnect),opts.immediate||"Request"==con.constructor.name?(emitter.connected=!0,emitter.emit("connect",con),con.once("data",function(){backoffMethod.reset()})):con.on("connect",connect)}function onCleanup(err){cleanup=noop,con.removeListener("connect",connect),con.removeListener("error",onDisconnect),con.removeListener("close",onDisconnect),con.removeListener("end",onDisconnect),"Request"==con.constructor.name&&con.on("error",noop)}function onDisconnect(err){if(emitter.connected=!1,onCleanup(err),emitter.emit("disconnect",err),emitter.reconnect)try{backoffMethod.backoff()}catch(_){}}function connect(){backoffMethod.reset(),emitter.connected=!0,onConnect&&con.removeListener("connect",onConnect),emitter.emit("connect",con)}}return backoffMethod.on("ready",attempt),emitter.connect=emitter.listen=function(){return this.reconnect=!0,backoffMethod.reset(),args=[].slice.call(arguments),attempt(0,0),emitter},emitter.end=emitter.disconnect=function(){return emitter.reconnect=!1,emitter._connection&&emitter._connection.end(),emitter.emit("disconnect"),emitter},emitter}}},{backoff:21,events:80}],172:[function(require1,module,exports){"use strict";var SDPUtils=require1("sdp");function fixStatsType(stat){return({inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"})[stat.type]||stat.type}function writeMediaSection(transceiver,caps,type,stream,dtlsRole){var sdp=SDPUtils.writeRtpDescription(transceiver.kind,caps);if(sdp+=SDPUtils.writeIceParameters(transceiver.iceGatherer.getLocalParameters())+SDPUtils.writeDtlsParameters(transceiver.dtlsTransport.getLocalParameters(),"offer"===type?"actpass":dtlsRole||"active")+"a=mid:"+transceiver.mid+"\r\n",transceiver.rtpSender&&transceiver.rtpReceiver?sdp+="a=sendrecv\r\n":transceiver.rtpSender?sdp+="a=sendonly\r\n":transceiver.rtpReceiver?sdp+="a=recvonly\r\n":sdp+="a=inactive\r\n",transceiver.rtpSender){var trackId=transceiver.rtpSender._initialTrackId||transceiver.rtpSender.track.id;transceiver.rtpSender._initialTrackId=trackId;var msid="msid:"+(stream?stream.id:"-")+" "+trackId+"\r\n";sdp+="a="+msid+("a=ssrc:"+transceiver.sendEncodingParameters[0].ssrc)+" "+msid,transceiver.sendEncodingParameters[0].rtx&&(sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].rtx.ssrc+" "+msid+("a=ssrc-group:FID "+transceiver.sendEncodingParameters[0].ssrc+" ")+transceiver.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].ssrc+" cname:"+SDPUtils.localCName+"\r\n",transceiver.rtpSender&&transceiver.sendEncodingParameters[0].rtx&&(sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].rtx.ssrc+" cname:"+SDPUtils.localCName+"\r\n"),sdp}function filterIceServers(iceServers,edgeVersion){var hasTurn=!1;return(iceServers=JSON.parse(JSON.stringify(iceServers))).filter(function(server){if(server&&(server.urls||server.url)){var urls=server.urls||server.url;server.url&&!server.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var isString="string"==typeof urls;return isString&&(urls=[urls]),urls=urls.filter(function(url){return 0!==url.indexOf("turn:")||-1===url.indexOf("transport=udp")||-1!==url.indexOf("turn:[")||hasTurn?0===url.indexOf("stun:")&&edgeVersion>=14393&&-1===url.indexOf("?transport=udp"):(hasTurn=!0,!0)}),delete server.url,server.urls=isString?urls[0]:urls,!!urls.length}})}function getCommonCapabilities(localCapabilities,remoteCapabilities){var commonCapabilities={codecs:[],headerExtensions:[],fecMechanisms:[]},findCodecByPayloadType=function(pt,codecs){pt=parseInt(pt,10);for(var i=0;i<codecs.length;i++)if(codecs[i].payloadType===pt||codecs[i].preferredPayloadType===pt)return codecs[i]},rtxCapabilityMatches=function(lRtx,rRtx,lCodecs,rCodecs){var lCodec=findCodecByPayloadType(lRtx.parameters.apt,lCodecs),rCodec=findCodecByPayloadType(rRtx.parameters.apt,rCodecs);return lCodec&&rCodec&&lCodec.name.toLowerCase()===rCodec.name.toLowerCase()};return localCapabilities.codecs.forEach(function(lCodec){for(var i=0;i<remoteCapabilities.codecs.length;i++){var rCodec=remoteCapabilities.codecs[i];if(lCodec.name.toLowerCase()===rCodec.name.toLowerCase()&&lCodec.clockRate===rCodec.clockRate){if("rtx"===lCodec.name.toLowerCase()&&lCodec.parameters&&rCodec.parameters.apt&&!rtxCapabilityMatches(lCodec,rCodec,localCapabilities.codecs,remoteCapabilities.codecs))continue;(rCodec=JSON.parse(JSON.stringify(rCodec))).numChannels=Math.min(lCodec.numChannels,rCodec.numChannels),commonCapabilities.codecs.push(rCodec),rCodec.rtcpFeedback=rCodec.rtcpFeedback.filter(function(fb){for(var j=0;j<lCodec.rtcpFeedback.length;j++)if(lCodec.rtcpFeedback[j].type===fb.type&&lCodec.rtcpFeedback[j].parameter===fb.parameter)return!0;return!1});break}}}),localCapabilities.headerExtensions.forEach(function(lHeaderExtension){for(var i=0;i<remoteCapabilities.headerExtensions.length;i++){var rHeaderExtension=remoteCapabilities.headerExtensions[i];if(lHeaderExtension.uri===rHeaderExtension.uri){commonCapabilities.headerExtensions.push(rHeaderExtension);break}}}),commonCapabilities}function isActionAllowedInSignalingState(action,type,signalingState){return -1!==({offer:{setLocalDescription:["stable","have-local-offer"],setRemoteDescription:["stable","have-remote-offer"]},answer:{setLocalDescription:["have-remote-offer","have-local-pranswer"],setRemoteDescription:["have-local-offer","have-remote-pranswer"]}})[type][action].indexOf(signalingState)}function maybeAddCandidate(iceTransport,candidate){var alreadyAdded=iceTransport.getRemoteCandidates().find(function(remoteCandidate){return candidate.foundation===remoteCandidate.foundation&&candidate.ip===remoteCandidate.ip&&candidate.port===remoteCandidate.port&&candidate.priority===remoteCandidate.priority&&candidate.protocol===remoteCandidate.protocol&&candidate.type===remoteCandidate.type});return alreadyAdded||iceTransport.addRemoteCandidate(candidate),!alreadyAdded}function makeError(name,description){var e=Error(description);return e.name=name,e.code=({NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0})[name],e}module.exports=function(window1,edgeVersion){function addTrackToStreamAndFireEvent(track,stream){stream.addTrack(track),stream.dispatchEvent(new window1.MediaStreamTrackEvent("addtrack",{track:track}))}function removeTrackFromStreamAndFireEvent(track,stream){stream.removeTrack(track),stream.dispatchEvent(new window1.MediaStreamTrackEvent("removetrack",{track:track}))}function fireAddTrack(pc,track,receiver,streams){var trackEvent=new Event("track");trackEvent.track=track,trackEvent.receiver=receiver,trackEvent.transceiver={receiver:receiver},trackEvent.streams=streams,window1.setTimeout(function(){pc._dispatchEvent("track",trackEvent)})}var RTCPeerConnection=function(config){var pc=this,_eventTarget=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach(function(method){pc[method]=_eventTarget[method].bind(_eventTarget)}),this.canTrickleIceCandidates=null,this.needNegotiation=!1,this.localStreams=[],this.remoteStreams=[],this._localDescription=null,this._remoteDescription=null,this.signalingState="stable",this.iceConnectionState="new",this.connectionState="new",this.iceGatheringState="new",config=JSON.parse(JSON.stringify(config||{})),this.usingBundle="max-bundle"===config.bundlePolicy,"negotiate"===config.rtcpMuxPolicy)throw makeError("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(config.rtcpMuxPolicy||(config.rtcpMuxPolicy="require"),config.iceTransportPolicy){case"all":case"relay":break;default:config.iceTransportPolicy="all"}switch(config.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:config.bundlePolicy="balanced"}if(config.iceServers=filterIceServers(config.iceServers||[],edgeVersion),this._iceGatherers=[],config.iceCandidatePoolSize)for(var i=config.iceCandidatePoolSize;i>0;i--)this._iceGatherers.push(new window1.RTCIceGatherer({iceServers:config.iceServers,gatherPolicy:config.iceTransportPolicy}));else config.iceCandidatePoolSize=0;this._config=config,this.transceivers=[],this._sdpSessionId=SDPUtils.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(RTCPeerConnection.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(RTCPeerConnection.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),RTCPeerConnection.prototype.onicecandidate=null,RTCPeerConnection.prototype.onaddstream=null,RTCPeerConnection.prototype.ontrack=null,RTCPeerConnection.prototype.onremovestream=null,RTCPeerConnection.prototype.onsignalingstatechange=null,RTCPeerConnection.prototype.oniceconnectionstatechange=null,RTCPeerConnection.prototype.onconnectionstatechange=null,RTCPeerConnection.prototype.onicegatheringstatechange=null,RTCPeerConnection.prototype.onnegotiationneeded=null,RTCPeerConnection.prototype.ondatachannel=null,RTCPeerConnection.prototype._dispatchEvent=function(name,event){this._isClosed||(this.dispatchEvent(event),"function"==typeof this["on"+name]&&this["on"+name](event))},RTCPeerConnection.prototype._emitGatheringStateChange=function(){var event=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",event)},RTCPeerConnection.prototype.getConfiguration=function(){return this._config},RTCPeerConnection.prototype.getLocalStreams=function(){return this.localStreams},RTCPeerConnection.prototype.getRemoteStreams=function(){return this.remoteStreams},RTCPeerConnection.prototype._createTransceiver=function(kind,doNotAdd){var hasBundleTransport=this.transceivers.length>0,transceiver={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:kind,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&hasBundleTransport)transceiver.iceTransport=this.transceivers[0].iceTransport,transceiver.dtlsTransport=this.transceivers[0].dtlsTransport;else{var transports=this._createIceAndDtlsTransports();transceiver.iceTransport=transports.iceTransport,transceiver.dtlsTransport=transports.dtlsTransport}return doNotAdd||this.transceivers.push(transceiver),transceiver},RTCPeerConnection.prototype.addTrack=function(track,stream){if(this._isClosed)throw makeError("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");if(this.transceivers.find(function(s){return s.track===track}))throw makeError("InvalidAccessError","Track already exists.");for(var transceiver,i=0;i<this.transceivers.length;i++)this.transceivers[i].track||this.transceivers[i].kind!==track.kind||(transceiver=this.transceivers[i]);return transceiver||(transceiver=this._createTransceiver(track.kind)),this._maybeFireNegotiationNeeded(),-1===this.localStreams.indexOf(stream)&&this.localStreams.push(stream),transceiver.track=track,transceiver.stream=stream,transceiver.rtpSender=new window1.RTCRtpSender(track,transceiver.dtlsTransport),transceiver.rtpSender},RTCPeerConnection.prototype.addStream=function(stream){var pc=this;if(edgeVersion>=15025)stream.getTracks().forEach(function(track){pc.addTrack(track,stream)});else{var clonedStream=stream.clone();stream.getTracks().forEach(function(track,idx){var clonedTrack=clonedStream.getTracks()[idx];track.addEventListener("enabled",function(event){clonedTrack.enabled=event.enabled})}),clonedStream.getTracks().forEach(function(track){pc.addTrack(track,clonedStream)})}},RTCPeerConnection.prototype.removeTrack=function(sender){if(this._isClosed)throw makeError("InvalidStateError","Attempted to call removeTrack on a closed peerconnection.");if(!(sender instanceof window1.RTCRtpSender))throw TypeError("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.");var transceiver=this.transceivers.find(function(t){return t.rtpSender===sender});if(!transceiver)throw makeError("InvalidAccessError","Sender was not created by this connection.");var stream=transceiver.stream;transceiver.rtpSender.stop(),transceiver.rtpSender=null,transceiver.track=null,transceiver.stream=null,-1===this.transceivers.map(function(t){return t.stream}).indexOf(stream)&&this.localStreams.indexOf(stream)>-1&&this.localStreams.splice(this.localStreams.indexOf(stream),1),this._maybeFireNegotiationNeeded()},RTCPeerConnection.prototype.removeStream=function(stream){var pc=this;stream.getTracks().forEach(function(track){var sender=pc.getSenders().find(function(s){return s.track===track});sender&&pc.removeTrack(sender)})},RTCPeerConnection.prototype.getSenders=function(){return this.transceivers.filter(function(transceiver){return!!transceiver.rtpSender}).map(function(transceiver){return transceiver.rtpSender})},RTCPeerConnection.prototype.getReceivers=function(){return this.transceivers.filter(function(transceiver){return!!transceiver.rtpReceiver}).map(function(transceiver){return transceiver.rtpReceiver})},RTCPeerConnection.prototype._createIceGatherer=function(sdpMLineIndex,usingBundle){var pc=this;if(usingBundle&&sdpMLineIndex>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var iceGatherer=new window1.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(iceGatherer,"state",{value:"new",writable:!0}),this.transceivers[sdpMLineIndex].bufferedCandidateEvents=[],this.transceivers[sdpMLineIndex].bufferCandidates=function(event){var end=!event.candidate||0===Object.keys(event.candidate).length;iceGatherer.state=end?"completed":"gathering",null!==pc.transceivers[sdpMLineIndex].bufferedCandidateEvents&&pc.transceivers[sdpMLineIndex].bufferedCandidateEvents.push(event)},iceGatherer.addEventListener("localcandidate",this.transceivers[sdpMLineIndex].bufferCandidates),iceGatherer},RTCPeerConnection.prototype._gather=function(mid,sdpMLineIndex){var pc=this,iceGatherer=this.transceivers[sdpMLineIndex].iceGatherer;if(!iceGatherer.onlocalcandidate){var bufferedCandidateEvents=this.transceivers[sdpMLineIndex].bufferedCandidateEvents;this.transceivers[sdpMLineIndex].bufferedCandidateEvents=null,iceGatherer.removeEventListener("localcandidate",this.transceivers[sdpMLineIndex].bufferCandidates),iceGatherer.onlocalcandidate=function(evt){if(!pc.usingBundle||!(sdpMLineIndex>0)){var event=new Event("icecandidate");event.candidate={sdpMid:mid,sdpMLineIndex:sdpMLineIndex};var cand=evt.candidate,end=!cand||0===Object.keys(cand).length;if(end)("new"===iceGatherer.state||"gathering"===iceGatherer.state)&&(iceGatherer.state="completed");else{"new"===iceGatherer.state&&(iceGatherer.state="gathering"),cand.component=1,cand.ufrag=iceGatherer.getLocalParameters().usernameFragment;var serializedCandidate=SDPUtils.writeCandidate(cand);event.candidate=Object.assign(event.candidate,SDPUtils.parseCandidate(serializedCandidate)),event.candidate.candidate=serializedCandidate,event.candidate.toJSON=function(){return{candidate:event.candidate.candidate,sdpMid:event.candidate.sdpMid,sdpMLineIndex:event.candidate.sdpMLineIndex,usernameFragment:event.candidate.usernameFragment}}}var sections=SDPUtils.getMediaSections(pc._localDescription.sdp);end?sections[event.candidate.sdpMLineIndex]+="a=end-of-candidates\r\n":sections[event.candidate.sdpMLineIndex]+="a="+event.candidate.candidate+"\r\n",pc._localDescription.sdp=SDPUtils.getDescription(pc._localDescription.sdp)+sections.join("");var complete=pc.transceivers.every(function(transceiver){return transceiver.iceGatherer&&"completed"===transceiver.iceGatherer.state});"gathering"!==pc.iceGatheringState&&(pc.iceGatheringState="gathering",pc._emitGatheringStateChange()),end||pc._dispatchEvent("icecandidate",event),complete&&(pc._dispatchEvent("icecandidate",new Event("icecandidate")),pc.iceGatheringState="complete",pc._emitGatheringStateChange())}},window1.setTimeout(function(){bufferedCandidateEvents.forEach(function(e){iceGatherer.onlocalcandidate(e)})},0)}},RTCPeerConnection.prototype._createIceAndDtlsTransports=function(){var pc=this,iceTransport=new window1.RTCIceTransport(null);iceTransport.onicestatechange=function(){pc._updateIceConnectionState(),pc._updateConnectionState()};var dtlsTransport=new window1.RTCDtlsTransport(iceTransport);return dtlsTransport.ondtlsstatechange=function(){pc._updateConnectionState()},dtlsTransport.onerror=function(){Object.defineProperty(dtlsTransport,"state",{value:"failed",writable:!0}),pc._updateConnectionState()},{iceTransport:iceTransport,dtlsTransport:dtlsTransport}},RTCPeerConnection.prototype._disposeIceAndDtlsTransports=function(sdpMLineIndex){var iceGatherer=this.transceivers[sdpMLineIndex].iceGatherer;iceGatherer&&(delete iceGatherer.onlocalcandidate,delete this.transceivers[sdpMLineIndex].iceGatherer);var iceTransport=this.transceivers[sdpMLineIndex].iceTransport;iceTransport&&(delete iceTransport.onicestatechange,delete this.transceivers[sdpMLineIndex].iceTransport);var dtlsTransport=this.transceivers[sdpMLineIndex].dtlsTransport;dtlsTransport&&(delete dtlsTransport.ondtlsstatechange,delete dtlsTransport.onerror,delete this.transceivers[sdpMLineIndex].dtlsTransport)},RTCPeerConnection.prototype._transceive=function(transceiver,send,recv){var params=getCommonCapabilities(transceiver.localCapabilities,transceiver.remoteCapabilities);send&&transceiver.rtpSender&&(params.encodings=transceiver.sendEncodingParameters,params.rtcp={cname:SDPUtils.localCName,compound:transceiver.rtcpParameters.compound},transceiver.recvEncodingParameters.length&&(params.rtcp.ssrc=transceiver.recvEncodingParameters[0].ssrc),transceiver.rtpSender.send(params)),recv&&transceiver.rtpReceiver&¶ms.codecs.length>0&&("video"===transceiver.kind&&transceiver.recvEncodingParameters&&edgeVersion<15019&&transceiver.recvEncodingParameters.forEach(function(p){delete p.rtx}),transceiver.recvEncodingParameters.length?params.encodings=transceiver.recvEncodingParameters:params.encodings=[{}],params.rtcp={compound:transceiver.rtcpParameters.compound},transceiver.rtcpParameters.cname&&(params.rtcp.cname=transceiver.rtcpParameters.cname),transceiver.sendEncodingParameters.length&&(params.rtcp.ssrc=transceiver.sendEncodingParameters[0].ssrc),transceiver.rtpReceiver.receive(params))},RTCPeerConnection.prototype.setLocalDescription=function(description){var sections,sessionpart,pc=this;if(-1===["offer","answer"].indexOf(description.type))return Promise.reject(makeError("TypeError",'Unsupported type "'+description.type+'"'));if(!isActionAllowedInSignalingState("setLocalDescription",description.type,pc.signalingState)||pc._isClosed)return Promise.reject(makeError("InvalidStateError","Can not set local "+description.type+" in state "+pc.signalingState));if("offer"===description.type)sessionpart=(sections=SDPUtils.splitSections(description.sdp)).shift(),sections.forEach(function(mediaSection,sdpMLineIndex){var caps=SDPUtils.parseRtpParameters(mediaSection);pc.transceivers[sdpMLineIndex].localCapabilities=caps}),pc.transceivers.forEach(function(transceiver,sdpMLineIndex){pc._gather(transceiver.mid,sdpMLineIndex)});else if("answer"===description.type){sessionpart=(sections=SDPUtils.splitSections(pc._remoteDescription.sdp)).shift();var isIceLite=SDPUtils.matchPrefix(sessionpart,"a=ice-lite").length>0;sections.forEach(function(mediaSection,sdpMLineIndex){var transceiver=pc.transceivers[sdpMLineIndex],iceGatherer=transceiver.iceGatherer,iceTransport=transceiver.iceTransport,dtlsTransport=transceiver.dtlsTransport,localCapabilities=transceiver.localCapabilities,remoteCapabilities=transceiver.remoteCapabilities;if(!(SDPUtils.isRejected(mediaSection)&&0===SDPUtils.matchPrefix(mediaSection,"a=bundle-only").length)&&!transceiver.rejected){var remoteIceParameters=SDPUtils.getIceParameters(mediaSection,sessionpart),remoteDtlsParameters=SDPUtils.getDtlsParameters(mediaSection,sessionpart);isIceLite&&(remoteDtlsParameters.role="server"),pc.usingBundle&&0!==sdpMLineIndex||(pc._gather(transceiver.mid,sdpMLineIndex),"new"===iceTransport.state&&iceTransport.start(iceGatherer,remoteIceParameters,isIceLite?"controlling":"controlled"),"new"===dtlsTransport.state&&dtlsTransport.start(remoteDtlsParameters));var params=getCommonCapabilities(localCapabilities,remoteCapabilities);pc._transceive(transceiver,params.codecs.length>0,!1)}})}return pc._localDescription={type:description.type,sdp:description.sdp},"offer"===description.type?pc._updateSignalingState("have-local-offer"):pc._updateSignalingState("stable"),Promise.resolve()},RTCPeerConnection.prototype.setRemoteDescription=function(description){var pc=this;if(-1===["offer","answer"].indexOf(description.type))return Promise.reject(makeError("TypeError",'Unsupported type "'+description.type+'"'));if(!isActionAllowedInSignalingState("setRemoteDescription",description.type,pc.signalingState)||pc._isClosed)return Promise.reject(makeError("InvalidStateError","Can not set remote "+description.type+" in state "+pc.signalingState));var streams={};pc.remoteStreams.forEach(function(stream){streams[stream.id]=stream});var receiverList=[],sections=SDPUtils.splitSections(description.sdp),sessionpart=sections.shift(),isIceLite=SDPUtils.matchPrefix(sessionpart,"a=ice-lite").length>0,usingBundle=SDPUtils.matchPrefix(sessionpart,"a=group:BUNDLE ").length>0;pc.usingBundle=usingBundle;var iceOptions=SDPUtils.matchPrefix(sessionpart,"a=ice-options:")[0];return iceOptions?pc.canTrickleIceCandidates=iceOptions.substr(14).split(" ").indexOf("trickle")>=0:pc.canTrickleIceCandidates=!1,sections.forEach(function(mediaSection,sdpMLineIndex){var lines=SDPUtils.splitLines(mediaSection),kind=SDPUtils.getKind(mediaSection),rejected=SDPUtils.isRejected(mediaSection)&&0===SDPUtils.matchPrefix(mediaSection,"a=bundle-only").length,protocol=lines[0].substr(2).split(" ")[2],direction=SDPUtils.getDirection(mediaSection,sessionpart),remoteMsid=SDPUtils.parseMsid(mediaSection),mid=SDPUtils.getMid(mediaSection)||SDPUtils.generateIdentifier();if(rejected||"application"===kind&&("DTLS/SCTP"===protocol||"UDP/DTLS/SCTP"===protocol)){pc.transceivers[sdpMLineIndex]={mid:mid,kind:kind,protocol:protocol,rejected:!0};return}!rejected&&pc.transceivers[sdpMLineIndex]&&pc.transceivers[sdpMLineIndex].rejected&&(pc.transceivers[sdpMLineIndex]=pc._createTransceiver(kind,!0));var remoteCapabilities=SDPUtils.parseRtpParameters(mediaSection);rejected||(remoteIceParameters=SDPUtils.getIceParameters(mediaSection,sessionpart),(remoteDtlsParameters=SDPUtils.getDtlsParameters(mediaSection,sessionpart)).role="client"),recvEncodingParameters=SDPUtils.parseRtpEncodingParameters(mediaSection);var rtcpParameters=SDPUtils.parseRtcpParameters(mediaSection),isComplete=SDPUtils.matchPrefix(mediaSection,"a=end-of-candidates",sessionpart).length>0,cands=SDPUtils.matchPrefix(mediaSection,"a=candidate:").map(function(cand){return SDPUtils.parseCandidate(cand)}).filter(function(cand){return 1===cand.component});if(("offer"===description.type||"answer"===description.type)&&!rejected&&usingBundle&&sdpMLineIndex>0&&pc.transceivers[sdpMLineIndex]&&(pc._disposeIceAndDtlsTransports(sdpMLineIndex),pc.transceivers[sdpMLineIndex].iceGatherer=pc.transceivers[0].iceGatherer,pc.transceivers[sdpMLineIndex].iceTransport=pc.transceivers[0].iceTransport,pc.transceivers[sdpMLineIndex].dtlsTransport=pc.transceivers[0].dtlsTransport,pc.transceivers[sdpMLineIndex].rtpSender&&pc.transceivers[sdpMLineIndex].rtpSender.setTransport(pc.transceivers[0].dtlsTransport),pc.transceivers[sdpMLineIndex].rtpReceiver&&pc.transceivers[sdpMLineIndex].rtpReceiver.setTransport(pc.transceivers[0].dtlsTransport)),"offer"!==description.type||rejected)"answer"!==description.type||rejected||(iceGatherer=(transceiver=pc.transceivers[sdpMLineIndex]).iceGatherer,iceTransport=transceiver.iceTransport,dtlsTransport=transceiver.dtlsTransport,rtpReceiver=transceiver.rtpReceiver,sendEncodingParameters=transceiver.sendEncodingParameters,localCapabilities=transceiver.localCapabilities,pc.transceivers[sdpMLineIndex].recvEncodingParameters=recvEncodingParameters,pc.transceivers[sdpMLineIndex].remoteCapabilities=remoteCapabilities,pc.transceivers[sdpMLineIndex].rtcpParameters=rtcpParameters,cands.length&&"new"===iceTransport.state&&((isIceLite||isComplete)&&(!usingBundle||0===sdpMLineIndex)?iceTransport.setRemoteCandidates(cands):cands.forEach(function(candidate){maybeAddCandidate(transceiver.iceTransport,candidate)})),usingBundle&&0!==sdpMLineIndex||("new"===iceTransport.state&&iceTransport.start(iceGatherer,remoteIceParameters,"controlling"),"new"===dtlsTransport.state&&dtlsTransport.start(remoteDtlsParameters)),!getCommonCapabilities(transceiver.localCapabilities,transceiver.remoteCapabilities).codecs.filter(function(c){return"rtx"===c.name.toLowerCase()}).length&&transceiver.sendEncodingParameters[0].rtx&&delete transceiver.sendEncodingParameters[0].rtx,pc._transceive(transceiver,"sendrecv"===direction||"recvonly"===direction,"sendrecv"===direction||"sendonly"===direction),rtpReceiver&&("sendrecv"===direction||"sendonly"===direction)?(track=rtpReceiver.track,remoteMsid?(streams[remoteMsid.stream]||(streams[remoteMsid.stream]=new window1.MediaStream),addTrackToStreamAndFireEvent(track,streams[remoteMsid.stream]),receiverList.push([track,rtpReceiver,streams[remoteMsid.stream]])):(streams.default||(streams.default=new window1.MediaStream),addTrackToStreamAndFireEvent(track,streams.default),receiverList.push([track,rtpReceiver,streams.default]))):delete transceiver.rtpReceiver);else{(transceiver=pc.transceivers[sdpMLineIndex]||pc._createTransceiver(kind)).mid=mid,transceiver.iceGatherer||(transceiver.iceGatherer=pc._createIceGatherer(sdpMLineIndex,usingBundle)),cands.length&&"new"===transceiver.iceTransport.state&&(isComplete&&(!usingBundle||0===sdpMLineIndex)?transceiver.iceTransport.setRemoteCandidates(cands):cands.forEach(function(candidate){maybeAddCandidate(transceiver.iceTransport,candidate)})),localCapabilities=window1.RTCRtpReceiver.getCapabilities(kind),edgeVersion<15019&&(localCapabilities.codecs=localCapabilities.codecs.filter(function(codec){return"rtx"!==codec.name})),sendEncodingParameters=transceiver.sendEncodingParameters||[{ssrc:(2*sdpMLineIndex+2)*1001}];var transceiver,iceGatherer,iceTransport,dtlsTransport,rtpReceiver,sendEncodingParameters,recvEncodingParameters,localCapabilities,track,remoteIceParameters,remoteDtlsParameters,stream,isNewTrack=!1;"sendrecv"===direction||"sendonly"===direction?(isNewTrack=!transceiver.rtpReceiver,rtpReceiver=transceiver.rtpReceiver||new window1.RTCRtpReceiver(transceiver.dtlsTransport,kind),isNewTrack&&(track=rtpReceiver.track,remoteMsid&&"-"===remoteMsid.stream||(remoteMsid?(streams[remoteMsid.stream]||(streams[remoteMsid.stream]=new window1.MediaStream,Object.defineProperty(streams[remoteMsid.stream],"id",{get:function(){return remoteMsid.stream}})),Object.defineProperty(track,"id",{get:function(){return remoteMsid.track}}),stream=streams[remoteMsid.stream]):(streams.default||(streams.default=new window1.MediaStream),stream=streams.default)),stream&&(addTrackToStreamAndFireEvent(track,stream),transceiver.associatedRemoteMediaStreams.push(stream)),receiverList.push([track,rtpReceiver,stream]))):transceiver.rtpReceiver&&transceiver.rtpReceiver.track&&(transceiver.associatedRemoteMediaStreams.forEach(function(s){var nativeTrack=s.getTracks().find(function(t){return t.id===transceiver.rtpReceiver.track.id});nativeTrack&&removeTrackFromStreamAndFireEvent(nativeTrack,s)}),transceiver.associatedRemoteMediaStreams=[]),transceiver.localCapabilities=localCapabilities,transceiver.remoteCapabilities=remoteCapabilities,transceiver.rtpReceiver=rtpReceiver,transceiver.rtcpParameters=rtcpParameters,transceiver.sendEncodingParameters=sendEncodingParameters,transceiver.recvEncodingParameters=recvEncodingParameters,pc._transceive(pc.transceivers[sdpMLineIndex],!1,isNewTrack)}}),void 0===pc._dtlsRole&&(pc._dtlsRole="offer"===description.type?"active":"passive"),pc._remoteDescription={type:description.type,sdp:description.sdp},"offer"===description.type?pc._updateSignalingState("have-remote-offer"):pc._updateSignalingState("stable"),Object.keys(streams).forEach(function(sid){var stream=streams[sid];if(stream.getTracks().length){if(-1===pc.remoteStreams.indexOf(stream)){pc.remoteStreams.push(stream);var event=new Event("addstream");event.stream=stream,window1.setTimeout(function(){pc._dispatchEvent("addstream",event)})}receiverList.forEach(function(item){var track=item[0],receiver=item[1];stream.id===item[2].id&&fireAddTrack(pc,track,receiver,[stream])})}}),receiverList.forEach(function(item){item[2]||fireAddTrack(pc,item[0],item[1],[])}),window1.setTimeout(function(){pc&&pc.transceivers&&pc.transceivers.forEach(function(transceiver){transceiver.iceTransport&&"new"===transceiver.iceTransport.state&&transceiver.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),transceiver.iceTransport.addRemoteCandidate({}))})},4e3),Promise.resolve()},RTCPeerConnection.prototype.close=function(){this.transceivers.forEach(function(transceiver){transceiver.iceTransport&&transceiver.iceTransport.stop(),transceiver.dtlsTransport&&transceiver.dtlsTransport.stop(),transceiver.rtpSender&&transceiver.rtpSender.stop(),transceiver.rtpReceiver&&transceiver.rtpReceiver.stop()}),this._isClosed=!0,this._updateSignalingState("closed")},RTCPeerConnection.prototype._updateSignalingState=function(newState){this.signalingState=newState;var event=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",event)},RTCPeerConnection.prototype._maybeFireNegotiationNeeded=function(){var pc=this;"stable"===this.signalingState&&!0!==this.needNegotiation&&(this.needNegotiation=!0,window1.setTimeout(function(){if(pc.needNegotiation){pc.needNegotiation=!1;var event=new Event("negotiationneeded");pc._dispatchEvent("negotiationneeded",event)}},0))},RTCPeerConnection.prototype._updateIceConnectionState=function(){var newState,states={new:0,closed:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(transceiver){transceiver.iceTransport&&!transceiver.rejected&&states[transceiver.iceTransport.state]++}),newState="new",states.failed>0?newState="failed":states.checking>0?newState="checking":states.disconnected>0?newState="disconnected":states.new>0?newState="new":states.connected>0?newState="connected":states.completed>0&&(newState="completed"),newState!==this.iceConnectionState){this.iceConnectionState=newState;var event=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",event)}},RTCPeerConnection.prototype._updateConnectionState=function(){var newState,states={new:0,closed:0,connecting:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(transceiver){transceiver.iceTransport&&transceiver.dtlsTransport&&!transceiver.rejected&&(states[transceiver.iceTransport.state]++,states[transceiver.dtlsTransport.state]++)}),states.connected+=states.completed,newState="new",states.failed>0?newState="failed":states.connecting>0?newState="connecting":states.disconnected>0?newState="disconnected":states.new>0?newState="new":states.connected>0&&(newState="connected"),newState!==this.connectionState){this.connectionState=newState;var event=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",event)}},RTCPeerConnection.prototype.createOffer=function(){var pc=this;if(pc._isClosed)return Promise.reject(makeError("InvalidStateError","Can not call createOffer after close"));var numAudioTracks=pc.transceivers.filter(function(t){return"audio"===t.kind}).length,numVideoTracks=pc.transceivers.filter(function(t){return"video"===t.kind}).length,offerOptions=arguments[0];if(offerOptions){if(offerOptions.mandatory||offerOptions.optional)throw TypeError("Legacy mandatory/optional constraints not supported.");void 0!==offerOptions.offerToReceiveAudio&&(numAudioTracks=!0===offerOptions.offerToReceiveAudio?1:!1===offerOptions.offerToReceiveAudio?0:offerOptions.offerToReceiveAudio),void 0!==offerOptions.offerToReceiveVideo&&(numVideoTracks=!0===offerOptions.offerToReceiveVideo?1:!1===offerOptions.offerToReceiveVideo?0:offerOptions.offerToReceiveVideo)}for(pc.transceivers.forEach(function(transceiver){"audio"===transceiver.kind?--numAudioTracks<0&&(transceiver.wantReceive=!1):"video"===transceiver.kind&&--numVideoTracks<0&&(transceiver.wantReceive=!1)});numAudioTracks>0||numVideoTracks>0;)numAudioTracks>0&&(pc._createTransceiver("audio"),numAudioTracks--),numVideoTracks>0&&(pc._createTransceiver("video"),numVideoTracks--);var sdp=SDPUtils.writeSessionBoilerplate(pc._sdpSessionId,pc._sdpSessionVersion++);return pc.transceivers.forEach(function(transceiver,sdpMLineIndex){var track=transceiver.track,kind=transceiver.kind,mid=transceiver.mid||SDPUtils.generateIdentifier();transceiver.mid=mid,transceiver.iceGatherer||(transceiver.iceGatherer=pc._createIceGatherer(sdpMLineIndex,pc.usingBundle));var localCapabilities=window1.RTCRtpSender.getCapabilities(kind);edgeVersion<15019&&(localCapabilities.codecs=localCapabilities.codecs.filter(function(codec){return"rtx"!==codec.name})),localCapabilities.codecs.forEach(function(codec){"H264"===codec.name&&void 0===codec.parameters["level-asymmetry-allowed"]&&(codec.parameters["level-asymmetry-allowed"]="1"),transceiver.remoteCapabilities&&transceiver.remoteCapabilities.codecs&&transceiver.remoteCapabilities.codecs.forEach(function(remoteCodec){codec.name.toLowerCase()===remoteCodec.name.toLowerCase()&&codec.clockRate===remoteCodec.clockRate&&(codec.preferredPayloadType=remoteCodec.payloadType)})}),localCapabilities.headerExtensions.forEach(function(hdrExt){(transceiver.remoteCapabilities&&transceiver.remoteCapabilities.headerExtensions||[]).forEach(function(rHdrExt){hdrExt.uri===rHdrExt.uri&&(hdrExt.id=rHdrExt.id)})});var sendEncodingParameters=transceiver.sendEncodingParameters||[{ssrc:(2*sdpMLineIndex+1)*1001}];track&&edgeVersion>=15019&&"video"===kind&&!sendEncodingParameters[0].rtx&&(sendEncodingParameters[0].rtx={ssrc:sendEncodingParameters[0].ssrc+1}),transceiver.wantReceive&&(transceiver.rtpReceiver=new window1.RTCRtpReceiver(transceiver.dtlsTransport,kind)),transceiver.localCapabilities=localCapabilities,transceiver.sendEncodingParameters=sendEncodingParameters}),"max-compat"!==pc._config.bundlePolicy&&(sdp+="a=group:BUNDLE "+pc.transceivers.map(function(t){return t.mid}).join(" ")+"\r\n"),sdp+="a=ice-options:trickle\r\n",pc.transceivers.forEach(function(transceiver,sdpMLineIndex){sdp+=writeMediaSection(transceiver,transceiver.localCapabilities,"offer",transceiver.stream,pc._dtlsRole)+"a=rtcp-rsize\r\n",transceiver.iceGatherer&&"new"!==pc.iceGatheringState&&(0===sdpMLineIndex||!pc.usingBundle)&&(transceiver.iceGatherer.getLocalCandidates().forEach(function(cand){cand.component=1,sdp+="a="+SDPUtils.writeCandidate(cand)+"\r\n"}),"completed"===transceiver.iceGatherer.state&&(sdp+="a=end-of-candidates\r\n"))}),Promise.resolve(new window1.RTCSessionDescription({type:"offer",sdp:sdp}))},RTCPeerConnection.prototype.createAnswer=function(){var pc=this;if(pc._isClosed)return Promise.reject(makeError("InvalidStateError","Can not call createAnswer after close"));if(!("have-remote-offer"===pc.signalingState||"have-local-pranswer"===pc.signalingState))return Promise.reject(makeError("InvalidStateError","Can not call createAnswer in signalingState "+pc.signalingState));var sdp=SDPUtils.writeSessionBoilerplate(pc._sdpSessionId,pc._sdpSessionVersion++);pc.usingBundle&&(sdp+="a=group:BUNDLE "+pc.transceivers.map(function(t){return t.mid}).join(" ")+"\r\n"),sdp+="a=ice-options:trickle\r\n";var mediaSectionsInOffer=SDPUtils.getMediaSections(pc._remoteDescription.sdp).length;return pc.transceivers.forEach(function(transceiver,sdpMLineIndex){if(!(sdpMLineIndex+1>mediaSectionsInOffer)){if(transceiver.rejected){"application"===transceiver.kind?"DTLS/SCTP"===transceiver.protocol?sdp+="m=application 0 DTLS/SCTP 5000\r\n":sdp+="m=application 0 "+transceiver.protocol+" webrtc-datachannel\r\n":"audio"===transceiver.kind?sdp+="m=audio 0 UDP/TLS/RTP/SAVPF 0\r\na=rtpmap:0 PCMU/8000\r\n":"video"===transceiver.kind&&(sdp+="m=video 0 UDP/TLS/RTP/SAVPF 120\r\na=rtpmap:120 VP8/90000\r\n"),sdp+="c=IN IP4 0.0.0.0\r\na=inactive\r\na=mid:"+transceiver.mid+"\r\n";return}if(transceiver.stream){var localTrack;"audio"===transceiver.kind?localTrack=transceiver.stream.getAudioTracks()[0]:"video"===transceiver.kind&&(localTrack=transceiver.stream.getVideoTracks()[0]),localTrack&&edgeVersion>=15019&&"video"===transceiver.kind&&!transceiver.sendEncodingParameters[0].rtx&&(transceiver.sendEncodingParameters[0].rtx={ssrc:transceiver.sendEncodingParameters[0].ssrc+1})}var commonCapabilities=getCommonCapabilities(transceiver.localCapabilities,transceiver.remoteCapabilities);!commonCapabilities.codecs.filter(function(c){return"rtx"===c.name.toLowerCase()}).length&&transceiver.sendEncodingParameters[0].rtx&&delete transceiver.sendEncodingParameters[0].rtx,sdp+=writeMediaSection(transceiver,commonCapabilities,"answer",transceiver.stream,pc._dtlsRole),transceiver.rtcpParameters&&transceiver.rtcpParameters.reducedSize&&(sdp+="a=rtcp-rsize\r\n")}}),Promise.resolve(new window1.RTCSessionDescription({type:"answer",sdp:sdp}))},RTCPeerConnection.prototype.addIceCandidate=function(candidate){var sections,pc=this;return candidate&&!(void 0!==candidate.sdpMLineIndex||candidate.sdpMid)?Promise.reject(TypeError("sdpMLineIndex or sdpMid required")):new Promise(function(resolve,reject){if(!pc._remoteDescription)return reject(makeError("InvalidStateError","Can not add ICE candidate without a remote description"));if(candidate&&""!==candidate.candidate){var sdpMLineIndex=candidate.sdpMLineIndex;if(candidate.sdpMid){for(var i=0;i<pc.transceivers.length;i++)if(pc.transceivers[i].mid===candidate.sdpMid){sdpMLineIndex=i;break}}var transceiver=pc.transceivers[sdpMLineIndex];if(!transceiver)return reject(makeError("OperationError","Can not add ICE candidate"));if(transceiver.rejected)return resolve();var cand=Object.keys(candidate.candidate).length>0?SDPUtils.parseCandidate(candidate.candidate):{};if("tcp"===cand.protocol&&(0===cand.port||9===cand.port)||cand.component&&1!==cand.component)return resolve();if((0===sdpMLineIndex||sdpMLineIndex>0&&transceiver.iceTransport!==pc.transceivers[0].iceTransport)&&!maybeAddCandidate(transceiver.iceTransport,cand))return reject(makeError("OperationError","Can not add ICE candidate"));var candidateString=candidate.candidate.trim();0===candidateString.indexOf("a=")&&(candidateString=candidateString.substr(2)),sections=SDPUtils.getMediaSections(pc._remoteDescription.sdp),sections[sdpMLineIndex]+="a="+(cand.type?candidateString:"end-of-candidates")+"\r\n",pc._remoteDescription.sdp=SDPUtils.getDescription(pc._remoteDescription.sdp)+sections.join("")}else for(var j=0;j<pc.transceivers.length&&(pc.transceivers[j].rejected||(pc.transceivers[j].iceTransport.addRemoteCandidate({}),sections=SDPUtils.getMediaSections(pc._remoteDescription.sdp),sections[j]+="a=end-of-candidates\r\n",pc._remoteDescription.sdp=SDPUtils.getDescription(pc._remoteDescription.sdp)+sections.join(""),!pc.usingBundle));j++);resolve()})},RTCPeerConnection.prototype.getStats=function(selector){if(selector&&selector instanceof window1.MediaStreamTrack){var senderOrReceiver=null;if(this.transceivers.forEach(function(transceiver){transceiver.rtpSender&&transceiver.rtpSender.track===selector?senderOrReceiver=transceiver.rtpSender:transceiver.rtpReceiver&&transceiver.rtpReceiver.track===selector&&(senderOrReceiver=transceiver.rtpReceiver)}),!senderOrReceiver)throw makeError("InvalidAccessError","Invalid selector.");return senderOrReceiver.getStats()}var promises=[];return this.transceivers.forEach(function(transceiver){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach(function(method){transceiver[method]&&promises.push(transceiver[method].getStats())})}),Promise.all(promises).then(function(allStats){var results=new Map;return allStats.forEach(function(stats){stats.forEach(function(stat){results.set(stat.id,stat)})}),results})},["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"].forEach(function(ortcObjectName){var obj=window1[ortcObjectName];if(obj&&obj.prototype&&obj.prototype.getStats){var nativeGetstats=obj.prototype.getStats;obj.prototype.getStats=function(){return nativeGetstats.apply(this).then(function(nativeStats){var mapStats=new Map;return Object.keys(nativeStats).forEach(function(id){nativeStats[id].type=fixStatsType(nativeStats[id]),mapStats.set(id,nativeStats[id])}),mapStats})}}});var methods=["createOffer","createAnswer"];return methods.forEach(function(method){var nativeMethod=RTCPeerConnection.prototype[method];RTCPeerConnection.prototype[method]=function(){var args=arguments;return"function"==typeof args[0]||"function"==typeof args[1]?nativeMethod.apply(this,[arguments[2]]).then(function(description){"function"==typeof args[0]&&args[0].apply(null,[description])},function(error){"function"==typeof args[1]&&args[1].apply(null,[error])}):nativeMethod.apply(this,arguments)}}),(methods=["setLocalDescription","setRemoteDescription","addIceCandidate"]).forEach(function(method){var nativeMethod=RTCPeerConnection.prototype[method];RTCPeerConnection.prototype[method]=function(){var args=arguments;return"function"==typeof args[1]||"function"==typeof args[2]?nativeMethod.apply(this,arguments).then(function(){"function"==typeof args[1]&&args[1].apply(null)},function(error){"function"==typeof args[2]&&args[2].apply(null,[error])}):nativeMethod.apply(this,arguments)}}),["getStats"].forEach(function(method){var nativeMethod=RTCPeerConnection.prototype[method];RTCPeerConnection.prototype[method]=function(){var args=arguments;return"function"==typeof args[1]?nativeMethod.apply(this,arguments).then(function(){"function"==typeof args[1]&&args[1].apply(null)}):nativeMethod.apply(this,arguments)}}),RTCPeerConnection}},{sdp:175}],173:[function(require1,module,exports){/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var buffer=require1("buffer"),Buffer=buffer.Buffer;function copyProps(src,dst){for(var key in src)dst[key]=src[key]}function SafeBuffer(arg,encodingOrOffset,length){return Buffer(arg,encodingOrOffset,length)}Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow?module.exports=buffer:(copyProps(buffer,exports),exports.Buffer=SafeBuffer),SafeBuffer.prototype=Object.create(Buffer.prototype),copyProps(Buffer,SafeBuffer),SafeBuffer.from=function(arg,encodingOrOffset,length){if("number"==typeof arg)throw TypeError("Argument must not be a number");return Buffer(arg,encodingOrOffset,length)},SafeBuffer.alloc=function(size,fill,encoding){if("number"!=typeof size)throw TypeError("Argument must be a number");var buf=Buffer(size);return void 0!==fill?"string"==typeof encoding?buf.fill(fill,encoding):buf.fill(fill):buf.fill(0),buf},SafeBuffer.allocUnsafe=function(size){if("number"!=typeof size)throw TypeError("Argument must be a number");return Buffer(size)},SafeBuffer.allocUnsafeSlow=function(size){if("number"!=typeof size)throw TypeError("Argument must be a number");return buffer.SlowBuffer(size)}},{buffer:47}],174:[function(require1,module,exports){(function(process){(function(){"use strict";var key,buffer=require1("buffer"),Buffer=buffer.Buffer,safer={};for(key in buffer)buffer.hasOwnProperty(key)&&"SlowBuffer"!==key&&"Buffer"!==key&&(safer[key]=buffer[key]);var Safer=safer.Buffer={};for(key in Buffer)Buffer.hasOwnProperty(key)&&"allocUnsafe"!==key&&"allocUnsafeSlow"!==key&&(Safer[key]=Buffer[key]);if(safer.Buffer.prototype=Buffer.prototype,Safer.from&&Safer.from!==Uint8Array.from||(Safer.from=function(value,encodingOrOffset,length){if("number"==typeof value)throw TypeError('The "value" argument must not be of type number. Received type '+typeof value);if(value&&void 0===value.length)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof value);return Buffer(value,encodingOrOffset,length)}),Safer.alloc||(Safer.alloc=function(size,fill,encoding){if("number"!=typeof size)throw TypeError('The "size" argument must be of type number. Received type '+typeof size);if(size<0||size>=2*1073741824)throw RangeError('The value "'+size+'" is invalid for option "size"');var buf=Buffer(size);return fill&&0!==fill.length?"string"==typeof encoding?buf.fill(fill,encoding):buf.fill(fill):buf.fill(0),buf}),!safer.kStringMaxLength)try{safer.kStringMaxLength=process.binding("buffer").kStringMaxLength}catch(e){}!safer.constants&&(safer.constants={MAX_LENGTH:safer.kMaxLength},safer.kStringMaxLength&&(safer.constants.MAX_STRING_LENGTH=safer.kStringMaxLength)),module.exports=safer}).call(this)}).call(this,require1("_process"))},{_process:152,buffer:47}],175:[function(require1,module,exports){"use strict";var SDPUtils={};SDPUtils.generateIdentifier=function(){return Math.random().toString(36).substr(2,10)},SDPUtils.localCName=SDPUtils.generateIdentifier(),SDPUtils.splitLines=function(blob){return blob.trim().split("\n").map(function(line){return line.trim()})},SDPUtils.splitSections=function(blob){return blob.split("\nm=").map(function(part,index){return(index>0?"m="+part:part).trim()+"\r\n"})},SDPUtils.getDescription=function(blob){var sections=SDPUtils.splitSections(blob);return sections&§ions[0]},SDPUtils.getMediaSections=function(blob){var sections=SDPUtils.splitSections(blob);return sections.shift(),sections},SDPUtils.matchPrefix=function(blob,prefix){return SDPUtils.splitLines(blob).filter(function(line){return 0===line.indexOf(prefix)})},SDPUtils.parseCandidate=function(line){for(var parts,candidate={foundation:(parts=0===line.indexOf("a=candidate:")?line.substring(12).split(" "):line.substring(10).split(" "))[0],component:parseInt(parts[1],10),protocol:parts[2].toLowerCase(),priority:parseInt(parts[3],10),ip:parts[4],address:parts[4],port:parseInt(parts[5],10),type:parts[7]},i=8;i<parts.length;i+=2)switch(parts[i]){case"raddr":candidate.relatedAddress=parts[i+1];break;case"rport":candidate.relatedPort=parseInt(parts[i+1],10);break;case"tcptype":candidate.tcpType=parts[i+1];break;case"ufrag":candidate.ufrag=parts[i+1],candidate.usernameFragment=parts[i+1];break;default:candidate[parts[i]]=parts[i+1]}return candidate},SDPUtils.writeCandidate=function(candidate){var sdp=[];sdp.push(candidate.foundation),sdp.push(candidate.component),sdp.push(candidate.protocol.toUpperCase()),sdp.push(candidate.priority),sdp.push(candidate.address||candidate.ip),sdp.push(candidate.port);var type=candidate.type;return sdp.push("typ"),sdp.push(type),"host"!==type&&candidate.relatedAddress&&candidate.relatedPort&&(sdp.push("raddr"),sdp.push(candidate.relatedAddress),sdp.push("rport"),sdp.push(candidate.relatedPort)),candidate.tcpType&&"tcp"===candidate.protocol.toLowerCase()&&(sdp.push("tcptype"),sdp.push(candidate.tcpType)),(candidate.usernameFragment||candidate.ufrag)&&(sdp.push("ufrag"),sdp.push(candidate.usernameFragment||candidate.ufrag)),"candidate:"+sdp.join(" ")},SDPUtils.parseIceOptions=function(line){return line.substr(14).split(" ")},SDPUtils.parseRtpMap=function(line){var parts=line.substr(9).split(" "),parsed={payloadType:parseInt(parts.shift(),10)};return parts=parts[0].split("/"),parsed.name=parts[0],parsed.clockRate=parseInt(parts[1],10),parsed.channels=3===parts.length?parseInt(parts[2],10):1,parsed.numChannels=parsed.channels,parsed},SDPUtils.writeRtpMap=function(codec){var pt=codec.payloadType;void 0!==codec.preferredPayloadType&&(pt=codec.preferredPayloadType);var channels=codec.channels||codec.numChannels||1;return"a=rtpmap:"+pt+" "+codec.name+"/"+codec.clockRate+(1!==channels?"/"+channels:"")+"\r\n"},SDPUtils.parseExtmap=function(line){var parts=line.substr(9).split(" ");return{id:parseInt(parts[0],10),direction:parts[0].indexOf("/")>0?parts[0].split("/")[1]:"sendrecv",uri:parts[1]}},SDPUtils.writeExtmap=function(headerExtension){return"a=extmap:"+(headerExtension.id||headerExtension.preferredId)+(headerExtension.direction&&"sendrecv"!==headerExtension.direction?"/"+headerExtension.direction:"")+" "+headerExtension.uri+"\r\n"},SDPUtils.parseFmtp=function(line){for(var kv,parsed={},parts=line.substr(line.indexOf(" ")+1).split(";"),j=0;j<parts.length;j++)parsed[(kv=parts[j].trim().split("="))[0].trim()]=kv[1];return parsed},SDPUtils.writeFmtp=function(codec){var line="",pt=codec.payloadType;if(void 0!==codec.preferredPayloadType&&(pt=codec.preferredPayloadType),codec.parameters&&Object.keys(codec.parameters).length){var params=[];Object.keys(codec.parameters).forEach(function(param){codec.parameters[param]?params.push(param+"="+codec.parameters[param]):params.push(param)}),line+="a=fmtp:"+pt+" "+params.join(";")+"\r\n"}return line},SDPUtils.parseRtcpFb=function(line){var parts=line.substr(line.indexOf(" ")+1).split(" ");return{type:parts.shift(),parameter:parts.join(" ")}},SDPUtils.writeRtcpFb=function(codec){var lines="",pt=codec.payloadType;return void 0!==codec.preferredPayloadType&&(pt=codec.preferredPayloadType),codec.rtcpFeedback&&codec.rtcpFeedback.length&&codec.rtcpFeedback.forEach(function(fb){lines+="a=rtcp-fb:"+pt+" "+fb.type+(fb.parameter&&fb.parameter.length?" "+fb.parameter:"")+"\r\n"}),lines},SDPUtils.parseSsrcMedia=function(line){var sp=line.indexOf(" "),parts={ssrc:parseInt(line.substr(7,sp-7),10)},colon=line.indexOf(":",sp);return colon>-1?(parts.attribute=line.substr(sp+1,colon-sp-1),parts.value=line.substr(colon+1)):parts.attribute=line.substr(sp+1),parts},SDPUtils.parseSsrcGroup=function(line){var parts=line.substr(13).split(" ");return{semantics:parts.shift(),ssrcs:parts.map(function(ssrc){return parseInt(ssrc,10)})}},SDPUtils.getMid=function(mediaSection){var mid=SDPUtils.matchPrefix(mediaSection,"a=mid:")[0];if(mid)return mid.substr(6)},SDPUtils.parseFingerprint=function(line){var parts=line.substr(14).split(" ");return{algorithm:parts[0].toLowerCase(),value:parts[1]}},SDPUtils.getDtlsParameters=function(mediaSection,sessionpart){return{role:"auto",fingerprints:SDPUtils.matchPrefix(mediaSection+sessionpart,"a=fingerprint:").map(SDPUtils.parseFingerprint)}},SDPUtils.writeDtlsParameters=function(params,setupType){var sdp="a=setup:"+setupType+"\r\n";return params.fingerprints.forEach(function(fp){sdp+="a=fingerprint:"+fp.algorithm+" "+fp.value+"\r\n"}),sdp},SDPUtils.parseCryptoLine=function(line){var parts=line.substr(9).split(" ");return{tag:parseInt(parts[0],10),cryptoSuite:parts[1],keyParams:parts[2],sessionParams:parts.slice(3)}},SDPUtils.writeCryptoLine=function(parameters){return"a=crypto:"+parameters.tag+" "+parameters.cryptoSuite+" "+("object"==typeof parameters.keyParams?SDPUtils.writeCryptoKeyParams(parameters.keyParams):parameters.keyParams)+(parameters.sessionParams?" "+parameters.sessionParams.join(" "):"")+"\r\n"},SDPUtils.parseCryptoKeyParams=function(keyParams){if(0!==keyParams.indexOf("inline:"))return null;var parts=keyParams.substr(7).split("|");return{keyMethod:"inline",keySalt:parts[0],lifeTime:parts[1],mkiValue:parts[2]?parts[2].split(":")[0]:void 0,mkiLength:parts[2]?parts[2].split(":")[1]:void 0}},SDPUtils.writeCryptoKeyParams=function(keyParams){return keyParams.keyMethod+":"+keyParams.keySalt+(keyParams.lifeTime?"|"+keyParams.lifeTime:"")+(keyParams.mkiValue&&keyParams.mkiLength?"|"+keyParams.mkiValue+":"+keyParams.mkiLength:"")},SDPUtils.getCryptoParameters=function(mediaSection,sessionpart){return SDPUtils.matchPrefix(mediaSection+sessionpart,"a=crypto:").map(SDPUtils.parseCryptoLine)},SDPUtils.getIceParameters=function(mediaSection,sessionpart){var ufrag=SDPUtils.matchPrefix(mediaSection+sessionpart,"a=ice-ufrag:")[0],pwd=SDPUtils.matchPrefix(mediaSection+sessionpart,"a=ice-pwd:")[0];return ufrag&&pwd?{usernameFragment:ufrag.substr(12),password:pwd.substr(10)}:null},SDPUtils.writeIceParameters=function(params){return"a=ice-ufrag:"+params.usernameFragment+"\r\na=ice-pwd:"+params.password+"\r\n"},SDPUtils.parseRtpParameters=function(mediaSection){for(var description={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},mline=SDPUtils.splitLines(mediaSection)[0].split(" "),i=3;i<mline.length;i++){var pt=mline[i],rtpmapline=SDPUtils.matchPrefix(mediaSection,"a=rtpmap:"+pt+" ")[0];if(rtpmapline){var codec=SDPUtils.parseRtpMap(rtpmapline),fmtps=SDPUtils.matchPrefix(mediaSection,"a=fmtp:"+pt+" ");switch(codec.parameters=fmtps.length?SDPUtils.parseFmtp(fmtps[0]):{},codec.rtcpFeedback=SDPUtils.matchPrefix(mediaSection,"a=rtcp-fb:"+pt+" ").map(SDPUtils.parseRtcpFb),description.codecs.push(codec),codec.name.toUpperCase()){case"RED":case"ULPFEC":description.fecMechanisms.push(codec.name.toUpperCase())}}}return SDPUtils.matchPrefix(mediaSection,"a=extmap:").forEach(function(line){description.headerExtensions.push(SDPUtils.parseExtmap(line))}),description},SDPUtils.writeRtpDescription=function(kind,caps){var sdp="";sdp+="m="+kind+" "+(caps.codecs.length>0?"9":"0")+" UDP/TLS/RTP/SAVPF "+caps.codecs.map(function(codec){return void 0!==codec.preferredPayloadType?codec.preferredPayloadType:codec.payloadType}).join(" ")+"\r\nc=IN IP4 0.0.0.0\r\na=rtcp:9 IN IP4 0.0.0.0\r\n",caps.codecs.forEach(function(codec){sdp+=SDPUtils.writeRtpMap(codec)+SDPUtils.writeFmtp(codec)+SDPUtils.writeRtcpFb(codec)});var maxptime=0;return caps.codecs.forEach(function(codec){codec.maxptime>maxptime&&(maxptime=codec.maxptime)}),maxptime>0&&(sdp+="a=maxptime:"+maxptime+"\r\n"),sdp+="a=rtcp-mux\r\n",caps.headerExtensions&&caps.headerExtensions.forEach(function(extension){sdp+=SDPUtils.writeExtmap(extension)}),sdp},SDPUtils.parseRtpEncodingParameters=function(mediaSection){var secondarySsrc,encodingParameters=[],description=SDPUtils.parseRtpParameters(mediaSection),hasRed=-1!==description.fecMechanisms.indexOf("RED"),hasUlpfec=-1!==description.fecMechanisms.indexOf("ULPFEC"),ssrcs=SDPUtils.matchPrefix(mediaSection,"a=ssrc:").map(function(line){return SDPUtils.parseSsrcMedia(line)}).filter(function(parts){return"cname"===parts.attribute}),primarySsrc=ssrcs.length>0&&ssrcs[0].ssrc,flows=SDPUtils.matchPrefix(mediaSection,"a=ssrc-group:FID").map(function(line){return line.substr(17).split(" ").map(function(part){return parseInt(part,10)})});flows.length>0&&flows[0].length>1&&flows[0][0]===primarySsrc&&(secondarySsrc=flows[0][1]),description.codecs.forEach(function(codec){if("RTX"===codec.name.toUpperCase()&&codec.parameters.apt){var encParam={ssrc:primarySsrc,codecPayloadType:parseInt(codec.parameters.apt,10)};primarySsrc&&secondarySsrc&&(encParam.rtx={ssrc:secondarySsrc}),encodingParameters.push(encParam),hasRed&&((encParam=JSON.parse(JSON.stringify(encParam))).fec={ssrc:primarySsrc,mechanism:hasUlpfec?"red+ulpfec":"red"},encodingParameters.push(encParam))}}),0===encodingParameters.length&&primarySsrc&&encodingParameters.push({ssrc:primarySsrc});var bandwidth=SDPUtils.matchPrefix(mediaSection,"b=");return bandwidth.length&&(bandwidth=0===bandwidth[0].indexOf("b=TIAS:")?parseInt(bandwidth[0].substr(7),10):0===bandwidth[0].indexOf("b=AS:")?950*parseInt(bandwidth[0].substr(5),10)-16e3:void 0,encodingParameters.forEach(function(params){params.maxBitrate=bandwidth})),encodingParameters},SDPUtils.parseRtcpParameters=function(mediaSection){var rtcpParameters={},remoteSsrc=SDPUtils.matchPrefix(mediaSection,"a=ssrc:").map(function(line){return SDPUtils.parseSsrcMedia(line)}).filter(function(obj){return"cname"===obj.attribute})[0];remoteSsrc&&(rtcpParameters.cname=remoteSsrc.value,rtcpParameters.ssrc=remoteSsrc.ssrc);var rsize=SDPUtils.matchPrefix(mediaSection,"a=rtcp-rsize");rtcpParameters.reducedSize=rsize.length>0,rtcpParameters.compound=0===rsize.length;var mux=SDPUtils.matchPrefix(mediaSection,"a=rtcp-mux");return rtcpParameters.mux=mux.length>0,rtcpParameters},SDPUtils.parseMsid=function(mediaSection){var parts,spec=SDPUtils.matchPrefix(mediaSection,"a=msid:");if(1===spec.length)return{stream:(parts=spec[0].substr(7).split(" "))[0],track:parts[1]};var planB=SDPUtils.matchPrefix(mediaSection,"a=ssrc:").map(function(line){return SDPUtils.parseSsrcMedia(line)}).filter(function(msidParts){return"msid"===msidParts.attribute});if(planB.length>0)return{stream:(parts=planB[0].value.split(" "))[0],track:parts[1]}},SDPUtils.parseSctpDescription=function(mediaSection){var maxMessageSize,mline=SDPUtils.parseMLine(mediaSection),maxSizeLine=SDPUtils.matchPrefix(mediaSection,"a=max-message-size:");maxSizeLine.length>0&&(maxMessageSize=parseInt(maxSizeLine[0].substr(19),10)),isNaN(maxMessageSize)&&(maxMessageSize=65536);var sctpPort=SDPUtils.matchPrefix(mediaSection,"a=sctp-port:");if(sctpPort.length>0)return{port:parseInt(sctpPort[0].substr(12),10),protocol:mline.fmt,maxMessageSize:maxMessageSize};if(SDPUtils.matchPrefix(mediaSection,"a=sctpmap:").length>0){var parts=SDPUtils.matchPrefix(mediaSection,"a=sctpmap:")[0].substr(10).split(" ");return{port:parseInt(parts[0],10),protocol:parts[1],maxMessageSize:maxMessageSize}}},SDPUtils.writeSctpDescription=function(media,sctp){var output=[];return output="DTLS/SCTP"!==media.protocol?["m="+media.kind+" 9 "+media.protocol+" "+sctp.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+sctp.port+"\r\n"]:["m="+media.kind+" 9 "+media.protocol+" "+sctp.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+sctp.port+" "+sctp.protocol+" 65535\r\n"],void 0!==sctp.maxMessageSize&&output.push("a=max-message-size:"+sctp.maxMessageSize+"\r\n"),output.join("")},SDPUtils.generateSessionId=function(){return Math.random().toString().substr(2,21)},SDPUtils.writeSessionBoilerplate=function(sessId,sessVer,sessUser){return"v=0\r\no="+(sessUser||"thisisadapterortc")+" "+(sessId||SDPUtils.generateSessionId())+" "+(void 0!==sessVer?sessVer:2)+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},SDPUtils.writeMediaSection=function(transceiver,caps,type,stream){var sdp=SDPUtils.writeRtpDescription(transceiver.kind,caps);if(sdp+=SDPUtils.writeIceParameters(transceiver.iceGatherer.getLocalParameters())+SDPUtils.writeDtlsParameters(transceiver.dtlsTransport.getLocalParameters(),"offer"===type?"actpass":"active")+"a=mid:"+transceiver.mid+"\r\n",transceiver.direction?sdp+="a="+transceiver.direction+"\r\n":transceiver.rtpSender&&transceiver.rtpReceiver?sdp+="a=sendrecv\r\n":transceiver.rtpSender?sdp+="a=sendonly\r\n":transceiver.rtpReceiver?sdp+="a=recvonly\r\n":sdp+="a=inactive\r\n",transceiver.rtpSender){var msid="msid:"+stream.id+" "+transceiver.rtpSender.track.id+"\r\n";sdp+="a="+msid+("a=ssrc:"+transceiver.sendEncodingParameters[0].ssrc)+" "+msid,transceiver.sendEncodingParameters[0].rtx&&(sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].rtx.ssrc+" "+msid+("a=ssrc-group:FID "+transceiver.sendEncodingParameters[0].ssrc+" ")+transceiver.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].ssrc+" cname:"+SDPUtils.localCName+"\r\n",transceiver.rtpSender&&transceiver.sendEncodingParameters[0].rtx&&(sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].rtx.ssrc+" cname:"+SDPUtils.localCName+"\r\n"),sdp},SDPUtils.getDirection=function(mediaSection,sessionpart){for(var lines=SDPUtils.splitLines(mediaSection),i=0;i<lines.length;i++)switch(lines[i]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return lines[i].substr(2)}return sessionpart?SDPUtils.getDirection(sessionpart):"sendrecv"},SDPUtils.getKind=function(mediaSection){return SDPUtils.splitLines(mediaSection)[0].split(" ")[0].substr(2)},SDPUtils.isRejected=function(mediaSection){return"0"===mediaSection.split(" ",2)[1]},SDPUtils.parseMLine=function(mediaSection){var parts=SDPUtils.splitLines(mediaSection)[0].substr(2).split(" ");return{kind:parts[0],port:parseInt(parts[1],10),protocol:parts[2],fmt:parts.slice(3).join(" ")}},SDPUtils.parseOLine=function(mediaSection){var parts=SDPUtils.matchPrefix(mediaSection,"o=")[0].substr(2).split(" ");return{username:parts[0],sessionId:parts[1],sessionVersion:parseInt(parts[2],10),netType:parts[3],addressType:parts[4],address:parts[5]}},SDPUtils.isValidSDP=function(blob){if("string"!=typeof blob||0===blob.length)return!1;for(var lines=SDPUtils.splitLines(blob),i=0;i<lines.length;i++)if(lines[i].length<2||"="!==lines[i].charAt(1))return!1;return!0},"object"==typeof module&&(module.exports=SDPUtils)},{}],176:[function(require1,module,exports){module.exports=Stream;var EE=require1("events").EventEmitter;function Stream(){EE.call(this)}require1("inherits")(Stream,EE),Stream.Readable=require1("readable-stream/readable.js"),Stream.Writable=require1("readable-stream/writable.js"),Stream.Duplex=require1("readable-stream/duplex.js"),Stream.Transform=require1("readable-stream/transform.js"),Stream.PassThrough=require1("readable-stream/passthrough.js"),Stream.Stream=Stream,Stream.prototype.pipe=function(dest,options){var source=this;function ondata(chunk){dest.writable&&!1===dest.write(chunk)&&source.pause&&source.pause()}function ondrain(){source.readable&&source.resume&&source.resume()}source.on("data",ondata),dest.on("drain",ondrain),dest._isStdio||options&&!1===options.end||(source.on("end",onend),source.on("close",onclose));var didOnEnd=!1;function onend(){didOnEnd||(didOnEnd=!0,dest.end())}function onclose(){didOnEnd||(didOnEnd=!0,"function"==typeof dest.destroy&&dest.destroy())}function onerror(er){if(cleanup(),0===EE.listenerCount(this,"error"))throw er}function cleanup(){source.removeListener("data",ondata),dest.removeListener("drain",ondrain),source.removeListener("end",onend),source.removeListener("close",onclose),source.removeListener("error",onerror),dest.removeListener("error",onerror),source.removeListener("end",cleanup),source.removeListener("close",cleanup),dest.removeListener("close",cleanup)}return source.on("error",onerror),dest.on("error",onerror),source.on("end",cleanup),source.on("close",cleanup),dest.on("close",cleanup),dest.emit("pipe",source),dest}},{events:80,inherits:85,"readable-stream/duplex.js":177,"readable-stream/passthrough.js":186,"readable-stream/readable.js":187,"readable-stream/transform.js":188,"readable-stream/writable.js":189}],177:[function(require1,module,exports){module.exports=require1("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":178}],178:[function(require1,module,exports){arguments[4][34][0].apply(exports,arguments)},{"./_stream_readable":180,"./_stream_writable":182,"core-util-is":49,dup:34,inherits:85,"process-nextick-args":151}],179:[function(require1,module,exports){arguments[4][35][0].apply(exports,arguments)},{"./_stream_transform":181,"core-util-is":49,dup:35,inherits:85}],180:[function(require1,module,exports){arguments[4][36][0].apply(exports,arguments)},{"./_stream_duplex":178,"./internal/streams/BufferList":183,"./internal/streams/destroy":184,"./internal/streams/stream":185,_process:152,"core-util-is":49,dup:36,events:80,inherits:85,isarray:88,"process-nextick-args":151,"safe-buffer":190,"string_decoder/":191,util:29}],181:[function(require1,module,exports){arguments[4][37][0].apply(exports,arguments)},{"./_stream_duplex":178,"core-util-is":49,dup:37,inherits:85}],182:[function(require1,module,exports){arguments[4][38][0].apply(exports,arguments)},{"./_stream_duplex":178,"./internal/streams/destroy":184,"./internal/streams/stream":185,_process:152,"core-util-is":49,dup:38,inherits:85,"process-nextick-args":151,"safe-buffer":190,timers:210,"util-deprecate":214}],183:[function(require1,module,exports){arguments[4][39][0].apply(exports,arguments)},{dup:39,"safe-buffer":190,util:29}],184:[function(require1,module,exports){arguments[4][40][0].apply(exports,arguments)},{dup:40,"process-nextick-args":151}],185:[function(require1,module,exports){arguments[4][41][0].apply(exports,arguments)},{dup:41,events:80}],186:[function(require1,module,exports){module.exports=require1("./readable").PassThrough},{"./readable":187}],187:[function(require1,module,exports){arguments[4][43][0].apply(exports,arguments)},{"./lib/_stream_duplex.js":178,"./lib/_stream_passthrough.js":179,"./lib/_stream_readable.js":180,"./lib/_stream_transform.js":181,"./lib/_stream_writable.js":182,dup:43}],188:[function(require1,module,exports){arguments[4][44][0].apply(exports,arguments)},{"./readable":187,dup:44}],189:[function(require1,module,exports){module.exports=require1("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":182}],190:[function(require1,module,exports){arguments[4][45][0].apply(exports,arguments)},{buffer:47,dup:45}],191:[function(require1,module,exports){arguments[4][42][0].apply(exports,arguments)},{dup:42,"safe-buffer":190}],192:[function(require1,module,exports){(function(global){(function(){var ClientRequest=require1("./lib/request"),response=require1("./lib/response"),extend=require1("xtend"),statusCodes=require1("builtin-status-codes"),url=require1("url");exports.request=function(opts,cb){opts="string"==typeof opts?url.parse(opts):extend(opts);var defaultProtocol=-1===global.location.protocol.search(/^https?:$/)?"http:":"",protocol=opts.protocol||defaultProtocol,host=opts.hostname||opts.host,port=opts.port,path=opts.path||"/";host&&-1!==host.indexOf(":")&&(host="["+host+"]"),opts.url=(host?protocol+"//"+host:"")+(port?":"+port:"")+path,opts.method=(opts.method||"GET").toUpperCase(),opts.headers=opts.headers||{};var req=new ClientRequest(opts);return cb&&req.on("response",cb),req},exports.get=function get(opts,cb){var req=exports.request(opts,cb);return req.end(),req},exports.ClientRequest=ClientRequest,exports.IncomingMessage=response.IncomingMessage,exports.Agent=function(){},exports.Agent.defaultMaxSockets=4,exports.globalAgent=new exports.Agent,exports.STATUS_CODES=statusCodes,exports.METHODS=["CHECKOUT","CONNECT","COPY","DELETE","GET","HEAD","LOCK","M-SEARCH","MERGE","MKACTIVITY","MKCOL","MOVE","NOTIFY","OPTIONS","PATCH","POST","PROPFIND","PROPPATCH","PURGE","PUT","REPORT","SEARCH","SUBSCRIBE","TRACE","UNLOCK","UNSUBSCRIBE"]}).call(this)}).call(this,void 0!==__webpack_require__.g?__webpack_require__.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./lib/request":194,"./lib/response":195,"builtin-status-codes":48,url:212,xtend:233}],193:[function(require1,module,exports){(function(global){(function(){exports.fetch=isFunction(global.fetch)&&isFunction(global.ReadableStream),exports.writableStream=isFunction(global.WritableStream),exports.abortController=isFunction(global.AbortController),exports.blobConstructor=!1;try{new Blob([new ArrayBuffer(1)]),exports.blobConstructor=!0}catch(e){}function getXHR(){if(void 0!==xhr)return xhr;if(global.XMLHttpRequest){xhr=new global.XMLHttpRequest;try{xhr.open("GET",global.XDomainRequest?"/":"https://example.com")}catch(e){xhr=null}}else xhr=null;return xhr}function checkTypeSupport(type){var xhr=getXHR();if(!xhr)return!1;try{return xhr.responseType=type,xhr.responseType===type}catch(e){}return!1}var xhr,haveArrayBuffer=void 0!==global.ArrayBuffer,haveSlice=haveArrayBuffer&&isFunction(global.ArrayBuffer.prototype.slice);function isFunction(value){return"function"==typeof value}exports.arraybuffer=exports.fetch||haveArrayBuffer&&checkTypeSupport("arraybuffer"),exports.msstream=!exports.fetch&&haveSlice&&checkTypeSupport("ms-stream"),exports.mozchunkedarraybuffer=!exports.fetch&&haveArrayBuffer&&checkTypeSupport("moz-chunked-arraybuffer"),exports.overrideMimeType=exports.fetch||!!getXHR()&&isFunction(getXHR().overrideMimeType),exports.vbArray=isFunction(global.VBArray),xhr=null}).call(this)}).call(this,void 0!==__webpack_require__.g?__webpack_require__.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],194:[function(require1,module,exports){(function(process,global,Buffer){(function(){var capability=require1("./capability"),inherits=require1("inherits"),response=require1("./response"),stream=require1("readable-stream"),toArrayBuffer=require1("to-arraybuffer"),IncomingMessage=response.IncomingMessage,rStates=response.readyStates;function decideMode(preferBinary,useFetch){return capability.fetch&&useFetch?"fetch":capability.mozchunkedarraybuffer?"moz-chunked-arraybuffer":capability.msstream?"ms-stream":capability.arraybuffer&&preferBinary?"arraybuffer":capability.vbArray&&preferBinary?"text:vbarray":"text"}var ClientRequest=module.exports=function(opts){var preferBinary,self1=this;stream.Writable.call(self1),self1._opts=opts,self1._body=[],self1._headers={},opts.auth&&self1.setHeader("Authorization","Basic "+new Buffer(opts.auth).toString("base64")),Object.keys(opts.headers).forEach(function(name){self1.setHeader(name,opts.headers[name])});var useFetch=!0;if("disable-fetch"===opts.mode||"requestTimeout"in opts&&!capability.abortController)useFetch=!1,preferBinary=!0;else if("prefer-streaming"===opts.mode)preferBinary=!1;else if("allow-wrong-content-type"===opts.mode)preferBinary=!capability.overrideMimeType;else if(opts.mode&&"default"!==opts.mode&&"prefer-fast"!==opts.mode)throw Error("Invalid value for opts.mode");else preferBinary=!0;self1._mode=decideMode(preferBinary,useFetch),self1._fetchTimer=null,self1.on("finish",function(){self1._onFinish()})};function statusValid(xhr){try{var status=xhr.status;return null!==status&&0!==status}catch(e){return!1}}inherits(ClientRequest,stream.Writable),ClientRequest.prototype.setHeader=function(name,value){var lowerName=name.toLowerCase();-1===unsafeHeaders.indexOf(lowerName)&&(this._headers[lowerName]={name:name,value:value})},ClientRequest.prototype.getHeader=function(name){var header=this._headers[name.toLowerCase()];return header?header.value:null},ClientRequest.prototype.removeHeader=function(name){delete this._headers[name.toLowerCase()]},ClientRequest.prototype._onFinish=function(){var self1=this;if(!self1._destroyed){var opts=self1._opts,headersObj=self1._headers,body=null;"GET"!==opts.method&&"HEAD"!==opts.method&&(body=capability.arraybuffer?toArrayBuffer(Buffer.concat(self1._body)):capability.blobConstructor?new global.Blob(self1._body.map(function(buffer){return toArrayBuffer(buffer)}),{type:(headersObj["content-type"]||{}).value||""}):Buffer.concat(self1._body).toString());var headersList=[];if(Object.keys(headersObj).forEach(function(keyName){var name=headersObj[keyName].name,value=headersObj[keyName].value;Array.isArray(value)?value.forEach(function(v){headersList.push([name,v])}):headersList.push([name,value])}),"fetch"===self1._mode){var signal=null;if(capability.abortController){var controller=new AbortController;signal=controller.signal,self1._fetchAbortController=controller,"requestTimeout"in opts&&0!==opts.requestTimeout&&(self1._fetchTimer=global.setTimeout(function(){self1.emit("requestTimeout"),self1._fetchAbortController&&self1._fetchAbortController.abort()},opts.requestTimeout))}global.fetch(self1._opts.url,{method:self1._opts.method,headers:headersList,body:body||void 0,mode:"cors",credentials:opts.withCredentials?"include":"same-origin",signal:signal}).then(function(response){self1._fetchResponse=response,self1._connect()},function(reason){global.clearTimeout(self1._fetchTimer),self1._destroyed||self1.emit("error",reason)})}else{var xhr=self1._xhr=new global.XMLHttpRequest;try{xhr.open(self1._opts.method,self1._opts.url,!0)}catch(err){process.nextTick(function(){self1.emit("error",err)});return}"responseType"in xhr&&(xhr.responseType=self1._mode.split(":")[0]),"withCredentials"in xhr&&(xhr.withCredentials=!!opts.withCredentials),"text"===self1._mode&&"overrideMimeType"in xhr&&xhr.overrideMimeType("text/plain; charset=x-user-defined"),"requestTimeout"in opts&&(xhr.timeout=opts.requestTimeout,xhr.ontimeout=function(){self1.emit("requestTimeout")}),headersList.forEach(function(header){xhr.setRequestHeader(header[0],header[1])}),self1._response=null,xhr.onreadystatechange=function(){switch(xhr.readyState){case rStates.LOADING:case rStates.DONE:self1._onXHRProgress()}},"moz-chunked-arraybuffer"===self1._mode&&(xhr.onprogress=function(){self1._onXHRProgress()}),xhr.onerror=function(){self1._destroyed||self1.emit("error",Error("XHR error"))};try{xhr.send(body)}catch(err){process.nextTick(function(){self1.emit("error",err)});return}}}},ClientRequest.prototype._onXHRProgress=function(){statusValid(this._xhr)&&!this._destroyed&&(this._response||this._connect(),this._response._onXHRProgress())},ClientRequest.prototype._connect=function(){var self1=this;self1._destroyed||(self1._response=new IncomingMessage(self1._xhr,self1._fetchResponse,self1._mode,self1._fetchTimer),self1._response.on("error",function(err){self1.emit("error",err)}),self1.emit("response",self1._response))},ClientRequest.prototype._write=function(chunk,encoding,cb){this._body.push(chunk),cb()},ClientRequest.prototype.abort=ClientRequest.prototype.destroy=function(){this._destroyed=!0,global.clearTimeout(this._fetchTimer),this._response&&(this._response._destroyed=!0),this._xhr?this._xhr.abort():this._fetchAbortController&&this._fetchAbortController.abort()},ClientRequest.prototype.end=function(data,encoding,cb){"function"==typeof data&&(cb=data,data=void 0),stream.Writable.prototype.end.call(this,data,encoding,cb)},ClientRequest.prototype.flushHeaders=function(){},ClientRequest.prototype.setTimeout=function(){},ClientRequest.prototype.setNoDelay=function(){},ClientRequest.prototype.setSocketKeepAlive=function(){};var unsafeHeaders=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","cookie","cookie2","date","dnt","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"]}).call(this)}).call(this,require1("_process"),void 0!==__webpack_require__.g?__webpack_require__.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},require1("buffer").Buffer)},{"./capability":193,"./response":195,_process:152,buffer:47,inherits:85,"readable-stream":204,"to-arraybuffer":211}],195:[function(require1,module,exports){(function(process,global,Buffer){(function(){var capability=require1("./capability"),inherits=require1("inherits"),stream=require1("readable-stream"),rStates=exports.readyStates={UNSENT:0,OPENED:1,HEADERS_RECEIVED:2,LOADING:3,DONE:4},IncomingMessage=exports.IncomingMessage=function(xhr,response,mode,fetchTimer){var self1=this;if(stream.Readable.call(self1),self1._mode=mode,self1.headers={},self1.rawHeaders=[],self1.trailers={},self1.rawTrailers=[],self1.on("end",function(){process.nextTick(function(){self1.emit("close")})}),"fetch"===mode){if(self1._fetchResponse=response,self1.url=response.url,self1.statusCode=response.status,self1.statusMessage=response.statusText,response.headers.forEach(function(header,key){self1.headers[key.toLowerCase()]=header,self1.rawHeaders.push(key,header)}),capability.writableStream){var writable=new WritableStream({write:function(chunk){return new Promise(function(resolve,reject){self1._destroyed?reject():self1.push(new Buffer(chunk))?resolve():self1._resumeFetch=resolve})},close:function(){global.clearTimeout(fetchTimer),self1._destroyed||self1.push(null)},abort:function(err){self1._destroyed||self1.emit("error",err)}});try{response.body.pipeTo(writable).catch(function(err){global.clearTimeout(fetchTimer),self1._destroyed||self1.emit("error",err)});return}catch(e){}}var reader=response.body.getReader();function read(){reader.read().then(function(result){if(!self1._destroyed){if(result.done){global.clearTimeout(fetchTimer),self1.push(null);return}self1.push(new Buffer(result.value)),read()}}).catch(function(err){global.clearTimeout(fetchTimer),self1._destroyed||self1.emit("error",err)})}read()}else if(self1._xhr=xhr,self1._pos=0,self1.url=xhr.responseURL,self1.statusCode=xhr.status,self1.statusMessage=xhr.statusText,xhr.getAllResponseHeaders().split(/\r?\n/).forEach(function(header){var matches=header.match(/^([^:]+):\s*(.*)/);if(matches){var key=matches[1].toLowerCase();"set-cookie"===key?(void 0===self1.headers[key]&&(self1.headers[key]=[]),self1.headers[key].push(matches[2])):void 0!==self1.headers[key]?self1.headers[key]+=", "+matches[2]:self1.headers[key]=matches[2],self1.rawHeaders.push(matches[1],matches[2])}}),self1._charset="x-user-defined",!capability.overrideMimeType){var mimeType=self1.rawHeaders["mime-type"];if(mimeType){var charsetMatch=mimeType.match(/;\s*charset=([^;])(;|$)/);charsetMatch&&(self1._charset=charsetMatch[1].toLowerCase())}self1._charset||(self1._charset="utf-8")}};inherits(IncomingMessage,stream.Readable),IncomingMessage.prototype._read=function(){var resolve=this._resumeFetch;resolve&&(this._resumeFetch=null,resolve())},IncomingMessage.prototype._onXHRProgress=function(){var self1=this,xhr=self1._xhr,response=null;switch(self1._mode){case"text:vbarray":if(xhr.readyState!==rStates.DONE)break;try{response=new global.VBArray(xhr.responseBody).toArray()}catch(e){}if(null!==response){self1.push(new Buffer(response));break}case"text":try{response=xhr.responseText}catch(e){self1._mode="text:vbarray";break}if(response.length>self1._pos){var newData=response.substr(self1._pos);if("x-user-defined"===self1._charset){for(var buffer=new Buffer(newData.length),i=0;i<newData.length;i++)buffer[i]=255&newData.charCodeAt(i);self1.push(buffer)}else self1.push(newData,self1._charset);self1._pos=response.length}break;case"arraybuffer":if(xhr.readyState!==rStates.DONE||!xhr.response)break;response=xhr.response,self1.push(new Buffer(new Uint8Array(response)));break;case"moz-chunked-arraybuffer":if(response=xhr.response,xhr.readyState!==rStates.LOADING||!response)break;self1.push(new Buffer(new Uint8Array(response)));break;case"ms-stream":if(response=xhr.response,xhr.readyState!==rStates.LOADING)break;var reader=new global.MSStreamReader;reader.onprogress=function(){reader.result.byteLength>self1._pos&&(self1.push(new Buffer(new Uint8Array(reader.result.slice(self1._pos)))),self1._pos=reader.result.byteLength)},reader.onload=function(){self1.push(null)},reader.readAsArrayBuffer(response)}self1._xhr.readyState===rStates.DONE&&"ms-stream"!==self1._mode&&self1.push(null)}}).call(this)}).call(this,require1("_process"),void 0!==__webpack_require__.g?__webpack_require__.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},require1("buffer").Buffer)},{"./capability":193,_process:152,buffer:47,inherits:85,"readable-stream":204}],196:[function(require1,module,exports){arguments[4][34][0].apply(exports,arguments)},{"./_stream_readable":198,"./_stream_writable":200,"core-util-is":49,dup:34,inherits:85,"process-nextick-args":151}],197:[function(require1,module,exports){arguments[4][35][0].apply(exports,arguments)},{"./_stream_transform":199,"core-util-is":49,dup:35,inherits:85}],198:[function(require1,module,exports){arguments[4][36][0].apply(exports,arguments)},{"./_stream_duplex":196,"./internal/streams/BufferList":201,"./internal/streams/destroy":202,"./internal/streams/stream":203,_process:152,"core-util-is":49,dup:36,events:80,inherits:85,isarray:88,"process-nextick-args":151,"safe-buffer":205,"string_decoder/":206,util:29}],199:[function(require1,module,exports){arguments[4][37][0].apply(exports,arguments)},{"./_stream_duplex":196,"core-util-is":49,dup:37,inherits:85}],200:[function(require1,module,exports){arguments[4][38][0].apply(exports,arguments)},{"./_stream_duplex":196,"./internal/streams/destroy":202,"./internal/streams/stream":203,_process:152,"core-util-is":49,dup:38,inherits:85,"process-nextick-args":151,"safe-buffer":205,timers:210,"util-deprecate":214}],201:[function(require1,module,exports){arguments[4][39][0].apply(exports,arguments)},{dup:39,"safe-buffer":205,util:29}],202:[function(require1,module,exports){arguments[4][40][0].apply(exports,arguments)},{dup:40,"process-nextick-args":151}],203:[function(require1,module,exports){arguments[4][41][0].apply(exports,arguments)},{dup:41,events:80}],204:[function(require1,module,exports){arguments[4][43][0].apply(exports,arguments)},{"./lib/_stream_duplex.js":196,"./lib/_stream_passthrough.js":197,"./lib/_stream_readable.js":198,"./lib/_stream_transform.js":199,"./lib/_stream_writable.js":200,dup:43}],205:[function(require1,module,exports){arguments[4][45][0].apply(exports,arguments)},{buffer:47,dup:45}],206:[function(require1,module,exports){arguments[4][42][0].apply(exports,arguments)},{dup:42,"safe-buffer":205}],207:[function(require1,module,exports){arguments[4][42][0].apply(exports,arguments)},{dup:42,"safe-buffer":173}],208:[function(require1,module,exports){(function(global){(function(){var global1,factory;global1=this,factory=function(exports){"use strict";var global$1=void 0!==global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};let WebSocket=function getWebSocketImplementation(){let WebSocketImplementation=global$1.WebSocket;if(void 0===WebSocketImplementation)try{WebSocketImplementation=require1("ws")}catch(err){throw Error('You must install the "ws" package to use Strophe in nodejs.')}return WebSocketImplementation}(),DOMParser1=function getDOMParserImplementation(){let DOMParserImplementation=global$1.DOMParser;if(void 0===DOMParserImplementation)try{DOMParserImplementation=require1("@xmldom/xmldom").DOMParser}catch(err){throw Error('You must install the "@xmldom/xmldom" package to use Strophe in nodejs.')}return DOMParserImplementation}();function _getIEXmlDom(){let docStrings=["Msxml2.DOMDocument.6.0","Msxml2.DOMDocument.5.0","Msxml2.DOMDocument.4.0","MSXML2.DOMDocument.3.0","MSXML2.DOMDocument","MSXML.DOMDocument","Microsoft.XMLDOM"];for(let d=0;d<docStrings.length;d++)try{return new ActiveXObject(docStrings[d])}catch(e){}}function getDummyXMLDOMDocument(){if("undefined"==typeof document)try{return new(require1("@xmldom/xmldom")).DOMImplementation().createDocument("jabber:client","strophe",null)}catch(err){throw Error('You must install the "@xmldom/xmldom" package to use Strophe in nodejs.')}if(void 0===document.implementation.createDocument||document.implementation.createDocument&&document.documentMode&&document.documentMode<10){let doc=_getIEXmlDom();return doc.appendChild(doc.createElement("strophe")),doc}return document.implementation.createDocument("jabber:client","strophe",null)}let safe_add$1=function(x,y){let lsw=(65535&x)+(65535&y);return(x>>16)+(y>>16)+(lsw>>16)<<16|65535&lsw},str2binl=function(str){if("string"!=typeof str)throw Error("str2binl was passed a non-string");let bin=[];for(let i=0;i<8*str.length;i+=8)bin[i>>5]|=(255&str.charCodeAt(i/8))<<i%32;return bin},binl2str=function(bin){let str="";for(let i=0;i<32*bin.length;i+=8)str+=String.fromCharCode(bin[i>>5]>>>i%32&255);return str},binl2hex=function(binarray){let hex_tab="0123456789abcdef",str="";for(let i=0;i<4*binarray.length;i++)str+=hex_tab.charAt(binarray[i>>2]>>i%4*8+4&15)+hex_tab.charAt(binarray[i>>2]>>i%4*8&15);return str},md5_cmn=function(q,a,b,x,s,t){var num;return safe_add$1((num=safe_add$1(safe_add$1(a,q),safe_add$1(x,t)))<<s|num>>>32-s,b)},md5_ff=function(a,b,c,d,x,s,t){return md5_cmn(b&c|~b&d,a,b,x,s,t)},md5_gg=function(a,b,c,d,x,s,t){return md5_cmn(b&d|c&~d,a,b,x,s,t)},md5_hh=function(a,b,c,d,x,s,t){return md5_cmn(b^c^d,a,b,x,s,t)},md5_ii=function(a,b,c,d,x,s,t){return md5_cmn(c^(b|~d),a,b,x,s,t)},core_md5=function(x,len){let olda,oldb,oldc,oldd;x[len>>5]|=128<<len%32,x[(len+64>>>9<<4)+14]=len;let a=1732584193,b=-271733879,c=-1732584194,d=271733878;for(let i=0;i<x.length;i+=16)olda=a,oldb=b,oldc=c,oldd=d,a=md5_ff(a,b,c,d,x[i+0],7,-680876936),d=md5_ff(d,a,b,c,x[i+1],12,-389564586),c=md5_ff(c,d,a,b,x[i+2],17,606105819),b=md5_ff(b,c,d,a,x[i+3],22,-1044525330),a=md5_ff(a,b,c,d,x[i+4],7,-176418897),d=md5_ff(d,a,b,c,x[i+5],12,1200080426),c=md5_ff(c,d,a,b,x[i+6],17,-1473231341),b=md5_ff(b,c,d,a,x[i+7],22,-45705983),a=md5_ff(a,b,c,d,x[i+8],7,1770035416),d=md5_ff(d,a,b,c,x[i+9],12,-1958414417),c=md5_ff(c,d,a,b,x[i+10],17,-42063),b=md5_ff(b,c,d,a,x[i+11],22,-1990404162),a=md5_ff(a,b,c,d,x[i+12],7,1804603682),d=md5_ff(d,a,b,c,x[i+13],12,-40341101),c=md5_ff(c,d,a,b,x[i+14],17,-1502002290),b=md5_ff(b,c,d,a,x[i+15],22,1236535329),a=md5_gg(a,b,c,d,x[i+1],5,-165796510),d=md5_gg(d,a,b,c,x[i+6],9,-1069501632),c=md5_gg(c,d,a,b,x[i+11],14,643717713),b=md5_gg(b,c,d,a,x[i+0],20,-373897302),a=md5_gg(a,b,c,d,x[i+5],5,-701558691),d=md5_gg(d,a,b,c,x[i+10],9,38016083),c=md5_gg(c,d,a,b,x[i+15],14,-660478335),b=md5_gg(b,c,d,a,x[i+4],20,-405537848),a=md5_gg(a,b,c,d,x[i+9],5,568446438),d=md5_gg(d,a,b,c,x[i+14],9,-1019803690),c=md5_gg(c,d,a,b,x[i+3],14,-187363961),b=md5_gg(b,c,d,a,x[i+8],20,1163531501),a=md5_gg(a,b,c,d,x[i+13],5,-1444681467),d=md5_gg(d,a,b,c,x[i+2],9,-51403784),c=md5_gg(c,d,a,b,x[i+7],14,1735328473),b=md5_gg(b,c,d,a,x[i+12],20,-1926607734),a=md5_hh(a,b,c,d,x[i+5],4,-378558),d=md5_hh(d,a,b,c,x[i+8],11,-2022574463),c=md5_hh(c,d,a,b,x[i+11],16,1839030562),b=md5_hh(b,c,d,a,x[i+14],23,-35309556),a=md5_hh(a,b,c,d,x[i+1],4,-1530992060),d=md5_hh(d,a,b,c,x[i+4],11,1272893353),c=md5_hh(c,d,a,b,x[i+7],16,-155497632),b=md5_hh(b,c,d,a,x[i+10],23,-1094730640),a=md5_hh(a,b,c,d,x[i+13],4,681279174),d=md5_hh(d,a,b,c,x[i+0],11,-358537222),c=md5_hh(c,d,a,b,x[i+3],16,-722521979),b=md5_hh(b,c,d,a,x[i+6],23,76029189),a=md5_hh(a,b,c,d,x[i+9],4,-640364487),d=md5_hh(d,a,b,c,x[i+12],11,-421815835),c=md5_hh(c,d,a,b,x[i+15],16,530742520),b=md5_hh(b,c,d,a,x[i+2],23,-995338651),a=md5_ii(a,b,c,d,x[i+0],6,-198630844),d=md5_ii(d,a,b,c,x[i+7],10,1126891415),c=md5_ii(c,d,a,b,x[i+14],15,-1416354905),b=md5_ii(b,c,d,a,x[i+5],21,-57434055),a=md5_ii(a,b,c,d,x[i+12],6,1700485571),d=md5_ii(d,a,b,c,x[i+3],10,-1894986606),c=md5_ii(c,d,a,b,x[i+10],15,-1051523),b=md5_ii(b,c,d,a,x[i+1],21,-2054922799),a=md5_ii(a,b,c,d,x[i+8],6,1873313359),d=md5_ii(d,a,b,c,x[i+15],10,-30611744),c=md5_ii(c,d,a,b,x[i+6],15,-1560198380),b=md5_ii(b,c,d,a,x[i+13],21,1309151649),a=md5_ii(a,b,c,d,x[i+4],6,-145523070),d=md5_ii(d,a,b,c,x[i+11],10,-1120210379),c=md5_ii(c,d,a,b,x[i+2],15,718787259),b=md5_ii(b,c,d,a,x[i+9],21,-343485551),a=safe_add$1(a,olda),b=safe_add$1(b,oldb),c=safe_add$1(c,oldc),d=safe_add$1(d,oldd);return[a,b,c,d]},MD5={hexdigest:function(s){return binl2hex(core_md5(str2binl(s),8*s.length))},hash:function(s){return binl2str(core_md5(str2binl(s),8*s.length))}};class SASLMechanism{constructor(name,isClientFirst,priority){this.mechname=name,this.isClientFirst=isClientFirst,this.priority=priority}test(){return!0}onStart(connection){this._connection=connection}onChallenge(connection,challenge){throw Error("You should implement challenge handling!")}clientChallenge(connection){if(!this.isClientFirst)throw Error("clientChallenge should not be called if isClientFirst is false!");return this.onChallenge(connection)}onFailure(){this._connection=null}onSuccess(){this._connection=null}}let utils={utf16to8:function(str){var i,c,out="",len=str.length;for(i=0;i<len;i++)(c=str.charCodeAt(i))>=0&&c<=127?out+=str.charAt(i):c>2047?out+=String.fromCharCode(224|c>>12&15)+String.fromCharCode(128|c>>6&63)+String.fromCharCode(128|c>>0&63):out+=String.fromCharCode(192|c>>6&31)+String.fromCharCode(128|c>>0&63);return out},addCookies:function(cookies){for(let cookieName in cookies=cookies||{})if(Object.prototype.hasOwnProperty.call(cookies,cookieName)){let expires="",domain="",path="",cookieObj=cookies[cookieName],isObj="object"==typeof cookieObj,cookieValue=escape(unescape(isObj?cookieObj.value:cookieObj));isObj&&(expires=cookieObj.expires?";expires="+cookieObj.expires:"",domain=cookieObj.domain?";domain="+cookieObj.domain:"",path=cookieObj.path?";path="+cookieObj.path:""),document.cookie=cookieName+"="+cookieValue+expires+domain+path}}};function core_sha1(x,len){x[len>>5]|=128<<24-len%32,x[(len+64>>9<<4)+15]=len;var i,j,t,olda,oldb,oldc,oldd,olde,w=Array(80),a=1732584193,b=-271733879,c=-1732584194,d=271733878,e=-1009589776;for(i=0;i<x.length;i+=16){for(j=0,olda=a,oldb=b,oldc=c,oldd=d,olde=e;j<80;j++)j<16?w[j]=x[i+j]:w[j]=rol(w[j-3]^w[j-8]^w[j-14]^w[j-16],1),t=safe_add(safe_add(rol(a,5),sha1_ft(j,b,c,d)),safe_add(safe_add(e,w[j]),sha1_kt(j))),e=d,d=c,c=rol(b,30),b=a,a=t;a=safe_add(a,olda),b=safe_add(b,oldb),c=safe_add(c,oldc),d=safe_add(d,oldd),e=safe_add(e,olde)}return[a,b,c,d,e]}function sha1_ft(t,b,c,d){return t<20?b&c|~b&d:t<40?b^c^d:t<60?b&c|b&d|c&d:b^c^d}function sha1_kt(t){return t<20?1518500249:t<40?1859775393:t<60?-1894007588:-899497514}function core_hmac_sha1(key,data){var bkey=str2binb(key);bkey.length>16&&(bkey=core_sha1(bkey,8*key.length));for(var ipad=Array(16),opad=Array(16),i=0;i<16;i++)ipad[i]=909522486^bkey[i],opad[i]=1549556828^bkey[i];var hash=core_sha1(ipad.concat(str2binb(data)),512+8*data.length);return core_sha1(opad.concat(hash),672)}function safe_add(x,y){var lsw=(65535&x)+(65535&y);return(x>>16)+(y>>16)+(lsw>>16)<<16|65535&lsw}function rol(num,cnt){return num<<cnt|num>>>32-cnt}function str2binb(str){for(var bin=[],i=0;i<8*str.length;i+=8)bin[i>>5]|=(255&str.charCodeAt(i/8))<<24-i%32;return bin}function binb2b64(binarray){for(var triplet,j,str="",i=0;i<4*binarray.length;i+=3)for(j=0,triplet=(binarray[i>>2]>>8*(3-i%4)&255)<<16|(binarray[i+1>>2]>>8*(3-(i+1)%4)&255)<<8|binarray[i+2>>2]>>8*(3-(i+2)%4)&255;j<4;j++)8*i+6*j>32*binarray.length?str+="=":str+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(triplet>>6*(3-j)&63);return str}function binb2str(bin){for(var str="",i=0;i<32*bin.length;i+=8)str+=String.fromCharCode(bin[i>>5]>>>24-i%32&255);return str}let SHA1={b64_hmac_sha1:function(key,data){return binb2b64(core_hmac_sha1(key,data))},b64_sha1:function(s){return binb2b64(core_sha1(str2binb(s),8*s.length))},binb2str:binb2str,core_hmac_sha1:core_hmac_sha1,str_hmac_sha1:function(key,data){return binb2str(core_hmac_sha1(key,data))},str_sha1:function(s){return binb2str(core_sha1(str2binb(s),8*s.length))}};function atobLookup(chr){let index="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(chr);return index<0?void 0:index}function btoaLookup(index){if(index>=0&&index<64)return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[index]}var abab={atob:function atob$2(data){if(0==arguments.length)throw TypeError("1 argument required, but only 0 present.");if((data=(data=`${data}`).replace(/[ \t\n\f\r]/g,"")).length%4==0&&(data=data.replace(/==?$/,"")),data.length%4==1||/[^+/0-9A-Za-z]/.test(data))return null;let output="",buffer=0,accumulatedBits=0;for(let i=0;i<data.length;i++)buffer<<=6,buffer|=atobLookup(data[i]),24===(accumulatedBits+=6)&&(output+=String.fromCharCode((16711680&buffer)>>16)+String.fromCharCode((65280&buffer)>>8)+String.fromCharCode(255&buffer),buffer=accumulatedBits=0);return 12===accumulatedBits?(buffer>>=4,output+=String.fromCharCode(buffer)):18===accumulatedBits&&(buffer>>=2,output+=String.fromCharCode((65280&buffer)>>8)+String.fromCharCode(255&buffer)),output},btoa:function btoa$2(s){let i;if(0==arguments.length)throw TypeError("1 argument required, but only 0 present.");for(i=0,s=`${s}`;i<s.length;i++)if(s.charCodeAt(i)>255)return null;let out="";for(i=0;i<s.length;i+=3){let groupsOfSix=[void 0,void 0,void 0,void 0];groupsOfSix[0]=s.charCodeAt(i)>>2,groupsOfSix[1]=(3&s.charCodeAt(i))<<4,s.length>i+1&&(groupsOfSix[1]|=s.charCodeAt(i+1)>>4,groupsOfSix[2]=(15&s.charCodeAt(i+1))<<2),s.length>i+2&&(groupsOfSix[2]|=s.charCodeAt(i+2)>>6,groupsOfSix[3]=63&s.charCodeAt(i+2));for(let j=0;j<groupsOfSix.length;j++)void 0===groupsOfSix[j]?out+="=":out+=btoaLookup(groupsOfSix[j])}return out}};function $build1(name,attrs){return new Strophe1.Builder(name,attrs)}function $msg1(attrs){return new Strophe1.Builder("message",attrs)}function $iq1(attrs){return new Strophe1.Builder("iq",attrs)}function $pres1(attrs){return new Strophe1.Builder("presence",attrs)}let Strophe1={VERSION:"1.5.0",NS:{HTTPBIND:"http://jabber.org/protocol/httpbind",BOSH:"urn:xmpp:xbosh",CLIENT:"jabber:client",AUTH:"jabber:iq:auth",ROSTER:"jabber:iq:roster",PROFILE:"jabber:iq:profile",DISCO_INFO:"http://jabber.org/protocol/disco#info",DISCO_ITEMS:"http://jabber.org/protocol/disco#items",MUC:"http://jabber.org/protocol/muc",SASL:"urn:ietf:params:xml:ns:xmpp-sasl",STREAM:"http://etherx.jabber.org/streams",FRAMING:"urn:ietf:params:xml:ns:xmpp-framing",BIND:"urn:ietf:params:xml:ns:xmpp-bind",SESSION:"urn:ietf:params:xml:ns:xmpp-session",VERSION:"jabber:iq:version",STANZAS:"urn:ietf:params:xml:ns:xmpp-stanzas",XHTML_IM:"http://jabber.org/protocol/xhtml-im",XHTML:"http://www.w3.org/1999/xhtml"},XHTML:{tags:["a","blockquote","br","cite","em","img","li","ol","p","span","strong","ul","body"],attributes:{a:["href"],blockquote:["style"],br:[],cite:["style"],em:[],img:["src","alt","style","height","width"],li:["style"],ol:["style"],p:["style"],span:["style"],strong:[],ul:["style"],body:[]},css:["background-color","color","font-family","font-size","font-style","font-weight","margin-left","margin-right","text-align","text-decoration"],validTag(tag){for(let i=0;i<Strophe1.XHTML.tags.length;i++)if(tag===Strophe1.XHTML.tags[i])return!0;return!1},validAttribute(tag,attribute){if(void 0!==Strophe1.XHTML.attributes[tag]&&Strophe1.XHTML.attributes[tag].length>0){for(let i=0;i<Strophe1.XHTML.attributes[tag].length;i++)if(attribute===Strophe1.XHTML.attributes[tag][i])return!0}return!1},validCSS(style){for(let i=0;i<Strophe1.XHTML.css.length;i++)if(style===Strophe1.XHTML.css[i])return!0;return!1}},Status:{ERROR:0,CONNECTING:1,CONNFAIL:2,AUTHENTICATING:3,AUTHFAIL:4,CONNECTED:5,DISCONNECTED:6,DISCONNECTING:7,ATTACHED:8,REDIRECT:9,CONNTIMEOUT:10,BINDREQUIRED:11,ATTACHFAIL:12},ErrorCondition:{BAD_FORMAT:"bad-format",CONFLICT:"conflict",MISSING_JID_NODE:"x-strophe-bad-non-anon-jid",NO_AUTH_MECH:"no-auth-mech",UNKNOWN_REASON:"unknown"},LogLevel:{DEBUG:0,INFO:1,WARN:2,ERROR:3,FATAL:4},ElementType:{NORMAL:1,TEXT:3,CDATA:4,FRAGMENT:11},TIMEOUT:1.1,SECONDARY_TIMEOUT:.1,addNamespace(name,value){Strophe1.NS[name]=value},forEachChild(elem,elemName,func){for(let i=0;i<elem.childNodes.length;i++){let childNode=elem.childNodes[i];childNode.nodeType===Strophe1.ElementType.NORMAL&&(!elemName||this.isTagEqual(childNode,elemName))&&func(childNode)}},isTagEqual:(el,name)=>el.tagName===name,_xmlGenerator:null,xmlGenerator:()=>(Strophe1._xmlGenerator||(Strophe1._xmlGenerator=getDummyXMLDOMDocument()),Strophe1._xmlGenerator),xmlElement(name){if(!name)return null;let node=Strophe1.xmlGenerator().createElement(name);for(let a=1;a<arguments.length;a++){let arg=arguments[a];if(arg){if("string"==typeof arg||"number"==typeof arg)node.appendChild(Strophe1.xmlTextNode(arg));else if("object"==typeof arg&&"function"==typeof arg.sort)for(let i=0;i<arg.length;i++){let attr=arg[i];"object"==typeof attr&&"function"==typeof attr.sort&&void 0!==attr[1]&&null!==attr[1]&&node.setAttribute(attr[0],attr[1])}else if("object"==typeof arg)for(let k in arg)Object.prototype.hasOwnProperty.call(arg,k)&&void 0!==arg[k]&&null!==arg[k]&&node.setAttribute(k,arg[k])}}return node},xmlescape:text=>text=(text=(text=(text=(text=text.replace(/\&/g,"&")).replace(/</g,"<")).replace(/>/g,">")).replace(/'/g,"'")).replace(/"/g,"""),xmlunescape:text=>text=(text=(text=(text=(text=text.replace(/\&/g,"&")).replace(/</g,"<")).replace(/>/g,">")).replace(/'/g,"'")).replace(/"/g,'"'),xmlTextNode:text=>Strophe1.xmlGenerator().createTextNode(text),xmlHtmlNode(html){let node;return DOMParser1?node=new DOMParser1().parseFromString(html,"text/xml"):((node=new ActiveXObject("Microsoft.XMLDOM")).async="false",node.loadXML(html)),node},getText(elem){if(!elem)return null;let str="";0===elem.childNodes.length&&elem.nodeType===Strophe1.ElementType.TEXT&&(str+=elem.nodeValue);for(let i=0;i<elem.childNodes.length;i++)elem.childNodes[i].nodeType===Strophe1.ElementType.TEXT&&(str+=elem.childNodes[i].nodeValue);return Strophe1.xmlescape(str)},copyElement(elem){let el;if(elem.nodeType===Strophe1.ElementType.NORMAL){el=Strophe1.xmlElement(elem.tagName);for(let i=0;i<elem.attributes.length;i++)el.setAttribute(elem.attributes[i].nodeName,elem.attributes[i].value);for(let i=0;i<elem.childNodes.length;i++)el.appendChild(Strophe1.copyElement(elem.childNodes[i]))}else elem.nodeType===Strophe1.ElementType.TEXT&&(el=Strophe1.xmlGenerator().createTextNode(elem.nodeValue));return el},createHtml(elem){let el;if(elem.nodeType===Strophe1.ElementType.NORMAL){let tag=elem.nodeName.toLowerCase();if(Strophe1.XHTML.validTag(tag))try{el=Strophe1.xmlElement(tag);for(let i=0;i<Strophe1.XHTML.attributes[tag].length;i++){let attribute=Strophe1.XHTML.attributes[tag][i],value=elem.getAttribute(attribute);if(null!=value&&""!==value&&!1!==value&&0!==value){if("style"===attribute&&"object"==typeof value&&void 0!==value.cssText&&(value=value.cssText),"style"===attribute){let css=[],cssAttrs=value.split(";");for(let j=0;j<cssAttrs.length;j++){let attr=cssAttrs[j].split(":"),cssName=attr[0].replace(/^\s*/,"").replace(/\s*$/,"").toLowerCase();if(Strophe1.XHTML.validCSS(cssName)){let cssValue=attr[1].replace(/^\s*/,"").replace(/\s*$/,"");css.push(cssName+": "+cssValue)}}css.length>0&&(value=css.join("; "),el.setAttribute(attribute,value))}else el.setAttribute(attribute,value)}}for(let i=0;i<elem.childNodes.length;i++)el.appendChild(Strophe1.createHtml(elem.childNodes[i]))}catch(e){el=Strophe1.xmlTextNode("")}else{el=Strophe1.xmlGenerator().createDocumentFragment();for(let i=0;i<elem.childNodes.length;i++)el.appendChild(Strophe1.createHtml(elem.childNodes[i]))}}else if(elem.nodeType===Strophe1.ElementType.FRAGMENT){el=Strophe1.xmlGenerator().createDocumentFragment();for(let i=0;i<elem.childNodes.length;i++)el.appendChild(Strophe1.createHtml(elem.childNodes[i]))}else elem.nodeType===Strophe1.ElementType.TEXT&&(el=Strophe1.xmlTextNode(elem.nodeValue));return el},escapeNode:node=>"string"!=typeof node?node:node.replace(/^\s+|\s+$/g,"").replace(/\\/g,"\\5c").replace(/ /g,"\\20").replace(/\"/g,"\\22").replace(/\&/g,"\\26").replace(/\'/g,"\\27").replace(/\//g,"\\2f").replace(/:/g,"\\3a").replace(/</g,"\\3c").replace(/>/g,"\\3e").replace(/@/g,"\\40"),unescapeNode:node=>"string"!=typeof node?node:node.replace(/\\20/g," ").replace(/\\22/g,'"').replace(/\\26/g,"&").replace(/\\27/g,"'").replace(/\\2f/g,"/").replace(/\\3a/g,":").replace(/\\3c/g,"<").replace(/\\3e/g,">").replace(/\\40/g,"@").replace(/\\5c/g,"\\"),getNodeFromJid:jid=>0>jid.indexOf("@")?null:jid.split("@")[0],getDomainFromJid(jid){let bare=Strophe1.getBareJidFromJid(jid);if(0>bare.indexOf("@"))return bare;{let parts=bare.split("@");return parts.splice(0,1),parts.join("@")}},getResourceFromJid(jid){if(!jid)return null;let s=jid.split("/");return s.length<2?null:(s.splice(0,1),s.join("/"))},getBareJidFromJid:jid=>jid?jid.split("/")[0]:null,_handleError(e){void 0!==e.stack&&Strophe1.fatal(e.stack),e.sourceURL?Strophe1.fatal("error: "+this.handler+" "+e.sourceURL+":"+e.line+" - "+e.name+": "+e.message):e.fileName?Strophe1.fatal("error: "+this.handler+" "+e.fileName+":"+e.lineNumber+" - "+e.name+": "+e.message):Strophe1.fatal("error: "+e.message)},log(level,msg){if(level===this.LogLevel.FATAL){var _console;null===(_console=console)||void 0===_console||_console.error(msg)}},debug(msg){this.log(this.LogLevel.DEBUG,msg)},info(msg){this.log(this.LogLevel.INFO,msg)},warn(msg){this.log(this.LogLevel.WARN,msg)},error(msg){this.log(this.LogLevel.ERROR,msg)},fatal(msg){this.log(this.LogLevel.FATAL,msg)},serialize(elem){if(!elem)return null;"function"==typeof elem.tree&&(elem=elem.tree());let names=[...Array(elem.attributes.length).keys()].map(i=>elem.attributes[i].nodeName);names.sort();let result=names.reduce((a,n)=>`${a} ${n}="${Strophe1.xmlescape(elem.attributes.getNamedItem(n).value)}"`,`<${elem.nodeName}`);if(elem.childNodes.length>0){result+=">";for(let i=0;i<elem.childNodes.length;i++){let child=elem.childNodes[i];switch(child.nodeType){case Strophe1.ElementType.NORMAL:result+=Strophe1.serialize(child);break;case Strophe1.ElementType.TEXT:result+=Strophe1.xmlescape(child.nodeValue);break;case Strophe1.ElementType.CDATA:result+="<![CDATA["+child.nodeValue+"]]>"}}result+="</"+elem.nodeName+">"}else result+="/>";return result},_requestId:0,_connectionPlugins:{},addConnectionPlugin(name,ptype){Strophe1._connectionPlugins[name]=ptype}};Strophe1.Builder=class{constructor(name,attrs){"presence"!==name&&"message"!==name&&"iq"!==name||(attrs&&!attrs.xmlns?attrs.xmlns=Strophe1.NS.CLIENT:attrs||(attrs={xmlns:Strophe1.NS.CLIENT})),this.nodeTree=Strophe1.xmlElement(name,attrs),this.node=this.nodeTree}tree(){return this.nodeTree}toString(){return Strophe1.serialize(this.nodeTree)}up(){return this.node=this.node.parentNode,this}root(){return this.node=this.nodeTree,this}attrs(moreattrs){for(let k in moreattrs)Object.prototype.hasOwnProperty.call(moreattrs,k)&&(void 0===moreattrs[k]?this.node.removeAttribute(k):this.node.setAttribute(k,moreattrs[k]));return this}c(name,attrs,text){let child=Strophe1.xmlElement(name,attrs,text);return this.node.appendChild(child),"string"!=typeof text&&"number"!=typeof text&&(this.node=child),this}cnode(elem){let impNode;let xmlGen=Strophe1.xmlGenerator();try{impNode=void 0!==xmlGen.importNode}catch(e){impNode=!1}let newElem=impNode?xmlGen.importNode(elem,!0):Strophe1.copyElement(elem);return this.node.appendChild(newElem),this.node=newElem,this}t(text){let child=Strophe1.xmlTextNode(text);return this.node.appendChild(child),this}h(html){let fragment=Strophe1.xmlGenerator().createElement("body");fragment.innerHTML=html;let xhtml=Strophe1.createHtml(fragment);for(;xhtml.childNodes.length>0;)this.node.appendChild(xhtml.childNodes[0]);return this}},Strophe1.Handler=function(handler,ns,name,type,id,from,options){this.handler=handler,this.ns=ns,this.name=name,this.type=type,this.id=id,this.options=options||{matchBareFromJid:!1,ignoreNamespaceFragment:!1},this.options.matchBare&&(Strophe1.warn('The "matchBare" option is deprecated, use "matchBareFromJid" instead.'),this.options.matchBareFromJid=this.options.matchBare,delete this.options.matchBare),this.options.matchBareFromJid?this.from=from?Strophe1.getBareJidFromJid(from):null:this.from=from,this.user=!0},Strophe1.Handler.prototype={getNamespace(elem){let elNamespace=elem.getAttribute("xmlns");return elNamespace&&this.options.ignoreNamespaceFragment&&(elNamespace=elNamespace.split("#")[0]),elNamespace},namespaceMatch(elem){let nsMatch=!1;return!this.ns||(Strophe1.forEachChild(elem,null,elem=>{this.getNamespace(elem)===this.ns&&(nsMatch=!0)}),nsMatch||this.getNamespace(elem)===this.ns)},isMatch(elem){let from=elem.getAttribute("from");this.options.matchBareFromJid&&(from=Strophe1.getBareJidFromJid(from));let elem_type=elem.getAttribute("type");return!!(this.namespaceMatch(elem)&&(!this.name||Strophe1.isTagEqual(elem,this.name)))&&(!this.type||(Array.isArray(this.type)?-1!==this.type.indexOf(elem_type):elem_type===this.type))&&(!this.id||elem.getAttribute("id")===this.id)&&(!this.from||from===this.from)},run(elem){let result=null;try{result=this.handler(elem)}catch(e){throw Strophe1._handleError(e),e}return result},toString(){return"{Handler: "+this.handler+"("+this.name+","+this.id+","+this.ns+")}"}},Strophe1.TimedHandler=class{constructor(period,handler){this.period=period,this.handler=handler,this.lastCalled=new Date().getTime(),this.user=!0}run(){return this.lastCalled=new Date().getTime(),this.handler()}reset(){this.lastCalled=new Date().getTime()}toString(){return"{TimedHandler: "+this.handler+"("+this.period+")}"}},Strophe1.Connection=class{constructor(service,options){for(let k in this.service=service,this.options=options||{},this.setProtocol(),this.jid="",this.domain=null,this.features=null,this._sasl_data={},this.do_bind=!1,this.do_session=!1,this.mechanisms={},this.timedHandlers=[],this.handlers=[],this.removeTimeds=[],this.removeHandlers=[],this.addTimeds=[],this.addHandlers=[],this.protocolErrorHandlers={HTTP:{},websocket:{}},this._idleTimeout=null,this._disconnectTimeout=null,this.authenticated=!1,this.connected=!1,this.disconnecting=!1,this.do_authentication=!0,this.paused=!1,this.restored=!1,this._data=[],this._uniqueId=0,this._sasl_success_handler=null,this._sasl_failure_handler=null,this._sasl_challenge_handler=null,this.maxRetries=5,this._idleTimeout=setTimeout(()=>this._onIdle(),100),utils.addCookies(this.options.cookies),this.registerSASLMechanisms(this.options.mechanisms),this.iqFallbackHandler=new Strophe1.Handler(iq=>this.send($iq1({type:"error",id:iq.getAttribute("id")}).c("error",{type:"cancel"}).c("service-unavailable",{xmlns:Strophe1.NS.STANZAS})),null,"iq",["get","set"]),Strophe1._connectionPlugins)if(Object.prototype.hasOwnProperty.call(Strophe1._connectionPlugins,k)){let F=function(){};F.prototype=Strophe1._connectionPlugins[k],this[k]=new F,this[k].init(this)}}setProtocol(){let proto=this.options.protocol||"";this.options.worker?this._proto=new Strophe1.WorkerWebsocket(this):0===this.service.indexOf("ws:")||0===this.service.indexOf("wss:")||0===proto.indexOf("ws")?this._proto=new Strophe1.Websocket(this):this._proto=new Strophe1.Bosh(this)}reset(){this._proto._reset(),this.do_session=!1,this.do_bind=!1,this.timedHandlers=[],this.handlers=[],this.removeTimeds=[],this.removeHandlers=[],this.addTimeds=[],this.addHandlers=[],this.authenticated=!1,this.connected=!1,this.disconnecting=!1,this.restored=!1,this._data=[],this._requests=[],this._uniqueId=0}pause(){this.paused=!0}resume(){this.paused=!1}getUniqueId(suffix){let uuid="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){let r=16*Math.random()|0;return("x"===c?r:3&r|8).toString(16)});return"string"==typeof suffix||"number"==typeof suffix?uuid+":"+suffix:uuid+""}addProtocolErrorHandler(protocol,status_code,callback){this.protocolErrorHandlers[protocol][status_code]=callback}connect(jid,pass,callback,wait,hold,route,authcid){let disconnection_timeout=arguments.length>7&&void 0!==arguments[7]?arguments[7]:3e3;this.jid=jid,this.authzid=Strophe1.getBareJidFromJid(this.jid),this.authcid=authcid||Strophe1.getNodeFromJid(this.jid),this.pass=pass,this.connect_callback=callback,this.disconnecting=!1,this.connected=!1,this.authenticated=!1,this.restored=!1,this.disconnection_timeout=disconnection_timeout,this.domain=Strophe1.getDomainFromJid(this.jid),this._changeConnectStatus(Strophe1.Status.CONNECTING,null),this._proto._connect(wait,hold,route)}attach(jid,sid,rid,callback,wait,hold,wind){if(this._proto._attach)return this._proto._attach(jid,sid,rid,callback,wait,hold,wind);{let error=Error('The "attach" method is not available for your connection protocol');throw error.name="StropheSessionError",error}}restore(jid,callback,wait,hold,wind){if(this._sessionCachingSupported())this._proto._restore(jid,callback,wait,hold,wind);else{let error=Error('The "restore" method can only be used with a BOSH connection.');throw error.name="StropheSessionError",error}}_sessionCachingSupported(){if(this._proto instanceof Strophe1.Bosh){if(!JSON)return!1;try{sessionStorage.setItem("_strophe_","_strophe_"),sessionStorage.removeItem("_strophe_")}catch(e){return!1}return!0}return!1}xmlInput(elem){}xmlOutput(elem){}rawInput(data){}rawOutput(data){}nextValidRid(rid){}send(elem){if(null!==elem){if("function"==typeof elem.sort)for(let i=0;i<elem.length;i++)this._queueData(elem[i]);else"function"==typeof elem.tree?this._queueData(elem.tree()):this._queueData(elem);this._proto._send()}}flush(){clearTimeout(this._idleTimeout),this._onIdle()}sendPresence(elem,callback,errback,timeout){let timeoutHandler=null;"function"==typeof elem.tree&&(elem=elem.tree());let id=elem.getAttribute("id");if(id||(id=this.getUniqueId("sendPresence"),elem.setAttribute("id",id)),"function"==typeof callback||"function"==typeof errback){let handler=this.addHandler(stanza=>{timeoutHandler&&this.deleteTimedHandler(timeoutHandler),"error"===stanza.getAttribute("type")?errback&&errback(stanza):callback&&callback(stanza)},null,"presence",null,id);timeout&&(timeoutHandler=this.addTimedHandler(timeout,()=>(this.deleteHandler(handler),errback&&errback(null),!1)))}return this.send(elem),id}sendIQ(elem,callback,errback,timeout){let timeoutHandler=null;"function"==typeof elem.tree&&(elem=elem.tree());let id=elem.getAttribute("id");if(id||(id=this.getUniqueId("sendIQ"),elem.setAttribute("id",id)),"function"==typeof callback||"function"==typeof errback){let handler=this.addHandler(stanza=>{timeoutHandler&&this.deleteTimedHandler(timeoutHandler);let iqtype=stanza.getAttribute("type");if("result"===iqtype)callback&&callback(stanza);else if("error"===iqtype)errback&&errback(stanza);else{let error=Error(`Got bad IQ type of ${iqtype}`);throw error.name="StropheError",error}},null,"iq",["error","result"],id);timeout&&(timeoutHandler=this.addTimedHandler(timeout,()=>(this.deleteHandler(handler),errback&&errback(null),!1)))}return this.send(elem),id}_queueData(element){if(null===element||!element.tagName||!element.childNodes){let error=Error("Cannot queue non-DOMElement.");throw error.name="StropheError",error}this._data.push(element)}_sendRestart(){this._data.push("restart"),this._proto._sendRestart(),this._idleTimeout=setTimeout(()=>this._onIdle(),100)}addTimedHandler(period,handler){let thand=new Strophe1.TimedHandler(period,handler);return this.addTimeds.push(thand),thand}deleteTimedHandler(handRef){this.removeTimeds.push(handRef)}addHandler(handler,ns,name,type,id,from,options){let hand=new Strophe1.Handler(handler,ns,name,type,id,from,options);return this.addHandlers.push(hand),hand}deleteHandler(handRef){this.removeHandlers.push(handRef);let i=this.addHandlers.indexOf(handRef);i>=0&&this.addHandlers.splice(i,1)}registerSASLMechanisms(mechanisms){this.mechanisms={},(mechanisms=mechanisms||[Strophe1.SASLAnonymous,Strophe1.SASLExternal,Strophe1.SASLOAuthBearer,Strophe1.SASLXOAuth2,Strophe1.SASLPlain,Strophe1.SASLSHA1]).forEach(m=>this.registerSASLMechanism(m))}registerSASLMechanism(Mechanism){let mechanism=new Mechanism;this.mechanisms[mechanism.mechname]=mechanism}disconnect(reason){if(this._changeConnectStatus(Strophe1.Status.DISCONNECTING,reason),reason?Strophe1.warn("Disconnect was called because: "+reason):Strophe1.info("Disconnect was called"),this.connected){let pres=!1;this.disconnecting=!0,this.authenticated&&(pres=$pres1({xmlns:Strophe1.NS.CLIENT,type:"unavailable"})),this._disconnectTimeout=this._addSysTimedHandler(this.disconnection_timeout,this._onDisconnectTimeout.bind(this)),this._proto._disconnect(pres)}else Strophe1.warn("Disconnect was called before Strophe connected to the server"),this._proto._abortAllRequests(),this._doDisconnect()}_changeConnectStatus(status,condition,elem){for(let k in Strophe1._connectionPlugins)if(Object.prototype.hasOwnProperty.call(Strophe1._connectionPlugins,k)){let plugin=this[k];if(plugin.statusChanged)try{plugin.statusChanged(status,condition)}catch(err){Strophe1.error(`${k} plugin caused an exception changing status: ${err}`)}}if(this.connect_callback)try{this.connect_callback(status,condition,elem)}catch(e){Strophe1._handleError(e),Strophe1.error(`User connection callback caused an exception: ${e}`)}}_doDisconnect(condition){"number"==typeof this._idleTimeout&&clearTimeout(this._idleTimeout),null!==this._disconnectTimeout&&(this.deleteTimedHandler(this._disconnectTimeout),this._disconnectTimeout=null),Strophe1.debug("_doDisconnect was called"),this._proto._doDisconnect(),this.authenticated=!1,this.disconnecting=!1,this.restored=!1,this.handlers=[],this.timedHandlers=[],this.removeTimeds=[],this.removeHandlers=[],this.addTimeds=[],this.addHandlers=[],this._changeConnectStatus(Strophe1.Status.DISCONNECTED,condition),this.connected=!1}_dataRecv(req,raw){let elem=this._proto._reqToData(req);if(null===elem)return;for(this.xmlInput!==Strophe1.Connection.prototype.xmlInput&&(elem.nodeName===this._proto.strip&&elem.childNodes.length?this.xmlInput(elem.childNodes[0]):this.xmlInput(elem)),this.rawInput!==Strophe1.Connection.prototype.rawInput&&(raw?this.rawInput(raw):this.rawInput(Strophe1.serialize(elem)));this.removeHandlers.length>0;){let hand=this.removeHandlers.pop(),i=this.handlers.indexOf(hand);i>=0&&this.handlers.splice(i,1)}for(;this.addHandlers.length>0;)this.handlers.push(this.addHandlers.pop());if(this.disconnecting&&this._proto._emptyQueue()){this._doDisconnect();return}let type=elem.getAttribute("type");if(null!==type&&"terminate"===type){if(this.disconnecting)return;let cond=elem.getAttribute("condition"),conflict=elem.getElementsByTagName("conflict");null!==cond?("remote-stream-error"===cond&&conflict.length>0&&(cond="conflict"),this._changeConnectStatus(Strophe1.Status.CONNFAIL,cond)):this._changeConnectStatus(Strophe1.Status.CONNFAIL,Strophe1.ErrorCondition.UNKOWN_REASON),this._doDisconnect(cond);return}Strophe1.forEachChild(elem,null,child=>{let matches=[];this.handlers=this.handlers.reduce((handlers,handler)=>{try{handler.isMatch(child)&&(this.authenticated||!handler.user)?(handler.run(child)&&handlers.push(handler),matches.push(handler)):handlers.push(handler)}catch(e){Strophe1.warn("Removing Strophe handlers due to uncaught exception: "+e.message)}return handlers},[]),!matches.length&&this.iqFallbackHandler.isMatch(child)&&this.iqFallbackHandler.run(child)})}_connect_cb(req,_callback,raw){let bodyWrap;Strophe1.debug("_connect_cb was called"),this.connected=!0;try{bodyWrap=this._proto._reqToData(req)}catch(e){if(e.name!==Strophe1.ErrorCondition.BAD_FORMAT)throw e;this._changeConnectStatus(Strophe1.Status.CONNFAIL,Strophe1.ErrorCondition.BAD_FORMAT),this._doDisconnect(Strophe1.ErrorCondition.BAD_FORMAT)}if(!bodyWrap||(this.xmlInput!==Strophe1.Connection.prototype.xmlInput&&(bodyWrap.nodeName===this._proto.strip&&bodyWrap.childNodes.length?this.xmlInput(bodyWrap.childNodes[0]):this.xmlInput(bodyWrap)),this.rawInput!==Strophe1.Connection.prototype.rawInput&&(raw?this.rawInput(raw):this.rawInput(Strophe1.serialize(bodyWrap))),this._proto._connect_cb(bodyWrap)===Strophe1.Status.CONNFAIL))return;if(!(bodyWrap.getElementsByTagNameNS?bodyWrap.getElementsByTagNameNS(Strophe1.NS.STREAM,"features").length>0:bodyWrap.getElementsByTagName("stream:features").length>0||bodyWrap.getElementsByTagName("features").length>0)){this._proto._no_auth_received(_callback);return}let matched=Array.from(bodyWrap.getElementsByTagName("mechanism")).map(m=>this.mechanisms[m.textContent]).filter(m=>m);if(0===matched.length&&0===bodyWrap.getElementsByTagName("auth").length){this._proto._no_auth_received(_callback);return}!1!==this.do_authentication&&this.authenticate(matched)}sortMechanismsByPriority(mechanisms){for(let i=0;i<mechanisms.length-1;++i){let higher=i;for(let j=i+1;j<mechanisms.length;++j)mechanisms[j].priority>mechanisms[higher].priority&&(higher=j);if(higher!==i){let swap=mechanisms[i];mechanisms[i]=mechanisms[higher],mechanisms[higher]=swap}}return mechanisms}authenticate(matched){this._attemptSASLAuth(matched)||this._attemptLegacyAuth()}_attemptSASLAuth(mechanisms){mechanisms=this.sortMechanismsByPriority(mechanisms||[]);let mechanism_found=!1;for(let i=0;i<mechanisms.length;++i){if(!mechanisms[i].test(this))continue;this._sasl_success_handler=this._addSysHandler(this._sasl_success_cb.bind(this),null,"success",null,null),this._sasl_failure_handler=this._addSysHandler(this._sasl_failure_cb.bind(this),null,"failure",null,null),this._sasl_challenge_handler=this._addSysHandler(this._sasl_challenge_cb.bind(this),null,"challenge",null,null),this._sasl_mechanism=mechanisms[i],this._sasl_mechanism.onStart(this);let request_auth_exchange=$build1("auth",{xmlns:Strophe1.NS.SASL,mechanism:this._sasl_mechanism.mechname});if(this._sasl_mechanism.isClientFirst){let response=this._sasl_mechanism.clientChallenge(this);request_auth_exchange.t(abab.btoa(response))}this.send(request_auth_exchange.tree()),mechanism_found=!0;break}return mechanism_found}_sasl_challenge_cb(elem){let challenge=abab.atob(Strophe1.getText(elem)),response=this._sasl_mechanism.onChallenge(this,challenge),stanza=$build1("response",{xmlns:Strophe1.NS.SASL});return""!==response&&stanza.t(abab.btoa(response)),this.send(stanza.tree()),!0}_attemptLegacyAuth(){null===Strophe1.getNodeFromJid(this.jid)?(this._changeConnectStatus(Strophe1.Status.CONNFAIL,Strophe1.ErrorCondition.MISSING_JID_NODE),this.disconnect(Strophe1.ErrorCondition.MISSING_JID_NODE)):(this._changeConnectStatus(Strophe1.Status.AUTHENTICATING,null),this._addSysHandler(this._onLegacyAuthIQResult.bind(this),null,null,null,"_auth_1"),this.send($iq1({type:"get",to:this.domain,id:"_auth_1"}).c("query",{xmlns:Strophe1.NS.AUTH}).c("username",{}).t(Strophe1.getNodeFromJid(this.jid)).tree()))}_onLegacyAuthIQResult(elem){let iq=$iq1({type:"set",id:"_auth_2"}).c("query",{xmlns:Strophe1.NS.AUTH}).c("username",{}).t(Strophe1.getNodeFromJid(this.jid)).up().c("password").t(this.pass);return Strophe1.getResourceFromJid(this.jid)||(this.jid=Strophe1.getBareJidFromJid(this.jid)+"/strophe"),iq.up().c("resource",{}).t(Strophe1.getResourceFromJid(this.jid)),this._addSysHandler(this._auth2_cb.bind(this),null,null,null,"_auth_2"),this.send(iq.tree()),!1}_sasl_success_cb(elem){if(this._sasl_data["server-signature"]){let serverSignature;let matches=abab.atob(Strophe1.getText(elem)).match(/([a-z]+)=([^,]+)(,|$)/);if("v"===matches[1]&&(serverSignature=matches[2]),serverSignature!==this._sasl_data["server-signature"])return this.deleteHandler(this._sasl_failure_handler),this._sasl_failure_handler=null,this._sasl_challenge_handler&&(this.deleteHandler(this._sasl_challenge_handler),this._sasl_challenge_handler=null),this._sasl_data={},this._sasl_failure_cb(null)}Strophe1.info("SASL authentication succeeded."),this._sasl_mechanism&&this._sasl_mechanism.onSuccess(),this.deleteHandler(this._sasl_failure_handler),this._sasl_failure_handler=null,this._sasl_challenge_handler&&(this.deleteHandler(this._sasl_challenge_handler),this._sasl_challenge_handler=null);let streamfeature_handlers=[],wrapper=(handlers,elem)=>{for(;handlers.length;)this.deleteHandler(handlers.pop());return this._onStreamFeaturesAfterSASL(elem),!1};return streamfeature_handlers.push(this._addSysHandler(elem=>wrapper(streamfeature_handlers,elem),null,"stream:features",null,null)),streamfeature_handlers.push(this._addSysHandler(elem=>wrapper(streamfeature_handlers,elem),Strophe1.NS.STREAM,"features",null,null)),this._sendRestart(),!1}_onStreamFeaturesAfterSASL(elem){this.features=elem;for(let i=0;i<elem.childNodes.length;i++){let child=elem.childNodes[i];"bind"===child.nodeName&&(this.do_bind=!0),"session"===child.nodeName&&(this.do_session=!0)}return this.do_bind?this.options.explicitResourceBinding?this._changeConnectStatus(Strophe1.Status.BINDREQUIRED,null):this.bind():this._changeConnectStatus(Strophe1.Status.AUTHFAIL,null),!1}bind(){if(!this.do_bind){Strophe1.log(Strophe1.LogLevel.INFO,'Strophe.Connection.prototype.bind called but "do_bind" is false');return}this._addSysHandler(this._onResourceBindResultIQ.bind(this),null,null,null,"_bind_auth_2");let resource=Strophe1.getResourceFromJid(this.jid);resource?this.send($iq1({type:"set",id:"_bind_auth_2"}).c("bind",{xmlns:Strophe1.NS.BIND}).c("resource",{}).t(resource).tree()):this.send($iq1({type:"set",id:"_bind_auth_2"}).c("bind",{xmlns:Strophe1.NS.BIND}).tree())}_onResourceBindResultIQ(elem){if("error"===elem.getAttribute("type")){let condition;return Strophe1.warn("Resource binding failed."),elem.getElementsByTagName("conflict").length>0&&(condition=Strophe1.ErrorCondition.CONFLICT),this._changeConnectStatus(Strophe1.Status.AUTHFAIL,condition,elem),!1}let bind=elem.getElementsByTagName("bind");if(!(bind.length>0))return Strophe1.warn("Resource binding failed."),this._changeConnectStatus(Strophe1.Status.AUTHFAIL,null,elem),!1;{let jidNode=bind[0].getElementsByTagName("jid");jidNode.length>0&&(this.authenticated=!0,this.jid=Strophe1.getText(jidNode[0]),this.do_session?this._establishSession():this._changeConnectStatus(Strophe1.Status.CONNECTED,null))}}_establishSession(){if(!this.do_session)throw Error(`Strophe.Connection.prototype._establishSession called but apparently ${Strophe1.NS.SESSION} wasn't advertised by the server`);this._addSysHandler(this._onSessionResultIQ.bind(this),null,null,null,"_session_auth_2"),this.send($iq1({type:"set",id:"_session_auth_2"}).c("session",{xmlns:Strophe1.NS.SESSION}).tree())}_onSessionResultIQ(elem){return"result"===elem.getAttribute("type")?(this.authenticated=!0,this._changeConnectStatus(Strophe1.Status.CONNECTED,null)):"error"===elem.getAttribute("type")&&(this.authenticated=!1,Strophe1.warn("Session creation failed."),this._changeConnectStatus(Strophe1.Status.AUTHFAIL,null,elem)),!1}_sasl_failure_cb(elem){return this._sasl_success_handler&&(this.deleteHandler(this._sasl_success_handler),this._sasl_success_handler=null),this._sasl_challenge_handler&&(this.deleteHandler(this._sasl_challenge_handler),this._sasl_challenge_handler=null),this._sasl_mechanism&&this._sasl_mechanism.onFailure(),this._changeConnectStatus(Strophe1.Status.AUTHFAIL,null,elem),!1}_auth2_cb(elem){return"result"===elem.getAttribute("type")?(this.authenticated=!0,this._changeConnectStatus(Strophe1.Status.CONNECTED,null)):"error"===elem.getAttribute("type")&&(this._changeConnectStatus(Strophe1.Status.AUTHFAIL,null,elem),this.disconnect("authentication failed")),!1}_addSysTimedHandler(period,handler){let thand=new Strophe1.TimedHandler(period,handler);return thand.user=!1,this.addTimeds.push(thand),thand}_addSysHandler(handler,ns,name,type,id){let hand=new Strophe1.Handler(handler,ns,name,type,id);return hand.user=!1,this.addHandlers.push(hand),hand}_onDisconnectTimeout(){return Strophe1.debug("_onDisconnectTimeout was called"),this._changeConnectStatus(Strophe1.Status.CONNTIMEOUT,null),this._proto._onDisconnectTimeout(),this._doDisconnect(),!1}_onIdle(){for(;this.addTimeds.length>0;)this.timedHandlers.push(this.addTimeds.pop());for(;this.removeTimeds.length>0;){let thand=this.removeTimeds.pop(),i=this.timedHandlers.indexOf(thand);i>=0&&this.timedHandlers.splice(i,1)}let now=new Date().getTime(),newList=[];for(let i=0;i<this.timedHandlers.length;i++){let thand=this.timedHandlers[i];(this.authenticated||!thand.user)&&(thand.lastCalled+thand.period-now<=0?thand.run()&&newList.push(thand):newList.push(thand))}this.timedHandlers=newList,clearTimeout(this._idleTimeout),this._proto._onIdle(),this.connected&&(this._idleTimeout=setTimeout(()=>this._onIdle(),100))}},Strophe1.SASLMechanism=SASLMechanism,Strophe1.SASLAnonymous=class extends SASLMechanism{constructor(){let mechname=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"ANONYMOUS",isClientFirst=arguments.length>1&&void 0!==arguments[1]&&arguments[1],priority=arguments.length>2&&void 0!==arguments[2]?arguments[2]:20;super(mechname,isClientFirst,priority)}test(connection){return null===connection.authcid}},Strophe1.SASLPlain=class extends SASLMechanism{constructor(){let mechname=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"PLAIN",isClientFirst=!(arguments.length>1)||void 0===arguments[1]||arguments[1],priority=arguments.length>2&&void 0!==arguments[2]?arguments[2]:50;super(mechname,isClientFirst,priority)}test(connection){return null!==connection.authcid}onChallenge(connection){let{authcid,authzid,domain,pass}=connection;if(!domain)throw Error("SASLPlain onChallenge: domain is not defined!");let auth_str=authzid!==`${authcid}@${domain}`?authzid:"";return auth_str+="\0"+authcid+"\0"+pass,utils.utf16to8(auth_str)}},Strophe1.SASLSHA1=class extends SASLMechanism{constructor(){let mechname=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"SCRAM-SHA-1",isClientFirst=!(arguments.length>1)||void 0===arguments[1]||arguments[1],priority=arguments.length>2&&void 0!==arguments[2]?arguments[2]:60;super(mechname,isClientFirst,priority)}test(connection){return null!==connection.authcid}onChallenge(connection,challenge){let nonce,salt,iter,Hi,U,U_old,i,k;let responseText="c=biws,",authMessage=`${connection._sasl_data["client-first-message-bare"]},${challenge},`,cnonce=connection._sasl_data.cnonce,attribMatch=/([a-z]+)=([^,]+)(,|$)/;for(;challenge.match(attribMatch);){let matches=challenge.match(attribMatch);switch(challenge=challenge.replace(matches[0],""),matches[1]){case"r":nonce=matches[2];break;case"s":salt=matches[2];break;case"i":iter=matches[2]}}if(nonce.slice(0,cnonce.length)!==cnonce)return connection._sasl_data={},connection._sasl_failure_cb();responseText+="r="+nonce,authMessage+=responseText,salt=atob(salt)+"\0\0\0\x01";let pass=utils.utf16to8(connection.pass);for(i=1,Hi=U_old=SHA1.core_hmac_sha1(pass,salt);i<iter;i++){for(k=0,U=SHA1.core_hmac_sha1(pass,SHA1.binb2str(U_old));k<5;k++)Hi[k]^=U[k];U_old=U}Hi=SHA1.binb2str(Hi);let clientKey=SHA1.core_hmac_sha1(Hi,"Client Key"),serverKey=SHA1.str_hmac_sha1(Hi,"Server Key"),clientSignature=SHA1.core_hmac_sha1(SHA1.str_sha1(SHA1.binb2str(clientKey)),authMessage);for(k=0,connection._sasl_data["server-signature"]=SHA1.b64_hmac_sha1(serverKey,authMessage);k<5;k++)clientKey[k]^=clientSignature[k];return responseText+",p="+btoa(SHA1.binb2str(clientKey))}clientChallenge(connection,test_cnonce){let cnonce=test_cnonce||MD5.hexdigest(""+1234567890*Math.random()),auth_str="n="+utils.utf16to8(connection.authcid);return auth_str+=",r="+cnonce,connection._sasl_data.cnonce=cnonce,connection._sasl_data["client-first-message-bare"]=auth_str,auth_str="n,,"+auth_str}},Strophe1.SASLOAuthBearer=class extends SASLMechanism{constructor(){let mechname=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"OAUTHBEARER",isClientFirst=!(arguments.length>1)||void 0===arguments[1]||arguments[1],priority=arguments.length>2&&void 0!==arguments[2]?arguments[2]:40;super(mechname,isClientFirst,priority)}test(connection){return null!==connection.pass}onChallenge(connection){let auth_str="n,";return null!==connection.authcid&&(auth_str=auth_str+"a="+connection.authzid),auth_str+=",\x01auth=Bearer "+connection.pass+"\x01\x01",utils.utf16to8(auth_str)}},Strophe1.SASLExternal=class extends SASLMechanism{constructor(){let mechname=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"EXTERNAL",isClientFirst=!(arguments.length>1)||void 0===arguments[1]||arguments[1],priority=arguments.length>2&&void 0!==arguments[2]?arguments[2]:10;super(mechname,isClientFirst,priority)}onChallenge(connection){return connection.authcid===connection.authzid?"":connection.authzid}},Strophe1.SASLXOAuth2=class extends SASLMechanism{constructor(){let mechname=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"X-OAUTH2",isClientFirst=!(arguments.length>1)||void 0===arguments[1]||arguments[1],priority=arguments.length>2&&void 0!==arguments[2]?arguments[2]:30;super(mechname,isClientFirst,priority)}test(connection){return null!==connection.pass}onChallenge(connection){let auth_str="\0";return null!==connection.authcid&&(auth_str+=connection.authzid),auth_str+="\0"+connection.pass,utils.utf16to8(auth_str)}};var core={Strophe:Strophe1,$build:$build1,$iq:$iq1,$msg:$msg1,$pres:$pres1,SHA1:SHA1,MD5:MD5,b64_hmac_sha1:SHA1.b64_hmac_sha1,b64_sha1:SHA1.b64_sha1,str_hmac_sha1:SHA1.str_hmac_sha1,str_sha1:SHA1.str_sha1};Strophe1.Request=class{constructor(elem,func,rid,sends){this.id=++Strophe1._requestId,this.xmlData=elem,this.data=Strophe1.serialize(elem),this.origFunc=func,this.func=func,this.rid=rid,this.date=NaN,this.sends=sends||0,this.abort=!1,this.dead=null,this.age=function(){return this.date?(new Date-this.date)/1e3:0},this.timeDead=function(){return this.dead?(new Date-this.dead)/1e3:0},this.xhr=this._newXHR()}getResponse(){let node=null;if(this.xhr.responseXML&&this.xhr.responseXML.documentElement){if("parsererror"===(node=this.xhr.responseXML.documentElement).tagName)throw Strophe1.error("invalid response received"),Strophe1.error("responseText: "+this.xhr.responseText),Strophe1.error("responseXML: "+Strophe1.serialize(this.xhr.responseXML)),Error("parsererror")}else if(this.xhr.responseText){if(Strophe1.debug("Got responseText but no responseXML; attempting to parse it with DOMParser..."),node=new DOMParser1().parseFromString(this.xhr.responseText,"application/xml").documentElement){if(node.querySelector("parsererror")){Strophe1.error("invalid response received: "+node.querySelector("parsererror").textContent),Strophe1.error("responseText: "+this.xhr.responseText);let error=Error();throw error.name=Strophe1.ErrorCondition.BAD_FORMAT,error}}else throw Error("Parsing produced null node")}return node}_newXHR(){let xhr=null;return window.XMLHttpRequest?(xhr=new XMLHttpRequest).overrideMimeType&&xhr.overrideMimeType("text/xml; charset=utf-8"):window.ActiveXObject&&(xhr=new ActiveXObject("Microsoft.XMLHTTP")),xhr.onreadystatechange=this.func.bind(null,this),xhr}},Strophe1.Bosh=class Bosh{constructor(connection){this._conn=connection,this.rid=Math.floor(4294967295*Math.random()),this.sid=null,this.hold=1,this.wait=60,this.window=5,this.errors=0,this.inactivity=null,this.lastResponseHeaders=null,this._requests=[]}_buildBody(){let bodyWrap=$build1("body",{rid:this.rid++,xmlns:Strophe1.NS.HTTPBIND});return null!==this.sid&&bodyWrap.attrs({sid:this.sid}),this._conn.options.keepalive&&this._conn._sessionCachingSupported()&&this._cacheSession(),bodyWrap}_reset(){this.rid=Math.floor(4294967295*Math.random()),this.sid=null,this.errors=0,this._conn._sessionCachingSupported()&&window.sessionStorage.removeItem("strophe-bosh-session"),this._conn.nextValidRid(this.rid)}_connect(wait,hold,route){this.wait=wait||this.wait,this.hold=hold||this.hold,this.errors=0;let body=this._buildBody().attrs({to:this._conn.domain,"xml:lang":"en",wait:this.wait,hold:this.hold,content:"text/xml; charset=utf-8",ver:"1.6","xmpp:version":"1.0","xmlns:xmpp":Strophe1.NS.BOSH});route&&body.attrs({route:route});let _connect_cb=this._conn._connect_cb;this._requests.push(new Strophe1.Request(body.tree(),this._onRequestStateChange.bind(this,_connect_cb.bind(this._conn)),body.tree().getAttribute("rid"))),this._throttledRequestHandler()}_attach(jid,sid,rid,callback,wait,hold,wind){this._conn.jid=jid,this.sid=sid,this.rid=rid,this._conn.connect_callback=callback,this._conn.domain=Strophe1.getDomainFromJid(this._conn.jid),this._conn.authenticated=!0,this._conn.connected=!0,this.wait=wait||this.wait,this.hold=hold||this.hold,this.window=wind||this.window,this._conn._changeConnectStatus(Strophe1.Status.ATTACHED,null)}_restore(jid,callback,wait,hold,wind){let session=JSON.parse(window.sessionStorage.getItem("strophe-bosh-session"));if(null!=session&&session.rid&&session.sid&&session.jid&&(null==jid||Strophe1.getBareJidFromJid(session.jid)===Strophe1.getBareJidFromJid(jid)||null===Strophe1.getNodeFromJid(jid)&&Strophe1.getDomainFromJid(session.jid)===jid))this._conn.restored=!0,this._attach(session.jid,session.sid,session.rid,callback,wait,hold,wind);else{let error=Error("_restore: no restoreable session.");throw error.name="StropheSessionError",error}}_cacheSession(){this._conn.authenticated?this._conn.jid&&this.rid&&this.sid&&window.sessionStorage.setItem("strophe-bosh-session",JSON.stringify({jid:this._conn.jid,rid:this.rid,sid:this.sid})):window.sessionStorage.removeItem("strophe-bosh-session")}_connect_cb(bodyWrap){let typ=bodyWrap.getAttribute("type");if(null!==typ&&"terminate"===typ){let cond=bodyWrap.getAttribute("condition");Strophe1.error("BOSH-Connection failed: "+cond);let conflict=bodyWrap.getElementsByTagName("conflict");return null!==cond?("remote-stream-error"===cond&&conflict.length>0&&(cond="conflict"),this._conn._changeConnectStatus(Strophe1.Status.CONNFAIL,cond)):this._conn._changeConnectStatus(Strophe1.Status.CONNFAIL,"unknown"),this._conn._doDisconnect(cond),Strophe1.Status.CONNFAIL}this.sid||(this.sid=bodyWrap.getAttribute("sid"));let wind=bodyWrap.getAttribute("requests");wind&&(this.window=parseInt(wind,10));let hold=bodyWrap.getAttribute("hold");hold&&(this.hold=parseInt(hold,10));let wait=bodyWrap.getAttribute("wait");wait&&(this.wait=parseInt(wait,10));let inactivity=bodyWrap.getAttribute("inactivity");inactivity&&(this.inactivity=parseInt(inactivity,10))}_disconnect(pres){this._sendTerminate(pres)}_doDisconnect(){this.sid=null,this.rid=Math.floor(4294967295*Math.random()),this._conn._sessionCachingSupported()&&window.sessionStorage.removeItem("strophe-bosh-session"),this._conn.nextValidRid(this.rid)}_emptyQueue(){return 0===this._requests.length}_callProtocolErrorHandlers(req){let reqStatus=Bosh._getRequestStatus(req),err_callback=this._conn.protocolErrorHandlers.HTTP[reqStatus];err_callback&&err_callback.call(this,reqStatus)}_hitError(reqStatus){this.errors++,Strophe1.warn("request errored, status: "+reqStatus+", number of errors: "+this.errors),this.errors>4&&this._conn._onDisconnectTimeout()}_no_auth_received(callback){Strophe1.warn("Server did not yet offer a supported authentication mechanism. Sending a blank poll request."),callback=callback?callback.bind(this._conn):this._conn._connect_cb.bind(this._conn);let body=this._buildBody();this._requests.push(new Strophe1.Request(body.tree(),this._onRequestStateChange.bind(this,callback),body.tree().getAttribute("rid"))),this._throttledRequestHandler()}_onDisconnectTimeout(){this._abortAllRequests()}_abortAllRequests(){for(;this._requests.length>0;){let req=this._requests.pop();req.abort=!0,req.xhr.abort(),req.xhr.onreadystatechange=function(){}}}_onIdle(){let data=this._conn._data;if(this._conn.authenticated&&0===this._requests.length&&0===data.length&&!this._conn.disconnecting&&(Strophe1.debug("no requests during idle cycle, sending blank request"),data.push(null)),!this._conn.paused){if(this._requests.length<2&&data.length>0){let body=this._buildBody();for(let i=0;i<data.length;i++)null!==data[i]&&("restart"===data[i]?body.attrs({to:this._conn.domain,"xml:lang":"en","xmpp:restart":"true","xmlns:xmpp":Strophe1.NS.BOSH}):body.cnode(data[i]).up());delete this._conn._data,this._conn._data=[],this._requests.push(new Strophe1.Request(body.tree(),this._onRequestStateChange.bind(this,this._conn._dataRecv.bind(this._conn)),body.tree().getAttribute("rid"))),this._throttledRequestHandler()}if(this._requests.length>0){let time_elapsed=this._requests[0].age();null!==this._requests[0].dead&&this._requests[0].timeDead()>Math.floor(Strophe1.SECONDARY_TIMEOUT*this.wait)&&this._throttledRequestHandler(),time_elapsed>Math.floor(Strophe1.TIMEOUT*this.wait)&&(Strophe1.warn("Request "+this._requests[0].id+" timed out, over "+Math.floor(Strophe1.TIMEOUT*this.wait)+" seconds since last activity"),this._throttledRequestHandler())}}}static _getRequestStatus(req,def){let reqStatus;if(4===req.xhr.readyState)try{reqStatus=req.xhr.status}catch(e){Strophe1.error("Caught an error while retrieving a request's status, reqStatus: "+reqStatus)}return void 0===reqStatus&&(reqStatus="number"==typeof def?def:0),reqStatus}_onRequestStateChange(func,req){if(Strophe1.debug("request id "+req.id+"."+req.sends+" state changed to "+req.xhr.readyState),req.abort){req.abort=!1;return}if(4!==req.xhr.readyState)return;let reqStatus=Bosh._getRequestStatus(req);if(this.lastResponseHeaders=req.xhr.getAllResponseHeaders(),this._conn.disconnecting&&reqStatus>=400){this._hitError(reqStatus),this._callProtocolErrorHandlers(req);return}let reqIs0=this._requests[0]===req,reqIs1=this._requests[1]===req,valid_request=reqStatus>0&&reqStatus<500,too_many_retries=req.sends>this._conn.maxRetries;(valid_request||too_many_retries)&&(this._removeRequest(req),Strophe1.debug("request id "+req.id+" should now be removed")),200===reqStatus?((reqIs1||reqIs0&&this._requests.length>0&&this._requests[0].age()>Math.floor(Strophe1.SECONDARY_TIMEOUT*this.wait))&&this._restartRequest(0),this._conn.nextValidRid(Number(req.rid)+1),Strophe1.debug("request id "+req.id+"."+req.sends+" got 200"),func(req),this.errors=0):0===reqStatus||reqStatus>=400&&reqStatus<600||reqStatus>=12e3?(Strophe1.error("request id "+req.id+"."+req.sends+" error "+reqStatus+" happened"),this._hitError(reqStatus),this._callProtocolErrorHandlers(req),reqStatus>=400&&reqStatus<500&&(this._conn._changeConnectStatus(Strophe1.Status.DISCONNECTING,null),this._conn._doDisconnect())):Strophe1.error("request id "+req.id+"."+req.sends+" error "+reqStatus+" happened"),valid_request||too_many_retries?too_many_retries&&!this._conn.connected&&this._conn._changeConnectStatus(Strophe1.Status.CONNFAIL,"giving-up"):this._throttledRequestHandler()}_processRequest(i){let req=this._requests[i],reqStatus=Bosh._getRequestStatus(req,-1);if(req.sends>this._conn.maxRetries){this._conn._onDisconnectTimeout();return}let time_elapsed=req.age(),primary_timeout=!isNaN(time_elapsed)&&time_elapsed>Math.floor(Strophe1.TIMEOUT*this.wait),secondary_timeout=null!==req.dead&&req.timeDead()>Math.floor(Strophe1.SECONDARY_TIMEOUT*this.wait),server_error=4===req.xhr.readyState&&(reqStatus<1||reqStatus>=500);if((primary_timeout||secondary_timeout||server_error)&&(secondary_timeout&&Strophe1.error(`Request ${this._requests[i].id} timed out (secondary), restarting`),req.abort=!0,req.xhr.abort(),req.xhr.onreadystatechange=function(){},this._requests[i]=new Strophe1.Request(req.xmlData,req.origFunc,req.rid,req.sends),req=this._requests[i]),0===req.xhr.readyState){Strophe1.debug("request id "+req.id+"."+req.sends+" posting");try{let content_type=this._conn.options.contentType||"text/xml; charset=utf-8";req.xhr.open("POST",this._conn.service,!this._conn.options.sync),void 0!==req.xhr.setRequestHeader&&req.xhr.setRequestHeader("Content-Type",content_type),this._conn.options.withCredentials&&(req.xhr.withCredentials=!0)}catch(e2){Strophe1.error("XHR open failed: "+e2.toString()),this._conn.connected||this._conn._changeConnectStatus(Strophe1.Status.CONNFAIL,"bad-service"),this._conn.disconnect();return}let sendFunc=()=>{if(req.date=new Date,this._conn.options.customHeaders){let headers=this._conn.options.customHeaders;for(let header in headers)Object.prototype.hasOwnProperty.call(headers,header)&&req.xhr.setRequestHeader(header,headers[header])}req.xhr.send(req.data)};req.sends>1?setTimeout(function(){sendFunc()},1e3*Math.min(Math.floor(Strophe1.TIMEOUT*this.wait),Math.pow(req.sends,3))):sendFunc(),req.sends++,this._conn.xmlOutput!==Strophe1.Connection.prototype.xmlOutput&&(req.xmlData.nodeName===this.strip&&req.xmlData.childNodes.length?this._conn.xmlOutput(req.xmlData.childNodes[0]):this._conn.xmlOutput(req.xmlData)),this._conn.rawOutput!==Strophe1.Connection.prototype.rawOutput&&this._conn.rawOutput(req.data)}else Strophe1.debug("_processRequest: "+(0===i?"first":"second")+" request has readyState of "+req.xhr.readyState)}_removeRequest(req){Strophe1.debug("removing request");for(let i=this._requests.length-1;i>=0;i--)req===this._requests[i]&&this._requests.splice(i,1);req.xhr.onreadystatechange=function(){},this._throttledRequestHandler()}_restartRequest(i){let req=this._requests[i];null===req.dead&&(req.dead=new Date),this._processRequest(i)}_reqToData(req){try{return req.getResponse()}catch(e){if("parsererror"!==e.message)throw e;this._conn.disconnect("strophe-parsererror")}}_sendTerminate(pres){Strophe1.debug("_sendTerminate was called");let body=this._buildBody().attrs({type:"terminate"});pres&&body.cnode(pres.tree());let req=new Strophe1.Request(body.tree(),this._onRequestStateChange.bind(this,this._conn._dataRecv.bind(this._conn)),body.tree().getAttribute("rid"));this._requests.push(req),this._throttledRequestHandler()}_send(){clearTimeout(this._conn._idleTimeout),this._throttledRequestHandler(),this._conn._idleTimeout=setTimeout(()=>this._conn._onIdle(),100)}_sendRestart(){this._throttledRequestHandler(),clearTimeout(this._conn._idleTimeout)}_throttledRequestHandler(){this._requests?Strophe1.debug("_throttledRequestHandler called with "+this._requests.length+" requests"):Strophe1.debug("_throttledRequestHandler called with undefined requests"),this._requests&&0!==this._requests.length&&(this._requests.length>0&&this._processRequest(0),this._requests.length>1&&Math.abs(this._requests[0].rid-this._requests[1].rid)<this.window&&this._processRequest(1))}},Strophe1.Bosh.prototype.strip=null,Strophe1.Websocket=class{constructor(connection){this._conn=connection,this.strip="wrapper";let service=connection.service;if(0!==service.indexOf("ws:")&&0!==service.indexOf("wss:")){let new_service="";"ws"===connection.options.protocol&&"https:"!==window.location.protocol?new_service+="ws":new_service+="wss",new_service+="://"+window.location.host,0!==service.indexOf("/")?new_service+=window.location.pathname+service:new_service+=service,connection.service=new_service}}_buildStream(){return $build1("open",{xmlns:Strophe1.NS.FRAMING,to:this._conn.domain,version:"1.0"})}_checkStreamError(bodyWrap,connectstatus){let errors;if(0===(errors=bodyWrap.getElementsByTagNameNS?bodyWrap.getElementsByTagNameNS(Strophe1.NS.STREAM,"error"):bodyWrap.getElementsByTagName("stream:error")).length)return!1;let error=errors[0],condition="",text="";for(let i=0;i<error.childNodes.length;i++){let e=error.childNodes[i];if("urn:ietf:params:xml:ns:xmpp-streams"!==e.getAttribute("xmlns"))break;"text"===e.nodeName?text=e.textContent:condition=e.nodeName}let errorString="WebSocket stream error: ";return condition?errorString+=condition:errorString+="unknown",text&&(errorString+=" - "+text),Strophe1.error(errorString),this._conn._changeConnectStatus(connectstatus,condition),this._conn._doDisconnect(),!0}_reset(){}_connect(){this._closeSocket(),this.socket=new WebSocket(this._conn.service,"xmpp"),this.socket.onopen=()=>this._onOpen(),this.socket.onerror=e=>this._onError(e),this.socket.onclose=e=>this._onClose(e),this.socket.onmessage=message=>this._onInitialMessage(message)}_connect_cb(bodyWrap){if(this._checkStreamError(bodyWrap,Strophe1.Status.CONNFAIL))return Strophe1.Status.CONNFAIL}_handleStreamStart(message){let error=!1,ns=message.getAttribute("xmlns");"string"!=typeof ns?error="Missing xmlns in <open />":ns!==Strophe1.NS.FRAMING&&(error="Wrong xmlns in <open />: "+ns);let ver=message.getAttribute("version");return"string"!=typeof ver?error="Missing version in <open />":"1.0"!==ver&&(error="Wrong version in <open />: "+ver),!error||(this._conn._changeConnectStatus(Strophe1.Status.CONNFAIL,error),this._conn._doDisconnect(),!1)}_onInitialMessage(message){if(0===message.data.indexOf("<open ")||0===message.data.indexOf("<?xml")){let data=message.data.replace(/^(<\?.*?\?>\s*)*/,"");if(""===data)return;let streamStart=new DOMParser1().parseFromString(data,"text/xml").documentElement;this._conn.xmlInput(streamStart),this._conn.rawInput(message.data),this._handleStreamStart(streamStart)&&this._connect_cb(streamStart)}else if(0===message.data.indexOf("<close ")){let parsedMessage=new DOMParser1().parseFromString(message.data,"text/xml").documentElement;this._conn.xmlInput(parsedMessage),this._conn.rawInput(message.data);let see_uri=parsedMessage.getAttribute("see-other-uri");if(see_uri){let service=this._conn.service;(service.indexOf("wss:")>=0&&see_uri.indexOf("wss:")>=0||service.indexOf("ws:")>=0)&&(this._conn._changeConnectStatus(Strophe1.Status.REDIRECT,"Received see-other-uri, resetting connection"),this._conn.reset(),this._conn.service=see_uri,this._connect())}else this._conn._changeConnectStatus(Strophe1.Status.CONNFAIL,"Received closing stream"),this._conn._doDisconnect()}else{this._replaceMessageHandler();let string=this._streamWrap(message.data),elem=new DOMParser1().parseFromString(string,"text/xml").documentElement;this._conn._connect_cb(elem,null,message.data)}}_replaceMessageHandler(){this.socket.onmessage=m=>this._onMessage(m)}_disconnect(pres){if(this.socket&&this.socket.readyState!==WebSocket.CLOSED){pres&&this._conn.send(pres);let close=$build1("close",{xmlns:Strophe1.NS.FRAMING});this._conn.xmlOutput(close.tree());let closeString=Strophe1.serialize(close);this._conn.rawOutput(closeString);try{this.socket.send(closeString)}catch(e){Strophe1.warn("Couldn't send <close /> tag.")}}setTimeout(()=>this._conn._doDisconnect,0)}_doDisconnect(){Strophe1.debug("WebSockets _doDisconnect was called"),this._closeSocket()}_streamWrap(stanza){return"<wrapper>"+stanza+"</wrapper>"}_closeSocket(){if(this.socket)try{this.socket.onclose=null,this.socket.onerror=null,this.socket.onmessage=null,this.socket.close()}catch(e){Strophe1.debug(e.message)}this.socket=null}_emptyQueue(){return!0}_onClose(e){this._conn.connected&&!this._conn.disconnecting?(Strophe1.error("Websocket closed unexpectedly"),this._conn._doDisconnect()):e&&1006===e.code&&!this._conn.connected&&this.socket?(Strophe1.error("Websocket closed unexcectedly"),this._conn._changeConnectStatus(Strophe1.Status.CONNFAIL,"The WebSocket connection could not be established or was disconnected."),this._conn._doDisconnect()):Strophe1.debug("Websocket closed")}_no_auth_received(callback){Strophe1.error("Server did not offer a supported authentication mechanism"),this._conn._changeConnectStatus(Strophe1.Status.CONNFAIL,Strophe1.ErrorCondition.NO_AUTH_MECH),callback&&callback.call(this._conn),this._conn._doDisconnect()}_onDisconnectTimeout(){}_abortAllRequests(){}_onError(error){Strophe1.error("Websocket error "+JSON.stringify(error)),this._conn._changeConnectStatus(Strophe1.Status.CONNFAIL,"The WebSocket connection could not be established or was disconnected."),this._disconnect()}_onIdle(){let data=this._conn._data;if(data.length>0&&!this._conn.paused){for(let i=0;i<data.length;i++)if(null!==data[i]){let stanza;stanza="restart"===data[i]?this._buildStream().tree():data[i];let rawStanza=Strophe1.serialize(stanza);this._conn.xmlOutput(stanza),this._conn.rawOutput(rawStanza),this.socket.send(rawStanza)}this._conn._data=[]}}_onMessage(message){let elem;let close='<close xmlns="urn:ietf:params:xml:ns:xmpp-framing" />';if(message.data===close){this._conn.rawInput(close),this._conn.xmlInput(message),this._conn.disconnecting||this._conn._doDisconnect();return}if(0===message.data.search("<open ")){if(elem=new DOMParser1().parseFromString(message.data,"text/xml").documentElement,!this._handleStreamStart(elem))return}else{let data=this._streamWrap(message.data);elem=new DOMParser1().parseFromString(data,"text/xml").documentElement}if(!this._checkStreamError(elem,Strophe1.Status.ERROR)){if(this._conn.disconnecting&&"presence"===elem.firstChild.nodeName&&"unavailable"===elem.firstChild.getAttribute("type")){this._conn.xmlInput(elem),this._conn.rawInput(Strophe1.serialize(elem));return}this._conn._dataRecv(elem,message.data)}}_onOpen(){Strophe1.debug("Websocket open");let start=this._buildStream();this._conn.xmlOutput(start.tree());let startString=Strophe1.serialize(start);this._conn.rawOutput(startString),this.socket.send(startString)}_reqToData(stanza){return stanza}_send(){this._conn.flush()}_sendRestart(){clearTimeout(this._conn._idleTimeout),this._conn._onIdle.bind(this._conn)()}};let lmap={};lmap.debug=Strophe1.LogLevel.DEBUG,lmap.info=Strophe1.LogLevel.INFO,lmap.warn=Strophe1.LogLevel.WARN,lmap.error=Strophe1.LogLevel.ERROR,lmap.fatal=Strophe1.LogLevel.FATAL,Strophe1.WorkerWebsocket=class extends Strophe1.Websocket{constructor(connection){super(connection),this._conn=connection,this.worker=new SharedWorker(this._conn.options.worker,"Strophe XMPP Connection"),this.worker.onerror=e=>{var _console;null===(_console=console)||void 0===_console||_console.error(e),Strophe1.log(Strophe1.LogLevel.ERROR,`Shared Worker Error: ${e}`)}}get socket(){return{send:str=>this.worker.port.postMessage(["send",str])}}_connect(){this._messageHandler=m=>this._onInitialMessage(m),this.worker.port.start(),this.worker.port.onmessage=ev=>this._onWorkerMessage(ev),this.worker.port.postMessage(["_connect",this._conn.service,this._conn.jid])}_attach(callback){this._messageHandler=m=>this._onMessage(m),this._conn.connect_callback=callback,this.worker.port.start(),this.worker.port.onmessage=ev=>this._onWorkerMessage(ev),this.worker.port.postMessage(["_attach",this._conn.service])}_attachCallback(status,jid){status===Strophe1.Status.ATTACHED?(this._conn.jid=jid,this._conn.authenticated=!0,this._conn.connected=!0,this._conn.restored=!0,this._conn._changeConnectStatus(Strophe1.Status.ATTACHED)):status===Strophe1.Status.ATTACHFAIL&&(this._conn.authenticated=!1,this._conn.connected=!1,this._conn.restored=!1,this._conn._changeConnectStatus(Strophe1.Status.ATTACHFAIL))}_disconnect(readyState,pres){pres&&this._conn.send(pres);let close=$build1("close",{xmlns:Strophe1.NS.FRAMING});this._conn.xmlOutput(close.tree());let closeString=Strophe1.serialize(close);this._conn.rawOutput(closeString),this.worker.port.postMessage(["send",closeString]),this._conn._doDisconnect()}_onClose(e){this._conn.connected&&!this._conn.disconnecting?(Strophe1.error("Websocket closed unexpectedly"),this._conn._doDisconnect()):e&&1006===e.code&&!this._conn.connected?(Strophe1.error("Websocket closed unexcectedly"),this._conn._changeConnectStatus(Strophe1.Status.CONNFAIL,"The WebSocket connection could not be established or was disconnected."),this._conn._doDisconnect()):Strophe1.debug("Websocket closed")}_closeSocket(){this.worker.port.postMessage(["_closeSocket"])}_replaceMessageHandler(){this._messageHandler=m=>this._onMessage(m)}_onWorkerMessage(ev){let{data}=ev,method_name=data[0];if("_onMessage"===method_name)this._messageHandler(data[1]);else if(method_name in this)try{this[method_name].apply(this,ev.data.slice(1))}catch(e){Strophe1.log(Strophe1.LogLevel.ERROR,e)}else if("log"===method_name){let level=data[1],msg=data[2];Strophe1.log(lmap[level],msg)}else Strophe1.log(Strophe1.LogLevel.ERROR,`Found unhandled service worker message: ${data}`)}},global$1.$build=core.$build,global$1.$iq=core.$iq,global$1.$msg=core.$msg,global$1.$pres=core.$pres,global$1.Strophe=core.Strophe;let{b64_sha1}=SHA1;exports.$build=$build1,exports.$iq=$iq1,exports.$msg=$msg1,exports.$pres=$pres1,exports.Strophe=Strophe1,exports.b64_sha1=b64_sha1,Object.defineProperty(exports,"__esModule",{value:!0})},"object"==typeof exports&&void 0!==module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global1="undefined"!=typeof globalThis?globalThis:global1||self).strophe={})}).call(this)}).call(this,void 0!==__webpack_require__.g?__webpack_require__.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"@xmldom/xmldom":5,ws:209}],209:[function(require1,module,exports){"use strict";module.exports=function(){throw Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}},{}],210:[function(require1,module,exports){(function(setImmediate,clearImmediate){(function(){var nextTick=require1("process/browser.js").nextTick,apply=Function.prototype.apply,slice=Array.prototype.slice,immediateIds={},nextImmediateId=0;function Timeout(id,clearFn){this._id=id,this._clearFn=clearFn}exports.setTimeout=function(){return new Timeout(apply.call(setTimeout,window,arguments),clearTimeout)},exports.setInterval=function(){return new Timeout(apply.call(setInterval,window,arguments),clearInterval)},exports.clearTimeout=exports.clearInterval=function(timeout){timeout.close()},Timeout.prototype.unref=Timeout.prototype.ref=function(){},Timeout.prototype.close=function(){this._clearFn.call(window,this._id)},exports.enroll=function(item,msecs){clearTimeout(item._idleTimeoutId),item._idleTimeout=msecs},exports.unenroll=function(item){clearTimeout(item._idleTimeoutId),item._idleTimeout=-1},exports._unrefActive=exports.active=function(item){clearTimeout(item._idleTimeoutId);var msecs=item._idleTimeout;msecs>=0&&(item._idleTimeoutId=setTimeout(function onTimeout(){item._onTimeout&&item._onTimeout()},msecs))},exports.setImmediate="function"==typeof setImmediate?setImmediate:function(fn){var id=nextImmediateId++,args=!(arguments.length<2)&&slice.call(arguments,1);return immediateIds[id]=!0,nextTick(function onNextTick(){immediateIds[id]&&(args?fn.apply(null,args):fn.call(null),exports.clearImmediate(id))}),id},exports.clearImmediate="function"==typeof clearImmediate?clearImmediate:function(id){delete immediateIds[id]}}).call(this)}).call(this,require1("timers").setImmediate,require1("timers").clearImmediate)},{"process/browser.js":152,timers:210}],211:[function(require1,module,exports){var Buffer=require1("buffer").Buffer;module.exports=function(buf){if(buf instanceof Uint8Array){if(0===buf.byteOffset&&buf.byteLength===buf.buffer.byteLength)return buf.buffer;if("function"==typeof buf.buffer.slice)return buf.buffer.slice(buf.byteOffset,buf.byteOffset+buf.byteLength)}if(Buffer.isBuffer(buf)){for(var arrayCopy=new Uint8Array(buf.length),len=buf.length,i=0;i<len;i++)arrayCopy[i]=buf[i];return arrayCopy.buffer}throw Error("Argument must be a Buffer")}},{buffer:47}],212:[function(require1,module,exports){"use strict";var punycode=require1("punycode"),util=require1("./util");function Url(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}exports.parse=urlParse,exports.resolve=urlResolve,exports.resolveObject=urlResolveObject,exports.format=urlFormat,exports.Url=Url;var protocolPattern=/^([a-z0-9.+-]+:)/i,portPattern=/:[0-9]*$/,simplePathPattern=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,autoEscape=["'"].concat(["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n"," "])),nonHostChars=["%","/","?",";","#"].concat(autoEscape),hostEndingChars=["/","?","#"],hostnamePartPattern=/^[+a-z0-9A-Z_-]{0,63}$/,hostnamePartStart=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,unsafeProtocol={javascript:!0,"javascript:":!0},hostlessProtocol={javascript:!0,"javascript:":!0},slashedProtocol={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},querystring=require1("querystring");function urlParse(url,parseQueryString,slashesDenoteHost){if(url&&util.isObject(url)&&url instanceof Url)return url;var u=new Url;return u.parse(url,parseQueryString,slashesDenoteHost),u}function urlFormat(obj){return(util.isString(obj)&&(obj=urlParse(obj)),obj instanceof Url)?obj.format():Url.prototype.format.call(obj)}function urlResolve(source,relative){return urlParse(source,!1,!0).resolve(relative)}function urlResolveObject(source,relative){return source?urlParse(source,!1,!0).resolveObject(relative):relative}Url.prototype.parse=function(url,parseQueryString,slashesDenoteHost){if(!util.isString(url))throw TypeError("Parameter 'url' must be a string, not "+typeof url);var queryIndex=url.indexOf("?"),splitter=-1!==queryIndex&&queryIndex<url.indexOf("#")?"?":"#",uSplit=url.split(splitter);uSplit[0]=uSplit[0].replace(/\\/g,"/");var rest=url=uSplit.join(splitter);if(rest=rest.trim(),!slashesDenoteHost&&1===url.split("#").length){var simplePath=simplePathPattern.exec(rest);if(simplePath)return this.path=rest,this.href=rest,this.pathname=simplePath[1],simplePath[2]?(this.search=simplePath[2],parseQueryString?this.query=querystring.parse(this.search.substr(1)):this.query=this.search.substr(1)):parseQueryString&&(this.search="",this.query={}),this}var proto=protocolPattern.exec(rest);if(proto){var lowerProto=(proto=proto[0]).toLowerCase();this.protocol=lowerProto,rest=rest.substr(proto.length)}if(slashesDenoteHost||proto||rest.match(/^\/\/[^@\/]+@[^@\/]+/)){var slashes="//"===rest.substr(0,2);slashes&&!(proto&&hostlessProtocol[proto])&&(rest=rest.substr(2),this.slashes=!0)}if(!hostlessProtocol[proto]&&(slashes||proto&&!slashedProtocol[proto])){for(var auth,atSign,hostEnd=-1,i=0;i<hostEndingChars.length;i++){var hec=rest.indexOf(hostEndingChars[i]);-1!==hec&&(-1===hostEnd||hec<hostEnd)&&(hostEnd=hec)}-1!==(atSign=-1===hostEnd?rest.lastIndexOf("@"):rest.lastIndexOf("@",hostEnd))&&(auth=rest.slice(0,atSign),rest=rest.slice(atSign+1),this.auth=decodeURIComponent(auth)),hostEnd=-1;for(var i=0;i<nonHostChars.length;i++){var hec=rest.indexOf(nonHostChars[i]);-1!==hec&&(-1===hostEnd||hec<hostEnd)&&(hostEnd=hec)}-1===hostEnd&&(hostEnd=rest.length),this.host=rest.slice(0,hostEnd),rest=rest.slice(hostEnd),this.parseHost(),this.hostname=this.hostname||"";var ipv6Hostname="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!ipv6Hostname)for(var hostparts=this.hostname.split(/\./),i=0,l=hostparts.length;i<l;i++){var part=hostparts[i];if(part&&!part.match(hostnamePartPattern)){for(var newpart="",j=0,k=part.length;j<k;j++)part.charCodeAt(j)>127?newpart+="x":newpart+=part[j];if(!newpart.match(hostnamePartPattern)){var validParts=hostparts.slice(0,i),notHost=hostparts.slice(i+1),bit=part.match(hostnamePartStart);bit&&(validParts.push(bit[1]),notHost.unshift(bit[2])),notHost.length&&(rest="/"+notHost.join(".")+rest),this.hostname=validParts.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),ipv6Hostname||(this.hostname=punycode.toASCII(this.hostname));var p=this.port?":"+this.port:"",h=this.hostname||"";this.host=h+p,this.href+=this.host,ipv6Hostname&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==rest[0]&&(rest="/"+rest))}if(!unsafeProtocol[lowerProto])for(var i=0,l=autoEscape.length;i<l;i++){var ae=autoEscape[i];if(-1!==rest.indexOf(ae)){var esc=encodeURIComponent(ae);esc===ae&&(esc=escape(ae)),rest=rest.split(ae).join(esc)}}var hash=rest.indexOf("#");-1!==hash&&(this.hash=rest.substr(hash),rest=rest.slice(0,hash));var qm=rest.indexOf("?");if(-1!==qm?(this.search=rest.substr(qm),this.query=rest.substr(qm+1),parseQueryString&&(this.query=querystring.parse(this.query)),rest=rest.slice(0,qm)):parseQueryString&&(this.search="",this.query={}),rest&&(this.pathname=rest),slashedProtocol[lowerProto]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var p=this.pathname||"",s=this.search||"";this.path=p+s}return this.href=this.format(),this},Url.prototype.format=function(){var auth=this.auth||"";auth&&(auth=(auth=encodeURIComponent(auth)).replace(/%3A/i,":")+"@");var protocol=this.protocol||"",pathname=this.pathname||"",hash=this.hash||"",host=!1,query="";this.host?host=auth+this.host:this.hostname&&(host=auth+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(host+=":"+this.port)),this.query&&util.isObject(this.query)&&Object.keys(this.query).length&&(query=querystring.stringify(this.query));var search=this.search||query&&"?"+query||"";return protocol&&":"!==protocol.substr(-1)&&(protocol+=":"),this.slashes||(!protocol||slashedProtocol[protocol])&&!1!==host?(host="//"+(host||""),pathname&&"/"!==pathname.charAt(0)&&(pathname="/"+pathname)):host||(host=""),hash&&"#"!==hash.charAt(0)&&(hash="#"+hash),search&&"?"!==search.charAt(0)&&(search="?"+search),protocol+host+(pathname=pathname.replace(/[?#]/g,function(match){return encodeURIComponent(match)}))+(search=search.replace("#","%23"))+hash},Url.prototype.resolve=function(relative){return this.resolveObject(urlParse(relative,!1,!0)).format()},Url.prototype.resolveObject=function(relative){if(util.isString(relative)){var rel=new Url;rel.parse(relative,!1,!0),relative=rel}for(var result=new Url,tkeys=Object.keys(this),tk=0;tk<tkeys.length;tk++){var tkey=tkeys[tk];result[tkey]=this[tkey]}if(result.hash=relative.hash,""===relative.href)return result.href=result.format(),result;if(relative.slashes&&!relative.protocol){for(var rkeys=Object.keys(relative),rk=0;rk<rkeys.length;rk++){var rkey=rkeys[rk];"protocol"!==rkey&&(result[rkey]=relative[rkey])}return slashedProtocol[result.protocol]&&result.hostname&&!result.pathname&&(result.path=result.pathname="/"),result.href=result.format(),result}if(relative.protocol&&relative.protocol!==result.protocol){if(!slashedProtocol[relative.protocol]){for(var keys=Object.keys(relative),v=0;v<keys.length;v++){var k=keys[v];result[k]=relative[k]}return result.href=result.format(),result}if(result.protocol=relative.protocol,relative.host||hostlessProtocol[relative.protocol])result.pathname=relative.pathname;else{for(var relPath=(relative.pathname||"").split("/");relPath.length&&!(relative.host=relPath.shift()););relative.host||(relative.host=""),relative.hostname||(relative.hostname=""),""!==relPath[0]&&relPath.unshift(""),relPath.length<2&&relPath.unshift(""),result.pathname=relPath.join("/")}if(result.search=relative.search,result.query=relative.query,result.host=relative.host||"",result.auth=relative.auth,result.hostname=relative.hostname||relative.host,result.port=relative.port,result.pathname||result.search){var p=result.pathname||"",s=result.search||"";result.path=p+s}return result.slashes=result.slashes||relative.slashes,result.href=result.format(),result}var isSourceAbs=result.pathname&&"/"===result.pathname.charAt(0),isRelAbs=relative.host||relative.pathname&&"/"===relative.pathname.charAt(0),mustEndAbs=isRelAbs||isSourceAbs||result.host&&relative.pathname,removeAllDots=mustEndAbs,srcPath=result.pathname&&result.pathname.split("/")||[],relPath=relative.pathname&&relative.pathname.split("/")||[],psychotic=result.protocol&&!slashedProtocol[result.protocol];if(psychotic&&(result.hostname="",result.port=null,result.host&&(""===srcPath[0]?srcPath[0]=result.host:srcPath.unshift(result.host)),result.host="",relative.protocol&&(relative.hostname=null,relative.port=null,relative.host&&(""===relPath[0]?relPath[0]=relative.host:relPath.unshift(relative.host)),relative.host=null),mustEndAbs=mustEndAbs&&(""===relPath[0]||""===srcPath[0])),isRelAbs)result.host=relative.host||""===relative.host?relative.host:result.host,result.hostname=relative.hostname||""===relative.hostname?relative.hostname:result.hostname,result.search=relative.search,result.query=relative.query,srcPath=relPath;else if(relPath.length)srcPath||(srcPath=[]),srcPath.pop(),srcPath=srcPath.concat(relPath),result.search=relative.search,result.query=relative.query;else if(!util.isNullOrUndefined(relative.search)){if(psychotic){result.hostname=result.host=srcPath.shift();var authInHost=!!(result.host&&result.host.indexOf("@")>0)&&result.host.split("@");authInHost&&(result.auth=authInHost.shift(),result.host=result.hostname=authInHost.shift())}return result.search=relative.search,result.query=relative.query,util.isNull(result.pathname)&&util.isNull(result.search)||(result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")),result.href=result.format(),result}if(!srcPath.length)return result.pathname=null,result.search?result.path="/"+result.search:result.path=null,result.href=result.format(),result;for(var last=srcPath.slice(-1)[0],hasTrailingSlash=(result.host||relative.host||srcPath.length>1)&&("."===last||".."===last)||""===last,up=0,i=srcPath.length;i>=0;i--)"."===(last=srcPath[i])?srcPath.splice(i,1):".."===last?(srcPath.splice(i,1),up++):up&&(srcPath.splice(i,1),up--);if(!mustEndAbs&&!removeAllDots)for(;up--;up)srcPath.unshift("..");mustEndAbs&&""!==srcPath[0]&&(!srcPath[0]||"/"!==srcPath[0].charAt(0))&&srcPath.unshift(""),hasTrailingSlash&&"/"!==srcPath.join("/").substr(-1)&&srcPath.push("");var isAbsolute=""===srcPath[0]||srcPath[0]&&"/"===srcPath[0].charAt(0);if(psychotic){result.hostname=result.host=isAbsolute?"":srcPath.length?srcPath.shift():"";var authInHost=!!(result.host&&result.host.indexOf("@")>0)&&result.host.split("@");authInHost&&(result.auth=authInHost.shift(),result.host=result.hostname=authInHost.shift())}return(mustEndAbs=mustEndAbs||result.host&&srcPath.length)&&!isAbsolute&&srcPath.unshift(""),srcPath.length?result.pathname=srcPath.join("/"):(result.pathname=null,result.path=null),util.isNull(result.pathname)&&util.isNull(result.search)||(result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")),result.auth=relative.auth||result.auth,result.slashes=result.slashes||relative.slashes,result.href=result.format(),result},Url.prototype.parseHost=function(){var host=this.host,port=portPattern.exec(host);port&&(":"!==(port=port[0])&&(this.port=port.substr(1)),host=host.substr(0,host.length-port.length)),host&&(this.hostname=host)}},{"./util":213,punycode:33,querystring:155}],213:[function(require1,module,exports){"use strict";module.exports={isString:function(arg){return"string"==typeof arg},isObject:function(arg){return"object"==typeof arg&&null!==arg},isNull:function(arg){return null===arg},isNullOrUndefined:function(arg){return null==arg}}},{}],214:[function(require1,module,exports){(function(global){(function(){function deprecate(fn,msg){if(config("noDeprecation"))return fn;var warned=!1;return function deprecated(){if(!warned){if(config("throwDeprecation"))throw Error(msg);config("traceDeprecation")?console.trace(msg):console.warn(msg),warned=!0}return fn.apply(this,arguments)}}function config(name){try{if(!global.localStorage)return!1}catch(_){return!1}var val=global.localStorage[name];return null!=val&&"true"===String(val).toLowerCase()}module.exports=deprecate}).call(this)}).call(this,void 0!==__webpack_require__.g?__webpack_require__.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],215:[function(require1,module,exports){arguments[4][18][0].apply(exports,arguments)},{dup:18}],216:[function(require1,module,exports){arguments[4][19][0].apply(exports,arguments)},{dup:19}],217:[function(require1,module,exports){arguments[4][20][0].apply(exports,arguments)},{"./support/isBuffer":216,_process:152,dup:20,inherits:215}],218:[function(require1,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var adapter=(0,require1("./adapter_factory.js").adapterFactory)({window:"undefined"==typeof window?void 0:window});exports.default=adapter},{"./adapter_factory.js":219}],219:[function(require1,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.adapterFactory=adapterFactory;var utils=_interopRequireWildcard(require1("./utils")),chromeShim=_interopRequireWildcard(require1("./chrome/chrome_shim")),edgeShim=_interopRequireWildcard(require1("./edge/edge_shim")),firefoxShim=_interopRequireWildcard(require1("./firefox/firefox_shim")),safariShim=_interopRequireWildcard(require1("./safari/safari_shim")),commonShim=_interopRequireWildcard(require1("./common_shim"));function _interopRequireWildcard(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}function adapterFactory(){var _ref=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},window1=_ref.window,options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0},logging=utils.log,browserDetails=utils.detectBrowser(window1),adapter={browserDetails:browserDetails,commonShim:commonShim,extractVersion:utils.extractVersion,disableLog:utils.disableLog,disableWarnings:utils.disableWarnings};switch(browserDetails.browser){case"chrome":if(!chromeShim||!chromeShim.shimPeerConnection||!options.shimChrome){logging("Chrome shim is not included in this adapter release.");break}if(null===browserDetails.version){logging("Chrome shim can not determine version, not shimming.");break}logging("adapter.js shimming chrome."),adapter.browserShim=chromeShim,commonShim.shimAddIceCandidateNullOrEmpty(window1,browserDetails),chromeShim.shimGetUserMedia(window1,browserDetails),chromeShim.shimMediaStream(window1,browserDetails),chromeShim.shimPeerConnection(window1,browserDetails),chromeShim.shimOnTrack(window1,browserDetails),chromeShim.shimAddTrackRemoveTrack(window1,browserDetails),chromeShim.shimGetSendersWithDtmf(window1,browserDetails),chromeShim.shimGetStats(window1,browserDetails),chromeShim.shimSenderReceiverGetStats(window1,browserDetails),chromeShim.fixNegotiationNeeded(window1,browserDetails),commonShim.shimRTCIceCandidate(window1,browserDetails),commonShim.shimConnectionState(window1,browserDetails),commonShim.shimMaxMessageSize(window1,browserDetails),commonShim.shimSendThrowTypeError(window1,browserDetails),commonShim.removeExtmapAllowMixed(window1,browserDetails);break;case"firefox":if(!firefoxShim||!firefoxShim.shimPeerConnection||!options.shimFirefox){logging("Firefox shim is not included in this adapter release.");break}logging("adapter.js shimming firefox."),adapter.browserShim=firefoxShim,commonShim.shimAddIceCandidateNullOrEmpty(window1,browserDetails),firefoxShim.shimGetUserMedia(window1,browserDetails),firefoxShim.shimPeerConnection(window1,browserDetails),firefoxShim.shimOnTrack(window1,browserDetails),firefoxShim.shimRemoveStream(window1,browserDetails),firefoxShim.shimSenderGetStats(window1,browserDetails),firefoxShim.shimReceiverGetStats(window1,browserDetails),firefoxShim.shimRTCDataChannel(window1,browserDetails),firefoxShim.shimAddTransceiver(window1,browserDetails),firefoxShim.shimGetParameters(window1,browserDetails),firefoxShim.shimCreateOffer(window1,browserDetails),firefoxShim.shimCreateAnswer(window1,browserDetails),commonShim.shimRTCIceCandidate(window1,browserDetails),commonShim.shimConnectionState(window1,browserDetails),commonShim.shimMaxMessageSize(window1,browserDetails),commonShim.shimSendThrowTypeError(window1,browserDetails);break;case"edge":if(!edgeShim||!edgeShim.shimPeerConnection||!options.shimEdge){logging("MS edge shim is not included in this adapter release.");break}logging("adapter.js shimming edge."),adapter.browserShim=edgeShim,edgeShim.shimGetUserMedia(window1,browserDetails),edgeShim.shimGetDisplayMedia(window1,browserDetails),edgeShim.shimPeerConnection(window1,browserDetails),edgeShim.shimReplaceTrack(window1,browserDetails),commonShim.shimMaxMessageSize(window1,browserDetails),commonShim.shimSendThrowTypeError(window1,browserDetails);break;case"safari":if(!safariShim||!options.shimSafari){logging("Safari shim is not included in this adapter release.");break}logging("adapter.js shimming safari."),adapter.browserShim=safariShim,commonShim.shimAddIceCandidateNullOrEmpty(window1,browserDetails),safariShim.shimRTCIceServerUrls(window1,browserDetails),safariShim.shimCreateOfferLegacy(window1,browserDetails),safariShim.shimCallbacksAPI(window1,browserDetails),safariShim.shimLocalStreamsAPI(window1,browserDetails),safariShim.shimRemoteStreamsAPI(window1,browserDetails),safariShim.shimTrackEventTransceiver(window1,browserDetails),safariShim.shimGetUserMedia(window1,browserDetails),safariShim.shimAudioContext(window1,browserDetails),commonShim.shimRTCIceCandidate(window1,browserDetails),commonShim.shimMaxMessageSize(window1,browserDetails),commonShim.shimSendThrowTypeError(window1,browserDetails),commonShim.removeExtmapAllowMixed(window1,browserDetails);break;default:logging("Unsupported browser!")}return adapter}},{"./chrome/chrome_shim":220,"./common_shim":223,"./edge/edge_shim":224,"./firefox/firefox_shim":228,"./safari/safari_shim":231,"./utils":232}],220:[function(require1,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=exports.shimGetUserMedia=void 0;var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},_getusermedia=require1("./getusermedia");Object.defineProperty(exports,"shimGetUserMedia",{enumerable:!0,get:function get(){return _getusermedia.shimGetUserMedia}});var _getdisplaymedia=require1("./getdisplaymedia");Object.defineProperty(exports,"shimGetDisplayMedia",{enumerable:!0,get:function get(){return _getdisplaymedia.shimGetDisplayMedia}}),exports.shimMediaStream=shimMediaStream,exports.shimOnTrack=shimOnTrack,exports.shimGetSendersWithDtmf=shimGetSendersWithDtmf,exports.shimGetStats=shimGetStats,exports.shimSenderReceiverGetStats=shimSenderReceiverGetStats,exports.shimAddTrackRemoveTrackWithNative=shimAddTrackRemoveTrackWithNative,exports.shimAddTrackRemoveTrack=shimAddTrackRemoveTrack,exports.shimPeerConnection=shimPeerConnection,exports.fixNegotiationNeeded=fixNegotiationNeeded;var utils=_interopRequireWildcard(require1("../utils.js"));function _interopRequireWildcard(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function shimMediaStream(window1){window1.MediaStream=window1.MediaStream||window1.webkitMediaStream}function shimOnTrack(window1){if((void 0===window1?"undefined":_typeof(window1))!=="object"||!window1.RTCPeerConnection||"ontrack"in window1.RTCPeerConnection.prototype)utils.wrapPeerConnectionEvent(window1,"track",function(e){return e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e});else{Object.defineProperty(window1.RTCPeerConnection.prototype,"ontrack",{get:function get(){return this._ontrack},set:function set(f){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=f)},enumerable:!0,configurable:!0});var origSetRemoteDescription=window1.RTCPeerConnection.prototype.setRemoteDescription;window1.RTCPeerConnection.prototype.setRemoteDescription=function setRemoteDescription(){var _this=this;return this._ontrackpoly||(this._ontrackpoly=function(e){e.stream.addEventListener("addtrack",function(te){var receiver=void 0;receiver=window1.RTCPeerConnection.prototype.getReceivers?_this.getReceivers().find(function(r){return r.track&&r.track.id===te.track.id}):{track:te.track};var event=new Event("track");event.track=te.track,event.receiver=receiver,event.transceiver={receiver:receiver},event.streams=[e.stream],_this.dispatchEvent(event)}),e.stream.getTracks().forEach(function(track){var receiver=void 0;receiver=window1.RTCPeerConnection.prototype.getReceivers?_this.getReceivers().find(function(r){return r.track&&r.track.id===track.id}):{track:track};var event=new Event("track");event.track=track,event.receiver=receiver,event.transceiver={receiver:receiver},event.streams=[e.stream],_this.dispatchEvent(event)})},this.addEventListener("addstream",this._ontrackpoly)),origSetRemoteDescription.apply(this,arguments)}}}function shimGetSendersWithDtmf(window1){if((void 0===window1?"undefined":_typeof(window1))==="object"&&window1.RTCPeerConnection&&!("getSenders"in window1.RTCPeerConnection.prototype)&&"createDTMFSender"in window1.RTCPeerConnection.prototype){var shimSenderWithDtmf=function(pc,track){return{track:track,get dtmf(){return void 0===this._dtmf&&("audio"===track.kind?this._dtmf=pc.createDTMFSender(track):this._dtmf=null),this._dtmf},_pc:pc}};if(!window1.RTCPeerConnection.prototype.getSenders){window1.RTCPeerConnection.prototype.getSenders=function getSenders(){return this._senders=this._senders||[],this._senders.slice()};var origAddTrack=window1.RTCPeerConnection.prototype.addTrack;window1.RTCPeerConnection.prototype.addTrack=function addTrack(track,stream){var sender=origAddTrack.apply(this,arguments);return sender||(sender=shimSenderWithDtmf(this,track),this._senders.push(sender)),sender};var origRemoveTrack=window1.RTCPeerConnection.prototype.removeTrack;window1.RTCPeerConnection.prototype.removeTrack=function removeTrack(sender){origRemoveTrack.apply(this,arguments);var idx=this._senders.indexOf(sender);-1!==idx&&this._senders.splice(idx,1)}}var origAddStream=window1.RTCPeerConnection.prototype.addStream;window1.RTCPeerConnection.prototype.addStream=function addStream(stream){var _this2=this;this._senders=this._senders||[],origAddStream.apply(this,[stream]),stream.getTracks().forEach(function(track){_this2._senders.push(shimSenderWithDtmf(_this2,track))})};var origRemoveStream=window1.RTCPeerConnection.prototype.removeStream;window1.RTCPeerConnection.prototype.removeStream=function removeStream(stream){var _this3=this;this._senders=this._senders||[],origRemoveStream.apply(this,[stream]),stream.getTracks().forEach(function(track){var sender=_this3._senders.find(function(s){return s.track===track});sender&&_this3._senders.splice(_this3._senders.indexOf(sender),1)})}}else if((void 0===window1?"undefined":_typeof(window1))==="object"&&window1.RTCPeerConnection&&"getSenders"in window1.RTCPeerConnection.prototype&&"createDTMFSender"in window1.RTCPeerConnection.prototype&&window1.RTCRtpSender&&!("dtmf"in window1.RTCRtpSender.prototype)){var origGetSenders=window1.RTCPeerConnection.prototype.getSenders;window1.RTCPeerConnection.prototype.getSenders=function getSenders(){var _this4=this,senders=origGetSenders.apply(this,[]);return senders.forEach(function(sender){return sender._pc=_this4}),senders},Object.defineProperty(window1.RTCRtpSender.prototype,"dtmf",{get:function get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function shimGetStats(window1){if(window1.RTCPeerConnection){var origGetStats=window1.RTCPeerConnection.prototype.getStats;window1.RTCPeerConnection.prototype.getStats=function getStats(){var _this5=this,_arguments=Array.prototype.slice.call(arguments),selector=_arguments[0],onSucc=_arguments[1],onErr=_arguments[2];if(arguments.length>0&&"function"==typeof selector)return origGetStats.apply(this,arguments);if(0===origGetStats.length&&(0==arguments.length||"function"!=typeof selector))return origGetStats.apply(this,[]);var fixChromeStats_=function(response){var standardReport={};return response.result().forEach(function(report){var standardStats={id:report.id,timestamp:report.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[report.type]||report.type};report.names().forEach(function(name){standardStats[name]=report.stat(name)}),standardReport[standardStats.id]=standardStats}),standardReport},makeMapStats=function(stats){return new Map(Object.keys(stats).map(function(key){return[key,stats[key]]}))};return arguments.length>=2?origGetStats.apply(this,[function(response){onSucc(makeMapStats(fixChromeStats_(response)))},selector]):new Promise(function(resolve,reject){origGetStats.apply(_this5,[function(response){resolve(makeMapStats(fixChromeStats_(response)))},reject])}).then(onSucc,onErr)}}}function shimSenderReceiverGetStats(window1){if((void 0===window1?"undefined":_typeof(window1))==="object"&&window1.RTCPeerConnection&&window1.RTCRtpSender&&window1.RTCRtpReceiver){if(!("getStats"in window1.RTCRtpSender.prototype)){var origGetSenders=window1.RTCPeerConnection.prototype.getSenders;origGetSenders&&(window1.RTCPeerConnection.prototype.getSenders=function getSenders(){var _this6=this,senders=origGetSenders.apply(this,[]);return senders.forEach(function(sender){return sender._pc=_this6}),senders});var origAddTrack=window1.RTCPeerConnection.prototype.addTrack;origAddTrack&&(window1.RTCPeerConnection.prototype.addTrack=function addTrack(){var sender=origAddTrack.apply(this,arguments);return sender._pc=this,sender}),window1.RTCRtpSender.prototype.getStats=function getStats(){var sender=this;return this._pc.getStats().then(function(result){return utils.filterStats(result,sender.track,!0)})}}if(!("getStats"in window1.RTCRtpReceiver.prototype)){var origGetReceivers=window1.RTCPeerConnection.prototype.getReceivers;origGetReceivers&&(window1.RTCPeerConnection.prototype.getReceivers=function getReceivers(){var _this7=this,receivers=origGetReceivers.apply(this,[]);return receivers.forEach(function(receiver){return receiver._pc=_this7}),receivers}),utils.wrapPeerConnectionEvent(window1,"track",function(e){return e.receiver._pc=e.srcElement,e}),window1.RTCRtpReceiver.prototype.getStats=function getStats(){var receiver=this;return this._pc.getStats().then(function(result){return utils.filterStats(result,receiver.track,!1)})}}if("getStats"in window1.RTCRtpSender.prototype&&"getStats"in window1.RTCRtpReceiver.prototype){var origGetStats=window1.RTCPeerConnection.prototype.getStats;window1.RTCPeerConnection.prototype.getStats=function getStats(){if(arguments.length>0&&arguments[0]instanceof window1.MediaStreamTrack){var track=arguments[0],sender=void 0,receiver=void 0,err=void 0;return(this.getSenders().forEach(function(s){s.track===track&&(sender?err=!0:sender=s)}),this.getReceivers().forEach(function(r){return r.track===track&&(receiver?err=!0:receiver=r),r.track===track}),err||sender&&receiver)?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):sender?sender.getStats():receiver?receiver.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return origGetStats.apply(this,arguments)}}}}function shimAddTrackRemoveTrackWithNative(window1){window1.RTCPeerConnection.prototype.getLocalStreams=function getLocalStreams(){var _this8=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(function(streamId){return _this8._shimmedLocalStreams[streamId][0]})};var origAddTrack=window1.RTCPeerConnection.prototype.addTrack;window1.RTCPeerConnection.prototype.addTrack=function addTrack(track,stream){if(!stream)return origAddTrack.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};var sender=origAddTrack.apply(this,arguments);return this._shimmedLocalStreams[stream.id]?-1===this._shimmedLocalStreams[stream.id].indexOf(sender)&&this._shimmedLocalStreams[stream.id].push(sender):this._shimmedLocalStreams[stream.id]=[stream,sender],sender};var origAddStream=window1.RTCPeerConnection.prototype.addStream;window1.RTCPeerConnection.prototype.addStream=function addStream(stream){var _this9=this;this._shimmedLocalStreams=this._shimmedLocalStreams||{},stream.getTracks().forEach(function(track){if(_this9.getSenders().find(function(s){return s.track===track}))throw new DOMException("Track already exists.","InvalidAccessError")});var existingSenders=this.getSenders();origAddStream.apply(this,arguments);var newSenders=this.getSenders().filter(function(newSender){return -1===existingSenders.indexOf(newSender)});this._shimmedLocalStreams[stream.id]=[stream].concat(newSenders)};var origRemoveStream=window1.RTCPeerConnection.prototype.removeStream;window1.RTCPeerConnection.prototype.removeStream=function removeStream(stream){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[stream.id],origRemoveStream.apply(this,arguments)};var origRemoveTrack=window1.RTCPeerConnection.prototype.removeTrack;window1.RTCPeerConnection.prototype.removeTrack=function removeTrack(sender){var _this10=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},sender&&Object.keys(this._shimmedLocalStreams).forEach(function(streamId){var idx=_this10._shimmedLocalStreams[streamId].indexOf(sender);-1!==idx&&_this10._shimmedLocalStreams[streamId].splice(idx,1),1===_this10._shimmedLocalStreams[streamId].length&&delete _this10._shimmedLocalStreams[streamId]}),origRemoveTrack.apply(this,arguments)}}function shimAddTrackRemoveTrack(window1,browserDetails){if(window1.RTCPeerConnection){if(window1.RTCPeerConnection.prototype.addTrack&&browserDetails.version>=65)return shimAddTrackRemoveTrackWithNative(window1);var origGetLocalStreams=window1.RTCPeerConnection.prototype.getLocalStreams;window1.RTCPeerConnection.prototype.getLocalStreams=function getLocalStreams(){var _this11=this,nativeStreams=origGetLocalStreams.apply(this);return this._reverseStreams=this._reverseStreams||{},nativeStreams.map(function(stream){return _this11._reverseStreams[stream.id]})};var origAddStream=window1.RTCPeerConnection.prototype.addStream;window1.RTCPeerConnection.prototype.addStream=function addStream(stream){var _this12=this;if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},stream.getTracks().forEach(function(track){if(_this12.getSenders().find(function(s){return s.track===track}))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[stream.id]){var newStream=new window1.MediaStream(stream.getTracks());this._streams[stream.id]=newStream,this._reverseStreams[newStream.id]=stream,stream=newStream}origAddStream.apply(this,[stream])};var origRemoveStream=window1.RTCPeerConnection.prototype.removeStream;window1.RTCPeerConnection.prototype.removeStream=function removeStream(stream){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},origRemoveStream.apply(this,[this._streams[stream.id]||stream]),delete this._reverseStreams[this._streams[stream.id]?this._streams[stream.id].id:stream.id],delete this._streams[stream.id]},window1.RTCPeerConnection.prototype.addTrack=function addTrack(track,stream){var _this13=this;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");var streams=[].slice.call(arguments,1);if(1!==streams.length||!streams[0].getTracks().find(function(t){return t===track}))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(function(s){return s.track===track}))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};var oldStream=this._streams[stream.id];if(oldStream)oldStream.addTrack(track),Promise.resolve().then(function(){_this13.dispatchEvent(new Event("negotiationneeded"))});else{var newStream=new window1.MediaStream([track]);this._streams[stream.id]=newStream,this._reverseStreams[newStream.id]=stream,this.addStream(newStream)}return this.getSenders().find(function(s){return s.track===track})},["createOffer","createAnswer"].forEach(function(method){var nativeMethod=window1.RTCPeerConnection.prototype[method],methodObj=_defineProperty({},method,function(){var _this14=this,args=arguments,isLegacyCall=arguments.length&&"function"==typeof arguments[0];return isLegacyCall?nativeMethod.apply(this,[function(description){var desc=replaceInternalStreamId(_this14,description);args[0].apply(null,[desc])},function(err){args[1]&&args[1].apply(null,err)},arguments[2]]):nativeMethod.apply(this,arguments).then(function(description){return replaceInternalStreamId(_this14,description)})});window1.RTCPeerConnection.prototype[method]=methodObj[method]});var origSetLocalDescription=window1.RTCPeerConnection.prototype.setLocalDescription;window1.RTCPeerConnection.prototype.setLocalDescription=function setLocalDescription(){return arguments.length&&arguments[0].type&&(arguments[0]=replaceExternalStreamId(this,arguments[0])),origSetLocalDescription.apply(this,arguments)};var origLocalDescription=Object.getOwnPropertyDescriptor(window1.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(window1.RTCPeerConnection.prototype,"localDescription",{get:function get(){var description=origLocalDescription.get.apply(this);return""===description.type?description:replaceInternalStreamId(this,description)}}),window1.RTCPeerConnection.prototype.removeTrack=function removeTrack(sender){var _this15=this;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!sender._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(sender._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};var stream=void 0;Object.keys(this._streams).forEach(function(streamid){_this15._streams[streamid].getTracks().find(function(track){return sender.track===track})&&(stream=_this15._streams[streamid])}),stream&&(1===stream.getTracks().length?this.removeStream(this._reverseStreams[stream.id]):stream.removeTrack(sender.track),this.dispatchEvent(new Event("negotiationneeded")))}}function replaceInternalStreamId(pc,description){var sdp=description.sdp;return Object.keys(pc._reverseStreams||[]).forEach(function(internalId){var externalStream=pc._reverseStreams[internalId],internalStream=pc._streams[externalStream.id];sdp=sdp.replace(RegExp(internalStream.id,"g"),externalStream.id)}),new RTCSessionDescription({type:description.type,sdp:sdp})}function replaceExternalStreamId(pc,description){var sdp=description.sdp;return Object.keys(pc._reverseStreams||[]).forEach(function(internalId){var externalStream=pc._reverseStreams[internalId],internalStream=pc._streams[externalStream.id];sdp=sdp.replace(RegExp(externalStream.id,"g"),internalStream.id)}),new RTCSessionDescription({type:description.type,sdp:sdp})}}function shimPeerConnection(window1,browserDetails){!window1.RTCPeerConnection&&window1.webkitRTCPeerConnection&&(window1.RTCPeerConnection=window1.webkitRTCPeerConnection),window1.RTCPeerConnection&&browserDetails.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(method){var nativeMethod=window1.RTCPeerConnection.prototype[method],methodObj=_defineProperty({},method,function(){return arguments[0]=new("addIceCandidate"===method?window1.RTCIceCandidate:window1.RTCSessionDescription)(arguments[0]),nativeMethod.apply(this,arguments)});window1.RTCPeerConnection.prototype[method]=methodObj[method]})}function fixNegotiationNeeded(window1,browserDetails){utils.wrapPeerConnectionEvent(window1,"negotiationneeded",function(e){var pc=e.target;if(!(browserDetails.version<72)&&(!pc.getConfiguration||"plan-b"!==pc.getConfiguration().sdpSemantics)||"stable"===pc.signalingState)return e})}},{"../utils.js":232,"./getdisplaymedia":221,"./getusermedia":222}],221:[function(require1,module,exports){"use strict";function shimGetDisplayMedia(window1,getSourceId){if((!window1.navigator.mediaDevices||!("getDisplayMedia"in window1.navigator.mediaDevices))&&window1.navigator.mediaDevices){if("function"!=typeof getSourceId){console.error("shimGetDisplayMedia: getSourceId argument is not a function");return}window1.navigator.mediaDevices.getDisplayMedia=function getDisplayMedia(constraints){return getSourceId(constraints).then(function(sourceId){var widthSpecified=constraints.video&&constraints.video.width,heightSpecified=constraints.video&&constraints.video.height,frameRateSpecified=constraints.video&&constraints.video.frameRate;return constraints.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:sourceId,maxFrameRate:frameRateSpecified||3}},widthSpecified&&(constraints.video.mandatory.maxWidth=widthSpecified),heightSpecified&&(constraints.video.mandatory.maxHeight=heightSpecified),window1.navigator.mediaDevices.getUserMedia(constraints)})}}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=shimGetDisplayMedia},{}],222:[function(require1,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};exports.shimGetUserMedia=shimGetUserMedia;var logging=function _interopRequireWildcard(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require1("../utils.js")).log;function shimGetUserMedia(window1,browserDetails){var navigator1=window1&&window1.navigator;if(navigator1.mediaDevices){var constraintsToChrome_=function(c){if((void 0===c?"undefined":_typeof(c))!=="object"||c.mandatory||c.optional)return c;var cc={};return Object.keys(c).forEach(function(key){if("require"!==key&&"advanced"!==key&&"mediaSource"!==key){var r="object"===_typeof(c[key])?c[key]:{ideal:c[key]};void 0!==r.exact&&"number"==typeof r.exact&&(r.min=r.max=r.exact);var oldname_=function(prefix,name){return prefix?prefix+name.charAt(0).toUpperCase()+name.slice(1):"deviceId"===name?"sourceId":name};if(void 0!==r.ideal){cc.optional=cc.optional||[];var oc={};"number"==typeof r.ideal?(oc[oldname_("min",key)]=r.ideal,cc.optional.push(oc),(oc={})[oldname_("max",key)]=r.ideal):oc[oldname_("",key)]=r.ideal,cc.optional.push(oc)}void 0!==r.exact&&"number"!=typeof r.exact?(cc.mandatory=cc.mandatory||{},cc.mandatory[oldname_("",key)]=r.exact):["min","max"].forEach(function(mix){void 0!==r[mix]&&(cc.mandatory=cc.mandatory||{},cc.mandatory[oldname_(mix,key)]=r[mix])})}}),c.advanced&&(cc.optional=(cc.optional||[]).concat(c.advanced)),cc},shimConstraints_=function(constraints,func){if(browserDetails.version>=61)return func(constraints);if((constraints=JSON.parse(JSON.stringify(constraints)))&&"object"===_typeof(constraints.audio)){var remap=function(obj,a,b){a in obj&&!(b in obj)&&(obj[b]=obj[a],delete obj[a])};remap((constraints=JSON.parse(JSON.stringify(constraints))).audio,"autoGainControl","googAutoGainControl"),remap(constraints.audio,"noiseSuppression","googNoiseSuppression"),constraints.audio=constraintsToChrome_(constraints.audio)}if(constraints&&"object"===_typeof(constraints.video)){var face=constraints.video.facingMode;face=face&&((void 0===face?"undefined":_typeof(face))==="object"?face:{ideal:face});var getSupportedFacingModeLies=browserDetails.version<66;if(face&&("user"===face.exact||"environment"===face.exact||"user"===face.ideal||"environment"===face.ideal)&&!(navigator1.mediaDevices.getSupportedConstraints&&navigator1.mediaDevices.getSupportedConstraints().facingMode&&!getSupportedFacingModeLies)){delete constraints.video.facingMode;var matches=void 0;if("environment"===face.exact||"environment"===face.ideal?matches=["back","rear"]:("user"===face.exact||"user"===face.ideal)&&(matches=["front"]),matches)return navigator1.mediaDevices.enumerateDevices().then(function(devices){var dev=(devices=devices.filter(function(d){return"videoinput"===d.kind})).find(function(d){return matches.some(function(match){return d.label.toLowerCase().includes(match)})});return!dev&&devices.length&&matches.includes("back")&&(dev=devices[devices.length-1]),dev&&(constraints.video.deviceId=face.exact?{exact:dev.deviceId}:{ideal:dev.deviceId}),constraints.video=constraintsToChrome_(constraints.video),logging("chrome: "+JSON.stringify(constraints)),func(constraints)})}constraints.video=constraintsToChrome_(constraints.video)}return logging("chrome: "+JSON.stringify(constraints)),func(constraints)},shimError_=function(e){return browserDetails.version>=64?e:{name:({PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"})[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString:function toString(){return this.name+(this.message&&": ")+this.message}}};if(navigator1.getUserMedia=(function(constraints,onSuccess,onError){shimConstraints_(constraints,function(c){navigator1.webkitGetUserMedia(c,onSuccess,function(e){onError&&onError(shimError_(e))})})}).bind(navigator1),navigator1.mediaDevices.getUserMedia){var origGetUserMedia=navigator1.mediaDevices.getUserMedia.bind(navigator1.mediaDevices);navigator1.mediaDevices.getUserMedia=function(cs){return shimConstraints_(cs,function(c){return origGetUserMedia(c).then(function(stream){if(c.audio&&!stream.getAudioTracks().length||c.video&&!stream.getVideoTracks().length)throw stream.getTracks().forEach(function(track){track.stop()}),new DOMException("","NotFoundError");return stream},function(e){return Promise.reject(shimError_(e))})})}}}}},{"../utils.js":232}],223:[function(require1,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};exports.shimRTCIceCandidate=shimRTCIceCandidate,exports.shimMaxMessageSize=shimMaxMessageSize,exports.shimSendThrowTypeError=shimSendThrowTypeError,exports.shimConnectionState=shimConnectionState,exports.removeExtmapAllowMixed=removeExtmapAllowMixed,exports.shimAddIceCandidateNullOrEmpty=shimAddIceCandidateNullOrEmpty;var _sdp2=_interopRequireDefault(require1("sdp")),utils=_interopRequireWildcard(require1("./utils"));function _interopRequireWildcard(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function shimRTCIceCandidate(window1){if(window1.RTCIceCandidate&&(!window1.RTCIceCandidate||!("foundation"in window1.RTCIceCandidate.prototype))){var NativeRTCIceCandidate=window1.RTCIceCandidate;window1.RTCIceCandidate=function RTCIceCandidate(args){if((void 0===args?"undefined":_typeof(args))==="object"&&args.candidate&&0===args.candidate.indexOf("a=")&&((args=JSON.parse(JSON.stringify(args))).candidate=args.candidate.substr(2)),args.candidate&&args.candidate.length){var augmentedCandidate=Object.assign(new NativeRTCIceCandidate(args),_sdp2.default.parseCandidate(args.candidate));return augmentedCandidate.toJSON=function toJSON(){return{candidate:augmentedCandidate.candidate,sdpMid:augmentedCandidate.sdpMid,sdpMLineIndex:augmentedCandidate.sdpMLineIndex,usernameFragment:augmentedCandidate.usernameFragment}},augmentedCandidate}return new NativeRTCIceCandidate(args)},window1.RTCIceCandidate.prototype=NativeRTCIceCandidate.prototype,utils.wrapPeerConnectionEvent(window1,"icecandidate",function(e){return e.candidate&&Object.defineProperty(e,"candidate",{value:new window1.RTCIceCandidate(e.candidate),writable:"false"}),e})}}function shimMaxMessageSize(window1,browserDetails){if(window1.RTCPeerConnection){"sctp"in window1.RTCPeerConnection.prototype||Object.defineProperty(window1.RTCPeerConnection.prototype,"sctp",{get:function get(){return void 0===this._sctp?null:this._sctp}});var sctpInDescription=function(description){if(!description||!description.sdp)return!1;var sections=_sdp2.default.splitSections(description.sdp);return sections.shift(),sections.some(function(mediaSection){var mLine=_sdp2.default.parseMLine(mediaSection);return mLine&&"application"===mLine.kind&&-1!==mLine.protocol.indexOf("SCTP")})},getRemoteFirefoxVersion=function(description){var match=description.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===match||match.length<2)return -1;var version=parseInt(match[1],10);return version!=version?-1:version},getCanSendMaxMessageSize=function(remoteIsFirefox){var canSendMaxMessageSize=65536;return"firefox"===browserDetails.browser&&(canSendMaxMessageSize=browserDetails.version<57?-1===remoteIsFirefox?16384:2147483637:browserDetails.version<60?57===browserDetails.version?65535:65536:2147483637),canSendMaxMessageSize},getMaxMessageSize=function(description,remoteIsFirefox){var maxMessageSize=65536;"firefox"===browserDetails.browser&&57===browserDetails.version&&(maxMessageSize=65535);var match=_sdp2.default.matchPrefix(description.sdp,"a=max-message-size:");return match.length>0?maxMessageSize=parseInt(match[0].substr(19),10):"firefox"===browserDetails.browser&&-1!==remoteIsFirefox&&(maxMessageSize=2147483637),maxMessageSize},origSetRemoteDescription=window1.RTCPeerConnection.prototype.setRemoteDescription;window1.RTCPeerConnection.prototype.setRemoteDescription=function setRemoteDescription(){if(this._sctp=null,"chrome"===browserDetails.browser&&browserDetails.version>=76&&"plan-b"===this.getConfiguration().sdpSemantics&&Object.defineProperty(this,"sctp",{get:function get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0}),sctpInDescription(arguments[0])){var isFirefox=getRemoteFirefoxVersion(arguments[0]),canSendMMS=getCanSendMaxMessageSize(isFirefox),remoteMMS=getMaxMessageSize(arguments[0],isFirefox),maxMessageSize=void 0;maxMessageSize=0===canSendMMS&&0===remoteMMS?Number.POSITIVE_INFINITY:0===canSendMMS||0===remoteMMS?Math.max(canSendMMS,remoteMMS):Math.min(canSendMMS,remoteMMS);var sctp={};Object.defineProperty(sctp,"maxMessageSize",{get:function get(){return maxMessageSize}}),this._sctp=sctp}return origSetRemoteDescription.apply(this,arguments)}}}function shimSendThrowTypeError(window1){if(window1.RTCPeerConnection&&"createDataChannel"in window1.RTCPeerConnection.prototype){var origCreateDataChannel=window1.RTCPeerConnection.prototype.createDataChannel;window1.RTCPeerConnection.prototype.createDataChannel=function createDataChannel(){var dataChannel=origCreateDataChannel.apply(this,arguments);return wrapDcSend(dataChannel,this),dataChannel},utils.wrapPeerConnectionEvent(window1,"datachannel",function(e){return wrapDcSend(e.channel,e.target),e})}function wrapDcSend(dc,pc){var origDataChannelSend=dc.send;dc.send=function send(){var data=arguments[0],length=data.length||data.size||data.byteLength;if("open"===dc.readyState&&pc.sctp&&length>pc.sctp.maxMessageSize)throw TypeError("Message too large (can send a maximum of "+pc.sctp.maxMessageSize+" bytes)");return origDataChannelSend.apply(dc,arguments)}}}function shimConnectionState(window1){if(window1.RTCPeerConnection&&!("connectionState"in window1.RTCPeerConnection.prototype)){var proto=window1.RTCPeerConnection.prototype;Object.defineProperty(proto,"connectionState",{get:function get(){return({completed:"connected",checking:"connecting"})[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(proto,"onconnectionstatechange",{get:function get(){return this._onconnectionstatechange||null},set:function set(cb){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),cb&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=cb)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(function(method){var origMethod=proto[method];proto[method]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=function(e){var pc=e.target;if(pc._lastConnectionState!==pc.connectionState){pc._lastConnectionState=pc.connectionState;var newEvent=new Event("connectionstatechange",e);pc.dispatchEvent(newEvent)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),origMethod.apply(this,arguments)}})}}function removeExtmapAllowMixed(window1,browserDetails){if(window1.RTCPeerConnection&&("chrome"!==browserDetails.browser||!(browserDetails.version>=71))&&("safari"!==browserDetails.browser||!(browserDetails.version>=605))){var nativeSRD=window1.RTCPeerConnection.prototype.setRemoteDescription;window1.RTCPeerConnection.prototype.setRemoteDescription=function setRemoteDescription(desc){if(desc&&desc.sdp&&-1!==desc.sdp.indexOf("\na=extmap-allow-mixed")){var sdp=desc.sdp.split("\n").filter(function(line){return"a=extmap-allow-mixed"!==line.trim()}).join("\n");window1.RTCSessionDescription&&desc instanceof window1.RTCSessionDescription?arguments[0]=new window1.RTCSessionDescription({type:desc.type,sdp:sdp}):desc.sdp=sdp}return nativeSRD.apply(this,arguments)}}}function shimAddIceCandidateNullOrEmpty(window1,browserDetails){if(window1.RTCPeerConnection&&window1.RTCPeerConnection.prototype){var nativeAddIceCandidate=window1.RTCPeerConnection.prototype.addIceCandidate;nativeAddIceCandidate&&0!==nativeAddIceCandidate.length&&(window1.RTCPeerConnection.prototype.addIceCandidate=function addIceCandidate(){return arguments[0]?("chrome"===browserDetails.browser&&browserDetails.version<78||"firefox"===browserDetails.browser&&browserDetails.version<68||"safari"===browserDetails.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():nativeAddIceCandidate.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}}},{"./utils":232,sdp:175}],224:[function(require1,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=exports.shimGetUserMedia=void 0;var _getusermedia=require1("./getusermedia");Object.defineProperty(exports,"shimGetUserMedia",{enumerable:!0,get:function get(){return _getusermedia.shimGetUserMedia}});var _getdisplaymedia=require1("./getdisplaymedia");Object.defineProperty(exports,"shimGetDisplayMedia",{enumerable:!0,get:function get(){return _getdisplaymedia.shimGetDisplayMedia}}),exports.shimPeerConnection=shimPeerConnection,exports.shimReplaceTrack=shimReplaceTrack;var utils=_interopRequireWildcard(require1("../utils")),_filtericeservers=require1("./filtericeservers"),_rtcpeerconnectionShim2=_interopRequireDefault(require1("rtcpeerconnection-shim"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _interopRequireWildcard(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}function shimPeerConnection(window1,browserDetails){if(window1.RTCIceGatherer&&(window1.RTCIceCandidate||(window1.RTCIceCandidate=function RTCIceCandidate(args){return args}),window1.RTCSessionDescription||(window1.RTCSessionDescription=function RTCSessionDescription1(args){return args}),browserDetails.version<15025)){var origMSTEnabled=Object.getOwnPropertyDescriptor(window1.MediaStreamTrack.prototype,"enabled");Object.defineProperty(window1.MediaStreamTrack.prototype,"enabled",{set:function set(value){origMSTEnabled.set.call(this,value);var ev=new Event("enabled");ev.enabled=value,this.dispatchEvent(ev)}})}!window1.RTCRtpSender||"dtmf"in window1.RTCRtpSender.prototype||Object.defineProperty(window1.RTCRtpSender.prototype,"dtmf",{get:function get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=new window1.RTCDtmfSender(this):"video"===this.track.kind&&(this._dtmf=null)),this._dtmf}}),window1.RTCDtmfSender&&!window1.RTCDTMFSender&&(window1.RTCDTMFSender=window1.RTCDtmfSender);var RTCPeerConnectionShim=(0,_rtcpeerconnectionShim2.default)(window1,browserDetails.version);window1.RTCPeerConnection=function RTCPeerConnection(config){return config&&config.iceServers&&(config.iceServers=(0,_filtericeservers.filterIceServers)(config.iceServers,browserDetails.version),utils.log("ICE servers after filtering:",config.iceServers)),new RTCPeerConnectionShim(config)},window1.RTCPeerConnection.prototype=RTCPeerConnectionShim.prototype}function shimReplaceTrack(window1){!window1.RTCRtpSender||"replaceTrack"in window1.RTCRtpSender.prototype||(window1.RTCRtpSender.prototype.replaceTrack=window1.RTCRtpSender.prototype.setTrack)}},{"../utils":232,"./filtericeservers":225,"./getdisplaymedia":226,"./getusermedia":227,"rtcpeerconnection-shim":172}],225:[function(require1,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.filterIceServers=filterIceServers;var utils=_interopRequireWildcard(require1("../utils"));function _interopRequireWildcard(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}function filterIceServers(iceServers,edgeVersion){var hasTurn=!1;return(iceServers=JSON.parse(JSON.stringify(iceServers))).filter(function(server){if(server&&(server.urls||server.url)){var urls=server.urls||server.url;server.url&&!server.urls&&utils.deprecated("RTCIceServer.url","RTCIceServer.urls");var isString="string"==typeof urls;return isString&&(urls=[urls]),urls=urls.filter(function(url){if(0===url.indexOf("stun:"))return!1;var validTurn=url.startsWith("turn")&&!url.startsWith("turn:[")&&url.includes("transport=udp");return validTurn&&!hasTurn?(hasTurn=!0,!0):validTurn&&!hasTurn}),delete server.url,server.urls=isString?urls[0]:urls,!!urls.length}})}},{"../utils":232}],226:[function(require1,module,exports){"use strict";function shimGetDisplayMedia(window1){"getDisplayMedia"in window1.navigator&&window1.navigator.mediaDevices&&(!window1.navigator.mediaDevices||!("getDisplayMedia"in window1.navigator.mediaDevices))&&(window1.navigator.mediaDevices.getDisplayMedia=window1.navigator.getDisplayMedia.bind(window1.navigator))}Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=shimGetDisplayMedia},{}],227:[function(require1,module,exports){"use strict";function shimGetUserMedia(window1){var navigator1=window1&&window1.navigator,origGetUserMedia=navigator1.mediaDevices.getUserMedia.bind(navigator1.mediaDevices);navigator1.mediaDevices.getUserMedia=function(c){return origGetUserMedia(c).catch(function(e){return Promise.reject({name:{PermissionDeniedError:"NotAllowedError"}[e.name]||e.name,message:e.message,constraint:e.constraint,toString:function toString(){return this.name}})})}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetUserMedia=shimGetUserMedia},{}],228:[function(require1,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=exports.shimGetUserMedia=void 0;var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},_getusermedia=require1("./getusermedia");Object.defineProperty(exports,"shimGetUserMedia",{enumerable:!0,get:function get(){return _getusermedia.shimGetUserMedia}});var _getdisplaymedia=require1("./getdisplaymedia");Object.defineProperty(exports,"shimGetDisplayMedia",{enumerable:!0,get:function get(){return _getdisplaymedia.shimGetDisplayMedia}}),exports.shimOnTrack=shimOnTrack,exports.shimPeerConnection=shimPeerConnection,exports.shimSenderGetStats=shimSenderGetStats,exports.shimReceiverGetStats=shimReceiverGetStats,exports.shimRemoveStream=shimRemoveStream,exports.shimRTCDataChannel=shimRTCDataChannel,exports.shimAddTransceiver=shimAddTransceiver,exports.shimGetParameters=shimGetParameters,exports.shimCreateOffer=shimCreateOffer,exports.shimCreateAnswer=shimCreateAnswer;var utils=_interopRequireWildcard(require1("../utils"));function _interopRequireWildcard(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function shimOnTrack(window1){(void 0===window1?"undefined":_typeof(window1))==="object"&&window1.RTCTrackEvent&&"receiver"in window1.RTCTrackEvent.prototype&&!("transceiver"in window1.RTCTrackEvent.prototype)&&Object.defineProperty(window1.RTCTrackEvent.prototype,"transceiver",{get:function get(){return{receiver:this.receiver}}})}function shimPeerConnection(window1,browserDetails){if((void 0===window1?"undefined":_typeof(window1))==="object"&&(window1.RTCPeerConnection||window1.mozRTCPeerConnection)){!window1.RTCPeerConnection&&window1.mozRTCPeerConnection&&(window1.RTCPeerConnection=window1.mozRTCPeerConnection),browserDetails.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(method){var nativeMethod=window1.RTCPeerConnection.prototype[method],methodObj=_defineProperty({},method,function(){return arguments[0]=new("addIceCandidate"===method?window1.RTCIceCandidate:window1.RTCSessionDescription)(arguments[0]),nativeMethod.apply(this,arguments)});window1.RTCPeerConnection.prototype[method]=methodObj[method]});var modernStatsTypes={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},nativeGetStats=window1.RTCPeerConnection.prototype.getStats;window1.RTCPeerConnection.prototype.getStats=function getStats(){var _arguments=Array.prototype.slice.call(arguments),selector=_arguments[0],onSucc=_arguments[1],onErr=_arguments[2];return nativeGetStats.apply(this,[selector||null]).then(function(stats){if(browserDetails.version<53&&!onSucc)try{stats.forEach(function(stat){stat.type=modernStatsTypes[stat.type]||stat.type})}catch(e){if("TypeError"!==e.name)throw e;stats.forEach(function(stat,i){stats.set(i,Object.assign({},stat,{type:modernStatsTypes[stat.type]||stat.type}))})}return stats}).then(onSucc,onErr)}}}function shimSenderGetStats(window1){if((void 0===window1?"undefined":_typeof(window1))==="object"&&window1.RTCPeerConnection&&window1.RTCRtpSender&&(!window1.RTCRtpSender||!("getStats"in window1.RTCRtpSender.prototype))){var origGetSenders=window1.RTCPeerConnection.prototype.getSenders;origGetSenders&&(window1.RTCPeerConnection.prototype.getSenders=function getSenders(){var _this=this,senders=origGetSenders.apply(this,[]);return senders.forEach(function(sender){return sender._pc=_this}),senders});var origAddTrack=window1.RTCPeerConnection.prototype.addTrack;origAddTrack&&(window1.RTCPeerConnection.prototype.addTrack=function addTrack(){var sender=origAddTrack.apply(this,arguments);return sender._pc=this,sender}),window1.RTCRtpSender.prototype.getStats=function getStats(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}}function shimReceiverGetStats(window1){if((void 0===window1?"undefined":_typeof(window1))==="object"&&window1.RTCPeerConnection&&window1.RTCRtpSender&&(!window1.RTCRtpSender||!("getStats"in window1.RTCRtpReceiver.prototype))){var origGetReceivers=window1.RTCPeerConnection.prototype.getReceivers;origGetReceivers&&(window1.RTCPeerConnection.prototype.getReceivers=function getReceivers(){var _this2=this,receivers=origGetReceivers.apply(this,[]);return receivers.forEach(function(receiver){return receiver._pc=_this2}),receivers}),utils.wrapPeerConnectionEvent(window1,"track",function(e){return e.receiver._pc=e.srcElement,e}),window1.RTCRtpReceiver.prototype.getStats=function getStats(){return this._pc.getStats(this.track)}}}function shimRemoveStream(window1){!window1.RTCPeerConnection||"removeStream"in window1.RTCPeerConnection.prototype||(window1.RTCPeerConnection.prototype.removeStream=function removeStream(stream){var _this3=this;utils.deprecated("removeStream","removeTrack"),this.getSenders().forEach(function(sender){sender.track&&stream.getTracks().includes(sender.track)&&_this3.removeTrack(sender)})})}function shimRTCDataChannel(window1){window1.DataChannel&&!window1.RTCDataChannel&&(window1.RTCDataChannel=window1.DataChannel)}function shimAddTransceiver(window1){if((void 0===window1?"undefined":_typeof(window1))==="object"&&window1.RTCPeerConnection){var origAddTransceiver=window1.RTCPeerConnection.prototype.addTransceiver;origAddTransceiver&&(window1.RTCPeerConnection.prototype.addTransceiver=function addTransceiver(){this.setParametersPromises=[];var initParameters=arguments[1],shouldPerformCheck=initParameters&&"sendEncodings"in initParameters;shouldPerformCheck&&initParameters.sendEncodings.forEach(function(encodingParam){if("rid"in encodingParam&&!/^[a-z0-9]{0,16}$/i.test(encodingParam.rid))throw TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in encodingParam&&!(parseFloat(encodingParam.scaleResolutionDownBy)>=1))throw RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in encodingParam&&!(parseFloat(encodingParam.maxFramerate)>=0))throw RangeError("max_framerate must be >= 0.0")});var transceiver=origAddTransceiver.apply(this,arguments);if(shouldPerformCheck){var sender=transceiver.sender,params=sender.getParameters();"encodings"in params&&(1!==params.encodings.length||0!==Object.keys(params.encodings[0]).length)||(params.encodings=initParameters.sendEncodings,sender.sendEncodings=initParameters.sendEncodings,this.setParametersPromises.push(sender.setParameters(params).then(function(){delete sender.sendEncodings}).catch(function(){delete sender.sendEncodings})))}return transceiver})}}function shimGetParameters(window1){if((void 0===window1?"undefined":_typeof(window1))==="object"&&window1.RTCRtpSender){var origGetParameters=window1.RTCRtpSender.prototype.getParameters;origGetParameters&&(window1.RTCRtpSender.prototype.getParameters=function getParameters(){var params=origGetParameters.apply(this,arguments);return"encodings"in params||(params.encodings=[].concat(this.sendEncodings||[{}])),params})}}function shimCreateOffer(window1){if((void 0===window1?"undefined":_typeof(window1))==="object"&&window1.RTCPeerConnection){var origCreateOffer=window1.RTCPeerConnection.prototype.createOffer;window1.RTCPeerConnection.prototype.createOffer=function createOffer(){var _this4=this,_arguments2=arguments;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return origCreateOffer.apply(_this4,_arguments2)}).finally(function(){_this4.setParametersPromises=[]}):origCreateOffer.apply(this,arguments)}}}function shimCreateAnswer(window1){if((void 0===window1?"undefined":_typeof(window1))==="object"&&window1.RTCPeerConnection){var origCreateAnswer=window1.RTCPeerConnection.prototype.createAnswer;window1.RTCPeerConnection.prototype.createAnswer=function createAnswer(){var _this5=this,_arguments3=arguments;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return origCreateAnswer.apply(_this5,_arguments3)}).finally(function(){_this5.setParametersPromises=[]}):origCreateAnswer.apply(this,arguments)}}}},{"../utils":232,"./getdisplaymedia":229,"./getusermedia":230}],229:[function(require1,module,exports){"use strict";function shimGetDisplayMedia(window1,preferredMediaSource){window1.navigator.mediaDevices&&"getDisplayMedia"in window1.navigator.mediaDevices||!window1.navigator.mediaDevices||(window1.navigator.mediaDevices.getDisplayMedia=function getDisplayMedia(constraints){if(!(constraints&&constraints.video)){var err=new DOMException("getDisplayMedia without video constraints is undefined");return err.name="NotFoundError",err.code=8,Promise.reject(err)}return!0===constraints.video?constraints.video={mediaSource:preferredMediaSource}:constraints.video.mediaSource=preferredMediaSource,window1.navigator.mediaDevices.getUserMedia(constraints)})}Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=shimGetDisplayMedia},{}],230:[function(require1,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};exports.shimGetUserMedia=shimGetUserMedia;var utils=_interopRequireWildcard(require1("../utils"));function _interopRequireWildcard(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}function shimGetUserMedia(window1,browserDetails){var navigator1=window1&&window1.navigator,MediaStreamTrack=window1&&window1.MediaStreamTrack;if(navigator1.getUserMedia=function(constraints,onSuccess,onError){utils.deprecated("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),navigator1.mediaDevices.getUserMedia(constraints).then(onSuccess,onError)},!(browserDetails.version>55&&"autoGainControl"in navigator1.mediaDevices.getSupportedConstraints())){var remap=function(obj,a,b){a in obj&&!(b in obj)&&(obj[b]=obj[a],delete obj[a])},nativeGetUserMedia=navigator1.mediaDevices.getUserMedia.bind(navigator1.mediaDevices);if(navigator1.mediaDevices.getUserMedia=function(c){return(void 0===c?"undefined":_typeof(c))==="object"&&"object"===_typeof(c.audio)&&(remap((c=JSON.parse(JSON.stringify(c))).audio,"autoGainControl","mozAutoGainControl"),remap(c.audio,"noiseSuppression","mozNoiseSuppression")),nativeGetUserMedia(c)},MediaStreamTrack&&MediaStreamTrack.prototype.getSettings){var nativeGetSettings=MediaStreamTrack.prototype.getSettings;MediaStreamTrack.prototype.getSettings=function(){var obj=nativeGetSettings.apply(this,arguments);return remap(obj,"mozAutoGainControl","autoGainControl"),remap(obj,"mozNoiseSuppression","noiseSuppression"),obj}}if(MediaStreamTrack&&MediaStreamTrack.prototype.applyConstraints){var nativeApplyConstraints=MediaStreamTrack.prototype.applyConstraints;MediaStreamTrack.prototype.applyConstraints=function(c){return"audio"===this.kind&&(void 0===c?"undefined":_typeof(c))==="object"&&(remap(c=JSON.parse(JSON.stringify(c)),"autoGainControl","mozAutoGainControl"),remap(c,"noiseSuppression","mozNoiseSuppression")),nativeApplyConstraints.apply(this,[c])}}}}},{"../utils":232}],231:[function(require1,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};exports.shimLocalStreamsAPI=shimLocalStreamsAPI,exports.shimRemoteStreamsAPI=shimRemoteStreamsAPI,exports.shimCallbacksAPI=shimCallbacksAPI,exports.shimGetUserMedia=shimGetUserMedia,exports.shimConstraints=shimConstraints,exports.shimRTCIceServerUrls=shimRTCIceServerUrls,exports.shimTrackEventTransceiver=shimTrackEventTransceiver,exports.shimCreateOfferLegacy=shimCreateOfferLegacy,exports.shimAudioContext=shimAudioContext;var utils=_interopRequireWildcard(require1("../utils"));function _interopRequireWildcard(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}function shimLocalStreamsAPI(window1){if((void 0===window1?"undefined":_typeof(window1))==="object"&&window1.RTCPeerConnection){if("getLocalStreams"in window1.RTCPeerConnection.prototype||(window1.RTCPeerConnection.prototype.getLocalStreams=function getLocalStreams(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in window1.RTCPeerConnection.prototype)){var _addTrack=window1.RTCPeerConnection.prototype.addTrack;window1.RTCPeerConnection.prototype.addStream=function addStream(stream){var _this=this;this._localStreams||(this._localStreams=[]),this._localStreams.includes(stream)||this._localStreams.push(stream),stream.getAudioTracks().forEach(function(track){return _addTrack.call(_this,track,stream)}),stream.getVideoTracks().forEach(function(track){return _addTrack.call(_this,track,stream)})},window1.RTCPeerConnection.prototype.addTrack=function addTrack(track){for(var _this2=this,_len=arguments.length,streams=Array(_len>1?_len-1:0),_key=1;_key<_len;_key++)streams[_key-1]=arguments[_key];return streams&&streams.forEach(function(stream){_this2._localStreams?_this2._localStreams.includes(stream)||_this2._localStreams.push(stream):_this2._localStreams=[stream]}),_addTrack.apply(this,arguments)}}"removeStream"in window1.RTCPeerConnection.prototype||(window1.RTCPeerConnection.prototype.removeStream=function removeStream(stream){var _this3=this;this._localStreams||(this._localStreams=[]);var index=this._localStreams.indexOf(stream);if(-1!==index){this._localStreams.splice(index,1);var tracks=stream.getTracks();this.getSenders().forEach(function(sender){tracks.includes(sender.track)&&_this3.removeTrack(sender)})}})}}function shimRemoteStreamsAPI(window1){if((void 0===window1?"undefined":_typeof(window1))==="object"&&window1.RTCPeerConnection&&("getRemoteStreams"in window1.RTCPeerConnection.prototype||(window1.RTCPeerConnection.prototype.getRemoteStreams=function getRemoteStreams(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in window1.RTCPeerConnection.prototype))){Object.defineProperty(window1.RTCPeerConnection.prototype,"onaddstream",{get:function get(){return this._onaddstream},set:function set(f){var _this4=this;this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=f),this.addEventListener("track",this._onaddstreampoly=function(e){e.streams.forEach(function(stream){if(_this4._remoteStreams||(_this4._remoteStreams=[]),!_this4._remoteStreams.includes(stream)){_this4._remoteStreams.push(stream);var event=new Event("addstream");event.stream=stream,_this4.dispatchEvent(event)}})})}});var origSetRemoteDescription=window1.RTCPeerConnection.prototype.setRemoteDescription;window1.RTCPeerConnection.prototype.setRemoteDescription=function setRemoteDescription(){var pc=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(e){e.streams.forEach(function(stream){if(pc._remoteStreams||(pc._remoteStreams=[]),!(pc._remoteStreams.indexOf(stream)>=0)){pc._remoteStreams.push(stream);var event=new Event("addstream");event.stream=stream,pc.dispatchEvent(event)}})}),origSetRemoteDescription.apply(pc,arguments)}}}function shimCallbacksAPI(window1){if((void 0===window1?"undefined":_typeof(window1))==="object"&&window1.RTCPeerConnection){var prototype=window1.RTCPeerConnection.prototype,origCreateOffer=prototype.createOffer,origCreateAnswer=prototype.createAnswer,setLocalDescription=prototype.setLocalDescription,setRemoteDescription=prototype.setRemoteDescription,addIceCandidate=prototype.addIceCandidate;prototype.createOffer=function createOffer(successCallback,failureCallback){var options=arguments.length>=2?arguments[2]:arguments[0],promise=origCreateOffer.apply(this,[options]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise},prototype.createAnswer=function createAnswer(successCallback,failureCallback){var options=arguments.length>=2?arguments[2]:arguments[0],promise=origCreateAnswer.apply(this,[options]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise};var withCallback=function(description,successCallback,failureCallback){var promise=setLocalDescription.apply(this,[description]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise};prototype.setLocalDescription=withCallback,withCallback=function withCallback(description,successCallback,failureCallback){var promise=setRemoteDescription.apply(this,[description]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise},prototype.setRemoteDescription=withCallback,withCallback=function withCallback(candidate,successCallback,failureCallback){var promise=addIceCandidate.apply(this,[candidate]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise},prototype.addIceCandidate=withCallback}}function shimGetUserMedia(window1){var navigator1=window1&&window1.navigator;if(navigator1.mediaDevices&&navigator1.mediaDevices.getUserMedia){var mediaDevices=navigator1.mediaDevices,_getUserMedia=mediaDevices.getUserMedia.bind(mediaDevices);navigator1.mediaDevices.getUserMedia=function(constraints){return _getUserMedia(shimConstraints(constraints))}}!navigator1.getUserMedia&&navigator1.mediaDevices&&navigator1.mediaDevices.getUserMedia&&(navigator1.getUserMedia=(function getUserMedia(constraints,cb,errcb){navigator1.mediaDevices.getUserMedia(constraints).then(cb,errcb)}).bind(navigator1))}function shimConstraints(constraints){return constraints&&void 0!==constraints.video?Object.assign({},constraints,{video:utils.compactObject(constraints.video)}):constraints}function shimRTCIceServerUrls(window1){if(window1.RTCPeerConnection){var OrigPeerConnection=window1.RTCPeerConnection;window1.RTCPeerConnection=function RTCPeerConnection(pcConfig,pcConstraints){if(pcConfig&&pcConfig.iceServers){for(var newIceServers=[],i=0;i<pcConfig.iceServers.length;i++){var server=pcConfig.iceServers[i];!server.hasOwnProperty("urls")&&server.hasOwnProperty("url")?(utils.deprecated("RTCIceServer.url","RTCIceServer.urls"),(server=JSON.parse(JSON.stringify(server))).urls=server.url,delete server.url,newIceServers.push(server)):newIceServers.push(pcConfig.iceServers[i])}pcConfig.iceServers=newIceServers}return new OrigPeerConnection(pcConfig,pcConstraints)},window1.RTCPeerConnection.prototype=OrigPeerConnection.prototype,"generateCertificate"in OrigPeerConnection&&Object.defineProperty(window1.RTCPeerConnection,"generateCertificate",{get:function get(){return OrigPeerConnection.generateCertificate}})}}function shimTrackEventTransceiver(window1){(void 0===window1?"undefined":_typeof(window1))==="object"&&window1.RTCTrackEvent&&"receiver"in window1.RTCTrackEvent.prototype&&!("transceiver"in window1.RTCTrackEvent.prototype)&&Object.defineProperty(window1.RTCTrackEvent.prototype,"transceiver",{get:function get(){return{receiver:this.receiver}}})}function shimCreateOfferLegacy(window1){var origCreateOffer=window1.RTCPeerConnection.prototype.createOffer;window1.RTCPeerConnection.prototype.createOffer=function createOffer(offerOptions){if(offerOptions){void 0!==offerOptions.offerToReceiveAudio&&(offerOptions.offerToReceiveAudio=!!offerOptions.offerToReceiveAudio);var audioTransceiver=this.getTransceivers().find(function(transceiver){return"audio"===transceiver.receiver.track.kind});!1===offerOptions.offerToReceiveAudio&&audioTransceiver?"sendrecv"===audioTransceiver.direction?audioTransceiver.setDirection?audioTransceiver.setDirection("sendonly"):audioTransceiver.direction="sendonly":"recvonly"===audioTransceiver.direction&&(audioTransceiver.setDirection?audioTransceiver.setDirection("inactive"):audioTransceiver.direction="inactive"):!0!==offerOptions.offerToReceiveAudio||audioTransceiver||this.addTransceiver("audio"),void 0!==offerOptions.offerToReceiveVideo&&(offerOptions.offerToReceiveVideo=!!offerOptions.offerToReceiveVideo);var videoTransceiver=this.getTransceivers().find(function(transceiver){return"video"===transceiver.receiver.track.kind});!1===offerOptions.offerToReceiveVideo&&videoTransceiver?"sendrecv"===videoTransceiver.direction?videoTransceiver.setDirection?videoTransceiver.setDirection("sendonly"):videoTransceiver.direction="sendonly":"recvonly"===videoTransceiver.direction&&(videoTransceiver.setDirection?videoTransceiver.setDirection("inactive"):videoTransceiver.direction="inactive"):!0!==offerOptions.offerToReceiveVideo||videoTransceiver||this.addTransceiver("video")}return origCreateOffer.apply(this,arguments)}}function shimAudioContext(window1){(void 0===window1?"undefined":_typeof(window1))!=="object"||window1.AudioContext||(window1.AudioContext=window1.webkitAudioContext)}},{"../utils":232}],232:[function(require1,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}exports.extractVersion=extractVersion,exports.wrapPeerConnectionEvent=wrapPeerConnectionEvent,exports.disableLog=disableLog,exports.disableWarnings=disableWarnings,exports.log=log,exports.deprecated=deprecated,exports.detectBrowser=detectBrowser,exports.compactObject=compactObject,exports.walkStats=walkStats,exports.filterStats=filterStats;var logDisabled_=!0,deprecationWarnings_=!0;function extractVersion(uastring,expr,pos){var match=uastring.match(expr);return match&&match.length>=pos&&parseInt(match[pos],10)}function wrapPeerConnectionEvent(window1,eventNameToWrap,wrapper){if(window1.RTCPeerConnection){var proto=window1.RTCPeerConnection.prototype,nativeAddEventListener=proto.addEventListener;proto.addEventListener=function(nativeEventName,cb){if(nativeEventName!==eventNameToWrap)return nativeAddEventListener.apply(this,arguments);var wrappedCallback=function(e){var modifiedEvent=wrapper(e);modifiedEvent&&(cb.handleEvent?cb.handleEvent(modifiedEvent):cb(modifiedEvent))};return this._eventMap=this._eventMap||{},this._eventMap[eventNameToWrap]||(this._eventMap[eventNameToWrap]=new Map),this._eventMap[eventNameToWrap].set(cb,wrappedCallback),nativeAddEventListener.apply(this,[nativeEventName,wrappedCallback])};var nativeRemoveEventListener=proto.removeEventListener;proto.removeEventListener=function(nativeEventName,cb){if(nativeEventName!==eventNameToWrap||!this._eventMap||!this._eventMap[eventNameToWrap]||!this._eventMap[eventNameToWrap].has(cb))return nativeRemoveEventListener.apply(this,arguments);var unwrappedCb=this._eventMap[eventNameToWrap].get(cb);return this._eventMap[eventNameToWrap].delete(cb),0===this._eventMap[eventNameToWrap].size&&delete this._eventMap[eventNameToWrap],0===Object.keys(this._eventMap).length&&delete this._eventMap,nativeRemoveEventListener.apply(this,[nativeEventName,unwrappedCb])},Object.defineProperty(proto,"on"+eventNameToWrap,{get:function get(){return this["_on"+eventNameToWrap]},set:function set(cb){this["_on"+eventNameToWrap]&&(this.removeEventListener(eventNameToWrap,this["_on"+eventNameToWrap]),delete this["_on"+eventNameToWrap]),cb&&this.addEventListener(eventNameToWrap,this["_on"+eventNameToWrap]=cb)},enumerable:!0,configurable:!0})}}function disableLog(bool){return"boolean"!=typeof bool?Error("Argument type: "+(void 0===bool?"undefined":_typeof(bool))+". Please use a boolean."):(logDisabled_=bool,bool?"adapter.js logging disabled":"adapter.js logging enabled")}function disableWarnings(bool){return"boolean"!=typeof bool?Error("Argument type: "+(void 0===bool?"undefined":_typeof(bool))+". Please use a boolean."):(deprecationWarnings_=!bool,"adapter.js deprecation warnings "+(bool?"disabled":"enabled"))}function log(){("undefined"==typeof window?"undefined":_typeof(window))!=="object"||logDisabled_||"undefined"==typeof console||"function"!=typeof console.log||console.log.apply(console,arguments)}function deprecated(oldMethod,newMethod){deprecationWarnings_&&console.warn(oldMethod+" is deprecated, please use "+newMethod+" instead.")}function detectBrowser(window1){var result={browser:null,version:null};if(void 0===window1||!window1.navigator)return result.browser="Not a browser.",result;var navigator1=window1.navigator;return navigator1.mozGetUserMedia?(result.browser="firefox",result.version=extractVersion(navigator1.userAgent,/Firefox\/(\d+)\./,1)):navigator1.webkitGetUserMedia||!1===window1.isSecureContext&&window1.webkitRTCPeerConnection&&!window1.RTCIceGatherer?(result.browser="chrome",result.version=extractVersion(navigator1.userAgent,/Chrom(e|ium)\/(\d+)\./,2)):navigator1.mediaDevices&&navigator1.userAgent.match(/Edge\/(\d+).(\d+)$/)?(result.browser="edge",result.version=extractVersion(navigator1.userAgent,/Edge\/(\d+).(\d+)$/,2)):window1.RTCPeerConnection&&navigator1.userAgent.match(/AppleWebKit\/(\d+)\./)?(result.browser="safari",result.version=extractVersion(navigator1.userAgent,/AppleWebKit\/(\d+)\./,1),result.supportsUnifiedPlan=window1.RTCRtpTransceiver&&"currentDirection"in window1.RTCRtpTransceiver.prototype):result.browser="Not a supported browser.",result}function isObject(val){return"[object Object]"===Object.prototype.toString.call(val)}function compactObject(data){return isObject(data)?Object.keys(data).reduce(function(accumulator,key){var isObj=isObject(data[key]),value=isObj?compactObject(data[key]):data[key],isEmptyObject=isObj&&!Object.keys(value).length;return void 0===value||isEmptyObject?accumulator:Object.assign(accumulator,_defineProperty({},key,value))},{}):data}function walkStats(stats,base,resultSet){!base||resultSet.has(base.id)||(resultSet.set(base.id,base),Object.keys(base).forEach(function(name){name.endsWith("Id")?walkStats(stats,stats.get(base[name]),resultSet):name.endsWith("Ids")&&base[name].forEach(function(id){walkStats(stats,stats.get(id),resultSet)})}))}function filterStats(result,track,outbound){var streamStatsType=outbound?"outbound-rtp":"inbound-rtp",filteredResult=new Map;if(null===track)return filteredResult;var trackStats=[];return result.forEach(function(value){"track"===value.type&&value.trackIdentifier===track.id&&trackStats.push(value)}),trackStats.forEach(function(trackStat){result.forEach(function(stats){stats.type===streamStatsType&&stats.trackId===trackStat.id&&walkStats(result,stats,filteredResult)})}),filteredResult}},{}],233:[function(require1,module,exports){module.exports=extend;var hasOwnProperty=Object.prototype.hasOwnProperty;function extend(){for(var target={},i=0;i<arguments.length;i++){var source=arguments[i];for(var key in source)hasOwnProperty.call(source,key)&&(target[key]=source[key])}return target}},{}],234:[function(require1,module,exports){"use strict";var XMPP,chatUtils=require1("./qbChatHelpers"),config=require1("../../qbConfig"),Utils=require1("../../qbUtils"),StreamManagement=require1("../../plugins/streamManagement"),unsupportedError="This function isn't supported outside of the browser (...yet)";if(Utils.getEnv().browser){var Connection=require1("../../qbStrophe");Strophe.addNamespace("CARBONS",chatUtils.MARKERS.CARBONS),Strophe.addNamespace("CHAT_MARKERS",chatUtils.MARKERS.CHAT),Strophe.addNamespace("PRIVACY_LIST",chatUtils.MARKERS.PRIVACY),Strophe.addNamespace("CHAT_STATES",chatUtils.MARKERS.STATES)}else Utils.getEnv().nativescript?XMPP=require1("nativescript-xmpp-client"):Utils.getEnv().node&&(XMPP=require1("node-xmpp-client"));function ChatProxy(service){var originSendFunction,self1=this;self1.webrtcSignalingProcessor=null,Utils.getEnv().browser?(self1.connection=Connection(),self1.connection.XHandlerReferences=[],self1.connection.XAddTrackedHandler=function(handler,ns,name,type,id,from,options){self1.connection.XHandlerReferences.push(self1.connection.addHandler(handler,ns,name,type,id,from,options))},self1.connection.XDeleteHandlers=function(){for(;self1.connection.XHandlerReferences.length;)self1.connection.deleteHandler(self1.connection.XHandlerReferences.pop())},originSendFunction=self1.connection.send,self1.connection.send=function(stanza){if(!self1.connection.connected)throw new chatUtils.ChatNotConnectedError("Chat is not connected");originSendFunction.call(self1.connection,stanza)}):(Utils.getEnv().nativescript?self1.Client=new XMPP.Client({websocket:{url:config.chatProtocol.websocket},autostart:!1}):Utils.getEnv().node&&(self1.Client=new XMPP({autostart:!1})),originSendFunction=self1.Client.send,self1.Client.send=function(stanza){Utils.QBLog("[QBChat]","SENT:",stanza.toString()),originSendFunction.call(self1.Client,stanza)},self1.nodeStanzasCallbacks={}),this.service=service,this.isConnected=!1,this._isConnecting=!1,this._isLogout=!1,this._checkConnectionTimer=void 0,this._checkConnectionPingTimer=void 0,this._chatPingFailedCounter=0,this._onlineStatus=!0,this._checkExpiredSessionTimer=void 0,this._sessionHasExpired=!1,this._pings={},this.helpers=new Helpers;var options={service:service,helpers:self1.helpers,stropheClient:self1.connection,xmppClient:self1.Client,nodeStanzasCallbacks:self1.nodeStanzasCallbacks};this.roster=new RosterProxy(options),this.privacylist=new PrivacyListProxy(options),this.muc=new MucProxy(options),this.chatUtils=chatUtils,config.streamManagement.enable&&(2===config.chatProtocol.active?(this.streamManagement=new StreamManagement(config.streamManagement),self1._sentMessageCallback=function(messageLost,messageSent){"function"==typeof self1.onSentMessageCallback&&(messageSent?self1.onSentMessageCallback(null,messageSent):self1.onSentMessageCallback(messageLost))}):Utils.QBLog("[QBChat] StreamManagement:",'BOSH protocol doesn\'t support stream management. Set WebSocket as the "chatProtocol" parameter to use this functionality. https://quickblox.com/developers/Javascript#Configuration')),this._onMessage=function(stanza){var extraParamsParsed,recipientId,recipient,jid,from=chatUtils.getAttr(stanza,"from"),type=(chatUtils.getAttr(stanza,"to"),chatUtils.getAttr(stanza,"type")),messageId=chatUtils.getAttr(stanza,"id"),markable=chatUtils.getElement(stanza,"markable"),delivered=chatUtils.getElement(stanza,"received"),read=chatUtils.getElement(stanza,"displayed"),composing=chatUtils.getElement(stanza,"composing"),paused=chatUtils.getElement(stanza,"paused"),invite=chatUtils.getElement(stanza,"invite"),delay=chatUtils.getElement(stanza,"delay"),extraParams=chatUtils.getElement(stanza,"extraParams"),bodyContent=chatUtils.getElementText(stanza,"body"),forwarded=chatUtils.getElement(stanza,"forwarded");if(Utils.getEnv().browser)recipient=stanza.querySelector("forwarded")?stanza.querySelector("forwarded").querySelector("message").getAttribute("to"):null,jid=self1.connection.jid;else{var forwardedMessage=forwarded?chatUtils.getElement(forwarded,"message"):null;recipient=forwardedMessage?chatUtils.getAttr(forwardedMessage,"to"):null,jid=self1.Client.options.jid.user}recipientId=recipient?self1.helpers.getIdFromNode(recipient):null;var dialogId="groupchat"===type?self1.helpers.getDialogIdFromNode(from):null,userId="groupchat"===type?self1.helpers.getIdFromResource(from):self1.helpers.getIdFromNode(from),marker=delivered||read||null;if(invite)return!0;if(extraParams&&(extraParamsParsed=chatUtils.parseExtraParams(extraParams)).dialogId&&(dialogId=extraParamsParsed.dialogId),composing||paused)return"function"!=typeof self1.onMessageTypingListener||"chat"!==type&&"groupchat"!==type&&delay||Utils.safeCallbackCall(self1.onMessageTypingListener,!!composing,userId,dialogId),!0;if(marker)return delivered?"function"==typeof self1.onDeliveredStatusListener&&"chat"===type&&Utils.safeCallbackCall(self1.onDeliveredStatusListener,chatUtils.getAttr(delivered,"id"),dialogId,userId):"function"==typeof self1.onReadStatusListener&&"chat"===type&&Utils.safeCallbackCall(self1.onReadStatusListener,chatUtils.getAttr(read,"id"),dialogId,userId),!0;if(markable&&userId!=self1.helpers.getIdFromNode(jid)){var autoSendReceiveStatusParams={messageId:messageId,userId:userId,dialogId:dialogId};self1.sendDeliveredStatus(autoSendReceiveStatusParams)}var message={id:messageId,dialog_id:dialogId,recipient_id:recipientId,type:type,body:bodyContent,extension:extraParamsParsed?extraParamsParsed.extension:null,delay:delay};return markable&&(message.markable=1),"function"==typeof self1.onMessageListener&&("chat"===type||"groupchat"===type)&&Utils.safeCallbackCall(self1.onMessageListener,userId,message),!0},this._onPresence=function(stanza){var xXMLNS,status,statusCode,dialogId,userId,from=chatUtils.getAttr(stanza,"from"),id=(chatUtils.getAttr(stanza,"to"),chatUtils.getAttr(stanza,"id")),type=chatUtils.getAttr(stanza,"type"),currentUserId=self1.helpers.getIdFromNode(self1.helpers.userCurrentJid(Utils.getEnv().browser?self1.connection:self1.Client)),x=chatUtils.getElement(stanza,"x");if(x&&(xXMLNS=chatUtils.getAttr(x,"xmlns"),(status=chatUtils.getElement(x,"status"))&&(statusCode=chatUtils.getAttr(status,"code"))),xXMLNS&&"http://jabber.org/protocol/muc#user"==xXMLNS){if(dialogId=self1.helpers.getDialogIdFromNode(from),userId=self1.helpers.getUserIdFromRoomJid(from),status&&"301"==statusCode){if("function"==typeof self1.onKickOccupant){var actorElement=chatUtils.getElement(chatUtils.getElement(x,"item"),"actor"),initiatorUserJid=chatUtils.getAttr(actorElement,"jid");Utils.safeCallbackCall(self1.onKickOccupant,dialogId,self1.helpers.getIdFromNode(initiatorUserJid))}return delete self1.muc.joinedRooms[self1.helpers.getRoomJidFromRoomFullJid(from)],!0}if(!status&&userId!=currentUserId)return type&&"unavailable"===type?"function"==typeof self1.onLeaveOccupant&&Utils.safeCallbackCall(self1.onLeaveOccupant,dialogId,parseInt(userId)):"function"==typeof self1.onJoinOccupant&&Utils.safeCallbackCall(self1.onJoinOccupant,dialogId,parseInt(userId)),!0}if(!Utils.getEnv().browser&&xXMLNS){if("http://jabber.org/protocol/muc#user"==xXMLNS){if(type&&"unavailable"===type)return status&&"110"==statusCode&&"function"==typeof self1.nodeStanzasCallbacks["muc:leave"]&&Utils.safeCallbackCall(self1.nodeStanzasCallbacks["muc:leave"],null),!0;if(id.endsWith(":join")&&status&&"110"==statusCode)return"function"==typeof self1.nodeStanzasCallbacks[id]&&self1.nodeStanzasCallbacks[id](stanza),!0}else if(type&&"error"===type&&"http://jabber.org/protocol/muc"==xXMLNS)return id.endsWith(":join")&&"function"==typeof self1.nodeStanzasCallbacks[id]&&self1.nodeStanzasCallbacks[id](stanza),!0}if(userId=self1.helpers.getIdFromNode(from),type)switch(type){case"subscribe":self1.roster.contacts[userId]&&"to"===self1.roster.contacts[userId].subscription?(self1.roster.contacts[userId]={subscription:"both",ask:null},self1.roster._sendSubscriptionPresence({jid:from,type:"subscribed"})):"function"==typeof self1.onSubscribeListener&&Utils.safeCallbackCall(self1.onSubscribeListener,userId);break;case"subscribed":self1.roster.contacts[userId]&&"from"===self1.roster.contacts[userId].subscription?self1.roster.contacts[userId]={subscription:"both",ask:null}:(self1.roster.contacts[userId]={subscription:"to",ask:null},"function"==typeof self1.onConfirmSubscribeListener&&Utils.safeCallbackCall(self1.onConfirmSubscribeListener,userId));break;case"unsubscribed":self1.roster.contacts[userId]={subscription:"none",ask:null},"function"==typeof self1.onRejectSubscribeListener&&Utils.safeCallbackCall(self1.onRejectSubscribeListener,userId);break;case"unsubscribe":self1.roster.contacts[userId]={subscription:"to",ask:null};break;case"unavailable":"function"==typeof self1.onContactListListener&&self1.roster.contacts[userId]&&"none"!==self1.roster.contacts[userId].subscription&&Utils.safeCallbackCall(self1.onContactListListener,userId,type),userId===currentUserId&&(Utils.getEnv().browser?self1.connection.send($pres()):self1.Client.send(chatUtils.createStanza(XMPP.Stanza,null,"presence")))}else"function"==typeof self1.onContactListListener&&self1.roster.contacts[userId]&&"none"!==self1.roster.contacts[userId].subscription&&Utils.safeCallbackCall(self1.onContactListListener,userId);return!0},this._onIQ=function(stanza){var stanzaId=chatUtils.getAttr(stanza,"id"),isLastActivity=stanzaId.indexOf("lastActivity")>-1,isPong=stanzaId.indexOf("ping")>-1,ping=chatUtils.getElement(stanza,"ping"),type=chatUtils.getAttr(stanza,"type"),from=chatUtils.getAttr(stanza,"from"),userId=from?self1.helpers.getIdFromNode(from):null;if("function"==typeof self1.onLastUserActivityListener&&isLastActivity){var query=chatUtils.getElement(stanza,"query"),seconds=chatUtils.getElement(stanza,"error")?void 0:+chatUtils.getAttr(query,"seconds");Utils.safeCallbackCall(self1.onLastUserActivityListener,userId,seconds)}if((ping||isPong)&&type){if("get"===type&&ping&&self1.isConnected){var builder=Utils.getEnv().browser?$iq:XMPP.Stanza,pongParams={from:self1.helpers.getUserCurrentJid(),id:stanzaId,to:from,type:"result"},pongStanza=chatUtils.createStanza(builder,pongParams,"iq");Utils.getEnv().browser?self1.connection.send(pongStanza):self1.Client.send(pongStanza)}else{var pingRequest=self1._pings[stanzaId];pingRequest&&(pingRequest.callback&&pingRequest.callback(null),pingRequest.interval&&clearInterval(pingRequest.interval),self1._pings[stanzaId]=void 0,delete self1._pings[stanzaId])}}return!Utils.getEnv().browser&&self1.nodeStanzasCallbacks[stanzaId]&&(Utils.safeCallbackCall(self1.nodeStanzasCallbacks[stanzaId],stanza),delete self1.nodeStanzasCallbacks[stanzaId]),!0},this._onSystemMessageListener=function(stanza){var message,from=chatUtils.getAttr(stanza,"from"),messageId=(chatUtils.getAttr(stanza,"to"),chatUtils.getAttr(stanza,"id")),extraParams=chatUtils.getElement(stanza,"extraParams"),userId=self1.helpers.getIdFromNode(from),delay=chatUtils.getElement(stanza,"delay"),moduleIdentifier=chatUtils.getElementText(extraParams,"moduleIdentifier"),bodyContent=chatUtils.getElementText(stanza,"body"),extraParamsParsed=chatUtils.parseExtraParams(extraParams);return"SystemNotifications"===moduleIdentifier&&"function"==typeof self1.onSystemMessageListener?(message={id:messageId,userId:userId,body:bodyContent,extension:extraParamsParsed.extension},Utils.safeCallbackCall(self1.onSystemMessageListener,message)):self1.webrtcSignalingProcessor&&!delay&&"WebRTCVideoChat"===moduleIdentifier&&self1.webrtcSignalingProcessor._onMessage(from,extraParams,delay,userId,extraParamsParsed.extension),!0},this._onMessageErrorListener=function(stanza){var messageId=chatUtils.getAttr(stanza,"id"),error=chatUtils.getErrorFromXMLNode(stanza);return"function"==typeof self1.onMessageErrorListener&&Utils.safeCallbackCall(self1.onMessageErrorListener,messageId,error),!0}}function RosterProxy(options){this.service=options.service,this.helpers=options.helpers,this.connection=options.stropheClient,this.Client=options.xmppClient,this.nodeStanzasCallbacks=options.nodeStanzasCallbacks,this.contacts={}}function MucProxy(options){this.service=options.service,this.helpers=options.helpers,this.connection=options.stropheClient,this.Client=options.xmppClient,this.nodeStanzasCallbacks=options.nodeStanzasCallbacks,this.joinedRooms={}}function PrivacyListProxy(options){this.service=options.service,this.helpers=options.helpers,this.connection=options.stropheClient,this.Client=options.xmppClient,this.nodeStanzasCallbacks=options.nodeStanzasCallbacks}function Helpers(){this._userCurrentJid=""}ChatProxy.prototype={connect:function(params,callback){Utils.QBLog("[QBChat]","Connect with parameters "+JSON.stringify(params));var err,self1=this,userJid=chatUtils.buildUserJid(params),isInitialConnect="function"==typeof callback;if(self1._isConnecting){err=Utils.getError(422,"Status.REJECT - The connection is still in the Status.CONNECTING state","QBChat"),isInitialConnect&&callback(err,null);return}if(self1.isConnected){Utils.QBLog("[QBChat]","Status.CONNECTED - You are already connected"),isInitialConnect&&callback(null,self1.roster.contacts);return}self1._isConnecting=!0,self1._isLogout=!1,Utils.getEnv().browser&&(Utils.QBLog("[QBChat]","!!---Browser env - connected--!!"),self1.connection.connect(userJid,params.password,function(status){switch(Utils.QBLog("[QBChat]","self.connection.connect called with status "+status),status){case Strophe.Status.ERROR:self1.isConnected=!1,self1._isConnecting=!1,err=Utils.getError(422,"Status.ERROR - An error has occurred","QBChat"),isInitialConnect&&callback(err,null);break;case Strophe.Status.CONNFAIL:self1.isConnected=!1,self1._isConnecting=!1,err=Utils.getError(422,"Status.CONNFAIL - The connection attempt failed","QBChat"),isInitialConnect&&callback(err,null);break;case Strophe.Status.AUTHENTICATING:Utils.QBLog("[QBChat]","Status.AUTHENTICATING");break;case Strophe.Status.AUTHFAIL:self1.isConnected=!1,self1._isConnecting=!1,err=Utils.getError(401,"Status.AUTHFAIL - The authentication attempt failed","QBChat"),isInitialConnect&&callback(err,null),self1.isConnected||"function"!=typeof self1.onReconnectFailedListener||Utils.safeCallbackCall(self1.onReconnectFailedListener,err);break;case Strophe.Status.CONNECTING:Utils.QBLog("[QBChat]","Status.CONNECTING","(Chat Protocol - "+(1===config.chatProtocol.active?"BOSH":"WebSocket)"));break;case Strophe.Status.CONNECTED:self1.connection.XDeleteHandlers(),self1.connection.XAddTrackedHandler(self1._onMessage,null,"message","chat"),self1.connection.XAddTrackedHandler(self1._onMessage,null,"message","groupchat"),self1.connection.XAddTrackedHandler(self1._onPresence,null,"presence"),self1.connection.XAddTrackedHandler(self1._onIQ,null,"iq"),self1.connection.XAddTrackedHandler(self1._onSystemMessageListener,null,"message","headline"),self1.connection.XAddTrackedHandler(self1._onMessageErrorListener,null,"message","error");var noTimerId=void 0===self1._checkConnectionPingTimer;(noTimerId=0!==config.pingLocalhostTimeInterval&&noTimerId)&&(Utils.QBLog("[QBChat]","Init ping to chat at ",Utils.getCurrentTime()),self1._checkConnectionPingTimer=setInterval(function(){try{self1.pingchat(function(error){error?(Utils.QBLog("[QBChat]","Chat Ping: ","failed, at ",Utils.getCurrentTime(),"_chatPingFailedCounter: ",self1._chatPingFailedCounter," error: ",error),self1._chatPingFailedCounter+=1,self1._chatPingFailedCounter>6&&(self1.isConnected=!1,self1._isConnecting=!1,self1._chatPingFailedCounter=0,self1._establishConnection(params))):(Utils.QBLog("[QBChat]","Chat Ping: ","ok, at ",Utils.getCurrentTime(),"_chatPingFailedCounter: ",self1._chatPingFailedCounter),self1._chatPingFailedCounter=0)})}catch(err){Utils.QBLog("[QBChat]","Chat Ping: ","Exception, at ",Utils.getCurrentTime(),", detail info: ",err)}},1e3*config.pingLocalhostTimeInterval)),"function"==typeof self1.onSessionExpiredListener&&void 0===self1._checkExpiredSessionTimer&&(Utils.QBLog("[QBChat]","Init timer for check session expired at ",new Date().toTimeString().split(" ")[0]),self1._checkExpiredSessionTimer=setInterval(function(){var timeNow=new Date;void 0!==config.qbTokenExpirationDate&&Math.round((timeNow.getTime()-config.qbTokenExpirationDate.getTime())/6e4)>=0&&(self1._sessionHasExpired=!0,Utils.safeCallbackCall(self1.onSessionExpiredListener,null))},5e3)),self1._postConnectActions(function(roster){callback(null,roster)},isInitialConnect);break;case Strophe.Status.DISCONNECTING:Utils.QBLog("[QBChat]","Status.DISCONNECTING");break;case Strophe.Status.DISCONNECTED:Utils.QBLog("[QBChat]","Status.DISCONNECTED at "+chatUtils.getLocalTime()),self1.isConnected&&"function"==typeof self1.onDisconnectedListener&&Utils.safeCallbackCall(self1.onDisconnectedListener),self1.isConnected=!1,self1._isConnecting=!1,self1.connection.reset(),self1._establishConnection(params);break;case Strophe.Status.ATTACHED:Utils.QBLog("[QBChat]","Status.ATTACHED")}})),Utils.getEnv().browser||(Utils.QBLog("[QBChat]","!!--call branch code connect for node--!!"),self1.Client.removeAllListeners(),self1.Client.on("connect",function(){Utils.QBLog("[QBChat]","Status.CONNECTING","(Chat Protocol - "+(1===config.chatProtocol.active?"BOSH":"WebSocket)"))}),self1.Client.on("auth",function(){Utils.QBLog("[QBChat]","Status.AUTHENTICATING")}),self1.Client.on("online",function(){self1._postConnectActions(function(roster){callback(null,roster)},isInitialConnect)}),self1.Client.on("stanza",function(stanza){Utils.QBLog("[QBChat] RECV:",stanza.toString()),stanza.is("presence")?self1._onPresence(stanza):stanza.is("iq")?self1._onIQ(stanza):stanza.is("message")&&("headline"===stanza.attrs.type?self1._onSystemMessageListener(stanza):"error"===stanza.attrs.type?self1._onMessageErrorListener(stanza):self1._onMessage(stanza))}),self1.Client.on("disconnect",function(){Utils.QBLog("[QBChat]","Status.DISCONNECTED - "+chatUtils.getLocalTime()),"function"==typeof self1.onDisconnectedListener&&Utils.safeCallbackCall(self1.onDisconnectedListener),self1.isConnected=!1,self1._isConnecting=!1,self1._establishConnection(params)}),self1.Client.on("error",function(){Utils.QBLog("[QBChat]","Status.ERROR - "+chatUtils.getLocalTime()),err=Utils.getError(422,"Status.ERROR - An error has occurred","QBChat"),isInitialConnect&&callback(err,null),self1.isConnected=!1,self1._isConnecting=!1}),self1.Client.on("end",function(){self1.Client.removeAllListeners()}),self1.Client.options.jid=userJid,self1.Client.options.password=params.password,self1.Client.connect())},_postConnectActions:function(callback,isInitialConnect){Utils.QBLog("[QBChat]","Status.CONNECTED at "+chatUtils.getLocalTime());var self1=this,isBrowser=Utils.getEnv().browser,xmppClient=isBrowser?self1.connection:self1.Client,presence=isBrowser?$pres():chatUtils.createStanza(XMPP.Stanza,null,"presence");if(config.streamManagement.enable&&2===config.chatProtocol.active&&(self1.streamManagement.enable(self1.connection,null),self1.streamManagement.sentMessageCallback=self1._sentMessageCallback),self1.helpers.setUserCurrentJid(self1.helpers.userCurrentJid(xmppClient)),self1.isConnected=!0,self1._isConnecting=!1,self1._sessionHasExpired=!1,self1._enableCarbons(),isInitialConnect)self1.roster.get(function(contacts){xmppClient.send(presence),self1.roster.contacts=contacts,callback(self1.roster.contacts)});else{var rooms=Object.keys(self1.muc.joinedRooms);xmppClient.send(presence),Utils.QBLog("[QBChat]","Re-joining "+rooms.length+" rooms...");for(var i=0,len=rooms.length;i<len;i++)self1.muc.join(rooms[i]);"function"==typeof self1.onReconnectListener&&Utils.safeCallbackCall(self1.onReconnectListener)}},_establishConnection:function(params){var self1=this;if(Utils.QBLog("[QBChat]","_establishConnection called"),self1._isLogout||self1._checkConnectionTimer){Utils.QBLog("[QBChat]","_establishConnection return");return}var _connect=function(){Utils.QBLog("[QBChat]","call _connect() in _establishConnection "),self1.isConnected||self1._isConnecting||self1._sessionHasExpired?(Utils.QBLog("[QBChat]","stop timer in _establishConnection "),clearInterval(self1._checkConnectionTimer),self1._checkConnectionTimer=void 0):(Utils.QBLog("[QBChat]","call connect() again in _establishConnection "),self1.connect(params))};_connect(),self1._checkConnectionTimer=setInterval(function(){Utils.QBLog("[QBChat]","self._checkConnectionTimer called with config.chatReconnectionTimeInterval = "+config.chatReconnectionTimeInterval),_connect()},1e3*config.chatReconnectionTimeInterval)},reconnect:function(){Utils.QBLog("[QBChat]","Call reconnect "),clearInterval(this._checkConnectionTimer),this._checkConnectionTimer=void 0,this.muc.joinedRooms={},this.helpers.setUserCurrentJid(""),Utils.getEnv().browser?(this.connection.flush(),this.connection.disconnect()):this.Client.end()},send:function(jid_or_user_id,message){Utils.QBLog("[QBChat]","Call send "+JSON.stringify(message));var builder=Utils.getEnv().browser?$msg:XMPP.Stanza,paramsCreateMsg={from:this.helpers.getUserCurrentJid(),to:this.helpers.jidOrUserId(jid_or_user_id),type:message.type?message.type:"chat",id:message.id?message.id:Utils.getBsonObjectId()},stanza=chatUtils.createStanza(builder,paramsCreateMsg);return message.body&&stanza.c("body",{xmlns:chatUtils.MARKERS.CLIENT}).t(message.body).up(),message.markable&&stanza.c("markable",{xmlns:chatUtils.MARKERS.CHAT}).up(),message.extension&&(stanza.c("extraParams",{xmlns:chatUtils.MARKERS.CLIENT}),stanza=chatUtils.filledExtraParams(stanza,message.extension)),Utils.getEnv().browser?config.streamManagement.enable?(message.id=paramsCreateMsg.id,message.jid_or_user_id=jid_or_user_id,this.connection.send(stanza,message)):this.connection.send(stanza):config.streamManagement.enable?(message.id=paramsCreateMsg.id,message.jid_or_user_id=jid_or_user_id,this.Client.send(stanza,message)):this.Client.send(stanza),paramsCreateMsg.id},sendSystemMessage:function(jid_or_user_id,message){Utils.QBLog("[QBChat]","Call sendSystemMessage "+JSON.stringify(message));var builder=Utils.getEnv().browser?$msg:XMPP.Stanza,paramsCreateMsg={type:"headline",id:message.id?message.id:Utils.getBsonObjectId(),to:this.helpers.jidOrUserId(jid_or_user_id)},stanza=chatUtils.createStanza(builder,paramsCreateMsg);return message.body&&stanza.c("body",{xmlns:chatUtils.MARKERS.CLIENT}).t(message.body).up(),Utils.getEnv().browser?(message.extension&&(stanza.c("extraParams",{xmlns:chatUtils.MARKERS.CLIENT}).c("moduleIdentifier").t("SystemNotifications").up(),stanza=chatUtils.filledExtraParams(stanza,message.extension)),this.connection.send(stanza)):(message.extension&&(stanza.c("extraParams",{xmlns:chatUtils.MARKERS.CLIENT}).c("moduleIdentifier").t("SystemNotifications"),stanza=chatUtils.filledExtraParams(stanza,message.extension)),this.Client.send(stanza)),paramsCreateMsg.id},sendIsTypingStatus:function(jid_or_user_id){Utils.QBLog("[QBChat]","Call sendIsTypingStatus ");var stanzaParams={from:this.helpers.getUserCurrentJid(),to:this.helpers.jidOrUserId(jid_or_user_id),type:this.helpers.typeChat(jid_or_user_id)},builder=Utils.getEnv().browser?$msg:XMPP.Stanza,stanza=chatUtils.createStanza(builder,stanzaParams);stanza.c("composing",{xmlns:chatUtils.MARKERS.STATES}),Utils.getEnv().browser?this.connection.send(stanza):this.Client.send(stanza)},sendIsStopTypingStatus:function(jid_or_user_id){Utils.QBLog("[QBChat]","Call sendIsStopTypingStatus ");var stanzaParams={from:this.helpers.getUserCurrentJid(),to:this.helpers.jidOrUserId(jid_or_user_id),type:this.helpers.typeChat(jid_or_user_id)},builder=Utils.getEnv().browser?$msg:XMPP.Stanza,stanza=chatUtils.createStanza(builder,stanzaParams);stanza.c("paused",{xmlns:chatUtils.MARKERS.STATES}),Utils.getEnv().browser?this.connection.send(stanza):this.Client.send(stanza)},sendDeliveredStatus:function(params){Utils.QBLog("[QBChat]","Call sendDeliveredStatus ");var stanzaParams={type:"chat",from:this.helpers.getUserCurrentJid(),id:Utils.getBsonObjectId(),to:this.helpers.jidOrUserId(params.userId)},builder=Utils.getEnv().browser?$msg:XMPP.Stanza,stanza=chatUtils.createStanza(builder,stanzaParams);stanza.c("received",{xmlns:chatUtils.MARKERS.MARKERS,id:params.messageId}).up(),stanza.c("extraParams",{xmlns:chatUtils.MARKERS.CLIENT}).c("dialog_id").t(params.dialogId),Utils.getEnv().browser?this.connection.send(stanza):this.Client.send(stanza)},sendReadStatus:function(params){Utils.QBLog("[QBChat]","Call sendReadStatus "+JSON.stringify(params));var stanzaParams={type:"chat",from:this.helpers.getUserCurrentJid(),to:this.helpers.jidOrUserId(params.userId),id:Utils.getBsonObjectId()},builder=Utils.getEnv().browser?$msg:XMPP.Stanza,stanza=chatUtils.createStanza(builder,stanzaParams);stanza.c("displayed",{xmlns:chatUtils.MARKERS.MARKERS,id:params.messageId}).up(),stanza.c("extraParams",{xmlns:chatUtils.MARKERS.CLIENT}).c("dialog_id").t(params.dialogId),Utils.getEnv().browser?this.connection.send(stanza):this.Client.send(stanza)},getLastUserActivity:function(jid_or_user_id){var iqParams,builder,iq;Utils.QBLog("[QBChat]","Call getLastUserActivity "),iqParams={from:this.helpers.getUserCurrentJid(),id:this.helpers.getUniqueId("lastActivity"),to:this.helpers.jidOrUserId(jid_or_user_id),type:"get"},builder=Utils.getEnv().browser?$iq:XMPP.Stanza,(iq=chatUtils.createStanza(builder,iqParams,"iq")).c("query",{xmlns:chatUtils.MARKERS.LAST}),Utils.getEnv().browser?this.connection.sendIQ(iq):this.Client.send(iq)},pingchat:function(callback){Utils.QBLog("[QBChat]","ping chat");var to,stanza,self1=this,id=this.helpers.getUniqueId("ping"),builder=Utils.getEnv().browser?$iq:XMPP.Stanza;to=config.endpoints.chat?config.endpoints.chat:"chat.quickblox.com";var iqParams={from:this.helpers.getUserCurrentJid(),id:id,to:to,type:"get"};return(stanza=chatUtils.createStanza(builder,iqParams,"iq")).c("ping",{xmlns:"urn:xmpp:ping"}),Utils.getEnv().browser?this.connection.send(stanza):this.Client.send(stanza),this._pings[id]={callback:callback,interval:setTimeout(function(){callback("Chat ping No answer"),self1._pings[id]=void 0,delete self1._pings[id]},1e3*config.pingTimeout)},id},ping:function(jid_or_user_id,callback){Utils.QBLog("[QBChat]","Call ping ");var to,_callback,stanza,self1=this,id=this.helpers.getUniqueId("ping"),builder=Utils.getEnv().browser?$iq:XMPP.Stanza;if(("string"==typeof jid_or_user_id||"number"==typeof jid_or_user_id)&&"function"==typeof callback)to=this.helpers.jidOrUserId(jid_or_user_id),_callback=callback;else{if("function"!=typeof jid_or_user_id||callback)throw Error("Invalid arguments provided. Either userId/jid (number/string) and callback or only callback should be provided.");to=config.endpoints.chat,_callback=jid_or_user_id}var iqParams={from:this.helpers.getUserCurrentJid(),id:id,to:to,type:"get"};return(stanza=chatUtils.createStanza(builder,iqParams,"iq")).c("ping",{xmlns:"urn:xmpp:ping"}),Utils.getEnv().browser?this.connection.send(stanza):this.Client.send(stanza),this._pings[id]={callback:_callback,interval:setTimeout(function(){_callback("No answer"),self1._pings[id]=void 0,delete self1._pings[id]},1e3*config.pingTimeout)},id},disconnect:function(){Utils.QBLog("[QBChat]","Call disconnect "),clearInterval(this._checkConnectionTimer),clearInterval(this._checkExpiredSessionTimer),this._checkConnectionTimer=void 0,this._checkExpiredSessionTimer=void 0,this.muc.joinedRooms={},this._isLogout=!0,this.helpers.setUserCurrentJid(""),Utils.getEnv().browser?(this.connection.flush(),this.connection.disconnect(),void 0!==this._checkConnectionPingTimer&&(Utils.QBLog("[QBChat]","Stop ping"),clearInterval(this._checkConnectionPingTimer),this._checkConnectionPingTimer=void 0)):this.Client.end()},addListener:function(params,callback){if(Utils.QBLog("[Deprecated!]","Avoid using it, this feature will be removed in future version."),!Utils.getEnv().browser)throw Error(unsupportedError);return this.connection.XAddTrackedHandler(handler,null,params.name||null,params.type||null,params.id||null,params.from||null);function handler(){return callback(),!1!==params.live}},deleteListener:function(ref){if(Utils.QBLog("[Deprecated!]","Avoid using it, this feature will be removed in future version."),!Utils.getEnv().browser)throw Error(unsupportedError);this.connection.deleteHandler(ref)},_enableCarbons:function(cb){var carbonParams={type:"set",from:this.helpers.getUserCurrentJid(),id:chatUtils.getUniqueId("enableCarbons")},builder=Utils.getEnv().browser?$iq:XMPP.Stanza,iq=chatUtils.createStanza(builder,carbonParams,"iq");iq.c("enable",{xmlns:chatUtils.MARKERS.CARBONS}),Utils.getEnv().browser?this.connection.sendIQ(iq):this.Client.send(iq)}},RosterProxy.prototype={get:function(callback){var self1=this,contacts={},iqParams={type:"get",from:self1.helpers.getUserCurrentJid(),id:chatUtils.getUniqueId("getRoster")},builder=Utils.getEnv().browser?$iq:XMPP.Stanza,iq=chatUtils.createStanza(builder,iqParams,"iq");function _getItems(stanza){return Utils.getEnv().browser?stanza.getElementsByTagName("item"):stanza.getChild("query").children}function _callbackWrap(stanza){for(var items=_getItems(stanza),i=0,len=items.length;i<len;i++){var userId=self1.helpers.getIdFromNode(chatUtils.getAttr(items[i],"jid")),ask=chatUtils.getAttr(items[i],"ask"),subscription=chatUtils.getAttr(items[i],"subscription");contacts[userId]={subscription:subscription,ask:ask||null}}callback(contacts)}iq.c("query",{xmlns:chatUtils.MARKERS.ROSTER}),Utils.getEnv().browser?self1.connection.sendIQ(iq,_callbackWrap):(self1.nodeStanzasCallbacks[iqParams.id]=_callbackWrap,self1.Client.send(iq))},add:function(jidOrUserId,callback){var userJid=this.helpers.jidOrUserId(jidOrUserId),userId=this.helpers.getIdFromNode(userJid).toString();this.contacts[userId]={subscription:"none",ask:"subscribe"},this._sendSubscriptionPresence({jid:userJid,type:"subscribe"}),"function"==typeof callback&&callback()},confirm:function(jidOrUserId,callback){var userJid=this.helpers.jidOrUserId(jidOrUserId),userId=this.helpers.getIdFromNode(userJid).toString();this.contacts[userId]={subscription:"from",ask:"subscribe"},this._sendSubscriptionPresence({jid:userJid,type:"subscribed"}),this._sendSubscriptionPresence({jid:userJid,type:"subscribe"}),"function"==typeof callback&&callback()},reject:function(jidOrUserId,callback){var userJid=this.helpers.jidOrUserId(jidOrUserId),userId=this.helpers.getIdFromNode(userJid).toString();this.contacts[userId]={subscription:"none",ask:null},this._sendSubscriptionPresence({jid:userJid,type:"unsubscribed"}),"function"==typeof callback&&callback()},remove:function(jidOrUserId,callback){var self1=this,userJid=this.helpers.jidOrUserId(jidOrUserId),userId=this.helpers.getIdFromNode(userJid),iqParams={type:"set",from:self1.connection?self1.connection.jid:self1.Client.jid.user,id:chatUtils.getUniqueId("getRoster")},builder=Utils.getEnv().browser?$iq:XMPP.Stanza,iq=chatUtils.createStanza(builder,iqParams,"iq");function _callbackWrap(){delete self1.contacts[userId],"function"==typeof callback&&callback()}iq.c("query",{xmlns:chatUtils.MARKERS.ROSTER}).c("item",{jid:userJid,subscription:"remove"}),Utils.getEnv().browser?self1.connection.sendIQ(iq,_callbackWrap):(self1.nodeStanzasCallbacks[iqParams.id]=_callbackWrap,self1.Client.send(iq))},_sendSubscriptionPresence:function(params){var builder=Utils.getEnv().browser?$pres:XMPP.Stanza,presParams={to:params.jid,type:params.type},pres=chatUtils.createStanza(builder,presParams,"presence");Utils.getEnv().browser?this.connection.send(pres):this.Client.send(pres)}},MucProxy.prototype={join:function(dialogIdOrJid,callback){var self1=this,id=chatUtils.getUniqueId("join"),dialogJid=this.helpers.getDialogJid(dialogIdOrJid),presParams={id:id,from:self1.helpers.getUserCurrentJid(),to:self1.helpers.getRoomJid(dialogJid)},builder=Utils.getEnv().browser?$pres:XMPP.Stanza,pres=chatUtils.createStanza(builder,presParams,"presence");function handleJoinAnswer(stanza){var id=chatUtils.getAttr(stanza,"id"),from=chatUtils.getAttr(stanza,"from"),dialogId=self1.helpers.getDialogIdFromNode(from),x=chatUtils.getElement(stanza,"x"),xXMLNS=chatUtils.getAttr(x,"xmlns"),status=chatUtils.getElement(x,"status"),statusCode=chatUtils.getAttr(status,"code");if(1==callback.length)return Utils.safeCallbackCall(callback,stanza),!0;if(status&&"110"==statusCode)Utils.safeCallbackCall(callback,null,{dialogId:dialogId});else{var type=chatUtils.getAttr(stanza,"type");if(type&&"error"===type&&"http://jabber.org/protocol/muc"==xXMLNS&&id.endsWith(":join")){var errorEl=chatUtils.getElement(stanza,"error"),code=chatUtils.getAttr(errorEl,"code"),errorMessage=chatUtils.getElementText(errorEl,"text");Utils.safeCallbackCall(callback,{code:code||500,message:errorMessage||"Unknown issue"},{dialogId:dialogId})}}}pres.c("x",{xmlns:chatUtils.MARKERS.MUC}).c("history",{maxstanzas:0}),this.joinedRooms[dialogJid]=!0,Utils.getEnv().browser?("function"==typeof callback&&self1.connection.XAddTrackedHandler(handleJoinAnswer,null,"presence",null,id),self1.connection.send(pres)):("function"==typeof callback&&(self1.nodeStanzasCallbacks[id]=handleJoinAnswer),self1.Client.send(pres))},leave:function(jid,callback){var self1=this,presParams={type:"unavailable",from:self1.helpers.getUserCurrentJid(),to:self1.helpers.getRoomJid(jid)},builder=Utils.getEnv().browser?$pres:XMPP.Stanza,pres=chatUtils.createStanza(builder,presParams,"presence");function handleLeaveAnswer(stanza){var id=chatUtils.getAttr(stanza,"id"),from=chatUtils.getAttr(stanza,"from"),dialogId=self1.helpers.getDialogIdFromNode(from),x=chatUtils.getElement(stanza,"x"),xXMLNS=chatUtils.getAttr(x,"xmlns"),status=chatUtils.getElement(x,"status"),statusCode=chatUtils.getAttr(status,"code");if(status&&"110"==statusCode)Utils.safeCallbackCall(callback,null,{dialogId:dialogId});else{var type=chatUtils.getAttr(stanza,"type");if(type&&"error"===type&&"http://jabber.org/protocol/muc"==xXMLNS&&id.endsWith(":join")){var errorEl=chatUtils.getElement(stanza,"error"),code=chatUtils.getAttr(errorEl,"code"),errorMessage=chatUtils.getElementText(errorEl,"text");Utils.safeCallbackCall(callback,{code:code||500,message:errorMessage||"Unknown issue"},{dialogId:dialogId})}}}if(delete this.joinedRooms[jid],Utils.getEnv().browser){var roomJid=self1.helpers.getRoomJid(jid);"function"==typeof callback&&self1.connection.XAddTrackedHandler(handleLeaveAnswer,null,"presence",presParams.type,null,roomJid),self1.connection.send(pres)}else"function"==typeof callback&&(self1.nodeStanzasCallbacks["muc:leave"]=handleLeaveAnswer),self1.Client.send(pres)},listOnlineUsers:function(dialogJID,callback){var self1=this,onlineUsers=[],iqParams={type:"get",to:dialogJID,from:self1.helpers.getUserCurrentJid(),id:chatUtils.getUniqueId("muc_disco_items")},builder=Utils.getEnv().browser?$iq:XMPP.Stanza,iq=chatUtils.createStanza(builder,iqParams,"iq");function _getUsers(stanza){var stanzaId=stanza.attrs.id;if(self1.nodeStanzasCallbacks[stanzaId]){for(var userId,users=[],items=stanza.getChild("query").getChildElements("item"),i=0,len=items.length;i<len;i++)userId=self1.helpers.getUserIdFromRoomJid(items[i].attrs.jid),users.push(parseInt(userId));callback(users)}}iq.c("query",{xmlns:"http://jabber.org/protocol/disco#items"}),Utils.getEnv().browser?self1.connection.sendIQ(iq,function(stanza){for(var userId,items=stanza.getElementsByTagName("item"),i=0,len=items.length;i<len;i++)userId=self1.helpers.getUserIdFromRoomJid(items[i].getAttribute("jid")),onlineUsers.push(parseInt(userId));callback(onlineUsers)}):(self1.Client.send(iq),self1.nodeStanzasCallbacks[iqParams.id]=_getUsers)}},PrivacyListProxy.prototype={create:function(list,callback){for(var userId,userJid,userMuc,userAction,mutualBlock,listPrivacy={},listUserId=[],i=list.items.length-1;i>=0;i--){var user=list.items[i];listPrivacy[user.user_id]={action:user.action,mutualBlock:!0===user.mutualBlock}}listUserId=Object.keys(listPrivacy);var iqParams={type:"set",from:this.helpers.getUserCurrentJid(),id:chatUtils.getUniqueId("edit")},builder=Utils.getEnv().browser?$iq:XMPP.Stanza,iq=chatUtils.createStanza(builder,iqParams,"iq");function createPrivacyItem(iq,params){return Utils.getEnv().browser?iq.c("item",{type:"jid",value:params.jidOrMuc,action:params.userAction,order:params.order}).c("message",{}).up().c("presence-in",{}).up().c("presence-out",{}).up().c("iq",{}).up().up():iq.getChild("query").getChild("list").c("item",{type:"jid",value:params.jidOrMuc,action:params.userAction,order:params.order}).c("message",{}).up().c("presence-in",{}).up().c("presence-out",{}).up().c("iq",{}).up().up(),iq}function createPrivacyItemMutal(iq,params){return Utils.getEnv().browser?iq.c("item",{type:"jid",value:params.jidOrMuc,action:params.userAction,order:params.order}).up():iq.getChild("query").getChild("list").c("item",{type:"jid",value:params.jidOrMuc,action:params.userAction,order:params.order}).up(),iq}iq.c("query",{xmlns:chatUtils.MARKERS.PRIVACY}).c("list",{name:list.name});for(var index=0,j=0,len=listUserId.length;index<len;index++,j+=2)mutualBlock=listPrivacy[userId=listUserId[index]].mutualBlock,userAction=listPrivacy[userId].action,userJid=this.helpers.jidOrUserId(parseInt(userId,10)),userMuc=this.helpers.getUserNickWithMucDomain(userId),mutualBlock&&"deny"===userAction?(iq=createPrivacyItemMutal(iq,{order:j+1,jidOrMuc:userJid,userAction:userAction}),iq=createPrivacyItemMutal(iq,{order:j+2,jidOrMuc:userMuc,userAction:userAction}).up().up()):(iq=createPrivacyItem(iq,{order:j+1,jidOrMuc:userJid,userAction:userAction}),iq=createPrivacyItem(iq,{order:j+2,jidOrMuc:userMuc,userAction:userAction}));Utils.getEnv().browser?this.connection.sendIQ(iq,function(stanzaResult){callback(null)},function(stanzaError){stanzaError?callback(chatUtils.getErrorFromXMLNode(stanzaError)):callback(Utils.getError(408))}):(this.Client.send(iq),this.nodeStanzasCallbacks[iqParams.id]=function(stanza){stanza.getChildElements("error").length?callback(Utils.getError(408)):callback(null)})},getList:function(name,callback){var items,userJid,userId,self1=this,usersList=[],iqParams={type:"get",from:self1.helpers.getUserCurrentJid(),id:chatUtils.getUniqueId("getlist")},builder=Utils.getEnv().browser?$iq:XMPP.Stanza,iq=chatUtils.createStanza(builder,iqParams,"iq");iq.c("query",{xmlns:chatUtils.MARKERS.PRIVACY}).c("list",{name:name}),Utils.getEnv().browser?self1.connection.sendIQ(iq,function(stanzaResult){items=stanzaResult.getElementsByTagName("item");for(var i=0,len=items.length;i<len;i+=2)userJid=items[i].getAttribute("value"),userId=self1.helpers.getIdFromNode(userJid),usersList.push({user_id:userId,action:items[i].getAttribute("action")});callback(null,{name:name,items:usersList})},function(stanzaError){stanzaError?callback(chatUtils.getErrorFromXMLNode(stanzaError),null):callback(Utils.getError(408),null)}):(self1.nodeStanzasCallbacks[iqParams.id]=function(stanza){for(var userJid,stanzaQuery=stanza.getChild("query"),list=stanzaQuery?stanzaQuery.getChild("list"):null,items=list?list.getChildElements("item"):null,usersList=[],i=0,len=items.length;i<len;i+=2)userJid=items[i].attrs.value,usersList.push({user_id:self1.helpers.getIdFromNode(userJid),action:items[i].attrs.action});callback(null,list={name:list.attrs.name,items:usersList}),delete self1.nodeStanzasCallbacks[iqParams.id]},self1.Client.send(iq))},update:function(listWithUpdates,callback){var self1=this;self1.getList(listWithUpdates.name,function(error,existentList){if(error)callback(error,null);else{var updatedList={};updatedList.items=Utils.MergeArrayOfObjects(existentList.items,listWithUpdates.items),updatedList.name=listWithUpdates.name,self1.create(updatedList,function(err,result){error?callback(err,null):callback(null,result)})}})},getNames:function(callback){var iq,stanzaParams={type:"get",from:this.helpers.getUserCurrentJid(),id:chatUtils.getUniqueId("getNames")};Utils.getEnv().browser?(iq=$iq(stanzaParams).c("query",{xmlns:Strophe.NS.PRIVACY_LIST}),this.connection.sendIQ(iq,function(stanzaResult){for(var allNames=[],defaultList=stanzaResult.getElementsByTagName("default"),activeList=stanzaResult.getElementsByTagName("active"),allLists=stanzaResult.getElementsByTagName("list"),defaultName=defaultList&&defaultList.length>0?defaultList[0].getAttribute("name"):null,activeName=activeList&&activeList.length>0?activeList[0].getAttribute("name"):null,i=0,len=allLists.length;i<len;i++)allNames.push(allLists[i].getAttribute("name"));callback(null,{default:defaultName,active:activeName,names:allNames})},function(stanzaError){stanzaError?callback(chatUtils.getErrorFromXMLNode(stanzaError),null):callback(Utils.getError(408),null)})):((iq=new XMPP.Stanza("iq",stanzaParams)).c("query",{xmlns:chatUtils.MARKERS.PRIVACY}),this.nodeStanzasCallbacks[iq.attrs.id]=function(stanza){if("error"!==stanza.attrs.type){for(var allNames=[],query=stanza.getChild("query"),defaultList=query.getChild("default"),activeList=query.getChild("active"),allLists=query.getChildElements("list"),defaultName=defaultList?defaultList.attrs.name:null,activeName=activeList?activeList.attrs.name:null,i=0,len=allLists.length;i<len;i++)allNames.push(allLists[i].attrs.name);callback(null,{default:defaultName,active:activeName,names:allNames})}else callback(Utils.getError(408))},this.Client.send(iq))},delete:function(name,callback){var iq,stanzaParams={from:this.connection?this.connection.jid:this.Client.jid.user,type:"set",id:chatUtils.getUniqueId("remove")};Utils.getEnv().browser?(iq=$iq(stanzaParams).c("query",{xmlns:Strophe.NS.PRIVACY_LIST}).c("list",{name:name||""}),this.connection.sendIQ(iq,function(stanzaResult){callback(null)},function(stanzaError){stanzaError?callback(chatUtils.getErrorFromXMLNode(stanzaError)):callback(Utils.getError(408))})):((iq=new XMPP.Stanza("iq",stanzaParams)).c("query",{xmlns:chatUtils.MARKERS.PRIVACY}).c("list",{name:name||""}),this.nodeStanzasCallbacks[stanzaParams.id]=function(stanza){stanza.getChildElements("error").length?callback(Utils.getError(408)):callback(null)},this.Client.send(iq))},setAsDefault:function(name,callback){var iq,self1=this,stanzaParams={from:this.connection?this.connection.jid:this.Client.jid.user,type:"set",id:chatUtils.getUniqueId("default")};function setAsActive(self1){var setAsActiveIq,setAsActiveStanzaParams={from:self1.connection?self1.connection.jid:self1.Client.jid.user,type:"set",id:chatUtils.getUniqueId("active1")};Utils.getEnv().browser?(setAsActiveIq=$iq(setAsActiveStanzaParams).c("query",{xmlns:Strophe.NS.PRIVACY_LIST}).c("active",name&&name.length>0?{name:name}:{}),self1.connection.sendIQ(setAsActiveIq,function(setAsActiveStanzaResult){callback(null)},function(setAsActiveStanzaError){setAsActiveStanzaError?callback(chatUtils.getErrorFromXMLNode(setAsActiveStanzaError)):callback(Utils.getError(408))})):((setAsActiveIq=new XMPP.Stanza("iq",setAsActiveStanzaParams)).c("query",{xmlns:chatUtils.MARKERS.PRIVACY}).c("active",name&&name.length>0?{name:name}:{}),self1.nodeStanzasCallbacks[setAsActiveStanzaParams.id]=function(setAsActistanza){setAsActistanza.getChildElements("error").length?callback(Utils.getError(408)):callback(null)},self1.Client.send(setAsActiveIq))}Utils.getEnv().browser?(iq=$iq(stanzaParams).c("query",{xmlns:Strophe.NS.PRIVACY_LIST}).c("default",name&&name.length>0?{name:name}:{}),this.connection.sendIQ(iq,function(stanzaResult){setAsActive(self1)},function(stanzaError){stanzaError?callback(chatUtils.getErrorFromXMLNode(stanzaError)):callback(Utils.getError(408))})):((iq=new XMPP.Stanza("iq",stanzaParams)).c("query",{xmlns:chatUtils.MARKERS.PRIVACY}).c("default",name&&name.length>0?{name:name}:{}),this.nodeStanzasCallbacks[stanzaParams.id]=function(stanza){stanza.getChildElements("error").length?callback(Utils.getError(408)):setAsActive(self1)},this.Client.send(iq))}},Helpers.prototype={getUniqueId:chatUtils.getUniqueId,jidOrUserId:function(jid_or_user_id){var jid;if("string"==typeof jid_or_user_id)jid=jid_or_user_id;else if("number"==typeof jid_or_user_id)jid=jid_or_user_id+"-"+config.creds.appId+"@"+config.endpoints.chat;else throw Error('The method "jidOrUserId" may take jid or id');return jid},typeChat:function(jid_or_user_id){var chatType;if("string"==typeof jid_or_user_id)chatType=jid_or_user_id.indexOf("muc")>-1?"groupchat":"chat";else if("number"==typeof jid_or_user_id)chatType="chat";else throw Error(unsupportedError);return chatType},getRecipientId:function(occupantsIds,UserId){var recipient=null;return occupantsIds.forEach(function(item){item!=UserId&&(recipient=item)}),recipient},getUserJid:function(userId,appId){return appId?userId+"-"+appId+"@"+config.endpoints.chat:userId+"-"+config.creds.appId+"@"+config.endpoints.chat},getUserNickWithMucDomain:function(userId){return config.endpoints.muc+"/"+userId},getIdFromNode:function(jid){return 0>jid.indexOf("@")?null:parseInt(jid.split("@")[0].split("-")[0])},getDialogIdFromNode:function(jid){return 0>jid.indexOf("@")?null:jid.split("@")[0].split("_")[1]},getRoomJidFromDialogId:function(dialogId){return config.creds.appId+"_"+dialogId+"@"+config.endpoints.muc},getRoomJid:function(jid){return jid+"/"+this.getIdFromNode(this._userCurrentJid)},getIdFromResource:function(jid){var s=jid.split("/");return s.length<2?null:(s.splice(0,1),parseInt(s.join("/")))},getRoomJidFromRoomFullJid:function(jid){var s=jid.split("/");return s.length<2?null:s[0]},getBsonObjectId:function(){return Utils.getBsonObjectId()},getUserIdFromRoomJid:function(jid){var arrayElements=jid.toString().split("/");return 0===arrayElements.length?null:arrayElements[arrayElements.length-1]},userCurrentJid:function(client){try{if(client instanceof Strophe.Connection)return client.jid;return client.jid.user+"@"+client.jid._domain+"/"+client.jid._resource}catch(e){return client.jid.user+"@"+client.jid._domain+"/"+client.jid._resource}},getUserCurrentJid:function(){return this._userCurrentJid},setUserCurrentJid:function(jid){this._userCurrentJid=jid},getDialogJid:function(identifier){return identifier.indexOf("@")>0?identifier:this.getRoomJidFromDialogId(identifier)}},module.exports=ChatProxy},{"../../plugins/streamManagement":251,"../../qbConfig":252,"../../qbStrophe":255,"../../qbUtils":256,"./qbChatHelpers":235,"nativescript-xmpp-client":void 0,"node-xmpp-client":111}],235:[function(require1,module,exports){"use strict";var utils=require1("../../qbUtils"),config=require1("../../qbConfig"),ERR_UNKNOWN_INTERFACE="Unknown interface. SDK support browser / node env.";function ChatNotConnectedError(message,fileName,lineNumber){var instance=Error(message,fileName,lineNumber);return instance.name="ChatNotConnectedError",Object.setPrototypeOf(instance,Object.getPrototypeOf(this)),Error.captureStackTrace&&Error.captureStackTrace(instance,ChatNotConnectedError),instance}ChatNotConnectedError.prototype=Object.create(Error.prototype,{constructor:{value:Error,enumerable:!1,writable:!0,configurable:!0}}),Object.setPrototypeOf?Object.setPrototypeOf(ChatNotConnectedError,Error):ChatNotConnectedError.__proto__=Error,module.exports={MARKERS:{CLIENT:"jabber:client",CHAT:"urn:xmpp:chat-markers:0",STATES:"http://jabber.org/protocol/chatstates",MARKERS:"urn:xmpp:chat-markers:0",CARBONS:"urn:xmpp:carbons:2",ROSTER:"jabber:iq:roster",MUC:"http://jabber.org/protocol/muc",PRIVACY:"jabber:iq:privacy",LAST:"jabber:iq:last"},ChatNotConnectedError:ChatNotConnectedError,buildUserJid:function(params){var jid;return"userId"in params?(jid=params.userId+"-"+config.creds.appId+"@"+config.endpoints.chat,"resource"in params&&(jid=jid+"/"+params.resource)):"jid"in params&&(jid=params.jid),jid},createStanza:function(builder,params,type){return utils.getEnv().browser?builder(params):new builder(type||"message",params)},getAttr:function(el,attrName){var attr;return el?("function"==typeof el.getAttribute?attr=el.getAttribute(attrName):el.attrs&&(attr=el.attrs[attrName]),attr||null):null},getElement:function(stanza,elName){var el;if("function"==typeof stanza.querySelector)el=stanza.querySelector(elName);else if("function"==typeof stanza.getChild)el=stanza.getChild(elName)||stanza.children.find(child=>"function"==typeof child.getChild&&this.getElement(child,elName));else throw ERR_UNKNOWN_INTERFACE;return el||null},getAllElements:function(stanza,elName){var el;if("function"==typeof stanza.querySelectorAll)el=stanza.querySelectorAll(elName);else if("function"==typeof stanza.getChild)el=stanza.getChild(elName);else throw ERR_UNKNOWN_INTERFACE;return el||null},getElementText:function(stanza,elName){var el,txt;if("function"==typeof stanza.querySelector)txt=(el=stanza.querySelector(elName))?el.textContent:null;else if("function"==typeof stanza.getChildText)txt=stanza.getChildText(elName)||stanza.children.find(child=>"function"==typeof child.getChildText&&this.getElementText(child,elName));else throw ERR_UNKNOWN_INTERFACE;return txt||null},_JStoXML:function(title,obj,msg){var self1=this;msg.c(title),Object.keys(obj).forEach(function(field){"object"==typeof obj[field]?self1._JStoXML(field,obj[field],msg):msg.c(field).t(obj[field]).up()}),msg.up()},_XMLtoJS:function(extension,title,obj){extension[title]={};for(var i=0,len=obj.childNodes.length;i<len;i++)obj.childNodes[i].childNodes.length>1?extension[title]=this._XMLtoJS(extension[title],obj.childNodes[i].tagName,obj.childNodes[i]):extension[title][obj.childNodes[i].tagName]=obj.childNodes[i].textContent;return extension},filledExtraParams:function(stanza,extension){var helper=this;return Object.keys(extension).forEach(function(field){"attachments"===field?extension[field].forEach(function(attach){utils.getEnv().browser?stanza.c("attachment",attach).up():stanza.getChild("extraParams").c("attachment",attach).up()}):"object"==typeof extension[field]?helper._JStoXML(field,extension[field],stanza):utils.getEnv().browser?stanza.c(field).t(extension[field]).up():stanza.getChild("extraParams").c(field).t(extension[field]).up()}),stanza.up(),stanza},parseExtraParams:function(extraParams){if(!extraParams)return null;var dialogId,attach,attributes,extension={},attachments=[];if(utils.getEnv().browser)for(var i=0,len=extraParams.childNodes.length;i<len;i++)if("attachment"===extraParams.childNodes[i].tagName){attach={},attributes=extraParams.childNodes[i].attributes;for(var j=0,len2=attributes.length;j<len2;j++)"size"===attributes[j].name?attach[attributes[j].name]=parseInt(attributes[j].value):attach[attributes[j].name]=attributes[j].value;attachments.push(attach)}else if("dialog_id"===extraParams.childNodes[i].tagName)dialogId=extraParams.childNodes[i].textContent,extension.dialog_id=dialogId;else if(extraParams.childNodes[i].childNodes.length>1){if(extraParams.childNodes[i].textContent.length>4096){for(var wholeNodeContent="",k=0;k<extraParams.childNodes[i].childNodes.length;++k)wholeNodeContent+=extraParams.childNodes[i].childNodes[k].textContent;extension[extraParams.childNodes[i].tagName]=wholeNodeContent}else extension=this._XMLtoJS(extension,extraParams.childNodes[i].tagName,extraParams.childNodes[i])}else extension[extraParams.childNodes[i].tagName]=extraParams.childNodes[i].textContent;else for(var c=0,lenght=extraParams.children.length;c<lenght;c++){if("attachment"===extraParams.children[c].name){attach={};for(var attrKeys=Object.keys(attributes=extraParams.children[c].attrs),l=0;l<attrKeys.length;l++)"size"===attrKeys[l]?attach.size=parseInt(attributes.size):attach[attrKeys[l]]=attributes[attrKeys[l]];attachments.push(attach)}else"dialog_id"===extraParams.children[c].name&&(dialogId=extraParams.getChildText("dialog_id"),extension.dialog_id=dialogId);if(1===extraParams.children[c].children.length){var child=extraParams.children[c];extension[child.name]=child.children[0]}}return attachments.length>0&&(extension.attachments=attachments),extension.moduleIdentifier&&delete extension.moduleIdentifier,{extension:extension,dialogId:dialogId}},getUniqueId:function(suffix){var uuid="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){var r=16*Math.random()|0;return("x"==c?r:3&r|8).toString(16)});return"string"==typeof suffix||"number"==typeof suffix?uuid+":"+suffix:uuid+""},getErrorFromXMLNode:function(stanzaError){var errorElement=this.getElement(stanzaError,"error"),errorCode=parseInt(this.getAttr(errorElement,"code")),errorText=this.getElementText(errorElement,"text");return utils.getError(errorCode,errorText)},getLocalTime:function(){return new Date().toTimeString().split(" ")[0]}}},{"../../qbConfig":252,"../../qbUtils":256}],236:[function(require1,module,exports){"use strict";var config=require1("../../qbConfig"),Utils=require1("../../qbUtils"),DIALOGS_API_URL=config.urls.chat+"/Dialog";function DialogProxy(service){this.service=service}DialogProxy.prototype={list:function(params,callback){"function"==typeof params&&void 0===callback&&(callback=params,params={}),this.service.ajax({url:Utils.getUrl(DIALOGS_API_URL),data:params},callback)},create:function(params,callback){params&¶ms.occupants_ids&&Utils.isArray(params.occupants_ids)&&(params.occupants_ids=params.occupants_ids.join(", ")),this.service.ajax({url:Utils.getUrl(DIALOGS_API_URL),type:"POST",data:params},callback)},update:function(id,params,callback){this.service.ajax({url:Utils.getUrl(DIALOGS_API_URL,id),type:"PUT",contentType:"application/json; charset=utf-8",isNeedStringify:!0,data:params},callback)},delete:function(id,params_or_callback,callback){var ajaxParams={url:Utils.getUrl(DIALOGS_API_URL,id),type:"DELETE",dataType:"text"};2==arguments.length?this.service.ajax(ajaxParams,params_or_callback):3==arguments.length&&(ajaxParams.data=params_or_callback,this.service.ajax(ajaxParams,callback))}},module.exports=DialogProxy},{"../../qbConfig":252,"../../qbUtils":256}],237:[function(require1,module,exports){"use strict";var config=require1("../../qbConfig"),Utils=require1("../../qbUtils"),MESSAGES_API_URL=config.urls.chat+"/Message";function MessageProxy(service){this.service=service}MessageProxy.prototype={list:function(params,callback){this.service.ajax({url:Utils.getUrl(MESSAGES_API_URL),data:params},callback)},create:function(params,callback){this.service.ajax({url:Utils.getUrl(MESSAGES_API_URL),type:"POST",data:params},callback)},update:function(id,params,callback){var attrAjax={type:"PUT",dataType:"text",url:Utils.getUrl(MESSAGES_API_URL,id),data:params};this.service.ajax(attrAjax,callback)},delete:function(id,params_or_callback,callback){var ajaxParams={url:Utils.getUrl(MESSAGES_API_URL,id),type:"DELETE",dataType:"text"};2==arguments.length?this.service.ajax(ajaxParams,params_or_callback):3==arguments.length&&(ajaxParams.data=params_or_callback,this.service.ajax(ajaxParams,callback))},unreadCount:function(params,callback){params&¶ms.chat_dialog_ids&&Utils.isArray(params.chat_dialog_ids)&&(params.chat_dialog_ids=params.chat_dialog_ids.join()),this.service.ajax({url:Utils.getUrl(MESSAGES_API_URL+"/unread"),data:params},callback)}},module.exports=MessageProxy},{"../../qbConfig":252,"../../qbUtils":256}],238:[function(require1,module,exports){"use strict";var Utils=require1("../qbUtils"),config=require1("../qbConfig");function AddressBook(service){this.service=service}function isFunction(func){return!!(func&&func.constructor&&func.call&&func.apply)}AddressBook.prototype={uploadAddressBook:function(list,optionsOrcallback,callback){if(!Array.isArray(list)){Error("First parameter must be an Array.");return}isFunction(optionsOrcallback)?cb=optionsOrcallback:(opts=optionsOrcallback,cb=callback);var opts,cb,data={contacts:list};opts&&(opts.force&&(data.force=opts.force),opts.udid&&(data.udid=opts.udid)),this.service.ajax({type:"POST",url:Utils.getUrl(config.urls.addressbook),data:data,contentType:"application/json; charset=utf-8",isNeedStringify:!0},function(err,res){err?cb(err,null):cb(null,res)})},_isFakeErrorEmptyAddressBook:function(err){var errDetails=err.detail?err.detail:err.message.errors;return 404===err.code&&"Empty address book"===errDetails[0]},get:function(udidOrCallback,callback){var udid,cb,self1=this;if(isFunction(udidOrCallback)?cb=udidOrCallback:(udid=udidOrCallback,cb=callback),!isFunction(cb))throw Error("The QB.addressbook.get accept callback function is required.");var ajaxParams={type:"GET",url:Utils.getUrl(config.urls.addressbook),contentType:"application/json; charset=utf-8",isNeedStringify:!0};udid&&(ajaxParams.data={udid:udid}),this.service.ajax(ajaxParams,function(err,res){err?self1._isFakeErrorEmptyAddressBook(err)?cb(null,[]):cb(err,null):cb(null,res)})},getRegisteredUsers:function(isCompactOrCallback,callback){var isCompact,cb,self1=this;if(isFunction(isCompactOrCallback)?cb=isCompactOrCallback:(isCompact=isCompactOrCallback,cb=callback),!isFunction(cb))throw Error("The QB.addressbook.get accept callback function is required.");var ajaxParams={type:"GET",url:Utils.getUrl(config.urls.addressbookRegistered),contentType:"application/json; charset=utf-8"};isCompact&&(ajaxParams.data={compact:1}),this.service.ajax(ajaxParams,function(err,res){err?self1._isFakeErrorEmptyAddressBook(err)?cb(null,[]):cb(err,null):cb(null,res)})}},module.exports=AddressBook},{"../qbConfig":252,"../qbUtils":256}],239:[function(require1,module,exports){"use strict";var config=require1("../qbConfig"),Utils=require1("../qbUtils"),sha1=require1("crypto-js/hmac-sha1"),sha256=require1("crypto-js/hmac-sha256");function AuthProxy(service){this.service=service}function generateAuthMsg(params){var message={application_id:config.creds.appId,auth_key:config.creds.authKey,nonce:Utils.randomNonce(),timestamp:Utils.unixTime()};return params.login&¶ms.password?message.user={login:params.login,password:params.password}:params.email&¶ms.password?message.user={email:params.email,password:params.password}:params.provider&&(message.provider=params.provider,params.scope&&(message.scope=params.scope),params.keys&¶ms.keys.token&&(message.keys={token:params.keys.token}),params.keys&¶ms.keys.secret&&(message.keys.secret=params.keys.secret)),message}function signMessage(message,secret){var cryptoSessionMsg,sessionMsg=Object.keys(message).map(function(val){return"object"==typeof message[val]?Object.keys(message[val]).map(function(val1){return val+"["+val1+"]="+message[val][val1]}).sort().join("&"):val+"="+message[val]}).sort().join("&");if("sha1"===config.hash)cryptoSessionMsg=sha1(sessionMsg,secret).toString();else if("sha256"===config.hash)cryptoSessionMsg=sha256(sessionMsg,secret).toString();else throw Error("Quickblox SDK: unknown crypto standards, available sha1 or sha256");return cryptoSessionMsg}AuthProxy.prototype={getSession:function(callback){this.service.ajax({url:Utils.getUrl(config.urls.session)},function(err,res){err?callback(err,null):callback(err,res)})},createSession:function(params,callback){if(""===config.creds.appId||""===config.creds.authKey||""===config.creds.authSecret)throw Error("Cannot create a new session without app credentials (app ID, auth key and auth secret)");var message,_this=this;"function"==typeof params&&void 0===callback&&(callback=params,params={}),(message=generateAuthMsg(params)).signature=signMessage(message,config.creds.authSecret),this.service.ajax({url:Utils.getUrl(config.urls.session),type:"POST",data:message},function(err,res){err?callback(err,null):(_this.service.setSession(res.session),callback(null,res.session))})},destroySession:function(callback){var _this=this;this.service.ajax({url:Utils.getUrl(config.urls.session),type:"DELETE",dataType:"text"},function(err,res){err?callback(err,null):(_this.service.setSession(null),callback(null,res))})},login:function(params,callback){var ajaxParams={type:"POST",url:Utils.getUrl(config.urls.login),data:params};function handleResponce(err,res){err?callback(err,null):callback(null,res.user)}this.service.ajax(ajaxParams,handleResponce)},logout:function(callback){this.service.ajax({url:Utils.getUrl(config.urls.login),type:"DELETE",dataType:"text"},callback)}},module.exports=AuthProxy},{"../qbConfig":252,"../qbUtils":256,"crypto-js/hmac-sha1":51,"crypto-js/hmac-sha256":52}],240:[function(require1,module,exports){"use strict";var config=require1("../qbConfig"),Utils=require1("../qbUtils");function ContentProxy(service){this.service=service}function parseUri(str){for(var o=parseUri.options,m=o.parser[o.strictMode?"strict":"loose"].exec(str),uri={},i=14;i--;)uri[o.key[i]]=m[i]||"";return uri[o.q.name]={},uri[o.key[12]].replace(o.q.parser,function($0,$1,$2){$1&&(uri[o.q.name][$1]=$2)}),uri}ContentProxy.prototype={list:function(params,callback){"function"==typeof params&&void 0===callback&&(callback=params,params=null),this.service.ajax({url:Utils.getUrl(config.urls.blobs),data:params,type:"GET"},function(err,result){err?callback(err,null):callback(err,result)})},create:function(params,callback){this.service.ajax({type:"POST",data:{blob:params},url:Utils.getUrl(config.urls.blobs)},function(err,result){err?callback(err,null):callback(err,result.blob)})},delete:function(id,callback){this.service.ajax({url:Utils.getUrl(config.urls.blobs,id),type:"DELETE",dataType:"text"},function(err,result){err?callback(err,null):callback(null,!0)})},createAndUpload:function(params,callback){var file,name,type,size,fileId,_this=this,createParams={};JSON.parse(JSON.stringify(params)).file.data="...",file=params.file,name=params.name||file.name,type=params.type||file.type,size=params.size||file.size,createParams.name=name,createParams.content_type=type,params.public&&(createParams.public=params.public),params.tag_list&&(createParams.tag_list=params.tag_list),this.create(createParams,function(err,createResult){if(err)callback(err,null);else{var uri=parseUri(createResult.blob_object_access.params),uploadParams={url:uri.protocol+"://"+uri.authority+uri.path},data={};fileId=createResult.id,createResult.size=size,Object.keys(uri.queryKey).forEach(function(val){data[val]=decodeURIComponent(uri.queryKey[val])}),data.file=file,uploadParams.data=data,_this.upload(uploadParams,function(err,result){err?callback(err,null):_this.markUploaded({id:fileId,size:size},function(err,result){err?callback(err,null):callback(null,createResult)})})}})},upload:function(params,callback){var uploadParams={type:"POST",dataType:"text",contentType:!1,url:params.url,data:params.data};this.service.ajax(uploadParams,function(err,xmlDoc){err?callback(err,null):callback(null,{})})},markUploaded:function(params,callback){this.service.ajax({url:Utils.getUrl(config.urls.blobs,params.id+"/complete"),type:"PUT",data:{size:params.size},dataType:"text"},function(err,res){err?callback(err,null):callback(null,res)})},getInfo:function(id,callback){this.service.ajax({url:Utils.getUrl(config.urls.blobs,id)},function(err,res){err?callback(err,null):callback(null,res)})},getFile:function(uid,callback){this.service.ajax({url:Utils.getUrl(config.urls.blobs,uid)},function(err,res){err?callback(err,null):callback(null,res)})},update:function(params,callback){var data={};data.blob={},void 0!==params.name&&(data.blob.name=params.name),this.service.ajax({url:Utils.getUrl(config.urls.blobs,params.id),data:data},function(err,res){err?callback(err,null):callback(null,res)})},privateUrl:function(fileUID){return"https://"+config.endpoints.api+"/blobs/"+fileUID+"?token="+this.service.getSession().token},publicUrl:function(fileUID){return"https://"+config.endpoints.api+"/blobs/"+fileUID}},module.exports=ContentProxy,parseUri.options={strictMode:!1,key:["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],q:{name:"queryKey",parser:/(?:^|&)([^&=]*)=?([^&]*)/g},parser:{strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/}}},{"../qbConfig":252,"../qbUtils":256}],241:[function(require1,module,exports){"use strict";var config=require1("../qbConfig"),Utils=require1("../qbUtils");function DataProxy(service){this.service=service}DataProxy.prototype={create:function(className,data,callback){var ajaxParams={type:"POST",data:data,isNeedStringify:!0,contentType:"application/json; charset=utf-8",url:Utils.getUrl(config.urls.data,className)};this.service.ajax(ajaxParams,function(err,res){err?callback(err,null):callback(err,res)})},list:function(className,filters,callback){void 0===callback&&"function"==typeof filters&&(callback=filters,filters=null),this.service.ajax({url:Utils.getUrl(config.urls.data,className),data:filters},function(err,result){err?callback(err,null):callback(err,result)})},update:function(className,data,callback){this.service.ajax({url:Utils.getUrl(config.urls.data,className+"/"+data._id),type:"PUT",contentType:"application/json; charset=utf-8",isNeedStringify:!0,data:data},function(err,result){err?callback(err,null):callback(err,result)})},delete:function(className,requestedData,callback){var requestedTypeOf,typesData={id:1,ids:2,criteria:3},responceNormalized={deleted:[],deletedCount:0},ajaxParams={type:"DELETE",dataType:"text"};function handleDeleteCO(error,result){if(error)callback(error,null);else{var response;requestedTypeOf===typesData.id?(responceNormalized.deleted.push(requestedData),responceNormalized.deletedCount=responceNormalized.deleted.length):requestedTypeOf===typesData.ids?(response=JSON.parse(result),responceNormalized.deleted=response.SuccessfullyDeleted.ids.slice(0),responceNormalized.deletedCount=responceNormalized.deleted.length):requestedTypeOf===typesData.criteria&&(response=JSON.parse(result),responceNormalized.deleted=null,responceNormalized.deletedCount=response.total_deleted),callback(error,responceNormalized)}}"string"==typeof requestedData?requestedTypeOf=typesData.id:Utils.isArray(requestedData)?requestedTypeOf=typesData.ids:Utils.isObject(requestedData)&&(requestedTypeOf=typesData.criteria),requestedTypeOf===typesData.id?ajaxParams.url=Utils.getUrl(config.urls.data,className+"/"+requestedData):requestedTypeOf===typesData.ids?ajaxParams.url=Utils.getUrl(config.urls.data,className+"/"+requestedData.toString()):requestedTypeOf===typesData.criteria&&(ajaxParams.url=Utils.getUrl(config.urls.data,className+"/by_criteria"),ajaxParams.data=requestedData),this.service.ajax(ajaxParams,handleDeleteCO)},uploadFile:function(className,params,callback){var data={field_name:params.field_name,file:{data:params.file,name:params.name}};this.service.ajax({url:Utils.getUrl(config.urls.data,className+"/"+params.id+"/file"),type:"POST",fileToCustomObject:!0,contentType:!1,data:data},function(err,result){err?callback(err,null):callback(err,result)})},downloadFile:function(className,params,callback){var result=Utils.getUrl(config.urls.data,className+"/"+params.id+"/file");callback(null,result+="?field_name="+params.field_name+"&token="+this.service.getSession().token)},fileUrl:function(className,params){return Utils.getUrl(config.urls.data,className+"/"+params.id+"/file")+("?field_name="+params.field_name+"&token=")+this.service.getSession().token},deleteFile:function(className,params,callback){this.service.ajax({url:Utils.getUrl(config.urls.data,className+"/"+params.id+"/file"),data:{field_name:params.field_name},dataType:"text",type:"DELETE"},function(err,result){err?callback(err,null):callback(err,!0)})}},module.exports=DataProxy},{"../qbConfig":252,"../qbUtils":256}],242:[function(require1,module,exports){(function(Buffer){(function(){"use strict";var config=require1("../qbConfig"),Utils=require1("../qbUtils"),isBrowser="undefined"!=typeof window;function PushNotificationsProxy(service){this.service=service,this.subscriptions=new SubscriptionsProxy(service),this.events=new EventsProxy(service),this.base64Encode=function(str){return isBrowser?btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,function(match,p1){return String.fromCharCode("0x"+p1)})):new Buffer(str).toString("base64")}}function SubscriptionsProxy(service){this.service=service}function EventsProxy(service){this.service=service}SubscriptionsProxy.prototype={create:function(params,callback){this.service.ajax({url:Utils.getUrl(config.urls.subscriptions),type:"POST",data:params},callback)},list:function(callback){this.service.ajax({url:Utils.getUrl(config.urls.subscriptions)},callback)},delete:function(id,callback){var attrAjax={type:"DELETE",dataType:"text",url:Utils.getUrl(config.urls.subscriptions,id)};this.service.ajax(attrAjax,function(err,res){err?callback(err,null):callback(null,!0)})}},EventsProxy.prototype={create:function(params,callback){this.service.ajax({url:Utils.getUrl(config.urls.events),type:"POST",contentType:"application/json; charset=utf-8",isNeedStringify:!0,data:{event:params}},callback)},list:function(params,callback){"function"==typeof params&&void 0===callback&&(callback=params,params=null),this.service.ajax({url:Utils.getUrl(config.urls.events),data:params},callback)},get:function(id,callback){this.service.ajax({url:Utils.getUrl(config.urls.events,id)},callback)},delete:function(id,callback){this.service.ajax({url:Utils.getUrl(config.urls.events,id),dataType:"text",type:"DELETE"},callback)},status:function(id,callback){this.service.ajax({url:Utils.getUrl(config.urls.events,id+"/status")},callback)}},module.exports=PushNotificationsProxy}).call(this)}).call(this,require1("buffer").Buffer)},{"../qbConfig":252,"../qbUtils":256,buffer:47}],243:[function(require1,module,exports){"use strict";var config=require1("../qbConfig"),Utils=require1("../qbUtils"),DATE_FIELDS=["created_at","updated_at","last_request_at"],NUMBER_FIELDS=["id","external_user_id"],resetPasswordUrl=config.urls.users+"/password/reset";function UsersProxy(service){this.service=service}function generateFilter(obj){var type=obj.field in DATE_FIELDS?"date":typeof obj.value;return Utils.isArray(obj.value)&&("object"===type&&(type=typeof obj.value[0]),obj.value=obj.value.toString()),[type,obj.field,obj.param,obj.value].join(" ")}function generateOrder(obj){var type=obj.field in DATE_FIELDS?"date":obj.field in NUMBER_FIELDS?"number":"string";return[obj.sort,type,obj.field].join(" ")}UsersProxy.prototype={listUsers:function(params,callback){var item,message={},filters=[];"function"==typeof params&&void 0===callback&&(callback=params,params={}),params&¶ms.filter&&(Utils.isArray(params.filter)?params.filter.forEach(function(el){item=generateFilter(el),filters.push(item)}):(item=generateFilter(params.filter),filters.push(item)),message.filter=filters),params.order&&(message.order=generateOrder(params.order)),params.page&&(message.page=params.page),params.per_page&&(message.per_page=params.per_page),this.service.ajax({url:Utils.getUrl(config.urls.users),data:message},callback)},get:function(params,callback){var url;"number"==typeof params?(url=params,params={}):params.login?url="by_login":params.full_name?url="by_full_name":params.facebook_id?url="by_facebook_id":params.twitter_id?url="by_twitter_id":params.phone?url="phone":params.email?url="by_email":params.tags?url="by_tags":params.external&&(url="external/"+params.external,params={}),this.service.ajax({url:Utils.getUrl(config.urls.users,url),data:params},function(err,res){err?callback(err,null):callback(null,res.user||res)})},create:function(params,callback){this.service.ajax({url:Utils.getUrl(config.urls.users),type:"POST",data:{user:params}},function(err,res){err?callback(err,null):callback(null,res.user)})},update:function(id,params,callback){this.service.ajax({url:Utils.getUrl(config.urls.users,id),type:"PUT",data:{user:params}},function(err,res){err?callback(err,null):callback(null,res.user)})},delete:function(params,callback){var url;"number"==typeof params?url=params:params.external&&(url="external/"+params.external),this.service.ajax({url:Utils.getUrl(config.urls.users,url),type:"DELETE",dataType:"text"},callback)},resetPassword:function(email,callback){this.service.ajax({url:Utils.getUrl(resetPasswordUrl),data:{email:email},dataType:"text"},callback)}},module.exports=UsersProxy},{"../qbConfig":252,"../qbUtils":256}],244:[function(require1,module,exports){"use strict";var config=require1("../../qbConfig"),Helpers=require1("./qbWebRTCHelpers"),qbRTCPeerConnection=function(config){this._pc=new window.RTCPeerConnection(config),this.remoteStream=void 0,this.preferredCodec="VP8"};function _getStats(peer,lastResults,successCallback,errorCallback){var statistic={local:{audio:{},video:{},candidate:{}},remote:{audio:{},video:{},candidate:{}}};if(Helpers.getVersionFirefox()){var localStream=peer.getLocalStreams().length?peer.getLocalStreams()[0]:peer.delegate.localStream,localVideoSettings=localStream.getVideoTracks().length?localStream.getVideoTracks()[0].getSettings():null;statistic.local.video.frameHeight=localVideoSettings&&localVideoSettings.height,statistic.local.video.frameWidth=localVideoSettings&&localVideoSettings.width}function _getBitratePerSecond(result,lastResults,isLocal){var lastResult=lastResults&&lastResults.get(result.id),seconds=lastResult?(result.timestamp-lastResult.timestamp)/1e3:5;return Math.round(lastResult?isLocal?8*(result.bytesSent-lastResult.bytesSent)/(1024*seconds):8*(result.bytesReceived-lastResult.bytesReceived)/(1024*seconds):0)}function _getFramesPerSecond(result,lastResults,isLocal){var lastResult=lastResults&&lastResults.get(result.id),seconds=lastResult?(result.timestamp-lastResult.timestamp)/1e3:5;return Math.round(10*(lastResult?isLocal?(result.framesSent-lastResult.framesSent)/seconds:(result.framesReceived-lastResult.framesReceived)/seconds:0))/10}peer.getStats(null).then(function(results){results.forEach(function(result){var item;result.bytesReceived&&"inbound-rtp"===result.type?((item=statistic.remote[result.mediaType]).bitrate=_getBitratePerSecond(result,lastResults,!1),item.bytesReceived=result.bytesReceived,item.packetsReceived=result.packetsReceived,item.timestamp=result.timestamp,"video"===result.mediaType&&result.framerateMean&&(item.framesPerSecond=Math.round(10*result.framerateMean)/10)):result.bytesSent&&"outbound-rtp"===result.type?((item=statistic.local[result.mediaType]).bitrate=_getBitratePerSecond(result,lastResults,!0),item.bytesSent=result.bytesSent,item.packetsSent=result.packetsSent,item.timestamp=result.timestamp,"video"===result.mediaType&&result.framerateMean&&(item.framesPerSecond=Math.round(10*result.framerateMean)/10)):"local-candidate"===result.type?(item=statistic.local.candidate,"host"===result.candidateType&&"udp"===result.mozLocalTransport&&"udp"===result.transport?(item.protocol=result.transport,item.ip=result.ipAddress,item.port=result.portNumber):Helpers.getVersionFirefox()||(item.protocol=result.protocol,item.ip=result.ip,item.port=result.port)):"remote-candidate"===result.type?((item=statistic.remote.candidate).protocol=result.protocol||result.transport,item.ip=result.ip||result.ipAddress,item.port=result.port||result.portNumber):"track"!==result.type||"video"!==result.kind||Helpers.getVersionFirefox()||(result.remoteSource?((item=statistic.remote.video).frameHeight=result.frameHeight,item.frameWidth=result.frameWidth,item.framesPerSecond=_getFramesPerSecond(result,lastResults,!1)):((item=statistic.local.video).frameHeight=result.frameHeight,item.frameWidth=result.frameWidth,item.framesPerSecond=_getFramesPerSecond(result,lastResults,!0)))}),successCallback(statistic,results)},errorCallback)}function findLineInRange(sdpLines,startLine,endLine,prefix,substr,direction){if(void 0===direction&&(direction="asc"),"asc"===(direction=direction||"asc")){for(var realEndLine=-1!==endLine?endLine:sdpLines.length,i=startLine;i<realEndLine;++i)if(0===sdpLines[i].indexOf(prefix)&&(!substr||-1!==sdpLines[i].toLowerCase().indexOf(substr.toLowerCase())))return i}else for(var realStartLine=-1!==startLine?startLine:sdpLines.length-1,j=realStartLine;j>=0;--j)if(0===sdpLines[j].indexOf(prefix)&&(!substr||-1!==sdpLines[j].toLowerCase().indexOf(substr.toLowerCase())))return j;return null}function getCodecPayloadTypeFromLine(sdpLine){var pattern=RegExp("a=rtpmap:(\\d+) [a-zA-Z0-9-]+\\/\\d+"),result=sdpLine.match(pattern);return result&&2===result.length?result[1]:null}function setDefaultCodec(mLine,payload){var elements=mLine.split(" "),newLine=elements.slice(0,3);newLine.push(payload);for(var i=3;i<elements.length;i++)elements[i]!==payload&&newLine.push(elements[i]);return newLine.join(" ")}function setPreferredCodec(sdp,type,codec){if(!codec)return sdp;var sdpLines=sdp.split("\r\n"),mLineIndex=findLineInRange(sdpLines,0,-1,"m=",type);if(null===mLineIndex)return sdp;for(var payload=null,i=sdpLines.length-1;i>=0;--i){var index=findLineInRange(sdpLines,i,0,"a=rtpmap",codec,"desc");if(null!==index)i=index,(payload=getCodecPayloadTypeFromLine(sdpLines[index]))&&(sdpLines[mLineIndex]=setDefaultCodec(sdpLines[mLineIndex],payload));else break}return sdp=sdpLines.join("\r\n")}function _removeExtmapMixedFromSDP(description){return description&&description.sdp&&-1!==description.sdp.indexOf("\na=extmap-allow-mixed")&&(description.sdp=description.sdp.split("\n").filter(function(line){return"a=extmap-allow-mixed"!==line.trim()}).join("\n")),description}function setMediaBitrate(sdp,media,bitrate){if(!bitrate)return sdp.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"");for(var lines=sdp.split("\n"),line=-1,modifier=Helpers.getVersionFirefox()?"TIAS":"AS",amount=Helpers.getVersionFirefox()?1024*bitrate:bitrate,i=0;i<lines.length;i++)if(0===lines[i].indexOf("m="+media)){line=i;break}if(-1===line)return sdp;for(line++;0===lines[line].indexOf("i=")||0===lines[line].indexOf("c=");)line++;if(0===lines[line].indexOf("b"))return lines[line]="b="+modifier+":"+amount,lines.join("\n");var newLines=lines.slice(0,line);return newLines.push("b="+modifier+":"+amount),(newLines=newLines.concat(lines.slice(line,lines.length))).join("\n")}qbRTCPeerConnection.State={NEW:1,CONNECTING:2,CHECKING:3,CONNECTED:4,DISCONNECTED:5,FAILED:6,CLOSED:7,COMPLETED:8},qbRTCPeerConnection.prototype._init=function(delegate,userID,sessionID,polite){Helpers.trace("RTCPeerConnection init.","userID: ",userID,", sessionID: ",sessionID,", polite: ",polite),this.delegate=delegate,this.localIceCandidates=[],this.remoteIceCandidates=[],this.remoteSDP=void 0,this.sessionID=sessionID,this.polite=polite,this.userID=userID,this._reconnecting=!1,this.state=qbRTCPeerConnection.State.NEW,this._pc.onicecandidate=this.onIceCandidateCallback.bind(this),this._pc.onsignalingstatechange=this.onSignalingStateCallback.bind(this),this._pc.oniceconnectionstatechange=this.onIceConnectionStateCallback.bind(this),this._pc.ontrack=this.onTrackCallback.bind(this),this.dialingTimer=null,this.answerTimeInterval=0,this.statsReportTimer=null},qbRTCPeerConnection.prototype.release=function(){this._clearDialingTimer(),this._clearStatsReportTimer(),this._pc.close(),this.state=qbRTCPeerConnection.State.CLOSED,this._pc.onicecandidate=null,this._pc.onsignalingstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.ontrack=null,navigator.userAgent.includes("Edge")&&(this.connectionState="closed",this.iceConnectionState="closed")},qbRTCPeerConnection.prototype.negotiate=function(){var self1=this;return this.setLocalSessionDescription({type:"offer",options:{iceRestart:!0}},function(error){if(error)return Helpers.traceError("Error in 'negotiate': "+error);var description=self1._pc.localDescription.toJSON();self1.delegate.update({reason:"reconnect",sessionDescription:{offerId:self1.offerId,sdp:description.sdp,type:description.type}},self1.userID)})},qbRTCPeerConnection.prototype.setRemoteSDP=function(newSDP){if(newSDP)this.remoteSDP=newSDP;else throw Error("sdp string can't be empty.")},qbRTCPeerConnection.prototype.getRemoteSDP=function(){return this.remoteSDP},qbRTCPeerConnection.prototype.setLocalSessionDescription=function(params,callback){var self1=this;function successCallback(description){var modifiedDescription=_removeExtmapMixedFromSDP(description);modifiedDescription.sdp=setPreferredCodec(modifiedDescription.sdp,"video",self1.preferredCodec),self1.delegate.bandwidth&&(modifiedDescription.sdp=setMediaBitrate(modifiedDescription.sdp,"video",self1.delegate.bandwidth)),self1._pc.setLocalDescription(modifiedDescription).then(function(){callback(null)}).catch(function(error){Helpers.traceError("Error in 'setLocalSessionDescription': "+error),callback(error)})}self1.state=qbRTCPeerConnection.State.CONNECTING,window.RTCRtpTransceiver&&"setCodecPreferences"in window.RTCRtpTransceiver.prototype&&Helpers.getVersionSafari()&&self1._pc.getTransceivers().forEach(function(transceiver){var kind=transceiver.sender.track.kind,sendCodecs=window.RTCRtpSender.getCapabilities(kind).codecs,recvCodecs=window.RTCRtpReceiver.getCapabilities(kind).codecs;if("video"===kind){var preferredCodecSendIndex=sendCodecs.findIndex(function(codec){return codec.mimeType.toLowerCase().includes(self1.preferredCodec.toLowerCase())});if(-1!==preferredCodecSendIndex){var arrayWithPreferredSendCodec=sendCodecs.splice(preferredCodecSendIndex,1);sendCodecs.unshift(arrayWithPreferredSendCodec[0])}var preferredCodecRecvIndex=recvCodecs.findIndex(function(codec){return codec.mimeType.toLowerCase().includes(self1.preferredCodec.toLowerCase())});if(-1!==preferredCodecRecvIndex){var arrayWithPreferredRecvCodec=recvCodecs.splice(preferredCodecRecvIndex,1);recvCodecs.unshift(arrayWithPreferredRecvCodec[0])}transceiver.setCodecPreferences(sendCodecs.concat(recvCodecs))}}),"answer"===params.type?this._pc.createAnswer(params.options).then(successCallback).catch(callback):this._pc.createOffer(params.options).then(successCallback).catch(callback)},qbRTCPeerConnection.prototype.setRemoteSessionDescription=function(description,callback){var modifiedSDP=this.delegate.bandwidth?{type:description.type,sdp:setMediaBitrate(description.sdp,"video",this.delegate.bandwidth)}:description;this._pc.setRemoteDescription(modifiedSDP).then(function(){callback()}).catch(function(error){Helpers.traceError("Error in 'setRemoteSessionDescription': "+error),callback(error)})},qbRTCPeerConnection.prototype.addLocalStream=function(stream){if(!stream)throw Error("'qbRTCPeerConnection.addLocalStream' error: stream is not defined");var self1=this;stream.getTracks().forEach(function(track){self1._pc.addTrack(track,stream)})},qbRTCPeerConnection.prototype._addIceCandidate=function(iceCandidate){return this._pc.addIceCandidate(iceCandidate).catch(function(error){Helpers.traceError("Error on 'addIceCandidate': "+error)})},qbRTCPeerConnection.prototype.addCandidates=function(iceCandidates){var self1=this;iceCandidates.forEach(function(candidate){self1.remoteIceCandidates.push(candidate)}),this._pc.remoteDescription&&self1.remoteIceCandidates.forEach(function(candidate){self1._addIceCandidate(candidate)})},qbRTCPeerConnection.prototype.toString=function sessionToString(){return"sessionID: "+this.sessionID+", userID: "+this.userID+", state: "+this.state},qbRTCPeerConnection.prototype.onSignalingStateCallback=function(){if("stable"===this._pc.signalingState&&this.localIceCandidates.length>0)for(this.delegate.processIceCandidates(this,this.localIceCandidates);this.localIceCandidates.length;)this.localIceCandidates.pop()},qbRTCPeerConnection.prototype.onIceCandidateCallback=function(event){if(event.candidate){var candidate={candidate:event.candidate.candidate,sdpMid:event.candidate.sdpMid,sdpMLineIndex:event.candidate.sdpMLineIndex};"stable"===this._pc.signalingState?this.delegate.processIceCandidates(this,[candidate]):this.localIceCandidates.push(candidate)}},qbRTCPeerConnection.prototype.onTrackCallback=function(event){this.remoteStream=event.streams[0],"function"==typeof this.delegate._onRemoteStreamListener&&["connected","completed"].includes(this._pc.iceConnectionState)&&this.delegate._onRemoteStreamListener(this.userID,this.remoteStream),this._getStatsWrap()},qbRTCPeerConnection.prototype.onIceConnectionStateCallback=function(){Helpers.trace("onIceConnectionStateCallback: "+this._pc.iceConnectionState);var connectionState=null;switch(this._pc.iceConnectionState){case"checking":this.state=qbRTCPeerConnection.State.CHECKING,connectionState=Helpers.SessionConnectionState.CONNECTING;break;case"connected":this._reconnecting&&this.delegate._stopReconnectTimer(this.userID),this.state=qbRTCPeerConnection.State.CONNECTED,connectionState=Helpers.SessionConnectionState.CONNECTED;break;case"completed":this._reconnecting&&this.delegate._stopReconnectTimer(this.userID),this.state=qbRTCPeerConnection.State.COMPLETED,connectionState=Helpers.SessionConnectionState.COMPLETED;break;case"failed":this.delegate._startReconnectTimer(this.userID),this.state=qbRTCPeerConnection.State.FAILED,connectionState=Helpers.SessionConnectionState.FAILED;break;case"disconnected":this.delegate._startReconnectTimer(this.userID),this.state=qbRTCPeerConnection.State.DISCONNECTED,connectionState=Helpers.SessionConnectionState.DISCONNECTED;break;case"closed":this.delegate._stopReconnectTimer(this.userID),this.state=qbRTCPeerConnection.State.CLOSED,connectionState=Helpers.SessionConnectionState.CLOSED}"function"==typeof this.delegate._onSessionConnectionStateChangedListener&&connectionState&&this.delegate._onSessionConnectionStateChangedListener(this.userID,connectionState),"connected"===this._pc.iceConnectionState&&"function"==typeof this.delegate._onRemoteStreamListener&&this.delegate._onRemoteStreamListener(this.userID,this.remoteStream)},qbRTCPeerConnection.prototype._clearStatsReportTimer=function(){this.statsReportTimer&&(clearInterval(this.statsReportTimer),this.statsReportTimer=null)},qbRTCPeerConnection.prototype._getStatsWrap=function(){var statsReportInterval,lastResult,self1=this;if(config.webrtc&&config.webrtc.statsReportTimeInterval&&!self1.statsReportTimer){if(isNaN(+config.webrtc.statsReportTimeInterval)){Helpers.traceError("statsReportTimeInterval ("+config.webrtc.statsReportTimeInterval+") must be integer.");return}statsReportInterval=1e3*config.webrtc.statsReportTimeInterval,Helpers.trace("Stats tracker has been started."),self1.statsReportTimer=setInterval(function(){_getStats(self1._pc,lastResult,function(results,lastResults){lastResult=lastResults,self1.delegate._onCallStatsReport(self1.userID,results,null)},function errorLog(err){Helpers.traceError("_getStats error. "+err.name+": "+err.message),self1.delegate._onCallStatsReport(self1.userID,null,err)})},statsReportInterval)}},qbRTCPeerConnection.prototype._clearDialingTimer=function(){this.dialingTimer&&(Helpers.trace("_clearDialingTimer"),clearInterval(this.dialingTimer),this.dialingTimer=null,this.answerTimeInterval=0)},qbRTCPeerConnection.prototype._startDialingTimer=function(extension){var self1=this,dialingTimeInterval=1e3*config.webrtc.dialingTimeInterval;Helpers.trace("_startDialingTimer, dialingTimeInterval: "+dialingTimeInterval);var _dialingCallback=function(extension,skipIncrement){skipIncrement||(self1.answerTimeInterval+=dialingTimeInterval),Helpers.trace("_dialingCallback, answerTimeInterval: "+self1.answerTimeInterval),self1.answerTimeInterval>=1e3*config.webrtc.answerTimeInterval?(self1._clearDialingTimer(),self1.delegate.processOnNotAnswer(self1)):self1.delegate.processCall(self1,extension)};self1.dialingTimer=setInterval(_dialingCallback,dialingTimeInterval,extension,!1),_dialingCallback(extension,!0)},module.exports=qbRTCPeerConnection},{"../../qbConfig":252,"./qbWebRTCHelpers":246}],245:[function(require1,module,exports){"use strict";var WebRTCSession=require1("./qbWebRTCSession"),WebRTCSignalingProcessor=require1("./qbWebRTCSignalingProcessor"),WebRTCSignalingProvider=require1("./qbWebRTCSignalingProvider"),Helpers=require1("./qbWebRTCHelpers"),RTCPeerConnection=require1("./qbRTCPeerConnection"),SignalingConstants=require1("./qbWebRTCSignalingConstants"),Utils=require1("../../qbUtils"),config=require1("../../qbConfig"),LiveSessionStates=[WebRTCSession.State.NEW,WebRTCSession.State.CONNECTING,WebRTCSession.State.ACTIVE];function WebRTCClient(service,chat){this.chat=chat,this.signalingProcessor=new WebRTCSignalingProcessor(service,this),this.signalingProvider=new WebRTCSignalingProvider(service,chat),chat.webrtcSignalingProcessor=this.signalingProcessor,this.SessionConnectionState=Helpers.SessionConnectionState,this.CallType=Helpers.CallType,this.PeerConnectionState=RTCPeerConnection.State,this.sessions={},navigator.mediaDevices&&"ondevicechange"in navigator.mediaDevices&&(navigator.mediaDevices.ondevicechange=this._onDevicesChangeListener.bind(this))}function isOpponentsEqual(exOpponents,currentOpponents){var ans=!1,cOpponents=currentOpponents.sort();return exOpponents.length&&exOpponents.forEach(function(i){var array=i.sort();ans=array.length==cOpponents.length&&array.every(function(el,index){return el===cOpponents[index]})}),ans}function getOpponentsIdNASessions(sessions){var opponents=[];return Object.keys(sessions).length>0&&Object.keys(sessions).forEach(function(key,i,arr){var session=sessions[key];(session.state===WebRTCSession.State.NEW||session.state===WebRTCSession.State.ACTIVE)&&opponents.push(session.opponentsIDs)}),opponents}WebRTCClient.prototype.getMediaDevices=function(spec){var specDevices=[],errMsg="Browser does not support output device selection.";return new Promise(function(resolve,reject){navigator.mediaDevices&&navigator.mediaDevices.enumerateDevices?navigator.mediaDevices.enumerateDevices().then(function(devices){spec?(devices.forEach(function(device,i){device.kind===spec&&specDevices.push(device)}),resolve(specDevices)):resolve(devices)}):(reject(errMsg),Helpers.traceWarning(errMsg))})},WebRTCClient.prototype.sessions={},WebRTCClient.prototype.createNewSession=function(opponentsIDs,ct,cID,opts){var opponentsIdNASessions=getOpponentsIdNASessions(this.sessions),callerID=cID||Helpers.getIdFromNode(this.chat.connection.jid),bandwidth=opts&&opts.bandwidth&&!isNaN(opts.bandwidth)?+opts.bandwidth:0;if(!opponentsIDs)throw Error("Can't create a session without the opponentsIDs.");if(!Array.isArray(opponentsIDs))throw Error('"opponentsIDs" should be Array of numbers');if(opponentsIDs.forEach(function(id){var value=parseInt(id);if(isNaN(value))throw Error('"opponentsIDs" should be Array of numbers');id=value}),!isOpponentsEqual(opponentsIdNASessions,opponentsIDs))return this._createAndStoreSession(null,callerID,opponentsIDs,ct||2,bandwidth);throw Error("Can't create a session with the same opponentsIDs. There is a session already in NEW or ACTIVE state.")},WebRTCClient.prototype._createAndStoreSession=function(sessionID,callerID,opponentsIDs,callType,bandwidth){var newSession=new WebRTCSession({sessionID:sessionID,initiatorID:callerID,opIDs:opponentsIDs,callType:callType,signalingProvider:this.signalingProvider,currentUserID:Helpers.getIdFromNode(this.chat.connection.jid),bandwidth:bandwidth});return newSession.onUserNotAnswerListener=this.onUserNotAnswerListener,newSession.onReconnectListener=this.onReconnectListener,newSession.onRemoteStreamListener=this.onRemoteStreamListener,newSession.onSessionConnectionStateChangedListener=this.onSessionConnectionStateChangedListener,newSession.onSessionCloseListener=this.onSessionCloseListener,newSession.onCallStatsReport=this.onCallStatsReport,this.sessions[newSession.ID]=newSession,newSession},WebRTCClient.prototype.clearSession=function(sessionId){delete WebRTCClient.sessions[sessionId]},WebRTCClient.prototype.isExistLiveSessionExceptSessionID=function(sessionID){var exist=!1,sessions=this.sessions;return Object.keys(sessions).length>0&&(exist=Object.keys(sessions).some(function(key){var session=sessions[key];return LiveSessionStates.includes(session.state)&&session.ID!==sessionID})),exist},WebRTCClient.prototype.getNewSessionsCount=function(exceptId){var sessions=this.sessions;return Object.keys(sessions).reduce(function(count,sessionId){var session=sessions[sessionId];return session.ID===exceptId?count:session.state===WebRTCSession.State.NEW?count+1:count},0)},WebRTCClient.prototype._onCallListener=function(userID,sessionID,extension){var userInfo=extension.userInfo||{},currentUserID=Helpers.getIdFromNode(this.chat.connection.jid);if(userID===currentUserID&&!extension.opponentsIDs.includes(currentUserID)){Helpers.trace('Ignore "onCall" signal from current user. userID:'+userID+", sessionID: "+sessionID);return}Helpers.trace("onCall. UserID:"+userID+". SessionID: "+sessionID);var otherActiveSessions=this.isExistLiveSessionExceptSessionID(sessionID),newSessionsCount=this.getNewSessionsCount(sessionID);if(otherActiveSessions&&!this.sessions[sessionID]&&newSessionsCount++,otherActiveSessions&&(config.webrtc.autoReject||newSessionsCount>config.webrtc.incomingLimit))Helpers.trace("User with id "+userID+" is busy at the moment."),delete extension.sessionDescription,delete extension.platform,extension.sessionID=sessionID,this.signalingProvider.sendMessage(userID,extension,SignalingConstants.SignalingType.REJECT),"function"==typeof this.onInvalidEventsListener&&Utils.safeCallbackCall(this.onInvalidEventsListener,"onCall",sessionID,userID,userInfo);else{var session=this.sessions[sessionID],bandwidth=+userInfo.bandwidth||0;session||(session=this._createAndStoreSession(sessionID,extension.callerID,extension.opponentsIDs,extension.callType,bandwidth),"function"==typeof this.onCallListener&&Utils.safeCallbackCall(this.onCallListener,session,userInfo)),session.processOnCall(userID,extension)}},WebRTCClient.prototype._onAcceptListener=function(userID,sessionID,extension){var session=this.sessions[sessionID],userInfo=extension.userInfo||{};Helpers.trace("onAccept. UserID:"+userID+". SessionID: "+sessionID),session?session.state===WebRTCSession.State.CONNECTING||session.state===WebRTCSession.State.ACTIVE?("function"==typeof this.onAcceptCallListener&&Utils.safeCallbackCall(this.onAcceptCallListener,session,userID,userInfo),session.processOnAccept(userID,extension)):("function"==typeof this.onInvalidEventsListener&&Utils.safeCallbackCall(this.onInvalidEventsListener,"onAccept",session,userID,userInfo),Helpers.traceWarning("Ignore 'onAccept', the session( "+sessionID+" ) has invalid state.")):Helpers.traceError("Ignore 'onAccept', there is no information about session "+sessionID+" by some reason.")},WebRTCClient.prototype._onRejectListener=function(userID,sessionID,extension){var session=this.sessions[sessionID];if(Helpers.trace("onReject. UserID:"+userID+". SessionID: "+sessionID),session){var userInfo=extension.userInfo||{};"function"==typeof this.onRejectCallListener&&Utils.safeCallbackCall(this.onRejectCallListener,session,userID,userInfo),session.processOnReject(userID,extension)}else Helpers.traceError("Ignore 'onReject', there is no information about session "+sessionID+" by some reason.")},WebRTCClient.prototype._onStopListener=function(userID,sessionID,extension){Helpers.trace("onStop. UserID:"+userID+". SessionID: "+sessionID);var session=this.sessions[sessionID],userInfo=extension.userInfo||{};session&&LiveSessionStates.includes(session.state)?("function"==typeof this.onStopCallListener&&Utils.safeCallbackCall(this.onStopCallListener,session,userID,userInfo),setTimeout(session.processOnStop.bind(session),10,userID,extension)):("function"==typeof this.onInvalidEventsListener&&Utils.safeCallbackCall(this.onInvalidEventsListener,"onStop",session,userID,userInfo),Helpers.traceError("Ignore 'onStop', there is no information about session "+sessionID+" by some reason."))},WebRTCClient.prototype._onIceCandidatesListener=function(userID,sessionID,extension){var session=this.sessions[sessionID];Helpers.trace("onIceCandidates. UserID:"+userID+". SessionID: "+sessionID+". ICE candidates count: "+extension.iceCandidates.length),session?session.state===WebRTCSession.State.CONNECTING||session.state===WebRTCSession.State.ACTIVE?session.processOnIceCandidates(userID,extension):Helpers.traceWarning("Ignore 'OnIceCandidates', the session ( "+sessionID+" ) has invalid state."):Helpers.traceError("Ignore 'OnIceCandidates', there is no information about session "+sessionID+" by some reason.")},WebRTCClient.prototype._onUpdateListener=function(userID,sessionID,extension){var session=this.sessions[sessionID],userInfo=extension.userInfo||{};Helpers.trace("onUpdate. UserID:"+userID+". SessionID: "+sessionID+". Extension: "+JSON.stringify(userInfo)),session&&(extension.reason&&session.processOnUpdate(userID,extension),"function"==typeof this.onUpdateCallListener&&Utils.safeCallbackCall(this.onUpdateCallListener,session,userID,userInfo))},WebRTCClient.prototype._onDevicesChangeListener=function(){"function"==typeof this.onDevicesChangeListener&&Utils.safeCallbackCall(this.onDevicesChangeListener)},module.exports=WebRTCClient},{"../../qbConfig":252,"../../qbUtils":256,"./qbRTCPeerConnection":244,"./qbWebRTCHelpers":246,"./qbWebRTCSession":247,"./qbWebRTCSignalingConstants":248,"./qbWebRTCSignalingProcessor":249,"./qbWebRTCSignalingProvider":250}],246:[function(require1,module,exports){"use strict";var config=require1("../../qbConfig");module.exports={getUserJid:function(id,appId){return id+"-"+appId+"@"+config.endpoints.chat},getIdFromNode:function(jid){return 0>jid.indexOf("@")?null:parseInt(jid.split("@")[0].split("-")[0])},trace:function(text){config.debug&&console.log("[QBWebRTC]:",text)},traceWarning:function(text){config.debug&&console.warn("[QBWebRTC]:",text)},traceError:function(text){config.debug&&console.error("[QBWebRTC]:",text)},getLocalTime:function(){return new Date().toString().split(" ").slice(1,5).join("-")},isIOS:function(){return!!window&&!!window.navigator&&!!window.navigator.userAgent&&!!window.navigator.userAgent.match(/iP(ad|hone)/i)},isIOSSafari:function(){if(!window||!window.navigator||!window.navigator.userAgent)return!1;var ua=window.navigator.userAgent,iOS=!!ua.match(/iP(ad|hone)/i),isWebkit=!!ua.match(/WebKit/i),isChrome=!!ua.match(/CriOS/i);return iOS&&isWebkit&&!isChrome},isIOSChrome:function(){if(!window||!window.navigator||!window.navigator.userAgent)return!1;var ua=window.navigator.userAgent,iOS=!!ua.match(/iP(ad|hone)/i),isWebkit=!!ua.match(/WebKit/i),isChrome=!!ua.match(/CriOS/i);return iOS&&!isWebkit&&isChrome},getVersionFirefox:function(){var version,ua=!!navigator&&navigator.userAgent;if(ua){var ffInfo=ua.match(/(?:firefox)[ \/](\d+)/i)||[];version=ffInfo[1]?+ffInfo[1]:null}return version},getVersionSafari:function(){var version,ua=!!navigator&&navigator.userAgent;if(ua){if((ua.match(/(?:safari)[ \/](\d+)/i)||[]).length){var sVer=ua.match(/(?:version)[ \/](\d+)/i)||[];version=sVer&&sVer[1]?+sVer[1]:null}else version=null}return version},delay:function(timeout){return timeout="number"==typeof timeout&&timeout>0?timeout:0,new Promise(function(resolve){setTimeout(resolve,timeout)})},SessionConnectionState:{UNDEFINED:0,CONNECTING:1,CONNECTED:2,FAILED:3,DISCONNECTED:4,CLOSED:5,COMPLETED:6},CallType:{VIDEO:1,AUDIO:2}}},{"../../qbConfig":252}],247:[function(require1,module,exports){"use strict";var config=require1("../../qbConfig"),qbRTCPeerConnection=require1("./qbRTCPeerConnection"),Utils=require1("../../qbUtils"),Helpers=require1("./qbWebRTCHelpers"),SignalingConstants=require1("./qbWebRTCSignalingConstants");WebRTCSession.State={NEW:1,ACTIVE:2,HUNGUP:3,REJECTED:4,CLOSED:5};var ReconnectionState={RECONNECTING:"reconnecting",RECONNECTED:"reconnected",FAILED:"failed"};function WebRTCSession(params){this.ID=params.sessionID?params.sessionID:generateUUID(),this.state=WebRTCSession.State.NEW,this.initiatorID=parseInt(params.initiatorID),this.opponentsIDs=params.opIDs,this.callType=parseInt(params.callType),this.peerConnections={},this.mediaParams=null,this.iceConnectTimers={},this.reconnectTimers={},this.signalingProvider=params.signalingProvider,this.currentUserID=params.currentUserID,this.bandwidth=params.bandwidth,this.answerTimer=null,this.startCallTime=0,this.acceptCallTime=0,this.localStream=void 0}function generateUUID(){var d=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){var r=(d+16*Math.random())%16|0;return d=Math.floor(d/16),("x"==c?r:3&r|8).toString(16)})}function _prepareExtension(extension){var ext={};try{if("[object Object]"===({}).toString.call(extension))ext.userInfo=extension,ext=JSON.parse(JSON.stringify(ext).replace(/null/g,'""'));else throw Error('Invalid type of "extension" object.')}catch(err){Helpers.traceWarning(err.message)}return ext}WebRTCSession.prototype.getUserMedia=function(params,callback){if(!navigator.mediaDevices.getUserMedia)throw Error("getUserMedia() is not supported in your browser");var self1=this,mediaConstraints={audio:params.audio||!1,video:params.video||!1};function successCallback(stream){self1.localStream=stream,self1.mediaParams=Object.assign({},params),params.elemId&&self1.attachMediaStream(params.elemId,stream,params.options),callback&&"function"==typeof callback&&callback(void 0,stream)}navigator.mediaDevices.getUserMedia(mediaConstraints).then(successCallback).catch(callback)},WebRTCSession.prototype.connectionStateForUser=function(userID){var peerConnection=this.peerConnections[userID];return peerConnection?peerConnection.state:void 0},WebRTCSession.prototype.attachMediaStream=function(elementId,stream,options){var elem=document.getElementById(elementId);if(elem){if(elem instanceof HTMLMediaElement)"srcObject"in elem?elem.srcObject=stream:elem.src=window.URL.createObjectURL(stream),options&&options.muted&&(elem.muted=!0),options&&options.mirror&&(elem.style.transform="scaleX(-1)"),elem.autoplay||(elem.onloadedmetadata=function(){elem.play()});else throw Error('Cannot attach media stream to element with id "'+elementId+'" because it is not of type HTMLMediaElement')}else throw Error('Unable to attach media stream, cannot find element by Id "'+elementId+'"')},WebRTCSession.prototype.detachMediaStream=function(elementId){var elem=document.getElementById(elementId);elem&&elem instanceof HTMLMediaElement&&(elem.pause(),elem.srcObject&&"object"==typeof elem.srcObject?(elem.srcObject.getTracks().forEach(function(track){track.stop(),track.enabled=!1}),elem.srcObject=null):elem.src="",elem.removeAttribute("src"),elem.removeAttribute("srcObject"))},WebRTCSession.prototype.switchMediaTracks=function(deviceIds,callback){if(!navigator.mediaDevices.getUserMedia)throw Error("getUserMedia() is not supported in your browser");var self1=this;deviceIds&&deviceIds.audio&&(this.mediaParams.audio.deviceId=deviceIds.audio),deviceIds&&deviceIds.video&&(this.mediaParams.video.deviceId=deviceIds.video),this.localStream.getTracks().forEach(function(track){track.stop()}),navigator.mediaDevices.getUserMedia({audio:self1.mediaParams.audio||!1,video:self1.mediaParams.video||!1}).then(function(stream){self1._replaceTracks(stream),callback(null,stream)}).catch(function(error){callback(error,null)})},WebRTCSession.prototype._replaceTracks=function(stream){var localStream=this.localStream,elemId=this.mediaParams.elemId,ops=this.mediaParams.options,currentStreamTracks=localStream.getTracks(),newStreamTracks=stream.getTracks();function _replaceTracksForPeer(peer){return Promise.all(peer.getSenders().map(function(sender){return sender.replaceTrack(newStreamTracks.find(function(track){return track.kind===sender.track.kind}))}))}return this.detachMediaStream(elemId),newStreamTracks.forEach(function(newTrack){let currentTrack=currentStreamTracks.find(function(track){return track.kind===newTrack.kind});currentTrack&&(currentTrack.stop(),localStream.removeTrack(currentTrack),localStream.addTrack(newTrack))}),elemId&&this.attachMediaStream(elemId,stream,ops),Promise.all(Object.values(this.peerConnections).map(function(peerConnection){return peerConnection._pc}).map(_replaceTracksForPeer))},WebRTCSession.prototype.call=function(extension,callback){var self1=this,ext=_prepareExtension(extension);Helpers.trace("Call, extension: "+JSON.stringify(ext.userInfo)),self1.state=WebRTCSession.State.ACTIVE,self1._reconnectToChat(function(){self1.state===WebRTCSession.State.ACTIVE&&self1.opponentsIDs.forEach(function(userID){self1._callInternal(userID,ext)})}),"function"==typeof callback&&callback(null)},WebRTCSession.prototype._callInternal=function(userID,extension){var peer=this._createPeer(userID,this.currentUserID<userID);this.peerConnections[userID]=peer,peer.addLocalStream(this.localStream),peer.setLocalSessionDescription({type:"offer"},function(error){error?Helpers.trace("setLocalSessionDescription error: "+error):(Helpers.trace("setLocalSessionDescription success"),peer._startDialingTimer(extension))})},WebRTCSession.prototype.accept=function(extension){var self1=this,ext=_prepareExtension(extension);if(Helpers.trace("Accept, extension: "+JSON.stringify(ext.userInfo)),self1.state===WebRTCSession.State.ACTIVE){Helpers.traceError("Can't accept, the session is already active, return.");return}if(self1.state===WebRTCSession.State.CLOSED){Helpers.traceError("Can't accept, the session is already closed, return."),self1.stop({});return}self1.state=WebRTCSession.State.ACTIVE,self1.acceptCallTime=new Date,self1._clearAnswerTimer(),self1._acceptInternal(self1.initiatorID,ext);var oppIDs=self1._uniqueOpponentsIDsWithoutInitiator();if(oppIDs.length>0){var offerTime=(self1.acceptCallTime-self1.startCallTime)/1e3;self1._startWaitingOfferOrAnswerTimer(offerTime),oppIDs.forEach(function(opID,i,arr){self1.currentUserID>opID&&self1._callInternal(opID,{},!0)})}},WebRTCSession.prototype._acceptInternal=function(userID,extension){var self1=this,peerConnection=this.peerConnections[userID];if(peerConnection){var remoteSDP=peerConnection.getRemoteSDP();peerConnection.addLocalStream(self1.localStream),peerConnection.setRemoteSessionDescription(remoteSDP,function(error){error?Helpers.traceError("'setRemoteSessionDescription' error: "+error):(Helpers.trace("'setRemoteSessionDescription' success"),peerConnection.setLocalSessionDescription({type:"answer"},function(err){err?Helpers.trace("setLocalSessionDescription error: "+err):(Helpers.trace("'setLocalSessionDescription' success"),extension.sessionID=self1.ID,extension.callType=self1.callType,extension.callerID=self1.initiatorID,extension.opponentsIDs=self1.opponentsIDs,peerConnection._pc.localDescription&&(extension.sdp=peerConnection._pc.localDescription.toJSON().sdp),self1.signalingProvider.sendMessage(userID,extension,SignalingConstants.SignalingType.ACCEPT))}))})}else Helpers.traceError("Can't accept the call, peer connection for userID "+userID+" was not found")},WebRTCSession.prototype.reject=function(extension){var self1=this,ext=_prepareExtension(extension);Helpers.trace("Reject, extension: "+JSON.stringify(ext.userInfo)),self1.state=WebRTCSession.State.REJECTED,self1._clearAnswerTimer(),ext.sessionID=self1.ID,ext.callType=self1.callType,ext.callerID=self1.initiatorID,ext.opponentsIDs=self1.opponentsIDs,Object.keys(self1.peerConnections).forEach(function(key){var peerConnection=self1.peerConnections[key];self1.signalingProvider.sendMessage(peerConnection.userID,ext,SignalingConstants.SignalingType.REJECT)}),self1._close()},WebRTCSession.prototype.stop=function(extension){var self1=this,ext=_prepareExtension(extension);Helpers.trace("Stop, extension: "+JSON.stringify(ext.userInfo)),self1.state=WebRTCSession.State.HUNGUP,self1.answerTimer&&self1._clearAnswerTimer(),ext.sessionID=self1.ID,ext.callType=self1.callType,ext.callerID=self1.initiatorID,ext.opponentsIDs=self1.opponentsIDs,Object.keys(self1.peerConnections).forEach(function(key){var peerConnection=self1.peerConnections[key];self1.signalingProvider.sendMessage(peerConnection.userID,ext,SignalingConstants.SignalingType.STOP)}),self1._close()},WebRTCSession.prototype.closeConnection=function(userId){var peer=this.peerConnections[userId];if(!peer)return Helpers.traceWarn("Not found connection with user ("+userId+")"),!1;try{peer.release()}catch(e){Helpers.traceError(e)}finally{this._closeSessionIfAllConnectionsClosed()}},WebRTCSession.prototype.update=function(extension,userID){var ext="object"==typeof extension?extension:{};if(Helpers.trace("Update, extension: "+JSON.stringify(extension)),null===extension){Helpers.trace("extension is null, no parameters to update");return}if(ext.sessionID=this.ID,ext.callType=this.callType,ext.callerID=this.initiatorID,ext.opponentsIDs=this.opponentsIDs,userID)this.signalingProvider.sendMessage(userID,ext,SignalingConstants.SignalingType.PARAMETERS_CHANGED);else for(var key in this.peerConnections){var peer=this.peerConnections[key];this.signalingProvider.sendMessage(peer.userID,ext,SignalingConstants.SignalingType.PARAMETERS_CHANGED)}},WebRTCSession.prototype.mute=function(type){this._muteStream(0,type)},WebRTCSession.prototype.unmute=function(type){this._muteStream(1,type)},WebRTCSession.prototype.processOnCall=function(callerID,extension){var self1=this;self1._uniqueOpponentsIDs().forEach(function(opponentID){var peer=self1.peerConnections[opponentID];peer||(peer=self1._createPeer(opponentID,self1.currentUserID<opponentID),self1.peerConnections[opponentID]=peer,opponentID==callerID&&self1._startAnswerTimer()),opponentID==callerID&&(peer.setRemoteSDP(new window.RTCSessionDescription({sdp:extension.sdp,type:"offer"})),callerID!=self1.initiatorID&&self1.state===WebRTCSession.State.ACTIVE&&self1._acceptInternal(callerID,{}))})},WebRTCSession.prototype.processOnAccept=function(userID,extension){var self1=this,peerConnection=this.peerConnections[userID];if(peerConnection){if(peerConnection._clearDialingTimer(),"stable"!==peerConnection._pc.signalingState){var remoteSessionDescription=new window.RTCSessionDescription({sdp:extension.sdp,type:"answer"});peerConnection.setRemoteSDP(remoteSessionDescription),peerConnection.setRemoteSessionDescription(remoteSessionDescription,function(error){error?Helpers.traceError("'setRemoteSessionDescription' error: "+error):(Helpers.trace("'setRemoteSessionDescription' success"),self1.state!==WebRTCSession.State.ACTIVE&&(self1.state=WebRTCSession.State.ACTIVE))})}else Helpers.traceError("Ignore 'onAccept', PeerConnection is already in 'stable' state")}else Helpers.traceError("Ignore 'OnAccept': peer connection for user with Id "+userID+" was not found")},WebRTCSession.prototype.processOnReject=function(userID,extension){var peerConnection=this.peerConnections[userID];this._clearWaitingOfferOrAnswerTimer(),peerConnection?peerConnection.release():Helpers.traceError("Ignore 'OnReject', there is no information about peer connection by some reason."),this._closeSessionIfAllConnectionsClosed()},WebRTCSession.prototype.processOnStop=function(userID,extension){this._clearAnswerTimer();var peerConnection=this.peerConnections[userID];peerConnection?(peerConnection.release(),peerConnection._reconnecting&&(peerConnection._reconnecting=!1),this._stopReconnectTimer(userID)):Helpers.traceError("Ignore 'OnStop', there is no information about peer connection by some reason."),this._closeSessionIfAllConnectionsClosed()},WebRTCSession.prototype.processOnIceCandidates=function(userID,extension){var peerConnection=this.peerConnections[userID];peerConnection?peerConnection.addCandidates(extension.iceCandidates):Helpers.traceError("Ignore 'OnIceCandidates', there is no information about peer connection by some reason.")},WebRTCSession.prototype.processOnUpdate=function(userID,extension){var SRD=extension.sessionDescription,reason=extension.reason;this.state===WebRTCSession.State.ACTIVE&&reason&&"reconnect"===reason&&(this.peerConnections[userID]?SRD&&("offer"===SRD.type?this._processReconnectOffer(userID,SRD):this._processReconnectAnswer(userID,SRD)):Helpers.traceError("Ignore 'OnUpdate': peer connection for user with Id "+userID+" was not found"))},WebRTCSession.prototype._processReconnectOffer=function(userID,SRD){var self1=this;if(this.peerConnections[userID].polite){this._reconnect(this.peerConnections[userID]);var peer=this.peerConnections[userID],offerId=SRD.offerId,remoteDescription=new window.RTCSessionDescription({sdp:SRD.sdp,type:SRD.type});peer.setRemoteSDP(remoteDescription),peer.setRemoteSessionDescription(remoteDescription,function(e){e?Helpers.traceError('"setRemoteSessionDescription" error:'+e.message):peer.setLocalSessionDescription({type:"answer"},function(){var description=peer._pc.localDescription.toJSON(),ext={reason:"reconnect",sessionDescription:{offerId:offerId,sdp:description.sdp,type:description.type}};self1.update(ext,userID)})})}else this._reconnect(this.peerConnections[userID],!0)},WebRTCSession.prototype._processReconnectAnswer=function(userID,SRD){var peer=this.peerConnections[userID],offerId=SRD.offerId;if(peer&&peer.offerId&&offerId&&peer.offerId===offerId){var remoteDescription=new window.RTCSessionDescription({sdp:SRD.sdp,type:SRD.type});peer.setRemoteSDP(remoteDescription),peer.setRemoteSessionDescription(remoteDescription,function(e){e&&Helpers.traceError('"setRemoteSessionDescription" error:'+e.message)})}},WebRTCSession.prototype.processCall=function(peerConnection,ext){var extension=ext||{};peerConnection._pc.localDescription&&(extension.sessionID=this.ID,extension.callType=this.callType,extension.callerID=this.initiatorID,extension.opponentsIDs=this.opponentsIDs,extension.sdp=peerConnection._pc.localDescription.sdp,extension.userInfo=ext&&ext.userInfo?ext.userInfo:{},extension.userInfo.bandwidth=this.bandwidth,this.signalingProvider.sendMessage(peerConnection.userID,extension,SignalingConstants.SignalingType.CALL))},WebRTCSession.prototype.processIceCandidates=function(peerConnection,iceCandidates){var extension={};extension.sessionID=this.ID,extension.callType=this.callType,extension.callerID=this.initiatorID,extension.opponentsIDs=this.opponentsIDs,this.signalingProvider.sendCandidate(peerConnection.userID,iceCandidates,extension)},WebRTCSession.prototype.processOnNotAnswer=function(peerConnection){Helpers.trace("Answer timeout callback for session "+this.ID+" for user "+peerConnection.userID),this._clearWaitingOfferOrAnswerTimer(),peerConnection.release(),"function"==typeof this.onUserNotAnswerListener&&Utils.safeCallbackCall(this.onUserNotAnswerListener,this,peerConnection.userID),this._closeSessionIfAllConnectionsClosed()},WebRTCSession.prototype._onRemoteStreamListener=function(userID,stream){"function"==typeof this.onRemoteStreamListener&&Utils.safeCallbackCall(this.onRemoteStreamListener,this,userID,stream)},WebRTCSession.prototype._onCallStatsReport=function(userId,stats,error){"function"==typeof this.onCallStatsReport&&Utils.safeCallbackCall(this.onCallStatsReport,this,userId,stats,error)},WebRTCSession.prototype._onSessionConnectionStateChangedListener=function(userID,connectionState){var StateClosed=Helpers.SessionConnectionState.CLOSED,peer=this.peerConnections[userID];"function"==typeof this.onSessionConnectionStateChangedListener&&Utils.safeCallbackCall(this.onSessionConnectionStateChangedListener,this,userID,connectionState),connectionState===StateClosed&&peer&&(peer._pc.onicecandidate=null,peer._pc.onsignalingstatechange=null,peer._pc.ontrack=null,peer._pc.oniceconnectionstatechange=null,delete this.peerConnections[userID])},WebRTCSession.prototype._createPeer=function(userId,polite){if(!window.RTCPeerConnection)throw Error("_createPeer error: RTCPeerConnection is not supported in your browser");this.startCallTime=new Date;var pcConfig={iceServers:config.webrtc.iceServers};Helpers.trace("_createPeer configuration: "+JSON.stringify(pcConfig));var peer=new qbRTCPeerConnection(pcConfig);return peer._init(this,userId,this.ID,polite),peer},WebRTCSession.prototype._startReconnectTimer=function(userID){var self1=this,delay=1e3*config.webrtc.disconnectTimeInterval,peer=this.peerConnections[userID];peer._reconnecting=!0;var reconnectTimeoutCallback=function(){Helpers.trace("disconnectTimeInterval reached for userID "+userID),self1._stopReconnectTimer(userID),self1.peerConnections[userID].release(),self1._onSessionConnectionStateChangedListener(userID,Helpers.SessionConnectionState.CLOSED),self1._closeSessionIfAllConnectionsClosed()};"function"==typeof this.onReconnectListener&&Utils.safeCallbackCall(this.onReconnectListener,this,userID,ReconnectionState.RECONNECTING),Helpers.trace("_startReconnectTimer for userID:"+userID+", timeout: "+delay),this.iceConnectTimers[userID]||(this.iceConnectTimers[userID]=setTimeout(function(){Helpers.trace("iceConnectTimeout reached for user "+userID),self1.iceConnectTimers[userID]&&(clearTimeout(self1.iceConnectTimers[userID]),self1.iceConnectTimers[userID]=void 0,self1.reconnectTimers[userID]||(self1.reconnectTimers[userID]=setTimeout(reconnectTimeoutCallback,delay-5e3),self1._reconnectToChat(function(){self1.state===WebRTCSession.State.ACTIVE&&self1.reconnectTimers[userID]&&self1._reconnect(peer,!0)})))},5e3))},WebRTCSession.prototype._stopReconnectTimer=function(userID){var peer=this.peerConnections[userID];if(this.iceConnectTimers[userID]&&(clearTimeout(this.iceConnectTimers[userID]),this.iceConnectTimers[userID]=void 0),this.reconnectTimers[userID]&&(Helpers.trace("_stopReconnectTimer for userID: "+userID),clearTimeout(this.reconnectTimers[userID]),this.reconnectTimers[userID]=void 0),peer&&peer._reconnecting&&(peer._reconnecting=!1,"function"==typeof this.onReconnectListener)){var state=peer._pc.iceConnectionState;Utils.safeCallbackCall(this.onReconnectListener,this,userID,"connected"===state?ReconnectionState.RECONNECTED:ReconnectionState.FAILED)}},WebRTCSession.prototype._reconnectToChat=function(callback){var self1=this,signalingProvider=this.signalingProvider,reconnectToChat=function(){var _onReconnectListener=signalingProvider.chat.onReconnectListener;signalingProvider.chat.onReconnectListener=function(){"function"==typeof _onReconnectListener&&_onReconnectListener(),signalingProvider.chat.onReconnectListener=_onReconnectListener,callback()},signalingProvider.chat.reconnect()};if(signalingProvider&&signalingProvider.chat)try{signalingProvider.chat.ping(function(e){self1.state!==WebRTCSession.State.CLOSED&&(e?reconnectToChat():callback())})}catch(e){self1.state!==WebRTCSession.State.CLOSED&&reconnectToChat()}},WebRTCSession.prototype._reconnect=function(peerConnection,negotiate){if(peerConnection&&peerConnection.userID){var userId=peerConnection.userID,polite=peerConnection.polite,_reconnecting=peerConnection._reconnecting;peerConnection.release();var pcConfig={iceServers:config.webrtc.iceServers};Helpers.trace("_reconnect peer configuration: "+JSON.stringify(pcConfig));var peer=new qbRTCPeerConnection(pcConfig);this.peerConnections[userId]=peer,peer._init(this,userId,this.ID,polite),peer._reconnecting=_reconnecting,peer.addLocalStream(this.localStream),negotiate&&(peer.offerId=generateUUID(),peer.negotiate())}},WebRTCSession.prototype._close=function(){for(var key in Helpers.trace("_close"),this.peerConnections){var peer=this.peerConnections[key];this._stopReconnectTimer(peer.userID);try{peer.release()}catch(e){console.warn("Peer close error:",e)}}this._closeLocalMediaStream(),"function"==typeof this._detectSilentAudioTaskCleanup&&(this._detectSilentAudioTaskCleanup(),this._detectSilentAudioTaskCleanup=void 0),"function"==typeof this._detectSilentVideoTaskCleanup&&(this._detectSilentVideoTaskCleanup(),this._detectSilentVideoTaskCleanup=void 0),this.state=WebRTCSession.State.CLOSED,"function"==typeof this.onSessionCloseListener&&Utils.safeCallbackCall(this.onSessionCloseListener,this)},WebRTCSession.prototype._closeSessionIfAllConnectionsClosed=function(){var isAllConnectionsClosed=Object.values(this.peerConnections).every(function(peer){return peer.state===qbRTCPeerConnection.State.CLOSED});Helpers.trace("All peer connections closed: "+isAllConnectionsClosed),isAllConnectionsClosed&&(this._closeLocalMediaStream(),"function"==typeof this.onSessionCloseListener&&this.onSessionCloseListener(this),this.state=WebRTCSession.State.CLOSED)},WebRTCSession.prototype._closeLocalMediaStream=function(){this.localStream&&(this.localStream.getTracks().forEach(function(track){track.stop(),track.enabled=!1}),this.localStream=null)},WebRTCSession.prototype._muteStream=function(bool,type){if("audio"===type&&this.localStream.getAudioTracks().length>0){this.localStream.getAudioTracks().forEach(function(track){track.enabled=!!bool});return}if("video"===type&&this.localStream.getVideoTracks().length>0){this.localStream.getVideoTracks().forEach(function(track){track.enabled=!!bool});return}},WebRTCSession.prototype._clearAnswerTimer=function(){this.answerTimer&&(Helpers.trace("_clearAnswerTimer"),clearTimeout(this.answerTimer),this.answerTimer=null)},WebRTCSession.prototype._startAnswerTimer=function(){Helpers.trace("_startAnswerTimer");var self1=this,answerTimeInterval=1e3*config.webrtc.answerTimeInterval;this.answerTimer=setTimeout(function(){Helpers.trace("_answerTimeoutCallback"),"function"==typeof self1.onSessionCloseListener&&self1._close(),self1.answerTimer=null},answerTimeInterval)},WebRTCSession.prototype._clearWaitingOfferOrAnswerTimer=function(){this.waitingOfferOrAnswerTimer&&(Helpers.trace("_clearWaitingOfferOrAnswerTimer"),clearTimeout(this.waitingOfferOrAnswerTimer),this.waitingOfferOrAnswerTimer=null)},WebRTCSession.prototype._startWaitingOfferOrAnswerTimer=function(time){var self1=this,timeout=config.webrtc.answerTimeInterval-time<0?1:config.webrtc.answerTimeInterval-time;Helpers.trace("_startWaitingOfferOrAnswerTimer, timeout: "+timeout),this.waitingOfferOrAnswerTimer=setTimeout(function(){Helpers.trace("waitingOfferOrAnswerTimeoutCallback"),Object.keys(self1.peerConnections).length>0&&Object.keys(self1.peerConnections).forEach(function(key){var peerConnection=self1.peerConnections[key];(peerConnection.state===qbRTCPeerConnection.State.CONNECTING||peerConnection.state===qbRTCPeerConnection.State.NEW)&&self1.processOnNotAnswer(peerConnection)}),self1.waitingOfferOrAnswerTimer=null},1e3*timeout)},WebRTCSession.prototype._uniqueOpponentsIDs=function(){var self1=this,opponents=[];return this.initiatorID!==this.currentUserID&&opponents.push(this.initiatorID),this.opponentsIDs.forEach(function(userID,i,arr){userID!=self1.currentUserID&&opponents.push(parseInt(userID))}),opponents},WebRTCSession.prototype._uniqueOpponentsIDsWithoutInitiator=function(){var self1=this,opponents=[];return this.opponentsIDs.forEach(function(userID,i,arr){userID!=self1.currentUserID&&opponents.push(parseInt(userID))}),opponents},WebRTCSession.prototype.toString=function sessionToString(){return"ID: "+this.ID+", initiatorID: "+this.initiatorID+", opponentsIDs: "+this.opponentsIDs+", state: "+this.state+", callType: "+this.callType},module.exports=WebRTCSession},{"../../qbConfig":252,"../../qbUtils":256,"./qbRTCPeerConnection":244,"./qbWebRTCHelpers":246,"./qbWebRTCSignalingConstants":248}],248:[function(require1,module,exports){"use strict";function WebRTCSignalingConstants(){}WebRTCSignalingConstants.MODULE_ID="WebRTCVideoChat",WebRTCSignalingConstants.SignalingType={CALL:"call",ACCEPT:"accept",REJECT:"reject",STOP:"hangUp",CANDIDATE:"iceCandidates",PARAMETERS_CHANGED:"update"},module.exports=WebRTCSignalingConstants},{}],249:[function(require1,module,exports){"use strict";require1("strophe.js");var SignalingConstants=require1("./qbWebRTCSignalingConstants");function WebRTCSignalingProcessor(service,delegate){var self1=this;self1.service=service,self1.delegate=delegate,this._onMessage=function(from,extraParams,delay,userId){var extension=self1._getExtension(extraParams),sessionId=extension.sessionID,signalType=extension.signalType;switch(delete extension.moduleIdentifier,delete extension.sessionID,delete extension.signalType,signalType){case SignalingConstants.SignalingType.CALL:"function"==typeof self1.delegate._onCallListener&&self1.delegate._onCallListener(userId,sessionId,extension);break;case SignalingConstants.SignalingType.ACCEPT:"function"==typeof self1.delegate._onAcceptListener&&self1.delegate._onAcceptListener(userId,sessionId,extension);break;case SignalingConstants.SignalingType.REJECT:"function"==typeof self1.delegate._onRejectListener&&self1.delegate._onRejectListener(userId,sessionId,extension);break;case SignalingConstants.SignalingType.STOP:"function"==typeof self1.delegate._onStopListener&&self1.delegate._onStopListener(userId,sessionId,extension);break;case SignalingConstants.SignalingType.CANDIDATE:"function"==typeof self1.delegate._onIceCandidatesListener&&self1.delegate._onIceCandidatesListener(userId,sessionId,extension);break;case SignalingConstants.SignalingType.PARAMETERS_CHANGED:"function"==typeof self1.delegate._onUpdateListener&&self1.delegate._onUpdateListener(userId,sessionId,extension)}},this._getExtension=function(extraParams){if(!extraParams)return{};var extension={},iceCandidates=[],opponents=[];return extraParams.childNodes.forEach(function(childNode){"iceCandidates"===childNode.nodeName?childNode.childNodes.forEach(function(candidateNode){var candidate={};candidateNode.childNodes.forEach(function(node){candidate[node.nodeName]=node.textContent}),iceCandidates.push(candidate)}):"opponentsIDs"===childNode.nodeName?childNode.childNodes.forEach(function(opponentNode){var opponentId=opponentNode.textContent;opponents.push(parseInt(opponentId))}):childNode.childNodes.length>1?extension=self1._XMLtoJS(extension,childNode.nodeName,childNode):"userInfo"===childNode.nodeName?extension=self1._XMLtoJS(extension,childNode.nodeName,childNode):extension[childNode.nodeName]=childNode.textContent}),iceCandidates.length>0&&(extension.iceCandidates=iceCandidates),opponents.length>0&&(extension.opponentsIDs=opponents),extension},this._XMLtoJS=function(extension,title,element){var self1=this;return extension[title]={},element.childNodes.forEach(function(childNode){childNode.childNodes.length>1?extension[title]=self1._XMLtoJS(extension[title],childNode.nodeName,childNode):extension[title][childNode.nodeName]=childNode.textContent}),extension}}module.exports=WebRTCSignalingProcessor},{"./qbWebRTCSignalingConstants":248,"strophe.js":208}],250:[function(require1,module,exports){"use strict";require1("strophe.js");var Helpers=require1("./qbWebRTCHelpers"),SignalingConstants=require1("./qbWebRTCSignalingConstants"),Utils=require1("../../qbUtils"),config=require1("../../qbConfig");function WebRTCSignalingProvider(service,chat){this.service=service,this.chat=chat}WebRTCSignalingProvider.prototype.sendCandidate=function(userId,iceCandidates,ext){var extension=ext||{};extension.iceCandidates=iceCandidates,this.sendMessage(userId,extension,SignalingConstants.SignalingType.CANDIDATE)},WebRTCSignalingProvider.prototype.sendMessage=function(userId,ext,signalingType){var extension=ext||{},self1=this;extension.moduleIdentifier=SignalingConstants.MODULE_ID,extension.signalType=signalingType,extension.platform="web",extension.userInfo&&!Object.keys(extension.userInfo).length&&delete extension.userInfo;var msg=$msg({to:Helpers.getUserJid(userId,config.creds.appId),type:"headline",id:Utils.getBsonObjectId()}).c("extraParams",{xmlns:Strophe.NS.CLIENT});Object.keys(extension).forEach(function(field){"iceCandidates"===field?(msg.c("iceCandidates"),extension[field].forEach(function(candidate){msg.c("iceCandidate"),Object.keys(candidate).forEach(function(key){msg.c(key).t(candidate[key]).up()}),msg.up()}),msg.up()):"opponentsIDs"===field?(msg.c("opponentsIDs"),extension[field].forEach(function(opponentId){msg.c("opponentID").t(opponentId).up()}),msg.up()):"object"==typeof extension[field]?self1._JStoXML(field,extension[field],msg):msg.c(field).t(extension[field]).up()}),this.chat.connection.send(msg)},WebRTCSignalingProvider.prototype._JStoXML=function(title,obj,msg){var self1=this;msg.c(title),Object.keys(obj).forEach(function(field){"object"==typeof obj[field]?self1._JStoXML(field,obj[field],msg):msg.c(field).t(obj[field]).up()}),msg.up()},module.exports=WebRTCSignalingProvider},{"../../qbConfig":252,"../../qbUtils":256,"./qbWebRTCHelpers":246,"./qbWebRTCSignalingConstants":248,"strophe.js":208}],251:[function(require1,module,exports){"use strict";var Utils=require1("../qbUtils"),chatUtils=require1("../modules/chat/qbChatHelpers");function StreamManagement(options){this._NS="urn:xmpp:sm:3",this._isStreamManagementEnabled=!1,this._clientProcessedStanzasCounter=null,this._clientSentStanzasCounter=null,this._intervalId=null,this._timeInterval=Utils.getTimeIntervalForCallBackMessage(),this.sentMessageCallback=null,Utils.getEnv().browser&&(this._parser=new DOMParser),this._c=null,this._nodeBuilder=null,this._originalSend=null,this._stanzasQueue=[]}StreamManagement.prototype.enable=function(connection,client){var stanza,enableParams={xmlns:this._NS};this._isStreamManagementEnabled||(this._c=connection,this._originalSend=this._c.send,this._c.send=this.send.bind(this)),Utils.getEnv().browser?(this._clientProcessedStanzasCounter=null,this._clientSentStanzasCounter=null,this._addEnableHandlers(),stanza=$build("enable",enableParams)):(this._nodeBuilder=client.Stanza,this._addEnableHandlers(),stanza=chatUtils.createStanza(this._nodeBuilder,enableParams,"enable")),this._c.send(stanza)},StreamManagement.prototype._timeoutCallback=function(){var now=Date.now(),updatedStanzasQueue=[];if(this._stanzasQueue.length){for(var i=0;i<this._stanzasQueue.length;i++)this._stanzasQueue[i]&&this._stanzasQueue[i].time<now?this.sentMessageCallback(this._stanzasQueue[i].message):updatedStanzasQueue.push(this._stanzasQueue[i]);this._stanzasQueue=updatedStanzasQueue}},StreamManagement.prototype._addEnableHandlers=function(){var self1=this;function _incomingStanzaHandler(stanza){var tagName=stanza.name||stanza.tagName||stanza.nodeTree.tagName;if("enabled"===tagName)return self1._isStreamManagementEnabled=!0,!0;if(self1._isStreamManagementEnabled&&"message"===tagName)return clearInterval(self1._intervalId),self1._intervalId=setInterval(self1._timeoutCallback.bind(self1),self1._timeInterval),!0;if(chatUtils.getAttr(stanza,"xmlns")!==self1._NS&&self1._increaseReceivedStanzasCounter(),"r"===tagName){var params={xmlns:self1._NS,h:self1._clientProcessedStanzasCounter},answerStanza=Utils.getEnv().browser?$build("a",params):chatUtils.createStanza(self1._nodeBuilder,params,"a");return self1._originalSend.call(self1._c,answerStanza),!0}if("a"===tagName){var h=parseInt(chatUtils.getAttr(stanza,"h"));self1._checkCounterOnIncomeStanza(h)}return!0}Utils.getEnv().browser?self1._c.XAddTrackedHandler(_incomingStanzaHandler.bind(self1)):self1._c.on("stanza",_incomingStanzaHandler.bind(self1))},StreamManagement.prototype.send=function(stanza,message){var stanzaXML=stanza.nodeTree?this._parser.parseFromString(stanza.nodeTree.outerHTML,"application/xml").childNodes[0]:stanza,tagName=stanzaXML.name||stanzaXML.tagName||stanzaXML.nodeTree.tagName,type=chatUtils.getAttr(stanzaXML,"type"),bodyContent=chatUtils.getElementText(stanzaXML,"body")||"",attachments=chatUtils.getAllElements(stanzaXML,"attachment")||"";try{this._originalSend.call(this._c,stanza)}catch(e){Utils.QBLog("[QBChat]",e.message)}finally{"message"===tagName&&("chat"===type||"groupchat"===type)&&(bodyContent||attachments.length)&&this._sendStanzasRequest({message:message,time:Date.now()+this._timeInterval,expect:this._clientSentStanzasCounter}),this._clientSentStanzasCounter++}},StreamManagement.prototype._sendStanzasRequest=function(data){if(this._isStreamManagementEnabled){this._stanzasQueue.push(data);var stanza=Utils.getEnv().browser?$build("r",{xmlns:this._NS}):chatUtils.createStanza(this._nodeBuilder,{xmlns:this._NS},"r");this._c.connected?this._originalSend.call(this._c,stanza):this._checkCounterOnIncomeStanza()}},StreamManagement.prototype.getClientSentStanzasCounter=function(){return this._clientSentStanzasCounter},StreamManagement.prototype._checkCounterOnIncomeStanza=function(count){var updatedStanzasQueue=[];if(this._stanzasQueue.length){for(var i=0;i<this._stanzasQueue.length;i++)this._stanzasQueue[i].expect==count?this.sentMessageCallback(null,this._stanzasQueue[i].message):updatedStanzasQueue.push(this._stanzasQueue[i]);this._stanzasQueue=updatedStanzasQueue}},StreamManagement.prototype._increaseReceivedStanzasCounter=function(){this._clientProcessedStanzasCounter++},module.exports=StreamManagement},{"../modules/chat/qbChatHelpers":235,"../qbUtils":256}],252:[function(require1,module,exports){"use strict";var config={version:"2.16.4",buildNumber:"1159",creds:{appId:0,authKey:"",authSecret:"",accountKey:""},endpoints:{api:"api.quickblox.com",chat:"chat.quickblox.com",muc:"muc.chat.quickblox.com"},hash:"sha1",streamManagement:{enable:!1},chatProtocol:{bosh:"https://chat.quickblox.com:5281",websocket:"wss://chat.quickblox.com:5291",active:2},pingTimeout:1,pingLocalhostTimeInterval:5,chatReconnectionTimeInterval:3,webrtc:{answerTimeInterval:60,autoReject:!0,incomingLimit:1,dialingTimeInterval:5,disconnectTimeInterval:30,statsReportTimeInterval:!1,iceServers:[{urls:["turn:turn.quickblox.com","stun:turn.quickblox.com"],username:"quickblox",credential:"baccb97ba2d92d71e26eb9886da5f1e0"}]},urls:{account:"account_settings",session:"session",login:"login",users:"users",chat:"chat",blobs:"blobs",geodata:"geodata",pushtokens:"push_tokens",subscriptions:"subscriptions",events:"events",data:"data",addressbook:"address_book",addressbookRegistered:"address_book/registered_users",type:".json"},on:{sessionExpired:null},timeout:null,debug:{mode:0,file:null},addISOTime:!1,qbTokenExpirationDate:null,liveSessionInterval:120,callBackInterval:30};config.set=function(options){"object"==typeof options.endpoints&&options.endpoints.chat&&(config.endpoints.muc="muc."+options.endpoints.chat,config.chatProtocol.bosh="https://"+options.endpoints.chat+":5281",config.chatProtocol.websocket="wss://"+options.endpoints.chat+":5291"),Object.keys(options).forEach(function(key){"set"!==key&&config.hasOwnProperty(key)&&("object"!=typeof options[key]?config[key]=options[key]:Object.keys(options[key]).forEach(function(nextkey){config[key].hasOwnProperty(nextkey)&&(config[key][nextkey]=options[key][nextkey])})),"iceServers"===key&&(config.webrtc.iceServers=options[key])})},config.updateSessionExpirationDate=function(tokenExpirationDate,headerHasToken=!1){var newDate;headerHasToken?(newDate=new Date(tokenExpirationDate.replaceAll("-","/"))).setMinutes(newDate.getMinutes()-1):((newDate=new Date(tokenExpirationDate)).setMinutes(newDate.getMinutes()-1),newDate.setMinutes(newDate.getMinutes()+config.liveSessionInterval)),config.qbTokenExpirationDate=newDate},module.exports=config},{}],253:[function(require1,module,exports){"use strict";var config=require1("./qbConfig"),Utils=require1("./qbUtils");function QuickBlox(){}QuickBlox.prototype={version:config.version,buildNumber:config.buildNumber,_getOS:Utils.getOS.bind(Utils),init:function(appIdOrToken,authKeyOrAppId,authSecret,accountKey,configMap){console.log("current platform: ",Utils.getEnv()),"string"==typeof accountKey&&accountKey.length?(configMap&&"object"==typeof configMap&&config.set(configMap),config.creds.accountKey=accountKey):(console.warn('Parameter "accountKey" is missing. This will lead to error in next major release'),console.warn('NOTE: Account migration will not work without "accountKey"'),"object"==typeof accountKey&&config.set(accountKey));var SHARED_API_ENDPOINT="api.quickblox.com",Proxy=require1("./qbProxy"),Auth=require1("./modules/qbAuth"),Users=require1("./modules/qbUsers"),Content=require1("./modules/qbContent"),PushNotifications=require1("./modules/qbPushNotifications"),Data=require1("./modules/qbData"),AddressBook=require1("./modules/qbAddressBook"),Chat=require1("./modules/chat/qbChat"),DialogProxy=require1("./modules/chat/qbDialog"),MessageProxy=require1("./modules/chat/qbMessage");if(this.service=new Proxy,this.auth=new Auth(this.service),this.users=new Users(this.service),this.content=new Content(this.service),this.pushnotifications=new PushNotifications(this.service),this.data=new Data(this.service),this.addressbook=new AddressBook(this.service),this.chat=new Chat(this.service),this.chat.dialog=new DialogProxy(this.service),this.chat.message=new MessageProxy(this.service),Utils.getEnv().browser){if(require1("webrtc-adapter"),Utils.isWebRTCAvailble()){var WebRTCClient=require1("./modules/webrtc/qbWebRTCClient");this.webrtc=new WebRTCClient(this.service,this.chat)}else this.webrtc=!1}else this.webrtc=!1;if("string"!=typeof appIdOrToken||authKeyOrAppId&&"number"!=typeof authKeyOrAppId||authSecret?(config.creds.appId=appIdOrToken,config.creds.authKey=authKeyOrAppId,config.creds.authSecret=authSecret):("number"==typeof authKeyOrAppId&&(config.creds.appId=authKeyOrAppId),this.service.setSession({token:appIdOrToken})),config.creds.accountKey&&(!config.endpoints.api||config.endpoints.api===SHARED_API_ENDPOINT||!config.endpoints.chat||"chat.quickblox.com"===config.endpoints.chat)){var accountSettingsUrl=["https://",SHARED_API_ENDPOINT,"/",config.urls.account,config.urls.type].join("");this.service.ajax({url:accountSettingsUrl},function(err,response){if(!err&&"object"==typeof response){var update={endpoints:{api:response.api_endpoint.replace(/^https?:\/\//,""),chat:response.chat_endpoint}};config.set(update)}})}},initWithAppId:function(appId,accountKey,configMap){if("number"!=typeof appId)throw Error("Type of appId must be a number");if(""===appId||null==appId||""===accountKey||null==accountKey)throw Error("Cannot init QuickBlox without app credentials (app ID, auth key)");this.init("",appId,null,accountKey,configMap)},getSession:function(callback){this.auth.getSession(callback)},startSessionWithToken:function(token,callback){if(void 0===token)throw Error("Cannot start session with undefined token");if(""===token)throw Error("Cannot start session with empty string token");if(null===token)throw Error("Cannot start session with null value token");if("function"!=typeof callback)throw Error("Cannot start session without callback function");try{this.service.setSession({token:token})}catch(err){callback(err,null)}if("function"==typeof callback)try{this.auth.getSession(callback)}catch(er){callback(er,null)}},createSession:function(params,callback){this.auth.createSession(params,callback)},destroySession:function(callback){this.auth.destroySession(callback)},login:function(params,callback){this.auth.login(params,callback)},logout:function(callback){this.auth.logout(callback)}};var QB=new QuickBlox;QB.QuickBlox=QuickBlox,module.exports=QB},{"./modules/chat/qbChat":234,"./modules/chat/qbDialog":236,"./modules/chat/qbMessage":237,"./modules/qbAddressBook":238,"./modules/qbAuth":239,"./modules/qbContent":240,"./modules/qbData":241,"./modules/qbPushNotifications":242,"./modules/qbUsers":243,"./modules/webrtc/qbWebRTCClient":245,"./qbConfig":252,"./qbProxy":254,"./qbUtils":256,"webrtc-adapter":218}],254:[function(require1,module,exports){"use strict";var qbFetch,qbFormData,config=require1("./qbConfig"),Utils=require1("./qbUtils");function ServiceProxy(){this.qbInst={config:config,session:null},this.reqCount=0}Utils.getEnv().node?(qbFetch=require1("node-fetch"),qbFormData=require1("form-data")):(qbFetch=fetch,qbFormData=FormData),ServiceProxy.prototype={_fetchingSettings:!1,_queue:[],setSession:function(session){this.qbInst.session=session},getSession:function(){return this.qbInst.session},handleResponse:function(error,response,next,retry){if(error){let errorMsg=JSON.stringify(error.message).toLowerCase();"function"==typeof config.on.sessionExpired&&401===error.code&&errorMsg.indexOf("session does not exist")>-1?config.on.sessionExpired(function(){next(error,response)},retry):next(error,null)}else config.addISOTime&&(response=Utils.injectISOTimes(response)),next(null,response)},startLogger:function(params){var clonedData;++this.reqCount,params.data&¶ms.data.file?(clonedData=JSON.parse(JSON.stringify(params.data))).file="...":clonedData=Utils.getEnv().nativescript?JSON.stringify(params.data):params.data,Utils.QBLog("[Request]["+this.reqCount+"]",(params.type||"GET")+" "+params.url,clonedData||"")},ajax:function(params,callback){if(this._fetchingSettings){this._queue.push([params,callback]);return}this.startLogger(params);var qbRequestBody,qbResponse,self1=this,isGetOrHeadType=!params.type||"GET"===params.type||"HEAD"===params.type,qbSessionToken=self1.qbInst&&self1.qbInst.session&&self1.qbInst.session.token,isQBRequest=-1===params.url.indexOf("s3.amazonaws.com"),isMultipartFormData=!1===params.contentType,qbDataType=params.dataType||"json",qbUrl=params.url,qbRequest={};function _fixedEncodeURIComponent(str){return encodeURIComponent(str).replace(/[#$&+,/:;=?@\[\]]/g,function(c){return"%"+c.charCodeAt(0).toString(16)})}function _getBodyRequest(){var qbData,data=params.data;return isMultipartFormData?(qbData=new qbFormData,Object.keys(data).forEach(function(item){params.fileToCustomObject&&"file"===item?qbData.append(item,data[item].data,data[item].name):qbData.append(item,params.data[item])})):qbData=params.isNeedStringify?JSON.stringify(data):Object.keys(data).map(function(k){return Utils.isObject(data[k])?Object.keys(data[k]).map(function(v){return _fixedEncodeURIComponent(k)+"["+(Utils.isArray(data[k])?"":v)+"]="+_fixedEncodeURIComponent(data[k][v])}).sort().join("&"):_fixedEncodeURIComponent(k)+(Utils.isArray(data[k])?"[]":"")+"="+_fixedEncodeURIComponent(data[k])}).sort().join("&"),qbData}function _requestCallback(error,response,body){var errorMsg,responseMessage,responseBody,statusCode=response&&(response.status||response.statusCode);if(error||200!==statusCode&&201!==statusCode&&202!==statusCode){try{errorMsg={code:response&&statusCode||error&&error.code,status:response&&response.headers&&response.headers.status||"error",message:body||error&&error.errno,detail:body&&body.errors||error&&error.syscall}}catch(e){errorMsg=error}responseBody=body||error||body.errors,responseMessage=Utils.getEnv().nativescript?JSON.stringify(responseBody):responseBody,Utils.QBLog("[Response]["+self1.reqCount+"]","error",statusCode,responseMessage),self1.handleResponse(errorMsg,null,callback,retry)}else responseBody=body&&" "!==body?body:"empty body",responseMessage=Utils.getEnv().nativescript?JSON.stringify(responseBody):responseBody,Utils.QBLog("[Response]["+self1.reqCount+"]",responseMessage),self1.handleResponse(null,body,callback,retry);if(self1._fetchingSettings)for(self1._fetchingSettings=!1;self1._queue.length;){var args=self1._queue.shift();self1.ajax.apply(self1,args)}}function retry(session){session&&(self1.setSession(session),self1.ajax(params,callback))}qbRequest.method=params.type||"GET",params.data&&(qbRequestBody=_getBodyRequest(),isGetOrHeadType?qbUrl+="?"+qbRequestBody:qbRequest.body=qbRequestBody),isMultipartFormData||(qbRequest.headers={"Content-Type":params.contentType||"application/x-www-form-urlencoded; charset=UTF-8"}),isQBRequest&&(qbRequest.headers||(qbRequest.headers={}),qbRequest.headers["QB-OS"]=Utils.getOS(),qbRequest.headers["QB-SDK"]="JS "+config.version+" - Client",qbSessionToken&&(qbRequest.headers["QB-Token"]=qbSessionToken),params.url.indexOf(config.urls.account)>-1&&(qbRequest.headers["QB-Account-Key"]=config.creds.accountKey,this._fetchingSettings=!0)),config.timeout&&(qbRequest.timeout=config.timeout),qbFetch(qbUrl,qbRequest).then(function(response){if(qbResponse=response,"GET"===qbRequest.method||"POST"===qbRequest.method){var qbTokenExpirationDate=qbResponse.headers.get("qb-token-expirationdate"),headerHasToken=null!=qbTokenExpirationDate;qbTokenExpirationDate=headerHasToken?qbTokenExpirationDate:new Date,self1.qbInst.config.updateSessionExpirationDate(qbTokenExpirationDate,headerHasToken),Utils.QBLog("[Request][ajax]","header has token:",headerHasToken),Utils.QBLog("[Request][ajax]","updateSessionExpirationDate ... Set value: ",self1.qbInst.config.qbTokenExpirationDate)}return"text"===qbDataType?response.text():response.json()},function(){return qbResponse={status:200}," "}).then(function(body){_requestCallback(null,qbResponse,body)},function(error){_requestCallback(error)}).catch(error=>{console.log("qbProxy fetch ... catch, error: ",error),_requestCallback(error)})}},module.exports=ServiceProxy},{"./qbConfig":252,"./qbUtils":256,"form-data":81,"node-fetch":105}],255:[function(require1,module,exports){"use strict";require1("strophe.js");var chatPRTCL=require1("./qbConfig").chatProtocol,Utils=require1("./qbUtils");function Connection(){var protocol=1===chatPRTCL.active?chatPRTCL.bosh:chatPRTCL.websocket,conn=new Strophe.Connection(protocol);return 1===chatPRTCL.active?(conn.xmlInput=function(data){if(data.childNodes[0])for(var i=0,len=data.childNodes.length;i<len;i++)Utils.QBLog("[QBChat]","RECV:",data.childNodes[i])},conn.xmlOutput=function(data){if(data.childNodes[0])for(var i=0,len=data.childNodes.length;i<len;i++)Utils.QBLog("[QBChat]","SENT:",data.childNodes[i])}):(conn.xmlInput=function(data){Utils.QBLog("[QBChat]","RECV:",data)},conn.xmlOutput=function(data){Utils.QBLog("[QBChat]","SENT:",data)}),conn}module.exports=Connection},{"./qbConfig":252,"./qbUtils":256,"strophe.js":208}],256:[function(require1,module,exports){(function(global){(function(){"use strict";var config=require1("./qbConfig"),isNativeScript="object"==typeof global&&(global.hasOwnProperty("android")||global.hasOwnProperty("NSObject")),isNode="undefined"==typeof window&&"object"==typeof exports&&!isNativeScript,isBrowser="undefined"!=typeof window;if(isNode)var fs=require1("fs"),os=require1("os");var ObjectId={machine:Math.floor(16777216*Math.random()).toString(16),pid:Math.floor(32767*Math.random()).toString(16),increment:0};module.exports={getEnv:function(){return{nativescript:isNativeScript,browser:isBrowser,node:isNode}},_getOSInfoFromNodeJS:function(){return os.platform()},_getOSInfoFromBrowser:function(){return window.navigator.userAgent},_getOSInfoFromNativeScript:function(){return(global&&global.hasOwnProperty("android")?"Android":"iOS")+" - NativeScript"},getOS:function(){var platformInfo,osName="An unknown OS";if(this.getEnv().browser)platformInfo=this._getOSInfoFromBrowser();else if(this.getEnv().node)platformInfo=this._getOSInfoFromNodeJS();else if(this.getEnv().nativescript)return this._getOSInfoFromNativeScript();return[{osName:"Windows",codeNames:["Windows","win32"]},{osName:"Linux",codeNames:["Linux","linux"]},{osName:"macOS",codeNames:["Mac OS","darwin"]}].forEach(function(osInfo){osInfo.codeNames.forEach(function(codeName){-1!==platformInfo.indexOf(codeName)&&(osName=osInfo.osName)})}),osName},safeCallbackCall:function(){for(var listenerCall,listenerString=arguments[0].toString(),listenerName=listenerString.split("(")[0].split(" ")[1],argumentsCopy=[],i=0;i<arguments.length;i++)argumentsCopy.push(arguments[i]);listenerCall=argumentsCopy.shift();try{listenerCall.apply(null,argumentsCopy)}catch(err){""===listenerName?console.error("Error: "+err):console.error("Error in listener "+listenerName+": "+err)}},randomNonce:function(){return Math.floor(1e4*Math.random())},unixTime:function(){return Math.floor(Date.now()/1e3)},getUrl:function(base,id){return"https://"+config.endpoints.api+"/"+base+(id?"/"+id:"")+config.urls.type},isArray:function(arg){return"[object Array]"===Object.prototype.toString.call(arg)},isObject:function(arg){return"[object Object]"===Object.prototype.toString.call(arg)},getBsonObjectId:function(){var timestamp=this.unixTime().toString(16),increment=(ObjectId.increment++).toString(16);return increment>16777215&&(ObjectId.increment=0),"00000000".substr(0,8-timestamp.length)+timestamp+"000000".substr(0,6-ObjectId.machine.length)+ObjectId.machine+"0000".substr(0,4-ObjectId.pid.length)+ObjectId.pid+"000000".substr(0,6-increment.length)+increment},getCurrentTime:function(){return new Date().toTimeString().split(" ")[0]},injectISOTimes:function(data){if(data.created_at)"number"==typeof data.created_at&&(data.iso_created_at=new Date(1e3*data.created_at).toISOString()),"number"==typeof data.updated_at&&(data.iso_updated_at=new Date(1e3*data.updated_at).toISOString());else if(data.items)for(var i=0,len=data.items.length;i<len;++i)"number"==typeof data.items[i].created_at&&(data.items[i].iso_created_at=new Date(1e3*data.items[i].created_at).toISOString()),"number"==typeof data.items[i].updated_at&&(data.items[i].iso_updated_at=new Date(1e3*data.items[i].updated_at).toISOString());return data},QBLog:function(){if(this.loggers){for(var logger,i=0;i<this.loggers.length;++i)this.loggers[i](arguments);return}this.loggers=[];var consoleLoggerFunction=function(){return function(args){console.log.apply(console,Array.prototype.slice.call(args))}},fileLoggerFunction=function(){return function(args){if(fs){for(var data=[],i=0;i<args.length;i++)data.push(JSON.stringify(args[i]));data=data.join(" ");var toLog="\n"+new Date+". "+data;fs.appendFile(config.debug.file,toLog,function(err){if(err)return console.error("Error while writing log to file. Error: "+err)})}else throw"This function isn't supported outside of the browser (...yet)"}};if("object"==typeof config.debug){if("number"==typeof config.debug.mode)1==config.debug.mode?(logger=consoleLoggerFunction(),this.loggers.push(logger)):2==config.debug.mode&&(logger=fileLoggerFunction(),this.loggers.push(logger));else if("object"==typeof config.debug.mode){var self1=this;config.debug.mode.forEach(function(mode){1===mode?(logger=consoleLoggerFunction(),self1.loggers.push(logger)):2===mode&&(logger=fileLoggerFunction(),self1.loggers.push(logger))})}}else"boolean"==typeof config.debug&&config.debug&&(logger=consoleLoggerFunction(),this.loggers.push(logger));if(this.loggers)for(var j=0;j<this.loggers.length;++j)this.loggers[j](arguments)},isWebRTCAvailble:function(){var RTCPeerConnection=window.RTCPeerConnection,IceCandidate=window.RTCIceCandidate,SessionDescription=window.RTCSessionDescription,MediaDevices=window.navigator.mediaDevices;return!!RTCPeerConnection&&!!IceCandidate&&!!SessionDescription&&!!MediaDevices},getError:function(code,detail,moduleName){var errorMsg={code:code,status:"error",detail:detail};switch(code){case 401:errorMsg.message="Unauthorized";break;case 403:errorMsg.message="Forbidden";break;case 408:errorMsg.message="Request Timeout";break;case 422:errorMsg.message="Unprocessable Entity";break;case 502:errorMsg.message="Bad Gateway";break;default:errorMsg.message="Unknown error"}return this.QBLog("["+moduleName+"]","Error:",detail),errorMsg},MergeArrayOfObjects:function(arrayTo,arrayFrom){var merged=JSON.parse(JSON.stringify(arrayTo));firstLevel:for(var i=0;i<arrayFrom.length;i++){for(var newItem=arrayFrom[i],j=0;j<merged.length;j++)if(newItem.user_id===merged[j].user_id){merged[j]=newItem;continue firstLevel}merged.push(newItem)}return merged},getTimeIntervalForCallBackMessage:function(){return 1e3*(void 0===config.callBackInterval?2:config.callBackInterval)}}}).call(this)}).call(this,void 0!==__webpack_require__.g?__webpack_require__.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./qbConfig":252,fs:32,os:139}]},{},[253])(253)},module.exports=f()},"./node_modules/react/cjs/react-jsx-runtime.production.min.js":(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";/**
|
|
24
|
+
*/"use strict";var getOwnPropertySymbols=Object.getOwnPropertySymbols,hasOwnProperty=Object.prototype.hasOwnProperty,propIsEnumerable=Object.prototype.propertyIsEnumerable;function toObject(val){if(null==val)throw TypeError("Object.assign cannot be called with null or undefined");return Object(val)}function shouldUseNative(){try{if(!Object.assign)return!1;var test1=new String("abc");if(test1[5]="de","5"===Object.getOwnPropertyNames(test1)[0])return!1;for(var test2={},i=0;i<10;i++)test2["_"+String.fromCharCode(i)]=i;var order2=Object.getOwnPropertyNames(test2).map(function(n){return test2[n]});if("0123456789"!==order2.join(""))return!1;var test3={};if("abcdefghijklmnopqrst".split("").forEach(function(letter){test3[letter]=letter}),"abcdefghijklmnopqrst"!==Object.keys(Object.assign({},test3)).join(""))return!1;return!0}catch(err){return!1}}module.exports=shouldUseNative()?Object.assign:function(target,source){for(var from,symbols,to=toObject(target),s=1;s<arguments.length;s++){for(var key in from=Object(arguments[s]))hasOwnProperty.call(from,key)&&(to[key]=from[key]);if(getOwnPropertySymbols){symbols=getOwnPropertySymbols(from);for(var i=0;i<symbols.length;i++)propIsEnumerable.call(from,symbols[i])&&(to[symbols[i]]=from[symbols[i]])}}return to}},{}],139:[function(require1,module,exports){exports.endianness=function(){return"LE"},exports.hostname=function(){return"undefined"!=typeof location?location.hostname:""},exports.loadavg=function(){return[]},exports.uptime=function(){return 0},exports.freemem=function(){return Number.MAX_VALUE},exports.totalmem=function(){return Number.MAX_VALUE},exports.cpus=function(){return[]},exports.type=function(){return"Browser"},exports.release=function(){return"undefined"!=typeof navigator?navigator.appVersion:""},exports.networkInterfaces=exports.getNetworkInterfaces=function(){return{}},exports.arch=function(){return"javascript"},exports.platform=function(){return"browser"},exports.tmpdir=exports.tmpDir=function(){return"/tmp"},exports.EOL="\n"},{}],140:[function(require1,module,exports){"use strict";var TYPED_OK="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;exports.assign=function(obj){for(var sources=Array.prototype.slice.call(arguments,1);sources.length;){var source=sources.shift();if(source){if("object"!=typeof source)throw TypeError(source+"must be non-object");for(var p in source)source.hasOwnProperty(p)&&(obj[p]=source[p])}}return obj},exports.shrinkBuf=function(buf,size){return buf.length===size?buf:buf.subarray?buf.subarray(0,size):(buf.length=size,buf)};var fnTyped={arraySet:function(dest,src,src_offs,len,dest_offs){if(src.subarray&&dest.subarray){dest.set(src.subarray(src_offs,src_offs+len),dest_offs);return}for(var i=0;i<len;i++)dest[dest_offs+i]=src[src_offs+i]},flattenChunks:function(chunks){var i,l,len,pos,chunk,result;for(i=0,len=0,l=chunks.length;i<l;i++)len+=chunks[i].length;for(i=0,result=new Uint8Array(len),pos=0,l=chunks.length;i<l;i++)chunk=chunks[i],result.set(chunk,pos),pos+=chunk.length;return result}},fnUntyped={arraySet:function(dest,src,src_offs,len,dest_offs){for(var i=0;i<len;i++)dest[dest_offs+i]=src[src_offs+i]},flattenChunks:function(chunks){return[].concat.apply([],chunks)}};exports.setTyped=function(on){on?(exports.Buf8=Uint8Array,exports.Buf16=Uint16Array,exports.Buf32=Int32Array,exports.assign(exports,fnTyped)):(exports.Buf8=Array,exports.Buf16=Array,exports.Buf32=Array,exports.assign(exports,fnUntyped))},exports.setTyped(TYPED_OK)},{}],141:[function(require1,module,exports){"use strict";function adler32(adler,buf,len,pos){for(var s1=65535&adler|0,s2=adler>>>16&65535|0,n=0;0!==len;){n=len>2e3?2e3:len,len-=n;do s2=s2+(s1=s1+buf[pos++]|0)|0;while(--n)s1%=65521,s2%=65521}return s1|s2<<16|0}module.exports=adler32},{}],142:[function(require1,module,exports){"use strict";module.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],143:[function(require1,module,exports){"use strict";var crcTable=function makeTable(){for(var c,table=[],n=0;n<256;n++){c=n;for(var k=0;k<8;k++)c=1&c?3988292384^c>>>1:c>>>1;table[n]=c}return table}();function crc32(crc,buf,len,pos){var end=pos+len;crc^=-1;for(var i=pos;i<end;i++)crc=crc>>>8^crcTable[(crc^buf[i])&255];return -1^crc}module.exports=crc32},{}],144:[function(require1,module,exports){"use strict";var configuration_table,utils=require1("../utils/common"),trees=require1("./trees"),adler32=require1("./adler32"),crc32=require1("./crc32"),msg=require1("./messages");function err(strm,errorCode){return strm.msg=msg[errorCode],errorCode}function rank(f){return(f<<1)-(f>4?9:0)}function zero(buf){for(var len=buf.length;--len>=0;)buf[len]=0}function flush_pending(strm){var s=strm.state,len=s.pending;len>strm.avail_out&&(len=strm.avail_out),0!==len&&(utils.arraySet(strm.output,s.pending_buf,s.pending_out,len,strm.next_out),strm.next_out+=len,s.pending_out+=len,strm.total_out+=len,strm.avail_out-=len,s.pending-=len,0===s.pending&&(s.pending_out=0))}function flush_block_only(s,last){trees._tr_flush_block(s,s.block_start>=0?s.block_start:-1,s.strstart-s.block_start,last),s.block_start=s.strstart,flush_pending(s.strm)}function put_byte(s,b){s.pending_buf[s.pending++]=b}function putShortMSB(s,b){s.pending_buf[s.pending++]=b>>>8&255,s.pending_buf[s.pending++]=255&b}function read_buf(strm,buf,start,size){var len=strm.avail_in;return(len>size&&(len=size),0===len)?0:(strm.avail_in-=len,utils.arraySet(buf,strm.input,strm.next_in,len,start),1===strm.state.wrap?strm.adler=adler32(strm.adler,buf,len,start):2===strm.state.wrap&&(strm.adler=crc32(strm.adler,buf,len,start)),strm.next_in+=len,strm.total_in+=len,len)}function longest_match(s,cur_match){var match,len,chain_length=s.max_chain_length,scan=s.strstart,best_len=s.prev_length,nice_match=s.nice_match,limit=s.strstart>s.w_size-262?s.strstart-(s.w_size-262):0,_win=s.window,wmask=s.w_mask,prev=s.prev,strend=s.strstart+258,scan_end1=_win[scan+best_len-1],scan_end=_win[scan+best_len];s.prev_length>=s.good_match&&(chain_length>>=2),nice_match>s.lookahead&&(nice_match=s.lookahead);do{if(_win[(match=cur_match)+best_len]!==scan_end||_win[match+best_len-1]!==scan_end1||_win[match]!==_win[scan]||_win[++match]!==_win[scan+1])continue;scan+=2,match++;do;while(_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&scan<strend)if(len=258-(strend-scan),scan=strend-258,len>best_len){if(s.match_start=cur_match,best_len=len,len>=nice_match)break;scan_end1=_win[scan+best_len-1],scan_end=_win[scan+best_len]}}while((cur_match=prev[cur_match&wmask])>limit&&0!=--chain_length)return best_len<=s.lookahead?best_len:s.lookahead}function fill_window(s){var p,n,m,more,str,_w_size=s.w_size;do{if(more=s.window_size-s.lookahead-s.strstart,s.strstart>=_w_size+(_w_size-262)){utils.arraySet(s.window,s.window,_w_size,_w_size,0),s.match_start-=_w_size,s.strstart-=_w_size,s.block_start-=_w_size,p=n=s.hash_size;do m=s.head[--p],s.head[p]=m>=_w_size?m-_w_size:0;while(--n)p=n=_w_size;do m=s.prev[--p],s.prev[p]=m>=_w_size?m-_w_size:0;while(--n)more+=_w_size}if(0===s.strm.avail_in)break;if(n=read_buf(s.strm,s.window,s.strstart+s.lookahead,more),s.lookahead+=n,s.lookahead+s.insert>=3)for(str=s.strstart-s.insert,s.ins_h=s.window[str],s.ins_h=(s.ins_h<<s.hash_shift^s.window[str+1])&s.hash_mask;s.insert&&(s.ins_h=(s.ins_h<<s.hash_shift^s.window[str+3-1])&s.hash_mask,s.prev[str&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=str,str++,s.insert--,!(s.lookahead+s.insert<3)););}while(s.lookahead<262&&0!==s.strm.avail_in)}function deflate_fast(s,flush){for(var hash_head,bflush;;){if(s.lookahead<262){if(fill_window(s),s.lookahead<262&&0===flush)return 1;if(0===s.lookahead)break}if(hash_head=0,s.lookahead>=3&&(s.ins_h=(s.ins_h<<s.hash_shift^s.window[s.strstart+3-1])&s.hash_mask,hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=s.strstart),0!==hash_head&&s.strstart-hash_head<=s.w_size-262&&(s.match_length=longest_match(s,hash_head)),s.match_length>=3){if(bflush=trees._tr_tally(s,s.strstart-s.match_start,s.match_length-3),s.lookahead-=s.match_length,s.match_length<=s.max_lazy_match&&s.lookahead>=3){s.match_length--;do s.strstart++,s.ins_h=(s.ins_h<<s.hash_shift^s.window[s.strstart+3-1])&s.hash_mask,hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=s.strstart;while(0!=--s.match_length)s.strstart++}else s.strstart+=s.match_length,s.match_length=0,s.ins_h=s.window[s.strstart],s.ins_h=(s.ins_h<<s.hash_shift^s.window[s.strstart+1])&s.hash_mask}else bflush=trees._tr_tally(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++;if(bflush&&(flush_block_only(s,!1),0===s.strm.avail_out))return 1}return(s.insert=s.strstart<2?s.strstart:2,4===flush)?(flush_block_only(s,!0),0===s.strm.avail_out)?3:4:s.last_lit&&(flush_block_only(s,!1),0===s.strm.avail_out)?1:2}function deflate_slow(s,flush){for(var hash_head,bflush,max_insert;;){if(s.lookahead<262){if(fill_window(s),s.lookahead<262&&0===flush)return 1;if(0===s.lookahead)break}if(hash_head=0,s.lookahead>=3&&(s.ins_h=(s.ins_h<<s.hash_shift^s.window[s.strstart+3-1])&s.hash_mask,hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=s.strstart),s.prev_length=s.match_length,s.prev_match=s.match_start,s.match_length=2,0!==hash_head&&s.prev_length<s.max_lazy_match&&s.strstart-hash_head<=s.w_size-262&&(s.match_length=longest_match(s,hash_head),s.match_length<=5&&(1===s.strategy||3===s.match_length&&s.strstart-s.match_start>4096)&&(s.match_length=2)),s.prev_length>=3&&s.match_length<=s.prev_length){max_insert=s.strstart+s.lookahead-3,bflush=trees._tr_tally(s,s.strstart-1-s.prev_match,s.prev_length-3),s.lookahead-=s.prev_length-1,s.prev_length-=2;do++s.strstart<=max_insert&&(s.ins_h=(s.ins_h<<s.hash_shift^s.window[s.strstart+3-1])&s.hash_mask,hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=s.strstart);while(0!=--s.prev_length)if(s.match_available=0,s.match_length=2,s.strstart++,bflush&&(flush_block_only(s,!1),0===s.strm.avail_out))return 1}else if(s.match_available){if((bflush=trees._tr_tally(s,0,s.window[s.strstart-1]))&&flush_block_only(s,!1),s.strstart++,s.lookahead--,0===s.strm.avail_out)return 1}else s.match_available=1,s.strstart++,s.lookahead--}return(s.match_available&&(bflush=trees._tr_tally(s,0,s.window[s.strstart-1]),s.match_available=0),s.insert=s.strstart<2?s.strstart:2,4===flush)?(flush_block_only(s,!0),0===s.strm.avail_out)?3:4:s.last_lit&&(flush_block_only(s,!1),0===s.strm.avail_out)?1:2}function deflate_rle(s,flush){for(var bflush,prev,scan,strend,_win=s.window;;){if(s.lookahead<=258){if(fill_window(s),s.lookahead<=258&&0===flush)return 1;if(0===s.lookahead)break}if(s.match_length=0,s.lookahead>=3&&s.strstart>0&&(prev=_win[scan=s.strstart-1])===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]){strend=s.strstart+258;do;while(prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&scan<strend)s.match_length=258-(strend-scan),s.match_length>s.lookahead&&(s.match_length=s.lookahead)}if(s.match_length>=3?(bflush=trees._tr_tally(s,1,s.match_length-3),s.lookahead-=s.match_length,s.strstart+=s.match_length,s.match_length=0):(bflush=trees._tr_tally(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++),bflush&&(flush_block_only(s,!1),0===s.strm.avail_out))return 1}return(s.insert=0,4===flush)?(flush_block_only(s,!0),0===s.strm.avail_out)?3:4:s.last_lit&&(flush_block_only(s,!1),0===s.strm.avail_out)?1:2}function deflate_huff(s,flush){for(var bflush;;){if(0===s.lookahead&&(fill_window(s),0===s.lookahead)){if(0===flush)return 1;break}if(s.match_length=0,bflush=trees._tr_tally(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++,bflush&&(flush_block_only(s,!1),0===s.strm.avail_out))return 1}return(s.insert=0,4===flush)?(flush_block_only(s,!0),0===s.strm.avail_out)?3:4:s.last_lit&&(flush_block_only(s,!1),0===s.strm.avail_out)?1:2}function Config(good_length,max_lazy,nice_length,max_chain,func){this.good_length=good_length,this.max_lazy=max_lazy,this.nice_length=nice_length,this.max_chain=max_chain,this.func=func}function lm_init(s){s.window_size=2*s.w_size,zero(s.head),s.max_lazy_match=configuration_table[s.level].max_lazy,s.good_match=configuration_table[s.level].good_length,s.nice_match=configuration_table[s.level].nice_length,s.max_chain_length=configuration_table[s.level].max_chain,s.strstart=0,s.block_start=0,s.lookahead=0,s.insert=0,s.match_length=s.prev_length=2,s.match_available=0,s.ins_h=0}function DeflateState(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=8,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new utils.Buf16(1146),this.dyn_dtree=new utils.Buf16(122),this.bl_tree=new utils.Buf16(78),zero(this.dyn_ltree),zero(this.dyn_dtree),zero(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new utils.Buf16(16),this.heap=new utils.Buf16(573),zero(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new utils.Buf16(573),zero(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function deflateResetKeep(strm){var s;return strm&&strm.state?(strm.total_in=strm.total_out=0,strm.data_type=2,(s=strm.state).pending=0,s.pending_out=0,s.wrap<0&&(s.wrap=-s.wrap),s.status=s.wrap?42:113,strm.adler=2===s.wrap?0:1,s.last_flush=0,trees._tr_init(s),0):err(strm,-2)}function deflateReset(strm){var ret=deflateResetKeep(strm);return 0===ret&&lm_init(strm.state),ret}function deflateSetHeader(strm,head){return strm&&strm.state&&2===strm.state.wrap?(strm.state.gzhead=head,0):-2}function deflateInit2(strm,level,method,windowBits,memLevel,strategy){if(!strm)return -2;var wrap=1;if(-1===level&&(level=6),windowBits<0?(wrap=0,windowBits=-windowBits):windowBits>15&&(wrap=2,windowBits-=16),memLevel<1||memLevel>9||8!==method||windowBits<8||windowBits>15||level<0||level>9||strategy<0||strategy>4)return err(strm,-2);8===windowBits&&(windowBits=9);var s=new DeflateState;return strm.state=s,s.strm=strm,s.wrap=wrap,s.gzhead=null,s.w_bits=windowBits,s.w_size=1<<s.w_bits,s.w_mask=s.w_size-1,s.hash_bits=memLevel+7,s.hash_size=1<<s.hash_bits,s.hash_mask=s.hash_size-1,s.hash_shift=~~((s.hash_bits+3-1)/3),s.window=new utils.Buf8(2*s.w_size),s.head=new utils.Buf16(s.hash_size),s.prev=new utils.Buf16(s.w_size),s.lit_bufsize=1<<memLevel+6,s.pending_buf_size=4*s.lit_bufsize,s.pending_buf=new utils.Buf8(s.pending_buf_size),s.d_buf=1*s.lit_bufsize,s.l_buf=3*s.lit_bufsize,s.level=level,s.strategy=strategy,s.method=method,deflateReset(strm)}function deflateInit(strm,level){return deflateInit2(strm,level,8,15,8,0)}function deflate(strm,flush){if(!strm||!strm.state||flush>5||flush<0)return strm?err(strm,-2):-2;if(s=strm.state,!strm.output||!strm.input&&0!==strm.avail_in||666===s.status&&4!==flush)return err(strm,0===strm.avail_out?-5:-2);if(s.strm=strm,old_flush=s.last_flush,s.last_flush=flush,42===s.status){if(2===s.wrap)strm.adler=0,put_byte(s,31),put_byte(s,139),put_byte(s,8),s.gzhead?(put_byte(s,(s.gzhead.text?1:0)+(s.gzhead.hcrc?2:0)+(s.gzhead.extra?4:0)+(s.gzhead.name?8:0)+(s.gzhead.comment?16:0)),put_byte(s,255&s.gzhead.time),put_byte(s,s.gzhead.time>>8&255),put_byte(s,s.gzhead.time>>16&255),put_byte(s,s.gzhead.time>>24&255),put_byte(s,9===s.level?2:s.strategy>=2||s.level<2?4:0),put_byte(s,255&s.gzhead.os),s.gzhead.extra&&s.gzhead.extra.length&&(put_byte(s,255&s.gzhead.extra.length),put_byte(s,s.gzhead.extra.length>>8&255)),s.gzhead.hcrc&&(strm.adler=crc32(strm.adler,s.pending_buf,s.pending,0)),s.gzindex=0,s.status=69):(put_byte(s,0),put_byte(s,0),put_byte(s,0),put_byte(s,0),put_byte(s,0),put_byte(s,9===s.level?2:s.strategy>=2||s.level<2?4:0),put_byte(s,3),s.status=113);else{var old_flush,s,beg,val,header=8+(s.w_bits-8<<4)<<8;header|=(s.strategy>=2||s.level<2?0:s.level<6?1:6===s.level?2:3)<<6,0!==s.strstart&&(header|=32),header+=31-header%31,s.status=113,putShortMSB(s,header),0!==s.strstart&&(putShortMSB(s,strm.adler>>>16),putShortMSB(s,65535&strm.adler)),strm.adler=1}}if(69===s.status){if(s.gzhead.extra){for(beg=s.pending;s.gzindex<(65535&s.gzhead.extra.length)&&(s.pending!==s.pending_buf_size||(s.gzhead.hcrc&&s.pending>beg&&(strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)),flush_pending(strm),beg=s.pending,s.pending!==s.pending_buf_size));)put_byte(s,255&s.gzhead.extra[s.gzindex]),s.gzindex++;s.gzhead.hcrc&&s.pending>beg&&(strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)),s.gzindex===s.gzhead.extra.length&&(s.gzindex=0,s.status=73)}else s.status=73}if(73===s.status){if(s.gzhead.name){beg=s.pending;do{if(s.pending===s.pending_buf_size&&(s.gzhead.hcrc&&s.pending>beg&&(strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)),flush_pending(strm),beg=s.pending,s.pending===s.pending_buf_size)){val=1;break}val=s.gzindex<s.gzhead.name.length?255&s.gzhead.name.charCodeAt(s.gzindex++):0,put_byte(s,val)}while(0!==val)s.gzhead.hcrc&&s.pending>beg&&(strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)),0===val&&(s.gzindex=0,s.status=91)}else s.status=91}if(91===s.status){if(s.gzhead.comment){beg=s.pending;do{if(s.pending===s.pending_buf_size&&(s.gzhead.hcrc&&s.pending>beg&&(strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)),flush_pending(strm),beg=s.pending,s.pending===s.pending_buf_size)){val=1;break}val=s.gzindex<s.gzhead.comment.length?255&s.gzhead.comment.charCodeAt(s.gzindex++):0,put_byte(s,val)}while(0!==val)s.gzhead.hcrc&&s.pending>beg&&(strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)),0===val&&(s.status=103)}else s.status=103}if(103===s.status&&(s.gzhead.hcrc?(s.pending+2>s.pending_buf_size&&flush_pending(strm),s.pending+2<=s.pending_buf_size&&(put_byte(s,255&strm.adler),put_byte(s,strm.adler>>8&255),strm.adler=0,s.status=113)):s.status=113),0!==s.pending){if(flush_pending(strm),0===strm.avail_out)return s.last_flush=-1,0}else if(0===strm.avail_in&&rank(flush)<=rank(old_flush)&&4!==flush)return err(strm,-5);if(666===s.status&&0!==strm.avail_in)return err(strm,-5);if(0!==strm.avail_in||0!==s.lookahead||0!==flush&&666!==s.status){var bstate=2===s.strategy?deflate_huff(s,flush):3===s.strategy?deflate_rle(s,flush):configuration_table[s.level].func(s,flush);if((3===bstate||4===bstate)&&(s.status=666),1===bstate||3===bstate)return 0===strm.avail_out&&(s.last_flush=-1),0;if(2===bstate&&(1===flush?trees._tr_align(s):5!==flush&&(trees._tr_stored_block(s,0,0,!1),3===flush&&(zero(s.head),0===s.lookahead&&(s.strstart=0,s.block_start=0,s.insert=0))),flush_pending(strm),0===strm.avail_out))return s.last_flush=-1,0}return 4!==flush?0:s.wrap<=0?1:(2===s.wrap?(put_byte(s,255&strm.adler),put_byte(s,strm.adler>>8&255),put_byte(s,strm.adler>>16&255),put_byte(s,strm.adler>>24&255),put_byte(s,255&strm.total_in),put_byte(s,strm.total_in>>8&255),put_byte(s,strm.total_in>>16&255),put_byte(s,strm.total_in>>24&255)):(putShortMSB(s,strm.adler>>>16),putShortMSB(s,65535&strm.adler)),flush_pending(strm),s.wrap>0&&(s.wrap=-s.wrap),0!==s.pending?0:1)}function deflateEnd(strm){var status;return strm&&strm.state?42!==(status=strm.state.status)&&69!==status&&73!==status&&91!==status&&103!==status&&113!==status&&666!==status?err(strm,-2):(strm.state=null,113===status?err(strm,-3):0):-2}function deflateSetDictionary(strm,dictionary){var s,str,n,wrap,avail,next,input,tmpDict,dictLength=dictionary.length;if(!strm||!strm.state||2===(wrap=(s=strm.state).wrap)||1===wrap&&42!==s.status||s.lookahead)return -2;for(1===wrap&&(strm.adler=adler32(strm.adler,dictionary,dictLength,0)),s.wrap=0,dictLength>=s.w_size&&(0===wrap&&(zero(s.head),s.strstart=0,s.block_start=0,s.insert=0),tmpDict=new utils.Buf8(s.w_size),utils.arraySet(tmpDict,dictionary,dictLength-s.w_size,s.w_size,0),dictionary=tmpDict,dictLength=s.w_size),avail=strm.avail_in,next=strm.next_in,input=strm.input,strm.avail_in=dictLength,strm.next_in=0,strm.input=dictionary,fill_window(s);s.lookahead>=3;){str=s.strstart,n=s.lookahead-2;do s.ins_h=(s.ins_h<<s.hash_shift^s.window[str+3-1])&s.hash_mask,s.prev[str&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=str,str++;while(--n)s.strstart=str,s.lookahead=2,fill_window(s)}return s.strstart+=s.lookahead,s.block_start=s.strstart,s.insert=s.lookahead,s.lookahead=0,s.match_length=s.prev_length=2,s.match_available=0,strm.next_in=next,strm.input=input,strm.avail_in=avail,s.wrap=wrap,0}configuration_table=[new Config(0,0,0,0,function deflate_stored(s,flush){var max_block_size=65535;for(65535>s.pending_buf_size-5&&(max_block_size=s.pending_buf_size-5);;){if(s.lookahead<=1){if(fill_window(s),0===s.lookahead&&0===flush)return 1;if(0===s.lookahead)break}s.strstart+=s.lookahead,s.lookahead=0;var max_start=s.block_start+max_block_size;if((0===s.strstart||s.strstart>=max_start)&&(s.lookahead=s.strstart-max_start,s.strstart=max_start,flush_block_only(s,!1),0===s.strm.avail_out)||s.strstart-s.block_start>=s.w_size-262&&(flush_block_only(s,!1),0===s.strm.avail_out))return 1}return(s.insert=0,4===flush)?(flush_block_only(s,!0),0===s.strm.avail_out)?3:4:(s.strstart>s.block_start&&(flush_block_only(s,!1),s.strm.avail_out),1)}),new Config(4,4,8,4,deflate_fast),new Config(4,5,16,8,deflate_fast),new Config(4,6,32,32,deflate_fast),new Config(4,4,16,16,deflate_slow),new Config(8,16,32,32,deflate_slow),new Config(8,16,128,128,deflate_slow),new Config(8,32,128,256,deflate_slow),new Config(32,128,258,1024,deflate_slow),new Config(32,258,258,4096,deflate_slow)],exports.deflateInit=deflateInit,exports.deflateInit2=deflateInit2,exports.deflateReset=deflateReset,exports.deflateResetKeep=deflateResetKeep,exports.deflateSetHeader=deflateSetHeader,exports.deflate=deflate,exports.deflateEnd=deflateEnd,exports.deflateSetDictionary=deflateSetDictionary,exports.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":140,"./adler32":141,"./crc32":143,"./messages":148,"./trees":149}],145:[function(require1,module,exports){"use strict";module.exports=function inflate_fast(strm,start){var state,_in,last,_out,beg,end,dmax,wsize,whave,wnext,s_window,hold,bits,lcode,dcode,lmask,dmask,here,op,len,dist,from,from_source,input,output;state=strm.state,_in=strm.next_in,input=strm.input,last=_in+(strm.avail_in-5),_out=strm.next_out,output=strm.output,beg=_out-(start-strm.avail_out),end=_out+(strm.avail_out-257),dmax=state.dmax,wsize=state.wsize,whave=state.whave,wnext=state.wnext,s_window=state.window,hold=state.hold,bits=state.bits,lcode=state.lencode,dcode=state.distcode,lmask=(1<<state.lenbits)-1,dmask=(1<<state.distbits)-1;top:do for(bits<15&&(hold+=input[_in++]<<bits,bits+=8,hold+=input[_in++]<<bits,bits+=8),here=lcode[hold&lmask];;){if(hold>>>=op=here>>>24,bits-=op,0==(op=here>>>16&255))output[_out++]=65535&here;else if(16&op)for(len=65535&here,(op&=15)&&(bits<op&&(hold+=input[_in++]<<bits,bits+=8),len+=hold&(1<<op)-1,hold>>>=op,bits-=op),bits<15&&(hold+=input[_in++]<<bits,bits+=8,hold+=input[_in++]<<bits,bits+=8),here=dcode[hold&dmask];;){if(hold>>>=op=here>>>24,bits-=op,16&(op=here>>>16&255)){if(dist=65535&here,bits<(op&=15)&&(hold+=input[_in++]<<bits,(bits+=8)<op&&(hold+=input[_in++]<<bits,bits+=8)),(dist+=hold&(1<<op)-1)>dmax){strm.msg="invalid distance too far back",state.mode=30;break top}if(hold>>>=op,bits-=op,dist>(op=_out-beg)){if((op=dist-op)>whave&&state.sane){strm.msg="invalid distance too far back",state.mode=30;break top}if(from=0,from_source=s_window,0===wnext){if(from+=wsize-op,op<len){len-=op;do output[_out++]=s_window[from++];while(--op)from=_out-dist,from_source=output}}else if(wnext<op){if(from+=wsize+wnext-op,(op-=wnext)<len){len-=op;do output[_out++]=s_window[from++];while(--op)if(from=0,wnext<len){len-=op=wnext;do output[_out++]=s_window[from++];while(--op)from=_out-dist,from_source=output}}}else if(from+=wnext-op,op<len){len-=op;do output[_out++]=s_window[from++];while(--op)from=_out-dist,from_source=output}for(;len>2;)output[_out++]=from_source[from++],output[_out++]=from_source[from++],output[_out++]=from_source[from++],len-=3;len&&(output[_out++]=from_source[from++],len>1&&(output[_out++]=from_source[from++]))}else{from=_out-dist;do output[_out++]=output[from++],output[_out++]=output[from++],output[_out++]=output[from++],len-=3;while(len>2)len&&(output[_out++]=output[from++],len>1&&(output[_out++]=output[from++]))}}else if((64&op)==0){here=dcode[(65535&here)+(hold&(1<<op)-1)];continue}else{strm.msg="invalid distance code",state.mode=30;break top}break}else if((64&op)==0){here=lcode[(65535&here)+(hold&(1<<op)-1)];continue}else if(32&op){state.mode=12;break top}else{strm.msg="invalid literal/length code",state.mode=30;break top}break}while(_in<last&&_out<end)_in-=len=bits>>3,bits-=len<<3,hold&=(1<<bits)-1,strm.next_in=_in,strm.next_out=_out,strm.avail_in=_in<last?5+(last-_in):5-(_in-last),strm.avail_out=_out<end?257+(end-_out):257-(_out-end),state.hold=hold,state.bits=bits}},{}],146:[function(require1,module,exports){"use strict";var lenfix,distfix,utils=require1("../utils/common"),adler32=require1("./adler32"),crc32=require1("./crc32"),inflate_fast=require1("./inffast"),inflate_table=require1("./inftrees");function zswap32(q){return(q>>>24&255)+(q>>>8&65280)+((65280&q)<<8)+((255&q)<<24)}function InflateState(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new utils.Buf16(320),this.work=new utils.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function inflateResetKeep(strm){var state;return strm&&strm.state?(state=strm.state,strm.total_in=strm.total_out=state.total=0,strm.msg="",state.wrap&&(strm.adler=1&state.wrap),state.mode=1,state.last=0,state.havedict=0,state.dmax=32768,state.head=null,state.hold=0,state.bits=0,state.lencode=state.lendyn=new utils.Buf32(852),state.distcode=state.distdyn=new utils.Buf32(592),state.sane=1,state.back=-1,0):-2}function inflateReset(strm){var state;return strm&&strm.state?((state=strm.state).wsize=0,state.whave=0,state.wnext=0,inflateResetKeep(strm)):-2}function inflateReset2(strm,windowBits){var wrap,state;return strm&&strm.state?(state=strm.state,windowBits<0?(wrap=0,windowBits=-windowBits):(wrap=(windowBits>>4)+1,windowBits<48&&(windowBits&=15)),windowBits&&(windowBits<8||windowBits>15))?-2:(null!==state.window&&state.wbits!==windowBits&&(state.window=null),state.wrap=wrap,state.wbits=windowBits,inflateReset(strm)):-2}function inflateInit2(strm,windowBits){var ret,state;return strm?(state=new InflateState,strm.state=state,state.window=null,0!==(ret=inflateReset2(strm,windowBits))&&(strm.state=null),ret):-2}function inflateInit(strm){return inflateInit2(strm,15)}var virgin=!0;function fixedtables(state){if(virgin){var sym;for(lenfix=new utils.Buf32(512),distfix=new utils.Buf32(32),sym=0;sym<144;)state.lens[sym++]=8;for(;sym<256;)state.lens[sym++]=9;for(;sym<280;)state.lens[sym++]=7;for(;sym<288;)state.lens[sym++]=8;for(inflate_table(1,state.lens,0,288,lenfix,0,state.work,{bits:9}),sym=0;sym<32;)state.lens[sym++]=5;inflate_table(2,state.lens,0,32,distfix,0,state.work,{bits:5}),virgin=!1}state.lencode=lenfix,state.lenbits=9,state.distcode=distfix,state.distbits=5}function updatewindow(strm,src,end,copy){var dist,state=strm.state;return null===state.window&&(state.wsize=1<<state.wbits,state.wnext=0,state.whave=0,state.window=new utils.Buf8(state.wsize)),copy>=state.wsize?(utils.arraySet(state.window,src,end-state.wsize,state.wsize,0),state.wnext=0,state.whave=state.wsize):((dist=state.wsize-state.wnext)>copy&&(dist=copy),utils.arraySet(state.window,src,end-copy,dist,state.wnext),(copy-=dist)?(utils.arraySet(state.window,src,end-copy,copy,0),state.wnext=copy,state.whave=state.wsize):(state.wnext+=dist,state.wnext===state.wsize&&(state.wnext=0),state.whave<state.wsize&&(state.whave+=dist))),0}function inflate(strm,flush){var state,input,output,next,put,have,left,hold,bits,_in,_out,copy,from,from_source,here_bits,here_op,here_val,last_bits,last_op,last_val,len,ret,opts,n,here=0,hbuf=new utils.Buf8(4),order=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!strm||!strm.state||!strm.output||!strm.input&&0!==strm.avail_in)return -2;12===(state=strm.state).mode&&(state.mode=13),put=strm.next_out,output=strm.output,left=strm.avail_out,next=strm.next_in,input=strm.input,have=strm.avail_in,hold=state.hold,bits=state.bits,_in=have,_out=left,ret=0;inf_leave:for(;;)switch(state.mode){case 1:if(0===state.wrap){state.mode=13;break}for(;bits<16;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(2&state.wrap&&35615===hold){state.check=0,hbuf[0]=255&hold,hbuf[1]=hold>>>8&255,state.check=crc32(state.check,hbuf,2,0),hold=0,bits=0,state.mode=2;break}if(state.flags=0,state.head&&(state.head.done=!1),!(1&state.wrap)||(((255&hold)<<8)+(hold>>8))%31){strm.msg="incorrect header check",state.mode=30;break}if((15&hold)!=8){strm.msg="unknown compression method",state.mode=30;break}if(hold>>>=4,bits-=4,len=(15&hold)+8,0===state.wbits)state.wbits=len;else if(len>state.wbits){strm.msg="invalid window size",state.mode=30;break}state.dmax=1<<len,strm.adler=state.check=1,state.mode=512&hold?10:12,hold=0,bits=0;break;case 2:for(;bits<16;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(state.flags=hold,(255&state.flags)!=8){strm.msg="unknown compression method",state.mode=30;break}if(57344&state.flags){strm.msg="unknown header flags set",state.mode=30;break}state.head&&(state.head.text=hold>>8&1),512&state.flags&&(hbuf[0]=255&hold,hbuf[1]=hold>>>8&255,state.check=crc32(state.check,hbuf,2,0)),hold=0,bits=0,state.mode=3;case 3:for(;bits<32;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}state.head&&(state.head.time=hold),512&state.flags&&(hbuf[0]=255&hold,hbuf[1]=hold>>>8&255,hbuf[2]=hold>>>16&255,hbuf[3]=hold>>>24&255,state.check=crc32(state.check,hbuf,4,0)),hold=0,bits=0,state.mode=4;case 4:for(;bits<16;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}state.head&&(state.head.xflags=255&hold,state.head.os=hold>>8),512&state.flags&&(hbuf[0]=255&hold,hbuf[1]=hold>>>8&255,state.check=crc32(state.check,hbuf,2,0)),hold=0,bits=0,state.mode=5;case 5:if(1024&state.flags){for(;bits<16;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}state.length=hold,state.head&&(state.head.extra_len=hold),512&state.flags&&(hbuf[0]=255&hold,hbuf[1]=hold>>>8&255,state.check=crc32(state.check,hbuf,2,0)),hold=0,bits=0}else state.head&&(state.head.extra=null);state.mode=6;case 6:if(1024&state.flags&&((copy=state.length)>have&&(copy=have),copy&&(state.head&&(len=state.head.extra_len-state.length,state.head.extra||(state.head.extra=Array(state.head.extra_len)),utils.arraySet(state.head.extra,input,next,copy,len)),512&state.flags&&(state.check=crc32(state.check,input,copy,next)),have-=copy,next+=copy,state.length-=copy),state.length))break inf_leave;state.length=0,state.mode=7;case 7:if(2048&state.flags){if(0===have)break inf_leave;copy=0;do len=input[next+copy++],state.head&&len&&state.length<65536&&(state.head.name+=String.fromCharCode(len));while(len&©<have)if(512&state.flags&&(state.check=crc32(state.check,input,copy,next)),have-=copy,next+=copy,len)break inf_leave}else state.head&&(state.head.name=null);state.length=0,state.mode=8;case 8:if(4096&state.flags){if(0===have)break inf_leave;copy=0;do len=input[next+copy++],state.head&&len&&state.length<65536&&(state.head.comment+=String.fromCharCode(len));while(len&©<have)if(512&state.flags&&(state.check=crc32(state.check,input,copy,next)),have-=copy,next+=copy,len)break inf_leave}else state.head&&(state.head.comment=null);state.mode=9;case 9:if(512&state.flags){for(;bits<16;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(hold!==(65535&state.check)){strm.msg="header crc mismatch",state.mode=30;break}hold=0,bits=0}state.head&&(state.head.hcrc=state.flags>>9&1,state.head.done=!0),strm.adler=state.check=0,state.mode=12;break;case 10:for(;bits<32;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}strm.adler=state.check=zswap32(hold),hold=0,bits=0,state.mode=11;case 11:if(0===state.havedict)return strm.next_out=put,strm.avail_out=left,strm.next_in=next,strm.avail_in=have,state.hold=hold,state.bits=bits,2;strm.adler=state.check=1,state.mode=12;case 12:if(5===flush||6===flush)break inf_leave;case 13:if(state.last){hold>>>=7&bits,bits-=7&bits,state.mode=27;break}for(;bits<3;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}switch(state.last=1&hold,bits-=1,3&(hold>>>=1)){case 0:state.mode=14;break;case 1:if(fixedtables(state),state.mode=20,6===flush){hold>>>=2,bits-=2;break inf_leave}break;case 2:state.mode=17;break;case 3:strm.msg="invalid block type",state.mode=30}hold>>>=2,bits-=2;break;case 14:for(hold>>>=7&bits,bits-=7&bits;bits<32;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if((65535&hold)!=(hold>>>16^65535)){strm.msg="invalid stored block lengths",state.mode=30;break}if(state.length=65535&hold,hold=0,bits=0,state.mode=15,6===flush)break inf_leave;case 15:state.mode=16;case 16:if(copy=state.length){if(copy>have&&(copy=have),copy>left&&(copy=left),0===copy)break inf_leave;utils.arraySet(output,input,next,copy,put),have-=copy,next+=copy,left-=copy,put+=copy,state.length-=copy;break}state.mode=12;break;case 17:for(;bits<14;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(state.nlen=(31&hold)+257,hold>>>=5,bits-=5,state.ndist=(31&hold)+1,hold>>>=5,bits-=5,state.ncode=(15&hold)+4,hold>>>=4,bits-=4,state.nlen>286||state.ndist>30){strm.msg="too many length or distance symbols",state.mode=30;break}state.have=0,state.mode=18;case 18:for(;state.have<state.ncode;){for(;bits<3;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}state.lens[order[state.have++]]=7&hold,hold>>>=3,bits-=3}for(;state.have<19;)state.lens[order[state.have++]]=0;if(state.lencode=state.lendyn,state.lenbits=7,opts={bits:state.lenbits},ret=inflate_table(0,state.lens,0,19,state.lencode,0,state.work,opts),state.lenbits=opts.bits,ret){strm.msg="invalid code lengths set",state.mode=30;break}state.have=0,state.mode=19;case 19:for(;state.have<state.nlen+state.ndist;){for(;here_bits=(here=state.lencode[hold&(1<<state.lenbits)-1])>>>24,here_op=here>>>16&255,here_val=65535&here,!(here_bits<=bits);){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(here_val<16)hold>>>=here_bits,bits-=here_bits,state.lens[state.have++]=here_val;else{if(16===here_val){for(n=here_bits+2;bits<n;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(hold>>>=here_bits,bits-=here_bits,0===state.have){strm.msg="invalid bit length repeat",state.mode=30;break}len=state.lens[state.have-1],copy=3+(3&hold),hold>>>=2,bits-=2}else if(17===here_val){for(n=here_bits+3;bits<n;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}hold>>>=here_bits,bits-=here_bits,len=0,copy=3+(7&hold),hold>>>=3,bits-=3}else{for(n=here_bits+7;bits<n;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}hold>>>=here_bits,bits-=here_bits,len=0,copy=11+(127&hold),hold>>>=7,bits-=7}if(state.have+copy>state.nlen+state.ndist){strm.msg="invalid bit length repeat",state.mode=30;break}for(;copy--;)state.lens[state.have++]=len}}if(30===state.mode)break;if(0===state.lens[256]){strm.msg="invalid code -- missing end-of-block",state.mode=30;break}if(state.lenbits=9,opts={bits:state.lenbits},ret=inflate_table(1,state.lens,0,state.nlen,state.lencode,0,state.work,opts),state.lenbits=opts.bits,ret){strm.msg="invalid literal/lengths set",state.mode=30;break}if(state.distbits=6,state.distcode=state.distdyn,opts={bits:state.distbits},ret=inflate_table(2,state.lens,state.nlen,state.ndist,state.distcode,0,state.work,opts),state.distbits=opts.bits,ret){strm.msg="invalid distances set",state.mode=30;break}if(state.mode=20,6===flush)break inf_leave;case 20:state.mode=21;case 21:if(have>=6&&left>=258){strm.next_out=put,strm.avail_out=left,strm.next_in=next,strm.avail_in=have,state.hold=hold,state.bits=bits,inflate_fast(strm,_out),put=strm.next_out,output=strm.output,left=strm.avail_out,next=strm.next_in,input=strm.input,have=strm.avail_in,hold=state.hold,bits=state.bits,12===state.mode&&(state.back=-1);break}for(state.back=0;here_bits=(here=state.lencode[hold&(1<<state.lenbits)-1])>>>24,here_op=here>>>16&255,here_val=65535&here,!(here_bits<=bits);){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(here_op&&(240&here_op)==0){for(last_bits=here_bits,last_op=here_op,last_val=here_val;here_bits=(here=state.lencode[last_val+((hold&(1<<last_bits+last_op)-1)>>last_bits)])>>>24,here_op=here>>>16&255,here_val=65535&here,!(last_bits+here_bits<=bits);){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}hold>>>=last_bits,bits-=last_bits,state.back+=last_bits}if(hold>>>=here_bits,bits-=here_bits,state.back+=here_bits,state.length=here_val,0===here_op){state.mode=26;break}if(32&here_op){state.back=-1,state.mode=12;break}if(64&here_op){strm.msg="invalid literal/length code",state.mode=30;break}state.extra=15&here_op,state.mode=22;case 22:if(state.extra){for(n=state.extra;bits<n;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}state.length+=hold&(1<<state.extra)-1,hold>>>=state.extra,bits-=state.extra,state.back+=state.extra}state.was=state.length,state.mode=23;case 23:for(;here_bits=(here=state.distcode[hold&(1<<state.distbits)-1])>>>24,here_op=here>>>16&255,here_val=65535&here,!(here_bits<=bits);){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if((240&here_op)==0){for(last_bits=here_bits,last_op=here_op,last_val=here_val;here_bits=(here=state.distcode[last_val+((hold&(1<<last_bits+last_op)-1)>>last_bits)])>>>24,here_op=here>>>16&255,here_val=65535&here,!(last_bits+here_bits<=bits);){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}hold>>>=last_bits,bits-=last_bits,state.back+=last_bits}if(hold>>>=here_bits,bits-=here_bits,state.back+=here_bits,64&here_op){strm.msg="invalid distance code",state.mode=30;break}state.offset=here_val,state.extra=15&here_op,state.mode=24;case 24:if(state.extra){for(n=state.extra;bits<n;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}state.offset+=hold&(1<<state.extra)-1,hold>>>=state.extra,bits-=state.extra,state.back+=state.extra}if(state.offset>state.dmax){strm.msg="invalid distance too far back",state.mode=30;break}state.mode=25;case 25:if(0===left)break inf_leave;if(copy=_out-left,state.offset>copy){if((copy=state.offset-copy)>state.whave&&state.sane){strm.msg="invalid distance too far back",state.mode=30;break}copy>state.wnext?(copy-=state.wnext,from=state.wsize-copy):from=state.wnext-copy,copy>state.length&&(copy=state.length),from_source=state.window}else from_source=output,from=put-state.offset,copy=state.length;copy>left&&(copy=left),left-=copy,state.length-=copy;do output[put++]=from_source[from++];while(--copy)0===state.length&&(state.mode=21);break;case 26:if(0===left)break inf_leave;output[put++]=state.length,left--,state.mode=21;break;case 27:if(state.wrap){for(;bits<32;){if(0===have)break inf_leave;have--,hold|=input[next++]<<bits,bits+=8}if(_out-=left,strm.total_out+=_out,state.total+=_out,_out&&(strm.adler=state.check=state.flags?crc32(state.check,output,_out,put-_out):adler32(state.check,output,_out,put-_out)),_out=left,(state.flags?hold:zswap32(hold))!==state.check){strm.msg="incorrect data check",state.mode=30;break}hold=0,bits=0}state.mode=28;case 28:if(state.wrap&&state.flags){for(;bits<32;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(hold!==(4294967295&state.total)){strm.msg="incorrect length check",state.mode=30;break}hold=0,bits=0}state.mode=29;case 29:ret=1;break inf_leave;case 30:ret=-3;break inf_leave;case 31:return -4;default:return -2}return(strm.next_out=put,strm.avail_out=left,strm.next_in=next,strm.avail_in=have,state.hold=hold,state.bits=bits,(state.wsize||_out!==strm.avail_out&&state.mode<30&&(state.mode<27||4!==flush))&&updatewindow(strm,strm.output,strm.next_out,_out-strm.avail_out))?(state.mode=31,-4):(_in-=strm.avail_in,_out-=strm.avail_out,strm.total_in+=_in,strm.total_out+=_out,state.total+=_out,state.wrap&&_out&&(strm.adler=state.check=state.flags?crc32(state.check,output,_out,strm.next_out-_out):adler32(state.check,output,_out,strm.next_out-_out)),strm.data_type=state.bits+(state.last?64:0)+(12===state.mode?128:0)+(20===state.mode||15===state.mode?256:0),(0===_in&&0===_out||4===flush)&&0===ret&&(ret=-5),ret)}function inflateEnd(strm){if(!strm||!strm.state)return -2;var state=strm.state;return state.window&&(state.window=null),strm.state=null,0}function inflateGetHeader(strm,head){var state;return strm&&strm.state&&(2&(state=strm.state).wrap)!=0?(state.head=head,head.done=!1,0):-2}function inflateSetDictionary(strm,dictionary){var state,dictLength=dictionary.length;return strm&&strm.state&&(0===(state=strm.state).wrap||11===state.mode)?11===state.mode&&adler32(1,dictionary,dictLength,0)!==state.check?-3:updatewindow(strm,dictionary,dictLength,dictLength)?(state.mode=31,-4):(state.havedict=1,0):-2}exports.inflateReset=inflateReset,exports.inflateReset2=inflateReset2,exports.inflateResetKeep=inflateResetKeep,exports.inflateInit=inflateInit,exports.inflateInit2=inflateInit2,exports.inflate=inflate,exports.inflateEnd=inflateEnd,exports.inflateGetHeader=inflateGetHeader,exports.inflateSetDictionary=inflateSetDictionary,exports.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":140,"./adler32":141,"./crc32":143,"./inffast":145,"./inftrees":147}],147:[function(require1,module,exports){"use strict";var utils=require1("../utils/common"),lbase=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],lext=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],dbase=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],dext=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];module.exports=function inflate_table(type,lens,lens_index,codes,table,table_index,work,opts){var incr,fill,low,mask,next,end,here_bits,here_op,here_val,bits=opts.bits,len=0,sym=0,min=0,max=0,root=0,curr=0,drop=0,left=0,used=0,huff=0,base=null,base_index=0,count=new utils.Buf16(16),offs=new utils.Buf16(16),extra=null,extra_index=0;for(len=0;len<=15;len++)count[len]=0;for(sym=0;sym<codes;sym++)count[lens[lens_index+sym]]++;for(max=15,root=bits;max>=1&&0===count[max];max--);if(root>max&&(root=max),0===max)return table[table_index++]=20971520,table[table_index++]=20971520,opts.bits=1,0;for(min=1;min<max&&0===count[min];min++);for(root<min&&(root=min),left=1,len=1;len<=15;len++)if(left<<=1,(left-=count[len])<0)return -1;if(left>0&&(0===type||1!==max))return -1;for(len=1,offs[1]=0;len<15;len++)offs[len+1]=offs[len]+count[len];for(sym=0;sym<codes;sym++)0!==lens[lens_index+sym]&&(work[offs[lens[lens_index+sym]]++]=sym);if(0===type?(base=extra=work,end=19):1===type?(base=lbase,base_index-=257,extra=lext,extra_index-=257,end=256):(base=dbase,extra=dext,end=-1),huff=0,sym=0,len=min,next=table_index,curr=root,drop=0,low=-1,mask=(used=1<<root)-1,1===type&&used>852||2===type&&used>592)return 1;for(;;){here_bits=len-drop,work[sym]<end?(here_op=0,here_val=work[sym]):work[sym]>end?(here_op=extra[extra_index+work[sym]],here_val=base[base_index+work[sym]]):(here_op=96,here_val=0),incr=1<<len-drop,min=fill=1<<curr;do table[next+(huff>>drop)+(fill-=incr)]=here_bits<<24|here_op<<16|here_val|0;while(0!==fill)for(incr=1<<len-1;huff&incr;)incr>>=1;if(0!==incr?(huff&=incr-1,huff+=incr):huff=0,sym++,0==--count[len]){if(len===max)break;len=lens[lens_index+work[sym]]}if(len>root&&(huff&mask)!==low){for(0===drop&&(drop=root),next+=min,left=1<<(curr=len-drop);curr+drop<max&&!((left-=count[curr+drop])<=0);)curr++,left<<=1;if(used+=1<<curr,1===type&&used>852||2===type&&used>592)return 1;table[low=huff&mask]=root<<24|curr<<16|next-table_index|0}}return 0!==huff&&(table[next+huff]=len-drop<<24|4194304),opts.bits=root,0}},{"../utils/common":140}],148:[function(require1,module,exports){"use strict";module.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],149:[function(require1,module,exports){"use strict";var static_l_desc,static_d_desc,static_bl_desc,utils=require1("../utils/common");function zero(buf){for(var len=buf.length;--len>=0;)buf[len]=0}var extra_lbits=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],extra_dbits=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],extra_blbits=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],bl_order=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],static_ltree=Array(576);zero(static_ltree);var static_dtree=Array(60);zero(static_dtree);var _dist_code=Array(512);zero(_dist_code);var _length_code=Array(256);zero(_length_code);var base_length=Array(29);zero(base_length);var base_dist=Array(30);function StaticTreeDesc(static_tree,extra_bits,extra_base,elems,max_length){this.static_tree=static_tree,this.extra_bits=extra_bits,this.extra_base=extra_base,this.elems=elems,this.max_length=max_length,this.has_stree=static_tree&&static_tree.length}function TreeDesc(dyn_tree,stat_desc){this.dyn_tree=dyn_tree,this.max_code=0,this.stat_desc=stat_desc}function d_code(dist){return dist<256?_dist_code[dist]:_dist_code[256+(dist>>>7)]}function put_short(s,w){s.pending_buf[s.pending++]=255&w,s.pending_buf[s.pending++]=w>>>8&255}function send_bits(s,value,length){s.bi_valid>16-length?(s.bi_buf|=value<<s.bi_valid&65535,put_short(s,s.bi_buf),s.bi_buf=value>>16-s.bi_valid,s.bi_valid+=length-16):(s.bi_buf|=value<<s.bi_valid&65535,s.bi_valid+=length)}function send_code(s,c,tree){send_bits(s,tree[2*c],tree[2*c+1])}function bi_reverse(code,len){var res=0;do res|=1&code,code>>>=1,res<<=1;while(--len>0)return res>>>1}function bi_flush(s){16===s.bi_valid?(put_short(s,s.bi_buf),s.bi_buf=0,s.bi_valid=0):s.bi_valid>=8&&(s.pending_buf[s.pending++]=255&s.bi_buf,s.bi_buf>>=8,s.bi_valid-=8)}function gen_bitlen(s,desc){var h,n,m,bits,xbits,f,tree=desc.dyn_tree,max_code=desc.max_code,stree=desc.stat_desc.static_tree,has_stree=desc.stat_desc.has_stree,extra=desc.stat_desc.extra_bits,base=desc.stat_desc.extra_base,max_length=desc.stat_desc.max_length,overflow=0;for(bits=0;bits<=15;bits++)s.bl_count[bits]=0;for(tree[2*s.heap[s.heap_max]+1]=0,h=s.heap_max+1;h<573;h++)(bits=tree[2*tree[2*(n=s.heap[h])+1]+1]+1)>max_length&&(bits=max_length,overflow++),tree[2*n+1]=bits,!(n>max_code)&&(s.bl_count[bits]++,xbits=0,n>=base&&(xbits=extra[n-base]),f=tree[2*n],s.opt_len+=f*(bits+xbits),has_stree&&(s.static_len+=f*(stree[2*n+1]+xbits)));if(0!==overflow){do{for(bits=max_length-1;0===s.bl_count[bits];)bits--;s.bl_count[bits]--,s.bl_count[bits+1]+=2,s.bl_count[max_length]--,overflow-=2}while(overflow>0)for(bits=max_length;0!==bits;bits--)for(n=s.bl_count[bits];0!==n;)!((m=s.heap[--h])>max_code)&&(tree[2*m+1]!==bits&&(s.opt_len+=(bits-tree[2*m+1])*tree[2*m],tree[2*m+1]=bits),n--)}}function gen_codes(tree,max_code,bl_count){var bits,n,next_code=Array(16),code=0;for(bits=1;bits<=15;bits++)next_code[bits]=code=code+bl_count[bits-1]<<1;for(n=0;n<=max_code;n++){var len=tree[2*n+1];0!==len&&(tree[2*n]=bi_reverse(next_code[len]++,len))}}function tr_static_init(){var n,bits,length,code,dist,bl_count=Array(16);for(code=0,length=0;code<28;code++)for(n=0,base_length[code]=length;n<1<<extra_lbits[code];n++)_length_code[length++]=code;for(_length_code[length-1]=code,dist=0,code=0;code<16;code++)for(n=0,base_dist[code]=dist;n<1<<extra_dbits[code];n++)_dist_code[dist++]=code;for(dist>>=7;code<30;code++)for(n=0,base_dist[code]=dist<<7;n<1<<extra_dbits[code]-7;n++)_dist_code[256+dist++]=code;for(bits=0;bits<=15;bits++)bl_count[bits]=0;for(n=0;n<=143;)static_ltree[2*n+1]=8,n++,bl_count[8]++;for(;n<=255;)static_ltree[2*n+1]=9,n++,bl_count[9]++;for(;n<=279;)static_ltree[2*n+1]=7,n++,bl_count[7]++;for(;n<=287;)static_ltree[2*n+1]=8,n++,bl_count[8]++;for(gen_codes(static_ltree,287,bl_count),n=0;n<30;n++)static_dtree[2*n+1]=5,static_dtree[2*n]=bi_reverse(n,5);static_l_desc=new StaticTreeDesc(static_ltree,extra_lbits,257,286,15),static_d_desc=new StaticTreeDesc(static_dtree,extra_dbits,0,30,15),static_bl_desc=new StaticTreeDesc([],extra_blbits,0,19,7)}function init_block(s){var n;for(n=0;n<286;n++)s.dyn_ltree[2*n]=0;for(n=0;n<30;n++)s.dyn_dtree[2*n]=0;for(n=0;n<19;n++)s.bl_tree[2*n]=0;s.dyn_ltree[512]=1,s.opt_len=s.static_len=0,s.last_lit=s.matches=0}function bi_windup(s){s.bi_valid>8?put_short(s,s.bi_buf):s.bi_valid>0&&(s.pending_buf[s.pending++]=s.bi_buf),s.bi_buf=0,s.bi_valid=0}function copy_block(s,buf,len,header){bi_windup(s),header&&(put_short(s,len),put_short(s,~len)),utils.arraySet(s.pending_buf,s.window,buf,len,s.pending),s.pending+=len}function smaller(tree,n,m,depth){var _n2=2*n,_m2=2*m;return tree[_n2]<tree[_m2]||tree[_n2]===tree[_m2]&&depth[n]<=depth[m]}function pqdownheap(s,tree,k){for(var v=s.heap[k],j=k<<1;j<=s.heap_len&&(j<s.heap_len&&smaller(tree,s.heap[j+1],s.heap[j],s.depth)&&j++,!smaller(tree,v,s.heap[j],s.depth));)s.heap[k]=s.heap[j],k=j,j<<=1;s.heap[k]=v}function compress_block(s,ltree,dtree){var dist,lc,code,extra,lx=0;if(0!==s.last_lit)do dist=s.pending_buf[s.d_buf+2*lx]<<8|s.pending_buf[s.d_buf+2*lx+1],lc=s.pending_buf[s.l_buf+lx],lx++,0===dist?send_code(s,lc,ltree):(send_code(s,(code=_length_code[lc])+256+1,ltree),0!==(extra=extra_lbits[code])&&send_bits(s,lc-=base_length[code],extra),send_code(s,code=d_code(--dist),dtree),0!==(extra=extra_dbits[code])&&send_bits(s,dist-=base_dist[code],extra));while(lx<s.last_lit)send_code(s,256,ltree)}function build_tree(s,desc){var n,m,node,tree=desc.dyn_tree,stree=desc.stat_desc.static_tree,has_stree=desc.stat_desc.has_stree,elems=desc.stat_desc.elems,max_code=-1;for(n=0,s.heap_len=0,s.heap_max=573;n<elems;n++)0!==tree[2*n]?(s.heap[++s.heap_len]=max_code=n,s.depth[n]=0):tree[2*n+1]=0;for(;s.heap_len<2;)tree[2*(node=s.heap[++s.heap_len]=max_code<2?++max_code:0)]=1,s.depth[node]=0,s.opt_len--,has_stree&&(s.static_len-=stree[2*node+1]);for(desc.max_code=max_code,n=s.heap_len>>1;n>=1;n--)pqdownheap(s,tree,n);node=elems;do n=s.heap[1],s.heap[1]=s.heap[s.heap_len--],pqdownheap(s,tree,1),m=s.heap[1],s.heap[--s.heap_max]=n,s.heap[--s.heap_max]=m,tree[2*node]=tree[2*n]+tree[2*m],s.depth[node]=(s.depth[n]>=s.depth[m]?s.depth[n]:s.depth[m])+1,tree[2*n+1]=tree[2*m+1]=node,s.heap[1]=node++,pqdownheap(s,tree,1);while(s.heap_len>=2)s.heap[--s.heap_max]=s.heap[1],gen_bitlen(s,desc),gen_codes(tree,max_code,s.bl_count)}function scan_tree(s,tree,max_code){var n,curlen,prevlen=-1,nextlen=tree[1],count=0,max_count=7,min_count=4;for(0===nextlen&&(max_count=138,min_count=3),tree[(max_code+1)*2+1]=65535,n=0;n<=max_code;n++)curlen=nextlen,nextlen=tree[(n+1)*2+1],++count<max_count&&curlen===nextlen||(count<min_count?s.bl_tree[2*curlen]+=count:0!==curlen?(curlen!==prevlen&&s.bl_tree[2*curlen]++,s.bl_tree[32]++):count<=10?s.bl_tree[34]++:s.bl_tree[36]++,count=0,prevlen=curlen,0===nextlen?(max_count=138,min_count=3):curlen===nextlen?(max_count=6,min_count=3):(max_count=7,min_count=4))}function send_tree(s,tree,max_code){var n,curlen,prevlen=-1,nextlen=tree[1],count=0,max_count=7,min_count=4;for(0===nextlen&&(max_count=138,min_count=3),n=0;n<=max_code;n++)if(curlen=nextlen,nextlen=tree[(n+1)*2+1],!(++count<max_count)||curlen!==nextlen){if(count<min_count)do send_code(s,curlen,s.bl_tree);while(0!=--count)else 0!==curlen?(curlen!==prevlen&&(send_code(s,curlen,s.bl_tree),count--),send_code(s,16,s.bl_tree),send_bits(s,count-3,2)):count<=10?(send_code(s,17,s.bl_tree),send_bits(s,count-3,3)):(send_code(s,18,s.bl_tree),send_bits(s,count-11,7));count=0,prevlen=curlen,0===nextlen?(max_count=138,min_count=3):curlen===nextlen?(max_count=6,min_count=3):(max_count=7,min_count=4)}}function build_bl_tree(s){var max_blindex;for(scan_tree(s,s.dyn_ltree,s.l_desc.max_code),scan_tree(s,s.dyn_dtree,s.d_desc.max_code),build_tree(s,s.bl_desc),max_blindex=18;max_blindex>=3&&0===s.bl_tree[2*bl_order[max_blindex]+1];max_blindex--);return s.opt_len+=3*(max_blindex+1)+5+5+4,max_blindex}function send_all_trees(s,lcodes,dcodes,blcodes){var rank;for(send_bits(s,lcodes-257,5),send_bits(s,dcodes-1,5),send_bits(s,blcodes-4,4),rank=0;rank<blcodes;rank++)send_bits(s,s.bl_tree[2*bl_order[rank]+1],3);send_tree(s,s.dyn_ltree,lcodes-1),send_tree(s,s.dyn_dtree,dcodes-1)}function detect_data_type(s){var n,black_mask=4093624447;for(n=0;n<=31;n++,black_mask>>>=1)if(1&black_mask&&0!==s.dyn_ltree[2*n])return 0;if(0!==s.dyn_ltree[18]||0!==s.dyn_ltree[20]||0!==s.dyn_ltree[26])return 1;for(n=32;n<256;n++)if(0!==s.dyn_ltree[2*n])return 1;return 0}zero(base_dist);var static_init_done=!1;function _tr_init(s){static_init_done||(tr_static_init(),static_init_done=!0),s.l_desc=new TreeDesc(s.dyn_ltree,static_l_desc),s.d_desc=new TreeDesc(s.dyn_dtree,static_d_desc),s.bl_desc=new TreeDesc(s.bl_tree,static_bl_desc),s.bi_buf=0,s.bi_valid=0,init_block(s)}function _tr_stored_block(s,buf,stored_len,last){send_bits(s,0+(last?1:0),3),copy_block(s,buf,stored_len,!0)}function _tr_align(s){send_bits(s,2,3),send_code(s,256,static_ltree),bi_flush(s)}function _tr_flush_block(s,buf,stored_len,last){var opt_lenb,static_lenb,max_blindex=0;s.level>0?(2===s.strm.data_type&&(s.strm.data_type=detect_data_type(s)),build_tree(s,s.l_desc),build_tree(s,s.d_desc),max_blindex=build_bl_tree(s),opt_lenb=s.opt_len+3+7>>>3,(static_lenb=s.static_len+3+7>>>3)<=opt_lenb&&(opt_lenb=static_lenb)):opt_lenb=static_lenb=stored_len+5,stored_len+4<=opt_lenb&&-1!==buf?_tr_stored_block(s,buf,stored_len,last):4===s.strategy||static_lenb===opt_lenb?(send_bits(s,2+(last?1:0),3),compress_block(s,static_ltree,static_dtree)):(send_bits(s,4+(last?1:0),3),send_all_trees(s,s.l_desc.max_code+1,s.d_desc.max_code+1,max_blindex+1),compress_block(s,s.dyn_ltree,s.dyn_dtree)),init_block(s),last&&bi_windup(s)}function _tr_tally(s,dist,lc){return s.pending_buf[s.d_buf+2*s.last_lit]=dist>>>8&255,s.pending_buf[s.d_buf+2*s.last_lit+1]=255&dist,s.pending_buf[s.l_buf+s.last_lit]=255&lc,s.last_lit++,0===dist?s.dyn_ltree[2*lc]++:(s.matches++,dist--,s.dyn_ltree[(_length_code[lc]+256+1)*2]++,s.dyn_dtree[2*d_code(dist)]++),s.last_lit===s.lit_bufsize-1}exports._tr_init=_tr_init,exports._tr_stored_block=_tr_stored_block,exports._tr_flush_block=_tr_flush_block,exports._tr_tally=_tr_tally,exports._tr_align=_tr_align},{"../utils/common":140}],150:[function(require1,module,exports){"use strict";function ZStream(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}module.exports=ZStream},{}],151:[function(require1,module,exports){(function(process){(function(){"use strict";function nextTick(fn,arg1,arg2,arg3){if("function"!=typeof fn)throw TypeError('"callback" argument must be a function');var args,i,len=arguments.length;switch(len){case 0:case 1:return process.nextTick(fn);case 2:return process.nextTick(function afterTickOne(){fn.call(null,arg1)});case 3:return process.nextTick(function afterTickTwo(){fn.call(null,arg1,arg2)});case 4:return process.nextTick(function afterTickThree(){fn.call(null,arg1,arg2,arg3)});default:for(args=Array(len-1),i=0;i<args.length;)args[i++]=arguments[i];return process.nextTick(function afterTick(){fn.apply(null,args)})}}void 0!==process&&process.version&&0!==process.version.indexOf("v0.")&&(0!==process.version.indexOf("v1.")||0===process.version.indexOf("v1.8."))?module.exports=process:module.exports={nextTick:nextTick}}).call(this)}).call(this,require1("_process"))},{_process:152}],152:[function(require1,module,exports){var cachedSetTimeout,cachedClearTimeout,currentQueue,process=module.exports={};function defaultSetTimout(){throw Error("setTimeout has not been defined")}function defaultClearTimeout(){throw Error("clearTimeout has not been defined")}function runTimeout(fun){if(cachedSetTimeout===setTimeout)return setTimeout(fun,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(fun,0);try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout)return clearTimeout(marker);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(marker);try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}!function(){try{cachedSetTimeout="function"==typeof setTimeout?setTimeout:defaultSetTimout}catch(e){cachedSetTimeout=defaultSetTimout}try{cachedClearTimeout="function"==typeof clearTimeout?clearTimeout:defaultClearTimeout}catch(e){cachedClearTimeout=defaultClearTimeout}}();var queue=[],draining=!1,queueIndex=-1;function cleanUpNextTick(){draining&¤tQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var timeout=runTimeout(cleanUpNextTick);draining=!0;for(var len=queue.length;len;){for(currentQueue=queue,queue=[];++queueIndex<len;)currentQueue&¤tQueue[queueIndex].run();queueIndex=-1,len=queue.length}currentQueue=null,draining=!1,runClearTimeout(timeout)}}function Item(fun,array){this.fun=fun,this.array=array}function noop(){}process.nextTick=function(fun){var args=Array(arguments.length-1);if(arguments.length>1)for(var i=1;i<arguments.length;i++)args[i-1]=arguments[i];queue.push(new Item(fun,args)),1!==queue.length||draining||runTimeout(drainQueue)},Item.prototype.run=function(){this.fun.apply(null,this.array)},process.title="browser",process.browser=!0,process.env={},process.argv=[],process.version="",process.versions={},process.on=noop,process.addListener=noop,process.once=noop,process.off=noop,process.removeListener=noop,process.removeAllListeners=noop,process.emit=noop,process.prependListener=noop,process.prependOnceListener=noop,process.listeners=function(name){return[]},process.binding=function(name){throw Error("process.binding is not supported")},process.cwd=function(){return"/"},process.chdir=function(dir){throw Error("process.chdir is not supported")},process.umask=function(){return 0}},{}],153:[function(require1,module,exports){"use strict";function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}module.exports=function(qs,sep,eq,options){sep=sep||"&",eq=eq||"=";var obj={};if("string"!=typeof qs||0===qs.length)return obj;var regexp=/\+/g;qs=qs.split(sep);var maxKeys=1e3;options&&"number"==typeof options.maxKeys&&(maxKeys=options.maxKeys);var len=qs.length;maxKeys>0&&len>maxKeys&&(len=maxKeys);for(var i=0;i<len;++i){var kstr,vstr,k,v,x=qs[i].replace(regexp,"%20"),idx=x.indexOf(eq);idx>=0?(kstr=x.substr(0,idx),vstr=x.substr(idx+1)):(kstr=x,vstr=""),k=decodeURIComponent(kstr),v=decodeURIComponent(vstr),hasOwnProperty(obj,k)?isArray(obj[k])?obj[k].push(v):obj[k]=[obj[k],v]:obj[k]=v}return obj};var isArray=Array.isArray||function(xs){return"[object Array]"===Object.prototype.toString.call(xs)}},{}],154:[function(require1,module,exports){"use strict";var stringifyPrimitive=function(v){switch(typeof v){case"string":return v;case"boolean":return v?"true":"false";case"number":return isFinite(v)?v:"";default:return""}};module.exports=function(obj,sep,eq,name){return(sep=sep||"&",eq=eq||"=",null===obj&&(obj=void 0),"object"==typeof obj)?map(objectKeys(obj),function(k){var ks=encodeURIComponent(stringifyPrimitive(k))+eq;return isArray(obj[k])?map(obj[k],function(v){return ks+encodeURIComponent(stringifyPrimitive(v))}).join(sep):ks+encodeURIComponent(stringifyPrimitive(obj[k]))}).join(sep):name?encodeURIComponent(stringifyPrimitive(name))+eq+encodeURIComponent(stringifyPrimitive(obj)):""};var isArray=Array.isArray||function(xs){return"[object Array]"===Object.prototype.toString.call(xs)};function map(xs,f){if(xs.map)return xs.map(f);for(var res=[],i=0;i<xs.length;i++)res.push(f(xs[i],i));return res}var objectKeys=Object.keys||function(obj){var res=[];for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&res.push(key);return res}},{}],155:[function(require1,module,exports){"use strict";exports.decode=exports.parse=require1("./decode"),exports.encode=exports.stringify=require1("./encode")},{"./decode":153,"./encode":154}],156:[function(require1,module,exports){"use strict";function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype),subClass.prototype.constructor=subClass,subClass.__proto__=superClass}var codes={};function createErrorType(code,message,Base){function getMessage(arg1,arg2,arg3){return"string"==typeof message?message:message(arg1,arg2,arg3)}Base||(Base=Error);var NodeError=function(_Base){function NodeError(arg1,arg2,arg3){return _Base.call(this,getMessage(arg1,arg2,arg3))||this}return _inheritsLoose(NodeError,_Base),NodeError}(Base);NodeError.prototype.name=Base.name,NodeError.prototype.code=code,codes[code]=NodeError}function oneOf(expected,thing){if(!Array.isArray(expected))return"of ".concat(thing," ").concat(String(expected));var len=expected.length;return(expected=expected.map(function(i){return String(i)}),len>2)?"one of ".concat(thing," ").concat(expected.slice(0,len-1).join(", "),", or ")+expected[len-1]:2===len?"one of ".concat(thing," ").concat(expected[0]," or ").concat(expected[1]):"of ".concat(thing," ").concat(expected[0])}function startsWith(str,search,pos){return str.substr(!pos||pos<0?0:+pos,search.length)===search}function endsWith(str,search,this_len){return(void 0===this_len||this_len>str.length)&&(this_len=str.length),str.substring(this_len-search.length,this_len)===search}function includes(str,search,start){return"number"!=typeof start&&(start=0),!(start+search.length>str.length)&&-1!==str.indexOf(search,start)}createErrorType("ERR_INVALID_OPT_VALUE",function(name,value){return'The value "'+value+'" is invalid for option "'+name+'"'},TypeError),createErrorType("ERR_INVALID_ARG_TYPE",function(name,expected,actual){if("string"==typeof expected&&startsWith(expected,"not ")?(determiner="must not be",expected=expected.replace(/^not /,"")):determiner="must be",endsWith(name," argument"))msg="The ".concat(name," ").concat(determiner," ").concat(oneOf(expected,"type"));else{var determiner,msg,type=includes(name,".")?"property":"argument";msg='The "'.concat(name,'" ').concat(type," ").concat(determiner," ").concat(oneOf(expected,"type"))}return msg+". Received type ".concat(typeof actual)},TypeError),createErrorType("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),createErrorType("ERR_METHOD_NOT_IMPLEMENTED",function(name){return"The "+name+" method is not implemented"}),createErrorType("ERR_STREAM_PREMATURE_CLOSE","Premature close"),createErrorType("ERR_STREAM_DESTROYED",function(name){return"Cannot call "+name+" after a stream was destroyed"}),createErrorType("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),createErrorType("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),createErrorType("ERR_STREAM_WRITE_AFTER_END","write after end"),createErrorType("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),createErrorType("ERR_UNKNOWN_ENCODING",function(arg){return"Unknown encoding: "+arg},TypeError),createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),module.exports.codes=codes},{}],157:[function(require1,module,exports){(function(process){(function(){"use strict";var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys};module.exports=Duplex;var Readable=require1("./_stream_readable"),Writable=require1("./_stream_writable");require1("inherits")(Duplex,Readable);for(var keys=objectKeys(Writable.prototype),v=0;v<keys.length;v++){var method=keys[v];Duplex.prototype[method]||(Duplex.prototype[method]=Writable.prototype[method])}function Duplex(options){if(!(this instanceof Duplex))return new Duplex(options);Readable.call(this,options),Writable.call(this,options),this.allowHalfOpen=!0,options&&(!1===options.readable&&(this.readable=!1),!1===options.writable&&(this.writable=!1),!1===options.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",onend)))}function onend(){this._writableState.ended||process.nextTick(onEndNT,this)}function onEndNT(self1){self1.end()}Object.defineProperty(Duplex.prototype,"writableHighWaterMark",{enumerable:!1,get:function get(){return this._writableState.highWaterMark}}),Object.defineProperty(Duplex.prototype,"writableBuffer",{enumerable:!1,get:function get(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(Duplex.prototype,"writableLength",{enumerable:!1,get:function get(){return this._writableState.length}}),Object.defineProperty(Duplex.prototype,"destroyed",{enumerable:!1,get:function get(){return void 0!==this._readableState&&void 0!==this._writableState&&this._readableState.destroyed&&this._writableState.destroyed},set:function set(value){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=value,this._writableState.destroyed=value)}})}).call(this)}).call(this,require1("_process"))},{"./_stream_readable":159,"./_stream_writable":161,_process:152,inherits:85}],158:[function(require1,module,exports){"use strict";module.exports=PassThrough;var Transform=require1("./_stream_transform");function PassThrough(options){if(!(this instanceof PassThrough))return new PassThrough(options);Transform.call(this,options)}require1("inherits")(PassThrough,Transform),PassThrough.prototype._transform=function(chunk,encoding,cb){cb(null,chunk)}},{"./_stream_transform":160,inherits:85}],159:[function(require1,module,exports){(function(process,global){(function(){"use strict";module.exports=Readable,Readable.ReadableState=ReadableState,require1("events").EventEmitter;var Duplex,debug,StringDecoder,createReadableStreamAsyncIterator,from,EElistenerCount=function(emitter,type){return emitter.listeners(type).length},Stream=require1("./internal/streams/stream"),Buffer=require1("buffer").Buffer,OurUint8Array=global.Uint8Array||function(){};function _uint8ArrayToBuffer(chunk){return Buffer.from(chunk)}function _isUint8Array(obj){return Buffer.isBuffer(obj)||obj instanceof OurUint8Array}var debugUtil=require1("util");debug=debugUtil&&debugUtil.debuglog?debugUtil.debuglog("stream"):function debug(){};var BufferList=require1("./internal/streams/buffer_list"),destroyImpl=require1("./internal/streams/destroy"),getHighWaterMark=require1("./internal/streams/state").getHighWaterMark,_require$codes=require1("../errors").codes,ERR_INVALID_ARG_TYPE=_require$codes.ERR_INVALID_ARG_TYPE,ERR_STREAM_PUSH_AFTER_EOF=_require$codes.ERR_STREAM_PUSH_AFTER_EOF,ERR_METHOD_NOT_IMPLEMENTED=_require$codes.ERR_METHOD_NOT_IMPLEMENTED,ERR_STREAM_UNSHIFT_AFTER_END_EVENT=_require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;require1("inherits")(Readable,Stream);var errorOrDestroy=destroyImpl.errorOrDestroy,kProxyEvents=["error","close","destroy","pause","resume"];function prependListener(emitter,event,fn){if("function"==typeof emitter.prependListener)return emitter.prependListener(event,fn);emitter._events&&emitter._events[event]?Array.isArray(emitter._events[event])?emitter._events[event].unshift(fn):emitter._events[event]=[fn,emitter._events[event]]:emitter.on(event,fn)}function ReadableState(options,stream,isDuplex){Duplex=Duplex||require1("./_stream_duplex"),options=options||{},"boolean"!=typeof isDuplex&&(isDuplex=stream instanceof Duplex),this.objectMode=!!options.objectMode,isDuplex&&(this.objectMode=this.objectMode||!!options.readableObjectMode),this.highWaterMark=getHighWaterMark(this,options,"readableHighWaterMark",isDuplex),this.buffer=new BufferList,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=!1!==options.emitClose,this.autoDestroy=!!options.autoDestroy,this.destroyed=!1,this.defaultEncoding=options.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,options.encoding&&(StringDecoder||(StringDecoder=require1("string_decoder/").StringDecoder),this.decoder=new StringDecoder(options.encoding),this.encoding=options.encoding)}function Readable(options){if(Duplex=Duplex||require1("./_stream_duplex"),!(this instanceof Readable))return new Readable(options);var isDuplex=this instanceof Duplex;this._readableState=new ReadableState(options,this,isDuplex),this.readable=!0,options&&("function"==typeof options.read&&(this._read=options.read),"function"==typeof options.destroy&&(this._destroy=options.destroy)),Stream.call(this)}function readableAddChunk(stream,chunk,encoding,addToFront,skipChunkCheck){debug("readableAddChunk",chunk);var er,state=stream._readableState;if(null===chunk)state.reading=!1,onEofChunk(stream,state);else if(skipChunkCheck||(er=chunkInvalid(state,chunk)),er)errorOrDestroy(stream,er);else if(state.objectMode||chunk&&chunk.length>0){if("string"==typeof chunk||state.objectMode||Object.getPrototypeOf(chunk)===Buffer.prototype||(chunk=_uint8ArrayToBuffer(chunk)),addToFront)state.endEmitted?errorOrDestroy(stream,new ERR_STREAM_UNSHIFT_AFTER_END_EVENT):addChunk(stream,state,chunk,!0);else if(state.ended)errorOrDestroy(stream,new ERR_STREAM_PUSH_AFTER_EOF);else{if(state.destroyed)return!1;state.reading=!1,state.decoder&&!encoding?(chunk=state.decoder.write(chunk),state.objectMode||0!==chunk.length?addChunk(stream,state,chunk,!1):maybeReadMore(stream,state)):addChunk(stream,state,chunk,!1)}}else addToFront||(state.reading=!1,maybeReadMore(stream,state));return!state.ended&&(state.length<state.highWaterMark||0===state.length)}function addChunk(stream,state,chunk,addToFront){state.flowing&&0===state.length&&!state.sync?(state.awaitDrain=0,stream.emit("data",chunk)):(state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):state.buffer.push(chunk),state.needReadable&&emitReadable(stream)),maybeReadMore(stream,state)}function chunkInvalid(state,chunk){var er;return _isUint8Array(chunk)||"string"==typeof chunk||void 0===chunk||state.objectMode||(er=new ERR_INVALID_ARG_TYPE("chunk",["string","Buffer","Uint8Array"],chunk)),er}function computeNewHighWaterMark(n){return n>=1073741824?n=1073741824:(n--,n|=n>>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n++),n}function howMuchToRead(n,state){return n<=0||0===state.length&&state.ended?0:state.objectMode?1:n!=n?state.flowing&&state.length?state.buffer.head.data.length:state.length:(n>state.highWaterMark&&(state.highWaterMark=computeNewHighWaterMark(n)),n<=state.length)?n:state.ended?state.length:(state.needReadable=!0,0)}function onEofChunk(stream,state){if(debug("onEofChunk"),!state.ended){if(state.decoder){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,state.sync?emitReadable(stream):(state.needReadable=!1,state.emittedReadable||(state.emittedReadable=!0,emitReadable_(stream)))}}function emitReadable(stream){var state=stream._readableState;debug("emitReadable",state.needReadable,state.emittedReadable),state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,process.nextTick(emitReadable_,stream))}function emitReadable_(stream){var state=stream._readableState;debug("emitReadable_",state.destroyed,state.length,state.ended),!state.destroyed&&(state.length||state.ended)&&(stream.emit("readable"),state.emittedReadable=!1),state.needReadable=!state.flowing&&!state.ended&&state.length<=state.highWaterMark,flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,process.nextTick(maybeReadMore_,stream,state))}function maybeReadMore_(stream,state){for(;!state.reading&&!state.ended&&(state.length<state.highWaterMark||state.flowing&&0===state.length);){var len=state.length;if(debug("maybeReadMore read 0"),stream.read(0),len===state.length)break}state.readingMore=!1}function pipeOnDrain(src){return function pipeOnDrainFunctionResult(){var state=src._readableState;debug("pipeOnDrain",state.awaitDrain),state.awaitDrain&&state.awaitDrain--,0===state.awaitDrain&&EElistenerCount(src,"data")&&(state.flowing=!0,flow(src))}}function updateReadableListening(self1){var state=self1._readableState;state.readableListening=self1.listenerCount("readable")>0,state.resumeScheduled&&!state.paused?state.flowing=!0:self1.listenerCount("data")>0&&self1.resume()}function nReadingNextTick(self1){debug("readable nexttick read 0"),self1.read(0)}function resume(stream,state){state.resumeScheduled||(state.resumeScheduled=!0,process.nextTick(resume_,stream,state))}function resume_(stream,state){debug("resume",state.reading),state.reading||stream.read(0),state.resumeScheduled=!1,stream.emit("resume"),flow(stream),state.flowing&&!state.reading&&stream.read(0)}function flow(stream){var state=stream._readableState;for(debug("flow",state.flowing);state.flowing&&null!==stream.read(););}function fromList(n,state){var ret;return 0===state.length?null:(state.objectMode?ret=state.buffer.shift():!n||n>=state.length?(ret=state.decoder?state.buffer.join(""):1===state.buffer.length?state.buffer.first():state.buffer.concat(state.length),state.buffer.clear()):ret=state.buffer.consume(n,state.decoder),ret)}function endReadable(stream){var state=stream._readableState;debug("endReadable",state.endEmitted),state.endEmitted||(state.ended=!0,process.nextTick(endReadableNT,state,stream))}function endReadableNT(state,stream){if(debug("endReadableNT",state.endEmitted,state.length),!state.endEmitted&&0===state.length&&(state.endEmitted=!0,stream.readable=!1,stream.emit("end"),state.autoDestroy)){var wState=stream._writableState;(!wState||wState.autoDestroy&&wState.finished)&&stream.destroy()}}function indexOf(xs,x){for(var i=0,l=xs.length;i<l;i++)if(xs[i]===x)return i;return -1}Object.defineProperty(Readable.prototype,"destroyed",{enumerable:!1,get:function get(){return void 0!==this._readableState&&this._readableState.destroyed},set:function set(value){this._readableState&&(this._readableState.destroyed=value)}}),Readable.prototype.destroy=destroyImpl.destroy,Readable.prototype._undestroy=destroyImpl.undestroy,Readable.prototype._destroy=function(err,cb){cb(err)},Readable.prototype.push=function(chunk,encoding){var skipChunkCheck,state=this._readableState;return state.objectMode?skipChunkCheck=!0:"string"==typeof chunk&&((encoding=encoding||state.defaultEncoding)!==state.encoding&&(chunk=Buffer.from(chunk,encoding),encoding=""),skipChunkCheck=!0),readableAddChunk(this,chunk,encoding,!1,skipChunkCheck)},Readable.prototype.unshift=function(chunk){return readableAddChunk(this,chunk,null,!0,!1)},Readable.prototype.isPaused=function(){return!1===this._readableState.flowing},Readable.prototype.setEncoding=function(enc){StringDecoder||(StringDecoder=require1("string_decoder/").StringDecoder);var decoder=new StringDecoder(enc);this._readableState.decoder=decoder,this._readableState.encoding=this._readableState.decoder.encoding;for(var p=this._readableState.buffer.head,content="";null!==p;)content+=decoder.write(p.data),p=p.next;return this._readableState.buffer.clear(),""!==content&&this._readableState.buffer.push(content),this._readableState.length=content.length,this},Readable.prototype.read=function(n){debug("read",n),n=parseInt(n,10);var ret,state=this._readableState,nOrig=n;if(0!==n&&(state.emittedReadable=!1),0===n&&state.needReadable&&((0!==state.highWaterMark?state.length>=state.highWaterMark:state.length>0)||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(0===(n=howMuchToRead(n,state))&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;return debug("need readable",doRead),(0===state.length||state.length-n<state.highWaterMark)&&debug("length less than watermark",doRead=!0),state.ended||state.reading?debug("reading or ended",doRead=!1):doRead&&(debug("do read"),state.reading=!0,state.sync=!0,0===state.length&&(state.needReadable=!0),this._read(state.highWaterMark),state.sync=!1,state.reading||(n=howMuchToRead(nOrig,state))),null===(ret=n>0?fromList(n,state):null)?(state.needReadable=state.length<=state.highWaterMark,n=0):(state.length-=n,state.awaitDrain=0),0===state.length&&(state.ended||(state.needReadable=!0),nOrig!==n&&state.ended&&endReadable(this)),null!==ret&&this.emit("data",ret),ret},Readable.prototype._read=function(n){errorOrDestroy(this,new ERR_METHOD_NOT_IMPLEMENTED("_read()"))},Readable.prototype.pipe=function(dest,pipeOpts){var src=this,state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest)}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var endFn=pipeOpts&&!1===pipeOpts.end||dest===process.stdout||dest===process.stderr?unpipe:onend;function onunpipe(readable,unpipeInfo){debug("onunpipe"),readable===src&&unpipeInfo&&!1===unpipeInfo.hasUnpiped&&(unpipeInfo.hasUnpiped=!0,cleanup())}function onend(){debug("onend"),dest.end()}state.endEmitted?process.nextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);var cleanedUp=!1;function cleanup(){debug("cleanup"),dest.removeListener("close",onclose),dest.removeListener("finish",onfinish),dest.removeListener("drain",ondrain),dest.removeListener("error",onerror),dest.removeListener("unpipe",onunpipe),src.removeListener("end",onend),src.removeListener("end",unpipe),src.removeListener("data",ondata),cleanedUp=!0,state.awaitDrain&&(!dest._writableState||dest._writableState.needDrain)&&ondrain()}function ondata(chunk){debug("ondata");var ret=dest.write(chunk);debug("dest.write",ret),!1===ret&&((1===state.pipesCount&&state.pipes===dest||state.pipesCount>1&&-1!==indexOf(state.pipes,dest))&&!cleanedUp&&(debug("false write response, pause",state.awaitDrain),state.awaitDrain++),src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EElistenerCount(dest,"error")&&errorOrDestroy(dest,er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}return src.on("data",ondata),prependListener(dest,"error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState,unpipeInfo={hasUnpiped:!1};if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes||(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this,unpipeInfo)),this;if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var i=0;i<len;i++)dests[i].emit("unpipe",this,{hasUnpiped:!1});return this}var index=indexOf(state.pipes,dest);return -1===index||(state.pipes.splice(index,1),state.pipesCount-=1,1===state.pipesCount&&(state.pipes=state.pipes[0]),dest.emit("unpipe",this,unpipeInfo)),this},Readable.prototype.on=function(ev,fn){var res=Stream.prototype.on.call(this,ev,fn),state=this._readableState;return"data"===ev?(state.readableListening=this.listenerCount("readable")>0,!1!==state.flowing&&this.resume()):"readable"!==ev||state.endEmitted||state.readableListening||(state.readableListening=state.needReadable=!0,state.flowing=!1,state.emittedReadable=!1,debug("on readable",state.length,state.reading),state.length?emitReadable(this):state.reading||process.nextTick(nReadingNextTick,this)),res},Readable.prototype.addListener=Readable.prototype.on,Readable.prototype.removeListener=function(ev,fn){var res=Stream.prototype.removeListener.call(this,ev,fn);return"readable"===ev&&process.nextTick(updateReadableListening,this),res},Readable.prototype.removeAllListeners=function(ev){var res=Stream.prototype.removeAllListeners.apply(this,arguments);return("readable"===ev||void 0===ev)&&process.nextTick(updateReadableListening,this),res},Readable.prototype.resume=function(){var state=this._readableState;return state.flowing||(debug("resume"),state.flowing=!state.readableListening,resume(this,state)),state.paused=!1,this},Readable.prototype.pause=function(){return debug("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(debug("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},Readable.prototype.wrap=function(stream){var _this=this,state=this._readableState,paused=!1;for(var i in stream.on("end",function(){if(debug("wrapped end"),state.decoder&&!state.ended){var chunk=state.decoder.end();chunk&&chunk.length&&_this.push(chunk)}_this.push(null)}),stream.on("data",function(chunk){debug("wrapped data"),state.decoder&&(chunk=state.decoder.write(chunk)),(!state.objectMode||null!=chunk)&&(state.objectMode||chunk&&chunk.length)&&(_this.push(chunk)||(paused=!0,stream.pause()))}),stream)void 0===this[i]&&"function"==typeof stream[i]&&(this[i]=function methodWrap(method){return function methodWrapReturnFunction(){return stream[method].apply(stream,arguments)}}(i));for(var n=0;n<kProxyEvents.length;n++)stream.on(kProxyEvents[n],this.emit.bind(this,kProxyEvents[n]));return this._read=function(n){debug("wrapped _read",n),paused&&(paused=!1,stream.resume())},this},"function"==typeof Symbol&&(Readable.prototype[Symbol.asyncIterator]=function(){return void 0===createReadableStreamAsyncIterator&&(createReadableStreamAsyncIterator=require1("./internal/streams/async_iterator")),createReadableStreamAsyncIterator(this)}),Object.defineProperty(Readable.prototype,"readableHighWaterMark",{enumerable:!1,get:function get(){return this._readableState.highWaterMark}}),Object.defineProperty(Readable.prototype,"readableBuffer",{enumerable:!1,get:function get(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(Readable.prototype,"readableFlowing",{enumerable:!1,get:function get(){return this._readableState.flowing},set:function set(state){this._readableState&&(this._readableState.flowing=state)}}),Readable._fromList=fromList,Object.defineProperty(Readable.prototype,"readableLength",{enumerable:!1,get:function get(){return this._readableState.length}}),"function"==typeof Symbol&&(Readable.from=function(iterable,opts){return void 0===from&&(from=require1("./internal/streams/from")),from(Readable,iterable,opts)})}).call(this)}).call(this,require1("_process"),void 0!==__webpack_require__.g?__webpack_require__.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../errors":156,"./_stream_duplex":157,"./internal/streams/async_iterator":162,"./internal/streams/buffer_list":163,"./internal/streams/destroy":164,"./internal/streams/from":166,"./internal/streams/state":168,"./internal/streams/stream":169,_process:152,buffer:47,events:80,inherits:85,"string_decoder/":207,util:29}],160:[function(require1,module,exports){"use strict";module.exports=Transform;var _require$codes=require1("../errors").codes,ERR_METHOD_NOT_IMPLEMENTED=_require$codes.ERR_METHOD_NOT_IMPLEMENTED,ERR_MULTIPLE_CALLBACK=_require$codes.ERR_MULTIPLE_CALLBACK,ERR_TRANSFORM_ALREADY_TRANSFORMING=_require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,ERR_TRANSFORM_WITH_LENGTH_0=_require$codes.ERR_TRANSFORM_WITH_LENGTH_0,Duplex=require1("./_stream_duplex");function afterTransform(er,data){var ts=this._transformState;ts.transforming=!1;var cb=ts.writecb;if(null===cb)return this.emit("error",new ERR_MULTIPLE_CALLBACK);ts.writechunk=null,ts.writecb=null,null!=data&&this.push(data),cb(er);var rs=this._readableState;rs.reading=!1,(rs.needReadable||rs.length<rs.highWaterMark)&&this._read(rs.highWaterMark)}function Transform(options){if(!(this instanceof Transform))return new Transform(options);Duplex.call(this,options),this._transformState={afterTransform:afterTransform.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,options&&("function"==typeof options.transform&&(this._transform=options.transform),"function"==typeof options.flush&&(this._flush=options.flush)),this.on("prefinish",prefinish)}function prefinish(){var _this=this;"function"!=typeof this._flush||this._readableState.destroyed?done(this,null,null):this._flush(function(er,data){done(_this,er,data)})}function done(stream,er,data){if(er)return stream.emit("error",er);if(null!=data&&stream.push(data),stream._writableState.length)throw new ERR_TRANSFORM_WITH_LENGTH_0;if(stream._transformState.transforming)throw new ERR_TRANSFORM_ALREADY_TRANSFORMING;return stream.push(null)}require1("inherits")(Transform,Duplex),Transform.prototype.push=function(chunk,encoding){return this._transformState.needTransform=!1,Duplex.prototype.push.call(this,chunk,encoding)},Transform.prototype._transform=function(chunk,encoding,cb){cb(new ERR_METHOD_NOT_IMPLEMENTED("_transform()"))},Transform.prototype._write=function(chunk,encoding,cb){var ts=this._transformState;if(ts.writecb=cb,ts.writechunk=chunk,ts.writeencoding=encoding,!ts.transforming){var rs=this._readableState;(ts.needTransform||rs.needReadable||rs.length<rs.highWaterMark)&&this._read(rs.highWaterMark)}},Transform.prototype._read=function(n){var ts=this._transformState;null===ts.writechunk||ts.transforming?ts.needTransform=!0:(ts.transforming=!0,this._transform(ts.writechunk,ts.writeencoding,ts.afterTransform))},Transform.prototype._destroy=function(err,cb){Duplex.prototype._destroy.call(this,err,function(err2){cb(err2)})}},{"../errors":156,"./_stream_duplex":157,inherits:85}],161:[function(require1,module,exports){(function(process,global){(function(){"use strict";function CorkedRequest(state){var _this=this;this.next=null,this.entry=null,this.finish=function(){onCorkedFinish(_this,state)}}module.exports=Writable,Writable.WritableState=WritableState;var Duplex,realHasInstance,internalUtil={deprecate:require1("util-deprecate")},Stream=require1("./internal/streams/stream"),Buffer=require1("buffer").Buffer,OurUint8Array=global.Uint8Array||function(){};function _uint8ArrayToBuffer(chunk){return Buffer.from(chunk)}function _isUint8Array(obj){return Buffer.isBuffer(obj)||obj instanceof OurUint8Array}var destroyImpl=require1("./internal/streams/destroy"),getHighWaterMark=require1("./internal/streams/state").getHighWaterMark,_require$codes=require1("../errors").codes,ERR_INVALID_ARG_TYPE=_require$codes.ERR_INVALID_ARG_TYPE,ERR_METHOD_NOT_IMPLEMENTED=_require$codes.ERR_METHOD_NOT_IMPLEMENTED,ERR_MULTIPLE_CALLBACK=_require$codes.ERR_MULTIPLE_CALLBACK,ERR_STREAM_CANNOT_PIPE=_require$codes.ERR_STREAM_CANNOT_PIPE,ERR_STREAM_DESTROYED=_require$codes.ERR_STREAM_DESTROYED,ERR_STREAM_NULL_VALUES=_require$codes.ERR_STREAM_NULL_VALUES,ERR_STREAM_WRITE_AFTER_END=_require$codes.ERR_STREAM_WRITE_AFTER_END,ERR_UNKNOWN_ENCODING=_require$codes.ERR_UNKNOWN_ENCODING,errorOrDestroy=destroyImpl.errorOrDestroy;function nop(){}function WritableState(options,stream,isDuplex){Duplex=Duplex||require1("./_stream_duplex"),options=options||{},"boolean"!=typeof isDuplex&&(isDuplex=stream instanceof Duplex),this.objectMode=!!options.objectMode,isDuplex&&(this.objectMode=this.objectMode||!!options.writableObjectMode),this.highWaterMark=getHighWaterMark(this,options,"writableHighWaterMark",isDuplex),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var noDecode=!1===options.decodeStrings;this.decodeStrings=!noDecode,this.defaultEncoding=options.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(er){onwrite(stream,er)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==options.emitClose,this.autoDestroy=!!options.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new CorkedRequest(this)}function Writable(options){var isDuplex=this instanceof(Duplex=Duplex||require1("./_stream_duplex"));if(!isDuplex&&!realHasInstance.call(Writable,this))return new Writable(options);this._writableState=new WritableState(options,this,isDuplex),this.writable=!0,options&&("function"==typeof options.write&&(this._write=options.write),"function"==typeof options.writev&&(this._writev=options.writev),"function"==typeof options.destroy&&(this._destroy=options.destroy),"function"==typeof options.final&&(this._final=options.final)),Stream.call(this)}function writeAfterEnd(stream,cb){var er=new ERR_STREAM_WRITE_AFTER_END;errorOrDestroy(stream,er),process.nextTick(cb,er)}function validChunk(stream,state,chunk,cb){var er;return null===chunk?er=new ERR_STREAM_NULL_VALUES:"string"==typeof chunk||state.objectMode||(er=new ERR_INVALID_ARG_TYPE("chunk",["string","Buffer"],chunk)),!er||(errorOrDestroy(stream,er),process.nextTick(cb,er),!1)}function decodeChunk(state,chunk,encoding){return state.objectMode||!1===state.decodeStrings||"string"!=typeof chunk||(chunk=Buffer.from(chunk,encoding)),chunk}function writeOrBuffer(stream,state,isBuf,chunk,encoding,cb){if(!isBuf){var newChunk=decodeChunk(state,chunk,encoding);chunk!==newChunk&&(isBuf=!0,encoding="buffer",chunk=newChunk)}var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length<state.highWaterMark;if(ret||(state.needDrain=!0),state.writing||state.corked){var last=state.lastBufferedRequest;state.lastBufferedRequest={chunk:chunk,encoding:encoding,isBuf:isBuf,callback:cb,next:null},last?last.next=state.lastBufferedRequest:state.bufferedRequest=state.lastBufferedRequest,state.bufferedRequestCount+=1}else doWrite(stream,state,!1,len,chunk,encoding,cb);return ret}function doWrite(stream,state,writev,len,chunk,encoding,cb){state.writelen=len,state.writecb=cb,state.writing=!0,state.sync=!0,state.destroyed?state.onwrite(new ERR_STREAM_DESTROYED("write")):writev?stream._writev(chunk,state.onwrite):stream._write(chunk,encoding,state.onwrite),state.sync=!1}function onwriteError(stream,state,sync,er,cb){--state.pendingcb,sync?(process.nextTick(cb,er),process.nextTick(finishMaybe,stream,state),stream._writableState.errorEmitted=!0,errorOrDestroy(stream,er)):(cb(er),stream._writableState.errorEmitted=!0,errorOrDestroy(stream,er),finishMaybe(stream,state))}function onwriteStateUpdate(state){state.writing=!1,state.writecb=null,state.length-=state.writelen,state.writelen=0}function onwrite(stream,er){var state=stream._writableState,sync=state.sync,cb=state.writecb;if("function"!=typeof cb)throw new ERR_MULTIPLE_CALLBACK;if(onwriteStateUpdate(state),er)onwriteError(stream,state,sync,er,cb);else{var finished=needFinish(state)||stream.destroyed;finished||state.corked||state.bufferProcessing||!state.bufferedRequest||clearBuffer(stream,state),sync?process.nextTick(afterWrite,stream,state,finished,cb):afterWrite(stream,state,finished,cb)}}function afterWrite(stream,state,finished,cb){finished||onwriteDrain(stream,state),state.pendingcb--,cb(),finishMaybe(stream,state)}function onwriteDrain(stream,state){0===state.length&&state.needDrain&&(state.needDrain=!1,stream.emit("drain"))}function clearBuffer(stream,state){state.bufferProcessing=!0;var entry=state.bufferedRequest;if(stream._writev&&entry&&entry.next){var buffer=Array(state.bufferedRequestCount),holder=state.corkedRequestsFree;holder.entry=entry;for(var count=0,allBuffers=!0;entry;)buffer[count]=entry,entry.isBuf||(allBuffers=!1),entry=entry.next,count+=1;buffer.allBuffers=allBuffers,doWrite(stream,state,!0,state.length,buffer,"",holder.finish),state.pendingcb++,state.lastBufferedRequest=null,holder.next?(state.corkedRequestsFree=holder.next,holder.next=null):state.corkedRequestsFree=new CorkedRequest(state),state.bufferedRequestCount=0}else{for(;entry;){var chunk=entry.chunk,encoding=entry.encoding,cb=entry.callback,len=state.objectMode?1:chunk.length;if(doWrite(stream,state,!1,len,chunk,encoding,cb),entry=entry.next,state.bufferedRequestCount--,state.writing)break}null===entry&&(state.lastBufferedRequest=null)}state.bufferedRequest=entry,state.bufferProcessing=!1}function needFinish(state){return state.ending&&0===state.length&&null===state.bufferedRequest&&!state.finished&&!state.writing}function callFinal(stream,state){stream._final(function(err){state.pendingcb--,err&&errorOrDestroy(stream,err),state.prefinished=!0,stream.emit("prefinish"),finishMaybe(stream,state)})}function prefinish(stream,state){state.prefinished||state.finalCalled||("function"!=typeof stream._final||state.destroyed?(state.prefinished=!0,stream.emit("prefinish")):(state.pendingcb++,state.finalCalled=!0,process.nextTick(callFinal,stream,state)))}function finishMaybe(stream,state){var need=needFinish(state);if(need&&(prefinish(stream,state),0===state.pendingcb&&(state.finished=!0,stream.emit("finish"),state.autoDestroy))){var rState=stream._readableState;(!rState||rState.autoDestroy&&rState.endEmitted)&&stream.destroy()}return need}function endWritable(stream,state,cb){state.ending=!0,finishMaybe(stream,state),cb&&(state.finished?process.nextTick(cb):stream.once("finish",cb)),state.ended=!0,stream.writable=!1}function onCorkedFinish(corkReq,state,err){var entry=corkReq.entry;for(corkReq.entry=null;entry;){var cb=entry.callback;state.pendingcb--,cb(err),entry=entry.next}state.corkedRequestsFree.next=corkReq}require1("inherits")(Writable,Stream),WritableState.prototype.getBuffer=function getBuffer(){for(var current=this.bufferedRequest,out=[];current;)out.push(current),current=current.next;return out},function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate(function writableStateBufferGetter(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(_){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(realHasInstance=Function.prototype[Symbol.hasInstance],Object.defineProperty(Writable,Symbol.hasInstance,{value:function value(object){return!!realHasInstance.call(this,object)||this===Writable&&object&&object._writableState instanceof WritableState}})):realHasInstance=function realHasInstance(object){return object instanceof this},Writable.prototype.pipe=function(){errorOrDestroy(this,new ERR_STREAM_CANNOT_PIPE)},Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState,ret=!1,isBuf=!state.objectMode&&_isUint8Array(chunk);return isBuf&&!Buffer.isBuffer(chunk)&&(chunk=_uint8ArrayToBuffer(chunk)),"function"==typeof encoding&&(cb=encoding,encoding=null),isBuf?encoding="buffer":encoding||(encoding=state.defaultEncoding),"function"!=typeof cb&&(cb=nop),state.ending?writeAfterEnd(this,cb):(isBuf||validChunk(this,state,chunk,cb))&&(state.pendingcb++,ret=writeOrBuffer(this,state,isBuf,chunk,encoding,cb)),ret},Writable.prototype.cork=function(){this._writableState.corked++},Writable.prototype.uncork=function(){var state=this._writableState;!state.corked||(state.corked--,state.writing||state.corked||state.bufferProcessing||!state.bufferedRequest||clearBuffer(this,state))},Writable.prototype.setDefaultEncoding=function setDefaultEncoding(encoding){if("string"==typeof encoding&&(encoding=encoding.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())>-1))throw new ERR_UNKNOWN_ENCODING(encoding);return this._writableState.defaultEncoding=encoding,this},Object.defineProperty(Writable.prototype,"writableBuffer",{enumerable:!1,get:function get(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(Writable.prototype,"writableHighWaterMark",{enumerable:!1,get:function get(){return this._writableState.highWaterMark}}),Writable.prototype._write=function(chunk,encoding,cb){cb(new ERR_METHOD_NOT_IMPLEMENTED("_write()"))},Writable.prototype._writev=null,Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;return"function"==typeof chunk?(cb=chunk,chunk=null,encoding=null):"function"==typeof encoding&&(cb=encoding,encoding=null),null!=chunk&&this.write(chunk,encoding),state.corked&&(state.corked=1,this.uncork()),state.ending||endWritable(this,state,cb),this},Object.defineProperty(Writable.prototype,"writableLength",{enumerable:!1,get:function get(){return this._writableState.length}}),Object.defineProperty(Writable.prototype,"destroyed",{enumerable:!1,get:function get(){return void 0!==this._writableState&&this._writableState.destroyed},set:function set(value){this._writableState&&(this._writableState.destroyed=value)}}),Writable.prototype.destroy=destroyImpl.destroy,Writable.prototype._undestroy=destroyImpl.undestroy,Writable.prototype._destroy=function(err,cb){cb(err)}}).call(this)}).call(this,require1("_process"),void 0!==__webpack_require__.g?__webpack_require__.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../errors":156,"./_stream_duplex":157,"./internal/streams/destroy":164,"./internal/streams/state":168,"./internal/streams/stream":169,_process:152,buffer:47,inherits:85,"util-deprecate":214}],162:[function(require1,module,exports){(function(process){(function(){"use strict";function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}var _Object$setPrototypeO,finished=require1("./end-of-stream"),kLastResolve=Symbol("lastResolve"),kLastReject=Symbol("lastReject"),kError=Symbol("error"),kEnded=Symbol("ended"),kLastPromise=Symbol("lastPromise"),kHandlePromise=Symbol("handlePromise"),kStream=Symbol("stream");function createIterResult(value,done){return{value:value,done:done}}function readAndResolve(iter){var resolve=iter[kLastResolve];if(null!==resolve){var data=iter[kStream].read();null!==data&&(iter[kLastPromise]=null,iter[kLastResolve]=null,iter[kLastReject]=null,resolve(createIterResult(data,!1)))}}function onReadable(iter){process.nextTick(readAndResolve,iter)}function wrapForNext(lastPromise,iter){return function(resolve,reject){lastPromise.then(function(){if(iter[kEnded]){resolve(createIterResult(void 0,!0));return}iter[kHandlePromise](resolve,reject)},reject)}}var AsyncIteratorPrototype=Object.getPrototypeOf(function(){}),ReadableStreamAsyncIteratorPrototype=Object.setPrototypeOf((_defineProperty(_Object$setPrototypeO={get stream(){return this[kStream]},next:function next(){var promise,_this=this,error=this[kError];if(null!==error)return Promise.reject(error);if(this[kEnded])return Promise.resolve(createIterResult(void 0,!0));if(this[kStream].destroyed)return new Promise(function(resolve,reject){process.nextTick(function(){_this[kError]?reject(_this[kError]):resolve(createIterResult(void 0,!0))})});var lastPromise=this[kLastPromise];if(lastPromise)promise=new Promise(wrapForNext(lastPromise,this));else{var data=this[kStream].read();if(null!==data)return Promise.resolve(createIterResult(data,!1));promise=new Promise(this[kHandlePromise])}return this[kLastPromise]=promise,promise}},Symbol.asyncIterator,function(){return this}),_defineProperty(_Object$setPrototypeO,"return",function _return(){var _this2=this;return new Promise(function(resolve,reject){_this2[kStream].destroy(null,function(err){if(err){reject(err);return}resolve(createIterResult(void 0,!0))})})}),_Object$setPrototypeO),AsyncIteratorPrototype);module.exports=function(stream){var _Object$create,iterator=Object.create(ReadableStreamAsyncIteratorPrototype,(_defineProperty(_Object$create={},kStream,{value:stream,writable:!0}),_defineProperty(_Object$create,kLastResolve,{value:null,writable:!0}),_defineProperty(_Object$create,kLastReject,{value:null,writable:!0}),_defineProperty(_Object$create,kError,{value:null,writable:!0}),_defineProperty(_Object$create,kEnded,{value:stream._readableState.endEmitted,writable:!0}),_defineProperty(_Object$create,kHandlePromise,{value:function value(resolve,reject){var data=iterator[kStream].read();data?(iterator[kLastPromise]=null,iterator[kLastResolve]=null,iterator[kLastReject]=null,resolve(createIterResult(data,!1))):(iterator[kLastResolve]=resolve,iterator[kLastReject]=reject)},writable:!0}),_Object$create));return iterator[kLastPromise]=null,finished(stream,function(err){if(err&&"ERR_STREAM_PREMATURE_CLOSE"!==err.code){var reject=iterator[kLastReject];null!==reject&&(iterator[kLastPromise]=null,iterator[kLastResolve]=null,iterator[kLastReject]=null,reject(err)),iterator[kError]=err;return}var resolve=iterator[kLastResolve];null!==resolve&&(iterator[kLastPromise]=null,iterator[kLastResolve]=null,iterator[kLastReject]=null,resolve(createIterResult(void 0,!0))),iterator[kEnded]=!0}),stream.on("readable",onReadable.bind(null,iterator)),iterator}}).call(this)}).call(this,require1("_process"))},{"./end-of-stream":165,_process:152}],163:[function(require1,module,exports){"use strict";function ownKeys(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);enumerableOnly&&(symbols=symbols.filter(function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable})),keys.push.apply(keys,symbols)}return keys}function _objectSpread(target){for(var i=1;i<arguments.length;i++){var source=null!=arguments[i]?arguments[i]:{};i%2?ownKeys(Object(source),!0).forEach(function(key){_defineProperty(target,key,source[key])}):Object.getOwnPropertyDescriptors?Object.defineProperties(target,Object.getOwnPropertyDescriptors(source)):ownKeys(Object(source)).forEach(function(key){Object.defineProperty(target,key,Object.getOwnPropertyDescriptor(source,key))})}return target}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw TypeError("Cannot call a class as a function")}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){return protoProps&&_defineProperties(Constructor.prototype,protoProps),staticProps&&_defineProperties(Constructor,staticProps),Constructor}var Buffer=require1("buffer").Buffer,inspect=require1("util").inspect,custom=inspect&&inspect.custom||"inspect";function copyBuffer(src,target,offset){Buffer.prototype.copy.call(src,target,offset)}module.exports=function(){function BufferList(){_classCallCheck(this,BufferList),this.head=null,this.tail=null,this.length=0}return _createClass(BufferList,[{key:"push",value:function push(v){var entry={data:v,next:null};this.length>0?this.tail.next=entry:this.head=entry,this.tail=entry,++this.length}},{key:"unshift",value:function unshift(v){var entry={data:v,next:this.head};0===this.length&&(this.tail=entry),this.head=entry,++this.length}},{key:"shift",value:function shift(){if(0!==this.length){var ret=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,ret}}},{key:"clear",value:function clear(){this.head=this.tail=null,this.length=0}},{key:"join",value:function join(s){if(0===this.length)return"";for(var p=this.head,ret=""+p.data;p=p.next;)ret+=s+p.data;return ret}},{key:"concat",value:function concat(n){if(0===this.length)return Buffer.alloc(0);for(var ret=Buffer.allocUnsafe(n>>>0),p=this.head,i=0;p;)copyBuffer(p.data,ret,i),i+=p.data.length,p=p.next;return ret}},{key:"consume",value:function consume(n,hasStrings){var ret;return n<this.head.data.length?(ret=this.head.data.slice(0,n),this.head.data=this.head.data.slice(n)):ret=n===this.head.data.length?this.shift():hasStrings?this._getString(n):this._getBuffer(n),ret}},{key:"first",value:function first(){return this.head.data}},{key:"_getString",value:function _getString(n){var p=this.head,c=1,ret=p.data;for(n-=ret.length;p=p.next;){var str=p.data,nb=n>str.length?str.length:n;if(nb===str.length?ret+=str:ret+=str.slice(0,n),0==(n-=nb)){nb===str.length?(++c,p.next?this.head=p.next:this.head=this.tail=null):(this.head=p,p.data=str.slice(nb));break}++c}return this.length-=c,ret}},{key:"_getBuffer",value:function _getBuffer(n){var ret=Buffer.allocUnsafe(n),p=this.head,c=1;for(p.data.copy(ret),n-=p.data.length;p=p.next;){var buf=p.data,nb=n>buf.length?buf.length:n;if(buf.copy(ret,ret.length-n,0,nb),0==(n-=nb)){nb===buf.length?(++c,p.next?this.head=p.next:this.head=this.tail=null):(this.head=p,p.data=buf.slice(nb));break}++c}return this.length-=c,ret}},{key:custom,value:function value(_,options){return inspect(this,_objectSpread({},options,{depth:0,customInspect:!1}))}}]),BufferList}()},{buffer:47,util:29}],164:[function(require1,module,exports){(function(process){(function(){"use strict";function destroy(err,cb){var _this=this,readableDestroyed=this._readableState&&this._readableState.destroyed,writableDestroyed=this._writableState&&this._writableState.destroyed;return readableDestroyed||writableDestroyed?cb?cb(err):err&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process.nextTick(emitErrorNT,this,err)):process.nextTick(emitErrorNT,this,err)):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(err||null,function(err){!cb&&err?_this._writableState?_this._writableState.errorEmitted?process.nextTick(emitCloseNT,_this):(_this._writableState.errorEmitted=!0,process.nextTick(emitErrorAndCloseNT,_this,err)):process.nextTick(emitErrorAndCloseNT,_this,err):cb?(process.nextTick(emitCloseNT,_this),cb(err)):process.nextTick(emitCloseNT,_this)})),this}function emitErrorAndCloseNT(self1,err){emitErrorNT(self1,err),emitCloseNT(self1)}function emitCloseNT(self1){(!self1._writableState||self1._writableState.emitClose)&&(!self1._readableState||self1._readableState.emitClose)&&self1.emit("close")}function undestroy(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function emitErrorNT(self1,err){self1.emit("error",err)}function errorOrDestroy(stream,err){var rState=stream._readableState,wState=stream._writableState;rState&&rState.autoDestroy||wState&&wState.autoDestroy?stream.destroy(err):stream.emit("error",err)}module.exports={destroy:destroy,undestroy:undestroy,errorOrDestroy:errorOrDestroy}}).call(this)}).call(this,require1("_process"))},{_process:152}],165:[function(require1,module,exports){"use strict";var ERR_STREAM_PREMATURE_CLOSE=require1("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;function once(callback){var called=!1;return function(){if(!called){called=!0;for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];callback.apply(this,args)}}}function noop(){}function isRequest(stream){return stream.setHeader&&"function"==typeof stream.abort}function eos(stream,opts,callback){if("function"==typeof opts)return eos(stream,null,opts);opts||(opts={}),callback=once(callback||noop);var readable=opts.readable||!1!==opts.readable&&stream.readable,writable=opts.writable||!1!==opts.writable&&stream.writable,onlegacyfinish=function(){stream.writable||onfinish()},writableEnded=stream._writableState&&stream._writableState.finished,onfinish=function(){writable=!1,writableEnded=!0,readable||callback.call(stream)},readableEnded=stream._readableState&&stream._readableState.endEmitted,onend=function(){readable=!1,readableEnded=!0,writable||callback.call(stream)},onerror=function(err){callback.call(stream,err)},onclose=function(){var err;return readable&&!readableEnded?(stream._readableState&&stream._readableState.ended||(err=new ERR_STREAM_PREMATURE_CLOSE),callback.call(stream,err)):writable&&!writableEnded?(stream._writableState&&stream._writableState.ended||(err=new ERR_STREAM_PREMATURE_CLOSE),callback.call(stream,err)):void 0},onrequest=function(){stream.req.on("finish",onfinish)};return isRequest(stream)?(stream.on("complete",onfinish),stream.on("abort",onclose),stream.req?onrequest():stream.on("request",onrequest)):writable&&!stream._writableState&&(stream.on("end",onlegacyfinish),stream.on("close",onlegacyfinish)),stream.on("end",onend),stream.on("finish",onfinish),!1!==opts.error&&stream.on("error",onerror),stream.on("close",onclose),function(){stream.removeListener("complete",onfinish),stream.removeListener("abort",onclose),stream.removeListener("request",onrequest),stream.req&&stream.req.removeListener("finish",onfinish),stream.removeListener("end",onlegacyfinish),stream.removeListener("close",onlegacyfinish),stream.removeListener("finish",onfinish),stream.removeListener("end",onend),stream.removeListener("error",onerror),stream.removeListener("close",onclose)}}module.exports=eos},{"../../../errors":156}],166:[function(require1,module,exports){module.exports=function(){throw Error("Readable.from is not available in the browser")}},{}],167:[function(require1,module,exports){"use strict";function once(callback){var called=!1;return function(){called||(called=!0,callback.apply(void 0,arguments))}}var eos,_require$codes=require1("../../../errors").codes,ERR_MISSING_ARGS=_require$codes.ERR_MISSING_ARGS,ERR_STREAM_DESTROYED=_require$codes.ERR_STREAM_DESTROYED;function noop(err){if(err)throw err}function isRequest(stream){return stream.setHeader&&"function"==typeof stream.abort}function destroyer(stream,reading,writing,callback){callback=once(callback);var closed=!1;stream.on("close",function(){closed=!0}),void 0===eos&&(eos=require1("./end-of-stream")),eos(stream,{readable:reading,writable:writing},function(err){if(err)return callback(err);closed=!0,callback()});var destroyed=!1;return function(err){if(!closed&&!destroyed){if(destroyed=!0,isRequest(stream))return stream.abort();if("function"==typeof stream.destroy)return stream.destroy();callback(err||new ERR_STREAM_DESTROYED("pipe"))}}}function call(fn){fn()}function pipe(from,to){return from.pipe(to)}function popCallback(streams){return streams.length&&"function"==typeof streams[streams.length-1]?streams.pop():noop}function pipeline(){for(var error,_len=arguments.length,streams=Array(_len),_key=0;_key<_len;_key++)streams[_key]=arguments[_key];var callback=popCallback(streams);if(Array.isArray(streams[0])&&(streams=streams[0]),streams.length<2)throw new ERR_MISSING_ARGS("streams");var destroys=streams.map(function(stream,i){var reading=i<streams.length-1;return destroyer(stream,reading,i>0,function(err){error||(error=err),err&&destroys.forEach(call),reading||(destroys.forEach(call),callback(error))})});return streams.reduce(pipe)}module.exports=pipeline},{"../../../errors":156,"./end-of-stream":165}],168:[function(require1,module,exports){"use strict";var ERR_INVALID_OPT_VALUE=require1("../../../errors").codes.ERR_INVALID_OPT_VALUE;function highWaterMarkFrom(options,isDuplex,duplexKey){return null!=options.highWaterMark?options.highWaterMark:isDuplex?options[duplexKey]:null}function getHighWaterMark(state,options,duplexKey,isDuplex){var hwm=highWaterMarkFrom(options,isDuplex,duplexKey);if(null!=hwm){if(!(isFinite(hwm)&&Math.floor(hwm)===hwm)||hwm<0)throw new ERR_INVALID_OPT_VALUE(isDuplex?duplexKey:"highWaterMark",hwm);return Math.floor(hwm)}return state.objectMode?16:16384}module.exports={getHighWaterMark:getHighWaterMark}},{"../../../errors":156}],169:[function(require1,module,exports){arguments[4][41][0].apply(exports,arguments)},{dup:41,events:80}],170:[function(require1,module,exports){(exports=module.exports=require1("./lib/_stream_readable.js")).Stream=exports,exports.Readable=exports,exports.Writable=require1("./lib/_stream_writable.js"),exports.Duplex=require1("./lib/_stream_duplex.js"),exports.Transform=require1("./lib/_stream_transform.js"),exports.PassThrough=require1("./lib/_stream_passthrough.js"),exports.finished=require1("./lib/internal/streams/end-of-stream.js"),exports.pipeline=require1("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":157,"./lib/_stream_passthrough.js":158,"./lib/_stream_readable.js":159,"./lib/_stream_transform.js":160,"./lib/_stream_writable.js":161,"./lib/internal/streams/end-of-stream.js":165,"./lib/internal/streams/pipeline.js":167}],171:[function(require1,module,exports){var EventEmitter=require1("events").EventEmitter,backoff=require1("backoff"),noop=function(){};module.exports=function(createConnection){return function(opts,onConnect){onConnect="function"==typeof opts?opts:onConnect,opts="object"==typeof opts?opts:{initialDelay:1e3,maxDelay:3e4},onConnect||(onConnect=opts.onConnect);var args,emitter=opts.emitter||new EventEmitter;emitter.connected=!1,emitter.reconnect=!0,onConnect&&emitter.on("connect",onConnect);var backoffMethod=(backoff[opts.type]||backoff.fibonacci)(opts);backoffMethod.on("backoff",function(n,d){emitter.emit("backoff",n,d)});var cleanup=noop;function attempt(n,delay){if(emitter.reconnect){cleanup(),emitter.emit("reconnect",n,delay);var con=createConnection.apply(null,args);con!==emitter._connection&&emitter.emit("connection",con),emitter._connection=con,cleanup=onCleanup,con.on("error",onDisconnect).on("close",onDisconnect).on("end",onDisconnect),opts.immediate||"Request"==con.constructor.name?(emitter.connected=!0,emitter.emit("connect",con),con.once("data",function(){backoffMethod.reset()})):con.on("connect",connect)}function onCleanup(err){cleanup=noop,con.removeListener("connect",connect),con.removeListener("error",onDisconnect),con.removeListener("close",onDisconnect),con.removeListener("end",onDisconnect),"Request"==con.constructor.name&&con.on("error",noop)}function onDisconnect(err){if(emitter.connected=!1,onCleanup(err),emitter.emit("disconnect",err),emitter.reconnect)try{backoffMethod.backoff()}catch(_){}}function connect(){backoffMethod.reset(),emitter.connected=!0,onConnect&&con.removeListener("connect",onConnect),emitter.emit("connect",con)}}return backoffMethod.on("ready",attempt),emitter.connect=emitter.listen=function(){return this.reconnect=!0,backoffMethod.reset(),args=[].slice.call(arguments),attempt(0,0),emitter},emitter.end=emitter.disconnect=function(){return emitter.reconnect=!1,emitter._connection&&emitter._connection.end(),emitter.emit("disconnect"),emitter},emitter}}},{backoff:21,events:80}],172:[function(require1,module,exports){"use strict";var SDPUtils=require1("sdp");function fixStatsType(stat){return({inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"})[stat.type]||stat.type}function writeMediaSection(transceiver,caps,type,stream,dtlsRole){var sdp=SDPUtils.writeRtpDescription(transceiver.kind,caps);if(sdp+=SDPUtils.writeIceParameters(transceiver.iceGatherer.getLocalParameters())+SDPUtils.writeDtlsParameters(transceiver.dtlsTransport.getLocalParameters(),"offer"===type?"actpass":dtlsRole||"active")+"a=mid:"+transceiver.mid+"\r\n",transceiver.rtpSender&&transceiver.rtpReceiver?sdp+="a=sendrecv\r\n":transceiver.rtpSender?sdp+="a=sendonly\r\n":transceiver.rtpReceiver?sdp+="a=recvonly\r\n":sdp+="a=inactive\r\n",transceiver.rtpSender){var trackId=transceiver.rtpSender._initialTrackId||transceiver.rtpSender.track.id;transceiver.rtpSender._initialTrackId=trackId;var msid="msid:"+(stream?stream.id:"-")+" "+trackId+"\r\n";sdp+="a="+msid+("a=ssrc:"+transceiver.sendEncodingParameters[0].ssrc)+" "+msid,transceiver.sendEncodingParameters[0].rtx&&(sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].rtx.ssrc+" "+msid+("a=ssrc-group:FID "+transceiver.sendEncodingParameters[0].ssrc+" ")+transceiver.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].ssrc+" cname:"+SDPUtils.localCName+"\r\n",transceiver.rtpSender&&transceiver.sendEncodingParameters[0].rtx&&(sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].rtx.ssrc+" cname:"+SDPUtils.localCName+"\r\n"),sdp}function filterIceServers(iceServers,edgeVersion){var hasTurn=!1;return(iceServers=JSON.parse(JSON.stringify(iceServers))).filter(function(server){if(server&&(server.urls||server.url)){var urls=server.urls||server.url;server.url&&!server.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var isString="string"==typeof urls;return isString&&(urls=[urls]),urls=urls.filter(function(url){return 0!==url.indexOf("turn:")||-1===url.indexOf("transport=udp")||-1!==url.indexOf("turn:[")||hasTurn?0===url.indexOf("stun:")&&edgeVersion>=14393&&-1===url.indexOf("?transport=udp"):(hasTurn=!0,!0)}),delete server.url,server.urls=isString?urls[0]:urls,!!urls.length}})}function getCommonCapabilities(localCapabilities,remoteCapabilities){var commonCapabilities={codecs:[],headerExtensions:[],fecMechanisms:[]},findCodecByPayloadType=function(pt,codecs){pt=parseInt(pt,10);for(var i=0;i<codecs.length;i++)if(codecs[i].payloadType===pt||codecs[i].preferredPayloadType===pt)return codecs[i]},rtxCapabilityMatches=function(lRtx,rRtx,lCodecs,rCodecs){var lCodec=findCodecByPayloadType(lRtx.parameters.apt,lCodecs),rCodec=findCodecByPayloadType(rRtx.parameters.apt,rCodecs);return lCodec&&rCodec&&lCodec.name.toLowerCase()===rCodec.name.toLowerCase()};return localCapabilities.codecs.forEach(function(lCodec){for(var i=0;i<remoteCapabilities.codecs.length;i++){var rCodec=remoteCapabilities.codecs[i];if(lCodec.name.toLowerCase()===rCodec.name.toLowerCase()&&lCodec.clockRate===rCodec.clockRate){if("rtx"===lCodec.name.toLowerCase()&&lCodec.parameters&&rCodec.parameters.apt&&!rtxCapabilityMatches(lCodec,rCodec,localCapabilities.codecs,remoteCapabilities.codecs))continue;(rCodec=JSON.parse(JSON.stringify(rCodec))).numChannels=Math.min(lCodec.numChannels,rCodec.numChannels),commonCapabilities.codecs.push(rCodec),rCodec.rtcpFeedback=rCodec.rtcpFeedback.filter(function(fb){for(var j=0;j<lCodec.rtcpFeedback.length;j++)if(lCodec.rtcpFeedback[j].type===fb.type&&lCodec.rtcpFeedback[j].parameter===fb.parameter)return!0;return!1});break}}}),localCapabilities.headerExtensions.forEach(function(lHeaderExtension){for(var i=0;i<remoteCapabilities.headerExtensions.length;i++){var rHeaderExtension=remoteCapabilities.headerExtensions[i];if(lHeaderExtension.uri===rHeaderExtension.uri){commonCapabilities.headerExtensions.push(rHeaderExtension);break}}}),commonCapabilities}function isActionAllowedInSignalingState(action,type,signalingState){return -1!==({offer:{setLocalDescription:["stable","have-local-offer"],setRemoteDescription:["stable","have-remote-offer"]},answer:{setLocalDescription:["have-remote-offer","have-local-pranswer"],setRemoteDescription:["have-local-offer","have-remote-pranswer"]}})[type][action].indexOf(signalingState)}function maybeAddCandidate(iceTransport,candidate){var alreadyAdded=iceTransport.getRemoteCandidates().find(function(remoteCandidate){return candidate.foundation===remoteCandidate.foundation&&candidate.ip===remoteCandidate.ip&&candidate.port===remoteCandidate.port&&candidate.priority===remoteCandidate.priority&&candidate.protocol===remoteCandidate.protocol&&candidate.type===remoteCandidate.type});return alreadyAdded||iceTransport.addRemoteCandidate(candidate),!alreadyAdded}function makeError(name,description){var e=Error(description);return e.name=name,e.code=({NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0})[name],e}module.exports=function(window1,edgeVersion){function addTrackToStreamAndFireEvent(track,stream){stream.addTrack(track),stream.dispatchEvent(new window1.MediaStreamTrackEvent("addtrack",{track:track}))}function removeTrackFromStreamAndFireEvent(track,stream){stream.removeTrack(track),stream.dispatchEvent(new window1.MediaStreamTrackEvent("removetrack",{track:track}))}function fireAddTrack(pc,track,receiver,streams){var trackEvent=new Event("track");trackEvent.track=track,trackEvent.receiver=receiver,trackEvent.transceiver={receiver:receiver},trackEvent.streams=streams,window1.setTimeout(function(){pc._dispatchEvent("track",trackEvent)})}var RTCPeerConnection=function(config){var pc=this,_eventTarget=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach(function(method){pc[method]=_eventTarget[method].bind(_eventTarget)}),this.canTrickleIceCandidates=null,this.needNegotiation=!1,this.localStreams=[],this.remoteStreams=[],this._localDescription=null,this._remoteDescription=null,this.signalingState="stable",this.iceConnectionState="new",this.connectionState="new",this.iceGatheringState="new",config=JSON.parse(JSON.stringify(config||{})),this.usingBundle="max-bundle"===config.bundlePolicy,"negotiate"===config.rtcpMuxPolicy)throw makeError("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(config.rtcpMuxPolicy||(config.rtcpMuxPolicy="require"),config.iceTransportPolicy){case"all":case"relay":break;default:config.iceTransportPolicy="all"}switch(config.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:config.bundlePolicy="balanced"}if(config.iceServers=filterIceServers(config.iceServers||[],edgeVersion),this._iceGatherers=[],config.iceCandidatePoolSize)for(var i=config.iceCandidatePoolSize;i>0;i--)this._iceGatherers.push(new window1.RTCIceGatherer({iceServers:config.iceServers,gatherPolicy:config.iceTransportPolicy}));else config.iceCandidatePoolSize=0;this._config=config,this.transceivers=[],this._sdpSessionId=SDPUtils.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(RTCPeerConnection.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(RTCPeerConnection.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),RTCPeerConnection.prototype.onicecandidate=null,RTCPeerConnection.prototype.onaddstream=null,RTCPeerConnection.prototype.ontrack=null,RTCPeerConnection.prototype.onremovestream=null,RTCPeerConnection.prototype.onsignalingstatechange=null,RTCPeerConnection.prototype.oniceconnectionstatechange=null,RTCPeerConnection.prototype.onconnectionstatechange=null,RTCPeerConnection.prototype.onicegatheringstatechange=null,RTCPeerConnection.prototype.onnegotiationneeded=null,RTCPeerConnection.prototype.ondatachannel=null,RTCPeerConnection.prototype._dispatchEvent=function(name,event){this._isClosed||(this.dispatchEvent(event),"function"==typeof this["on"+name]&&this["on"+name](event))},RTCPeerConnection.prototype._emitGatheringStateChange=function(){var event=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",event)},RTCPeerConnection.prototype.getConfiguration=function(){return this._config},RTCPeerConnection.prototype.getLocalStreams=function(){return this.localStreams},RTCPeerConnection.prototype.getRemoteStreams=function(){return this.remoteStreams},RTCPeerConnection.prototype._createTransceiver=function(kind,doNotAdd){var hasBundleTransport=this.transceivers.length>0,transceiver={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:kind,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&hasBundleTransport)transceiver.iceTransport=this.transceivers[0].iceTransport,transceiver.dtlsTransport=this.transceivers[0].dtlsTransport;else{var transports=this._createIceAndDtlsTransports();transceiver.iceTransport=transports.iceTransport,transceiver.dtlsTransport=transports.dtlsTransport}return doNotAdd||this.transceivers.push(transceiver),transceiver},RTCPeerConnection.prototype.addTrack=function(track,stream){if(this._isClosed)throw makeError("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");if(this.transceivers.find(function(s){return s.track===track}))throw makeError("InvalidAccessError","Track already exists.");for(var transceiver,i=0;i<this.transceivers.length;i++)this.transceivers[i].track||this.transceivers[i].kind!==track.kind||(transceiver=this.transceivers[i]);return transceiver||(transceiver=this._createTransceiver(track.kind)),this._maybeFireNegotiationNeeded(),-1===this.localStreams.indexOf(stream)&&this.localStreams.push(stream),transceiver.track=track,transceiver.stream=stream,transceiver.rtpSender=new window1.RTCRtpSender(track,transceiver.dtlsTransport),transceiver.rtpSender},RTCPeerConnection.prototype.addStream=function(stream){var pc=this;if(edgeVersion>=15025)stream.getTracks().forEach(function(track){pc.addTrack(track,stream)});else{var clonedStream=stream.clone();stream.getTracks().forEach(function(track,idx){var clonedTrack=clonedStream.getTracks()[idx];track.addEventListener("enabled",function(event){clonedTrack.enabled=event.enabled})}),clonedStream.getTracks().forEach(function(track){pc.addTrack(track,clonedStream)})}},RTCPeerConnection.prototype.removeTrack=function(sender){if(this._isClosed)throw makeError("InvalidStateError","Attempted to call removeTrack on a closed peerconnection.");if(!(sender instanceof window1.RTCRtpSender))throw TypeError("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.");var transceiver=this.transceivers.find(function(t){return t.rtpSender===sender});if(!transceiver)throw makeError("InvalidAccessError","Sender was not created by this connection.");var stream=transceiver.stream;transceiver.rtpSender.stop(),transceiver.rtpSender=null,transceiver.track=null,transceiver.stream=null,-1===this.transceivers.map(function(t){return t.stream}).indexOf(stream)&&this.localStreams.indexOf(stream)>-1&&this.localStreams.splice(this.localStreams.indexOf(stream),1),this._maybeFireNegotiationNeeded()},RTCPeerConnection.prototype.removeStream=function(stream){var pc=this;stream.getTracks().forEach(function(track){var sender=pc.getSenders().find(function(s){return s.track===track});sender&&pc.removeTrack(sender)})},RTCPeerConnection.prototype.getSenders=function(){return this.transceivers.filter(function(transceiver){return!!transceiver.rtpSender}).map(function(transceiver){return transceiver.rtpSender})},RTCPeerConnection.prototype.getReceivers=function(){return this.transceivers.filter(function(transceiver){return!!transceiver.rtpReceiver}).map(function(transceiver){return transceiver.rtpReceiver})},RTCPeerConnection.prototype._createIceGatherer=function(sdpMLineIndex,usingBundle){var pc=this;if(usingBundle&&sdpMLineIndex>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var iceGatherer=new window1.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(iceGatherer,"state",{value:"new",writable:!0}),this.transceivers[sdpMLineIndex].bufferedCandidateEvents=[],this.transceivers[sdpMLineIndex].bufferCandidates=function(event){var end=!event.candidate||0===Object.keys(event.candidate).length;iceGatherer.state=end?"completed":"gathering",null!==pc.transceivers[sdpMLineIndex].bufferedCandidateEvents&&pc.transceivers[sdpMLineIndex].bufferedCandidateEvents.push(event)},iceGatherer.addEventListener("localcandidate",this.transceivers[sdpMLineIndex].bufferCandidates),iceGatherer},RTCPeerConnection.prototype._gather=function(mid,sdpMLineIndex){var pc=this,iceGatherer=this.transceivers[sdpMLineIndex].iceGatherer;if(!iceGatherer.onlocalcandidate){var bufferedCandidateEvents=this.transceivers[sdpMLineIndex].bufferedCandidateEvents;this.transceivers[sdpMLineIndex].bufferedCandidateEvents=null,iceGatherer.removeEventListener("localcandidate",this.transceivers[sdpMLineIndex].bufferCandidates),iceGatherer.onlocalcandidate=function(evt){if(!pc.usingBundle||!(sdpMLineIndex>0)){var event=new Event("icecandidate");event.candidate={sdpMid:mid,sdpMLineIndex:sdpMLineIndex};var cand=evt.candidate,end=!cand||0===Object.keys(cand).length;if(end)("new"===iceGatherer.state||"gathering"===iceGatherer.state)&&(iceGatherer.state="completed");else{"new"===iceGatherer.state&&(iceGatherer.state="gathering"),cand.component=1,cand.ufrag=iceGatherer.getLocalParameters().usernameFragment;var serializedCandidate=SDPUtils.writeCandidate(cand);event.candidate=Object.assign(event.candidate,SDPUtils.parseCandidate(serializedCandidate)),event.candidate.candidate=serializedCandidate,event.candidate.toJSON=function(){return{candidate:event.candidate.candidate,sdpMid:event.candidate.sdpMid,sdpMLineIndex:event.candidate.sdpMLineIndex,usernameFragment:event.candidate.usernameFragment}}}var sections=SDPUtils.getMediaSections(pc._localDescription.sdp);end?sections[event.candidate.sdpMLineIndex]+="a=end-of-candidates\r\n":sections[event.candidate.sdpMLineIndex]+="a="+event.candidate.candidate+"\r\n",pc._localDescription.sdp=SDPUtils.getDescription(pc._localDescription.sdp)+sections.join("");var complete=pc.transceivers.every(function(transceiver){return transceiver.iceGatherer&&"completed"===transceiver.iceGatherer.state});"gathering"!==pc.iceGatheringState&&(pc.iceGatheringState="gathering",pc._emitGatheringStateChange()),end||pc._dispatchEvent("icecandidate",event),complete&&(pc._dispatchEvent("icecandidate",new Event("icecandidate")),pc.iceGatheringState="complete",pc._emitGatheringStateChange())}},window1.setTimeout(function(){bufferedCandidateEvents.forEach(function(e){iceGatherer.onlocalcandidate(e)})},0)}},RTCPeerConnection.prototype._createIceAndDtlsTransports=function(){var pc=this,iceTransport=new window1.RTCIceTransport(null);iceTransport.onicestatechange=function(){pc._updateIceConnectionState(),pc._updateConnectionState()};var dtlsTransport=new window1.RTCDtlsTransport(iceTransport);return dtlsTransport.ondtlsstatechange=function(){pc._updateConnectionState()},dtlsTransport.onerror=function(){Object.defineProperty(dtlsTransport,"state",{value:"failed",writable:!0}),pc._updateConnectionState()},{iceTransport:iceTransport,dtlsTransport:dtlsTransport}},RTCPeerConnection.prototype._disposeIceAndDtlsTransports=function(sdpMLineIndex){var iceGatherer=this.transceivers[sdpMLineIndex].iceGatherer;iceGatherer&&(delete iceGatherer.onlocalcandidate,delete this.transceivers[sdpMLineIndex].iceGatherer);var iceTransport=this.transceivers[sdpMLineIndex].iceTransport;iceTransport&&(delete iceTransport.onicestatechange,delete this.transceivers[sdpMLineIndex].iceTransport);var dtlsTransport=this.transceivers[sdpMLineIndex].dtlsTransport;dtlsTransport&&(delete dtlsTransport.ondtlsstatechange,delete dtlsTransport.onerror,delete this.transceivers[sdpMLineIndex].dtlsTransport)},RTCPeerConnection.prototype._transceive=function(transceiver,send,recv){var params=getCommonCapabilities(transceiver.localCapabilities,transceiver.remoteCapabilities);send&&transceiver.rtpSender&&(params.encodings=transceiver.sendEncodingParameters,params.rtcp={cname:SDPUtils.localCName,compound:transceiver.rtcpParameters.compound},transceiver.recvEncodingParameters.length&&(params.rtcp.ssrc=transceiver.recvEncodingParameters[0].ssrc),transceiver.rtpSender.send(params)),recv&&transceiver.rtpReceiver&¶ms.codecs.length>0&&("video"===transceiver.kind&&transceiver.recvEncodingParameters&&edgeVersion<15019&&transceiver.recvEncodingParameters.forEach(function(p){delete p.rtx}),transceiver.recvEncodingParameters.length?params.encodings=transceiver.recvEncodingParameters:params.encodings=[{}],params.rtcp={compound:transceiver.rtcpParameters.compound},transceiver.rtcpParameters.cname&&(params.rtcp.cname=transceiver.rtcpParameters.cname),transceiver.sendEncodingParameters.length&&(params.rtcp.ssrc=transceiver.sendEncodingParameters[0].ssrc),transceiver.rtpReceiver.receive(params))},RTCPeerConnection.prototype.setLocalDescription=function(description){var sections,sessionpart,pc=this;if(-1===["offer","answer"].indexOf(description.type))return Promise.reject(makeError("TypeError",'Unsupported type "'+description.type+'"'));if(!isActionAllowedInSignalingState("setLocalDescription",description.type,pc.signalingState)||pc._isClosed)return Promise.reject(makeError("InvalidStateError","Can not set local "+description.type+" in state "+pc.signalingState));if("offer"===description.type)sessionpart=(sections=SDPUtils.splitSections(description.sdp)).shift(),sections.forEach(function(mediaSection,sdpMLineIndex){var caps=SDPUtils.parseRtpParameters(mediaSection);pc.transceivers[sdpMLineIndex].localCapabilities=caps}),pc.transceivers.forEach(function(transceiver,sdpMLineIndex){pc._gather(transceiver.mid,sdpMLineIndex)});else if("answer"===description.type){sessionpart=(sections=SDPUtils.splitSections(pc._remoteDescription.sdp)).shift();var isIceLite=SDPUtils.matchPrefix(sessionpart,"a=ice-lite").length>0;sections.forEach(function(mediaSection,sdpMLineIndex){var transceiver=pc.transceivers[sdpMLineIndex],iceGatherer=transceiver.iceGatherer,iceTransport=transceiver.iceTransport,dtlsTransport=transceiver.dtlsTransport,localCapabilities=transceiver.localCapabilities,remoteCapabilities=transceiver.remoteCapabilities;if(!(SDPUtils.isRejected(mediaSection)&&0===SDPUtils.matchPrefix(mediaSection,"a=bundle-only").length)&&!transceiver.rejected){var remoteIceParameters=SDPUtils.getIceParameters(mediaSection,sessionpart),remoteDtlsParameters=SDPUtils.getDtlsParameters(mediaSection,sessionpart);isIceLite&&(remoteDtlsParameters.role="server"),pc.usingBundle&&0!==sdpMLineIndex||(pc._gather(transceiver.mid,sdpMLineIndex),"new"===iceTransport.state&&iceTransport.start(iceGatherer,remoteIceParameters,isIceLite?"controlling":"controlled"),"new"===dtlsTransport.state&&dtlsTransport.start(remoteDtlsParameters));var params=getCommonCapabilities(localCapabilities,remoteCapabilities);pc._transceive(transceiver,params.codecs.length>0,!1)}})}return pc._localDescription={type:description.type,sdp:description.sdp},"offer"===description.type?pc._updateSignalingState("have-local-offer"):pc._updateSignalingState("stable"),Promise.resolve()},RTCPeerConnection.prototype.setRemoteDescription=function(description){var pc=this;if(-1===["offer","answer"].indexOf(description.type))return Promise.reject(makeError("TypeError",'Unsupported type "'+description.type+'"'));if(!isActionAllowedInSignalingState("setRemoteDescription",description.type,pc.signalingState)||pc._isClosed)return Promise.reject(makeError("InvalidStateError","Can not set remote "+description.type+" in state "+pc.signalingState));var streams={};pc.remoteStreams.forEach(function(stream){streams[stream.id]=stream});var receiverList=[],sections=SDPUtils.splitSections(description.sdp),sessionpart=sections.shift(),isIceLite=SDPUtils.matchPrefix(sessionpart,"a=ice-lite").length>0,usingBundle=SDPUtils.matchPrefix(sessionpart,"a=group:BUNDLE ").length>0;pc.usingBundle=usingBundle;var iceOptions=SDPUtils.matchPrefix(sessionpart,"a=ice-options:")[0];return iceOptions?pc.canTrickleIceCandidates=iceOptions.substr(14).split(" ").indexOf("trickle")>=0:pc.canTrickleIceCandidates=!1,sections.forEach(function(mediaSection,sdpMLineIndex){var lines=SDPUtils.splitLines(mediaSection),kind=SDPUtils.getKind(mediaSection),rejected=SDPUtils.isRejected(mediaSection)&&0===SDPUtils.matchPrefix(mediaSection,"a=bundle-only").length,protocol=lines[0].substr(2).split(" ")[2],direction=SDPUtils.getDirection(mediaSection,sessionpart),remoteMsid=SDPUtils.parseMsid(mediaSection),mid=SDPUtils.getMid(mediaSection)||SDPUtils.generateIdentifier();if(rejected||"application"===kind&&("DTLS/SCTP"===protocol||"UDP/DTLS/SCTP"===protocol)){pc.transceivers[sdpMLineIndex]={mid:mid,kind:kind,protocol:protocol,rejected:!0};return}!rejected&&pc.transceivers[sdpMLineIndex]&&pc.transceivers[sdpMLineIndex].rejected&&(pc.transceivers[sdpMLineIndex]=pc._createTransceiver(kind,!0));var remoteCapabilities=SDPUtils.parseRtpParameters(mediaSection);rejected||(remoteIceParameters=SDPUtils.getIceParameters(mediaSection,sessionpart),(remoteDtlsParameters=SDPUtils.getDtlsParameters(mediaSection,sessionpart)).role="client"),recvEncodingParameters=SDPUtils.parseRtpEncodingParameters(mediaSection);var rtcpParameters=SDPUtils.parseRtcpParameters(mediaSection),isComplete=SDPUtils.matchPrefix(mediaSection,"a=end-of-candidates",sessionpart).length>0,cands=SDPUtils.matchPrefix(mediaSection,"a=candidate:").map(function(cand){return SDPUtils.parseCandidate(cand)}).filter(function(cand){return 1===cand.component});if(("offer"===description.type||"answer"===description.type)&&!rejected&&usingBundle&&sdpMLineIndex>0&&pc.transceivers[sdpMLineIndex]&&(pc._disposeIceAndDtlsTransports(sdpMLineIndex),pc.transceivers[sdpMLineIndex].iceGatherer=pc.transceivers[0].iceGatherer,pc.transceivers[sdpMLineIndex].iceTransport=pc.transceivers[0].iceTransport,pc.transceivers[sdpMLineIndex].dtlsTransport=pc.transceivers[0].dtlsTransport,pc.transceivers[sdpMLineIndex].rtpSender&&pc.transceivers[sdpMLineIndex].rtpSender.setTransport(pc.transceivers[0].dtlsTransport),pc.transceivers[sdpMLineIndex].rtpReceiver&&pc.transceivers[sdpMLineIndex].rtpReceiver.setTransport(pc.transceivers[0].dtlsTransport)),"offer"!==description.type||rejected)"answer"!==description.type||rejected||(iceGatherer=(transceiver=pc.transceivers[sdpMLineIndex]).iceGatherer,iceTransport=transceiver.iceTransport,dtlsTransport=transceiver.dtlsTransport,rtpReceiver=transceiver.rtpReceiver,sendEncodingParameters=transceiver.sendEncodingParameters,localCapabilities=transceiver.localCapabilities,pc.transceivers[sdpMLineIndex].recvEncodingParameters=recvEncodingParameters,pc.transceivers[sdpMLineIndex].remoteCapabilities=remoteCapabilities,pc.transceivers[sdpMLineIndex].rtcpParameters=rtcpParameters,cands.length&&"new"===iceTransport.state&&((isIceLite||isComplete)&&(!usingBundle||0===sdpMLineIndex)?iceTransport.setRemoteCandidates(cands):cands.forEach(function(candidate){maybeAddCandidate(transceiver.iceTransport,candidate)})),usingBundle&&0!==sdpMLineIndex||("new"===iceTransport.state&&iceTransport.start(iceGatherer,remoteIceParameters,"controlling"),"new"===dtlsTransport.state&&dtlsTransport.start(remoteDtlsParameters)),!getCommonCapabilities(transceiver.localCapabilities,transceiver.remoteCapabilities).codecs.filter(function(c){return"rtx"===c.name.toLowerCase()}).length&&transceiver.sendEncodingParameters[0].rtx&&delete transceiver.sendEncodingParameters[0].rtx,pc._transceive(transceiver,"sendrecv"===direction||"recvonly"===direction,"sendrecv"===direction||"sendonly"===direction),rtpReceiver&&("sendrecv"===direction||"sendonly"===direction)?(track=rtpReceiver.track,remoteMsid?(streams[remoteMsid.stream]||(streams[remoteMsid.stream]=new window1.MediaStream),addTrackToStreamAndFireEvent(track,streams[remoteMsid.stream]),receiverList.push([track,rtpReceiver,streams[remoteMsid.stream]])):(streams.default||(streams.default=new window1.MediaStream),addTrackToStreamAndFireEvent(track,streams.default),receiverList.push([track,rtpReceiver,streams.default]))):delete transceiver.rtpReceiver);else{(transceiver=pc.transceivers[sdpMLineIndex]||pc._createTransceiver(kind)).mid=mid,transceiver.iceGatherer||(transceiver.iceGatherer=pc._createIceGatherer(sdpMLineIndex,usingBundle)),cands.length&&"new"===transceiver.iceTransport.state&&(isComplete&&(!usingBundle||0===sdpMLineIndex)?transceiver.iceTransport.setRemoteCandidates(cands):cands.forEach(function(candidate){maybeAddCandidate(transceiver.iceTransport,candidate)})),localCapabilities=window1.RTCRtpReceiver.getCapabilities(kind),edgeVersion<15019&&(localCapabilities.codecs=localCapabilities.codecs.filter(function(codec){return"rtx"!==codec.name})),sendEncodingParameters=transceiver.sendEncodingParameters||[{ssrc:(2*sdpMLineIndex+2)*1001}];var transceiver,iceGatherer,iceTransport,dtlsTransport,rtpReceiver,sendEncodingParameters,recvEncodingParameters,localCapabilities,track,remoteIceParameters,remoteDtlsParameters,stream,isNewTrack=!1;"sendrecv"===direction||"sendonly"===direction?(isNewTrack=!transceiver.rtpReceiver,rtpReceiver=transceiver.rtpReceiver||new window1.RTCRtpReceiver(transceiver.dtlsTransport,kind),isNewTrack&&(track=rtpReceiver.track,remoteMsid&&"-"===remoteMsid.stream||(remoteMsid?(streams[remoteMsid.stream]||(streams[remoteMsid.stream]=new window1.MediaStream,Object.defineProperty(streams[remoteMsid.stream],"id",{get:function(){return remoteMsid.stream}})),Object.defineProperty(track,"id",{get:function(){return remoteMsid.track}}),stream=streams[remoteMsid.stream]):(streams.default||(streams.default=new window1.MediaStream),stream=streams.default)),stream&&(addTrackToStreamAndFireEvent(track,stream),transceiver.associatedRemoteMediaStreams.push(stream)),receiverList.push([track,rtpReceiver,stream]))):transceiver.rtpReceiver&&transceiver.rtpReceiver.track&&(transceiver.associatedRemoteMediaStreams.forEach(function(s){var nativeTrack=s.getTracks().find(function(t){return t.id===transceiver.rtpReceiver.track.id});nativeTrack&&removeTrackFromStreamAndFireEvent(nativeTrack,s)}),transceiver.associatedRemoteMediaStreams=[]),transceiver.localCapabilities=localCapabilities,transceiver.remoteCapabilities=remoteCapabilities,transceiver.rtpReceiver=rtpReceiver,transceiver.rtcpParameters=rtcpParameters,transceiver.sendEncodingParameters=sendEncodingParameters,transceiver.recvEncodingParameters=recvEncodingParameters,pc._transceive(pc.transceivers[sdpMLineIndex],!1,isNewTrack)}}),void 0===pc._dtlsRole&&(pc._dtlsRole="offer"===description.type?"active":"passive"),pc._remoteDescription={type:description.type,sdp:description.sdp},"offer"===description.type?pc._updateSignalingState("have-remote-offer"):pc._updateSignalingState("stable"),Object.keys(streams).forEach(function(sid){var stream=streams[sid];if(stream.getTracks().length){if(-1===pc.remoteStreams.indexOf(stream)){pc.remoteStreams.push(stream);var event=new Event("addstream");event.stream=stream,window1.setTimeout(function(){pc._dispatchEvent("addstream",event)})}receiverList.forEach(function(item){var track=item[0],receiver=item[1];stream.id===item[2].id&&fireAddTrack(pc,track,receiver,[stream])})}}),receiverList.forEach(function(item){item[2]||fireAddTrack(pc,item[0],item[1],[])}),window1.setTimeout(function(){pc&&pc.transceivers&&pc.transceivers.forEach(function(transceiver){transceiver.iceTransport&&"new"===transceiver.iceTransport.state&&transceiver.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),transceiver.iceTransport.addRemoteCandidate({}))})},4e3),Promise.resolve()},RTCPeerConnection.prototype.close=function(){this.transceivers.forEach(function(transceiver){transceiver.iceTransport&&transceiver.iceTransport.stop(),transceiver.dtlsTransport&&transceiver.dtlsTransport.stop(),transceiver.rtpSender&&transceiver.rtpSender.stop(),transceiver.rtpReceiver&&transceiver.rtpReceiver.stop()}),this._isClosed=!0,this._updateSignalingState("closed")},RTCPeerConnection.prototype._updateSignalingState=function(newState){this.signalingState=newState;var event=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",event)},RTCPeerConnection.prototype._maybeFireNegotiationNeeded=function(){var pc=this;"stable"===this.signalingState&&!0!==this.needNegotiation&&(this.needNegotiation=!0,window1.setTimeout(function(){if(pc.needNegotiation){pc.needNegotiation=!1;var event=new Event("negotiationneeded");pc._dispatchEvent("negotiationneeded",event)}},0))},RTCPeerConnection.prototype._updateIceConnectionState=function(){var newState,states={new:0,closed:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(transceiver){transceiver.iceTransport&&!transceiver.rejected&&states[transceiver.iceTransport.state]++}),newState="new",states.failed>0?newState="failed":states.checking>0?newState="checking":states.disconnected>0?newState="disconnected":states.new>0?newState="new":states.connected>0?newState="connected":states.completed>0&&(newState="completed"),newState!==this.iceConnectionState){this.iceConnectionState=newState;var event=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",event)}},RTCPeerConnection.prototype._updateConnectionState=function(){var newState,states={new:0,closed:0,connecting:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(transceiver){transceiver.iceTransport&&transceiver.dtlsTransport&&!transceiver.rejected&&(states[transceiver.iceTransport.state]++,states[transceiver.dtlsTransport.state]++)}),states.connected+=states.completed,newState="new",states.failed>0?newState="failed":states.connecting>0?newState="connecting":states.disconnected>0?newState="disconnected":states.new>0?newState="new":states.connected>0&&(newState="connected"),newState!==this.connectionState){this.connectionState=newState;var event=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",event)}},RTCPeerConnection.prototype.createOffer=function(){var pc=this;if(pc._isClosed)return Promise.reject(makeError("InvalidStateError","Can not call createOffer after close"));var numAudioTracks=pc.transceivers.filter(function(t){return"audio"===t.kind}).length,numVideoTracks=pc.transceivers.filter(function(t){return"video"===t.kind}).length,offerOptions=arguments[0];if(offerOptions){if(offerOptions.mandatory||offerOptions.optional)throw TypeError("Legacy mandatory/optional constraints not supported.");void 0!==offerOptions.offerToReceiveAudio&&(numAudioTracks=!0===offerOptions.offerToReceiveAudio?1:!1===offerOptions.offerToReceiveAudio?0:offerOptions.offerToReceiveAudio),void 0!==offerOptions.offerToReceiveVideo&&(numVideoTracks=!0===offerOptions.offerToReceiveVideo?1:!1===offerOptions.offerToReceiveVideo?0:offerOptions.offerToReceiveVideo)}for(pc.transceivers.forEach(function(transceiver){"audio"===transceiver.kind?--numAudioTracks<0&&(transceiver.wantReceive=!1):"video"===transceiver.kind&&--numVideoTracks<0&&(transceiver.wantReceive=!1)});numAudioTracks>0||numVideoTracks>0;)numAudioTracks>0&&(pc._createTransceiver("audio"),numAudioTracks--),numVideoTracks>0&&(pc._createTransceiver("video"),numVideoTracks--);var sdp=SDPUtils.writeSessionBoilerplate(pc._sdpSessionId,pc._sdpSessionVersion++);return pc.transceivers.forEach(function(transceiver,sdpMLineIndex){var track=transceiver.track,kind=transceiver.kind,mid=transceiver.mid||SDPUtils.generateIdentifier();transceiver.mid=mid,transceiver.iceGatherer||(transceiver.iceGatherer=pc._createIceGatherer(sdpMLineIndex,pc.usingBundle));var localCapabilities=window1.RTCRtpSender.getCapabilities(kind);edgeVersion<15019&&(localCapabilities.codecs=localCapabilities.codecs.filter(function(codec){return"rtx"!==codec.name})),localCapabilities.codecs.forEach(function(codec){"H264"===codec.name&&void 0===codec.parameters["level-asymmetry-allowed"]&&(codec.parameters["level-asymmetry-allowed"]="1"),transceiver.remoteCapabilities&&transceiver.remoteCapabilities.codecs&&transceiver.remoteCapabilities.codecs.forEach(function(remoteCodec){codec.name.toLowerCase()===remoteCodec.name.toLowerCase()&&codec.clockRate===remoteCodec.clockRate&&(codec.preferredPayloadType=remoteCodec.payloadType)})}),localCapabilities.headerExtensions.forEach(function(hdrExt){(transceiver.remoteCapabilities&&transceiver.remoteCapabilities.headerExtensions||[]).forEach(function(rHdrExt){hdrExt.uri===rHdrExt.uri&&(hdrExt.id=rHdrExt.id)})});var sendEncodingParameters=transceiver.sendEncodingParameters||[{ssrc:(2*sdpMLineIndex+1)*1001}];track&&edgeVersion>=15019&&"video"===kind&&!sendEncodingParameters[0].rtx&&(sendEncodingParameters[0].rtx={ssrc:sendEncodingParameters[0].ssrc+1}),transceiver.wantReceive&&(transceiver.rtpReceiver=new window1.RTCRtpReceiver(transceiver.dtlsTransport,kind)),transceiver.localCapabilities=localCapabilities,transceiver.sendEncodingParameters=sendEncodingParameters}),"max-compat"!==pc._config.bundlePolicy&&(sdp+="a=group:BUNDLE "+pc.transceivers.map(function(t){return t.mid}).join(" ")+"\r\n"),sdp+="a=ice-options:trickle\r\n",pc.transceivers.forEach(function(transceiver,sdpMLineIndex){sdp+=writeMediaSection(transceiver,transceiver.localCapabilities,"offer",transceiver.stream,pc._dtlsRole)+"a=rtcp-rsize\r\n",transceiver.iceGatherer&&"new"!==pc.iceGatheringState&&(0===sdpMLineIndex||!pc.usingBundle)&&(transceiver.iceGatherer.getLocalCandidates().forEach(function(cand){cand.component=1,sdp+="a="+SDPUtils.writeCandidate(cand)+"\r\n"}),"completed"===transceiver.iceGatherer.state&&(sdp+="a=end-of-candidates\r\n"))}),Promise.resolve(new window1.RTCSessionDescription({type:"offer",sdp:sdp}))},RTCPeerConnection.prototype.createAnswer=function(){var pc=this;if(pc._isClosed)return Promise.reject(makeError("InvalidStateError","Can not call createAnswer after close"));if(!("have-remote-offer"===pc.signalingState||"have-local-pranswer"===pc.signalingState))return Promise.reject(makeError("InvalidStateError","Can not call createAnswer in signalingState "+pc.signalingState));var sdp=SDPUtils.writeSessionBoilerplate(pc._sdpSessionId,pc._sdpSessionVersion++);pc.usingBundle&&(sdp+="a=group:BUNDLE "+pc.transceivers.map(function(t){return t.mid}).join(" ")+"\r\n"),sdp+="a=ice-options:trickle\r\n";var mediaSectionsInOffer=SDPUtils.getMediaSections(pc._remoteDescription.sdp).length;return pc.transceivers.forEach(function(transceiver,sdpMLineIndex){if(!(sdpMLineIndex+1>mediaSectionsInOffer)){if(transceiver.rejected){"application"===transceiver.kind?"DTLS/SCTP"===transceiver.protocol?sdp+="m=application 0 DTLS/SCTP 5000\r\n":sdp+="m=application 0 "+transceiver.protocol+" webrtc-datachannel\r\n":"audio"===transceiver.kind?sdp+="m=audio 0 UDP/TLS/RTP/SAVPF 0\r\na=rtpmap:0 PCMU/8000\r\n":"video"===transceiver.kind&&(sdp+="m=video 0 UDP/TLS/RTP/SAVPF 120\r\na=rtpmap:120 VP8/90000\r\n"),sdp+="c=IN IP4 0.0.0.0\r\na=inactive\r\na=mid:"+transceiver.mid+"\r\n";return}if(transceiver.stream){var localTrack;"audio"===transceiver.kind?localTrack=transceiver.stream.getAudioTracks()[0]:"video"===transceiver.kind&&(localTrack=transceiver.stream.getVideoTracks()[0]),localTrack&&edgeVersion>=15019&&"video"===transceiver.kind&&!transceiver.sendEncodingParameters[0].rtx&&(transceiver.sendEncodingParameters[0].rtx={ssrc:transceiver.sendEncodingParameters[0].ssrc+1})}var commonCapabilities=getCommonCapabilities(transceiver.localCapabilities,transceiver.remoteCapabilities);!commonCapabilities.codecs.filter(function(c){return"rtx"===c.name.toLowerCase()}).length&&transceiver.sendEncodingParameters[0].rtx&&delete transceiver.sendEncodingParameters[0].rtx,sdp+=writeMediaSection(transceiver,commonCapabilities,"answer",transceiver.stream,pc._dtlsRole),transceiver.rtcpParameters&&transceiver.rtcpParameters.reducedSize&&(sdp+="a=rtcp-rsize\r\n")}}),Promise.resolve(new window1.RTCSessionDescription({type:"answer",sdp:sdp}))},RTCPeerConnection.prototype.addIceCandidate=function(candidate){var sections,pc=this;return candidate&&!(void 0!==candidate.sdpMLineIndex||candidate.sdpMid)?Promise.reject(TypeError("sdpMLineIndex or sdpMid required")):new Promise(function(resolve,reject){if(!pc._remoteDescription)return reject(makeError("InvalidStateError","Can not add ICE candidate without a remote description"));if(candidate&&""!==candidate.candidate){var sdpMLineIndex=candidate.sdpMLineIndex;if(candidate.sdpMid){for(var i=0;i<pc.transceivers.length;i++)if(pc.transceivers[i].mid===candidate.sdpMid){sdpMLineIndex=i;break}}var transceiver=pc.transceivers[sdpMLineIndex];if(!transceiver)return reject(makeError("OperationError","Can not add ICE candidate"));if(transceiver.rejected)return resolve();var cand=Object.keys(candidate.candidate).length>0?SDPUtils.parseCandidate(candidate.candidate):{};if("tcp"===cand.protocol&&(0===cand.port||9===cand.port)||cand.component&&1!==cand.component)return resolve();if((0===sdpMLineIndex||sdpMLineIndex>0&&transceiver.iceTransport!==pc.transceivers[0].iceTransport)&&!maybeAddCandidate(transceiver.iceTransport,cand))return reject(makeError("OperationError","Can not add ICE candidate"));var candidateString=candidate.candidate.trim();0===candidateString.indexOf("a=")&&(candidateString=candidateString.substr(2)),sections=SDPUtils.getMediaSections(pc._remoteDescription.sdp),sections[sdpMLineIndex]+="a="+(cand.type?candidateString:"end-of-candidates")+"\r\n",pc._remoteDescription.sdp=SDPUtils.getDescription(pc._remoteDescription.sdp)+sections.join("")}else for(var j=0;j<pc.transceivers.length&&(pc.transceivers[j].rejected||(pc.transceivers[j].iceTransport.addRemoteCandidate({}),sections=SDPUtils.getMediaSections(pc._remoteDescription.sdp),sections[j]+="a=end-of-candidates\r\n",pc._remoteDescription.sdp=SDPUtils.getDescription(pc._remoteDescription.sdp)+sections.join(""),!pc.usingBundle));j++);resolve()})},RTCPeerConnection.prototype.getStats=function(selector){if(selector&&selector instanceof window1.MediaStreamTrack){var senderOrReceiver=null;if(this.transceivers.forEach(function(transceiver){transceiver.rtpSender&&transceiver.rtpSender.track===selector?senderOrReceiver=transceiver.rtpSender:transceiver.rtpReceiver&&transceiver.rtpReceiver.track===selector&&(senderOrReceiver=transceiver.rtpReceiver)}),!senderOrReceiver)throw makeError("InvalidAccessError","Invalid selector.");return senderOrReceiver.getStats()}var promises=[];return this.transceivers.forEach(function(transceiver){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach(function(method){transceiver[method]&&promises.push(transceiver[method].getStats())})}),Promise.all(promises).then(function(allStats){var results=new Map;return allStats.forEach(function(stats){stats.forEach(function(stat){results.set(stat.id,stat)})}),results})},["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"].forEach(function(ortcObjectName){var obj=window1[ortcObjectName];if(obj&&obj.prototype&&obj.prototype.getStats){var nativeGetstats=obj.prototype.getStats;obj.prototype.getStats=function(){return nativeGetstats.apply(this).then(function(nativeStats){var mapStats=new Map;return Object.keys(nativeStats).forEach(function(id){nativeStats[id].type=fixStatsType(nativeStats[id]),mapStats.set(id,nativeStats[id])}),mapStats})}}});var methods=["createOffer","createAnswer"];return methods.forEach(function(method){var nativeMethod=RTCPeerConnection.prototype[method];RTCPeerConnection.prototype[method]=function(){var args=arguments;return"function"==typeof args[0]||"function"==typeof args[1]?nativeMethod.apply(this,[arguments[2]]).then(function(description){"function"==typeof args[0]&&args[0].apply(null,[description])},function(error){"function"==typeof args[1]&&args[1].apply(null,[error])}):nativeMethod.apply(this,arguments)}}),(methods=["setLocalDescription","setRemoteDescription","addIceCandidate"]).forEach(function(method){var nativeMethod=RTCPeerConnection.prototype[method];RTCPeerConnection.prototype[method]=function(){var args=arguments;return"function"==typeof args[1]||"function"==typeof args[2]?nativeMethod.apply(this,arguments).then(function(){"function"==typeof args[1]&&args[1].apply(null)},function(error){"function"==typeof args[2]&&args[2].apply(null,[error])}):nativeMethod.apply(this,arguments)}}),["getStats"].forEach(function(method){var nativeMethod=RTCPeerConnection.prototype[method];RTCPeerConnection.prototype[method]=function(){var args=arguments;return"function"==typeof args[1]?nativeMethod.apply(this,arguments).then(function(){"function"==typeof args[1]&&args[1].apply(null)}):nativeMethod.apply(this,arguments)}}),RTCPeerConnection}},{sdp:175}],173:[function(require1,module,exports){/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var buffer=require1("buffer"),Buffer=buffer.Buffer;function copyProps(src,dst){for(var key in src)dst[key]=src[key]}function SafeBuffer(arg,encodingOrOffset,length){return Buffer(arg,encodingOrOffset,length)}Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow?module.exports=buffer:(copyProps(buffer,exports),exports.Buffer=SafeBuffer),SafeBuffer.prototype=Object.create(Buffer.prototype),copyProps(Buffer,SafeBuffer),SafeBuffer.from=function(arg,encodingOrOffset,length){if("number"==typeof arg)throw TypeError("Argument must not be a number");return Buffer(arg,encodingOrOffset,length)},SafeBuffer.alloc=function(size,fill,encoding){if("number"!=typeof size)throw TypeError("Argument must be a number");var buf=Buffer(size);return void 0!==fill?"string"==typeof encoding?buf.fill(fill,encoding):buf.fill(fill):buf.fill(0),buf},SafeBuffer.allocUnsafe=function(size){if("number"!=typeof size)throw TypeError("Argument must be a number");return Buffer(size)},SafeBuffer.allocUnsafeSlow=function(size){if("number"!=typeof size)throw TypeError("Argument must be a number");return buffer.SlowBuffer(size)}},{buffer:47}],174:[function(require1,module,exports){(function(process){(function(){"use strict";var key,buffer=require1("buffer"),Buffer=buffer.Buffer,safer={};for(key in buffer)buffer.hasOwnProperty(key)&&"SlowBuffer"!==key&&"Buffer"!==key&&(safer[key]=buffer[key]);var Safer=safer.Buffer={};for(key in Buffer)Buffer.hasOwnProperty(key)&&"allocUnsafe"!==key&&"allocUnsafeSlow"!==key&&(Safer[key]=Buffer[key]);if(safer.Buffer.prototype=Buffer.prototype,Safer.from&&Safer.from!==Uint8Array.from||(Safer.from=function(value,encodingOrOffset,length){if("number"==typeof value)throw TypeError('The "value" argument must not be of type number. Received type '+typeof value);if(value&&void 0===value.length)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof value);return Buffer(value,encodingOrOffset,length)}),Safer.alloc||(Safer.alloc=function(size,fill,encoding){if("number"!=typeof size)throw TypeError('The "size" argument must be of type number. Received type '+typeof size);if(size<0||size>=2*1073741824)throw RangeError('The value "'+size+'" is invalid for option "size"');var buf=Buffer(size);return fill&&0!==fill.length?"string"==typeof encoding?buf.fill(fill,encoding):buf.fill(fill):buf.fill(0),buf}),!safer.kStringMaxLength)try{safer.kStringMaxLength=process.binding("buffer").kStringMaxLength}catch(e){}!safer.constants&&(safer.constants={MAX_LENGTH:safer.kMaxLength},safer.kStringMaxLength&&(safer.constants.MAX_STRING_LENGTH=safer.kStringMaxLength)),module.exports=safer}).call(this)}).call(this,require1("_process"))},{_process:152,buffer:47}],175:[function(require1,module,exports){"use strict";var SDPUtils={};SDPUtils.generateIdentifier=function(){return Math.random().toString(36).substr(2,10)},SDPUtils.localCName=SDPUtils.generateIdentifier(),SDPUtils.splitLines=function(blob){return blob.trim().split("\n").map(function(line){return line.trim()})},SDPUtils.splitSections=function(blob){return blob.split("\nm=").map(function(part,index){return(index>0?"m="+part:part).trim()+"\r\n"})},SDPUtils.getDescription=function(blob){var sections=SDPUtils.splitSections(blob);return sections&§ions[0]},SDPUtils.getMediaSections=function(blob){var sections=SDPUtils.splitSections(blob);return sections.shift(),sections},SDPUtils.matchPrefix=function(blob,prefix){return SDPUtils.splitLines(blob).filter(function(line){return 0===line.indexOf(prefix)})},SDPUtils.parseCandidate=function(line){for(var parts,candidate={foundation:(parts=0===line.indexOf("a=candidate:")?line.substring(12).split(" "):line.substring(10).split(" "))[0],component:parseInt(parts[1],10),protocol:parts[2].toLowerCase(),priority:parseInt(parts[3],10),ip:parts[4],address:parts[4],port:parseInt(parts[5],10),type:parts[7]},i=8;i<parts.length;i+=2)switch(parts[i]){case"raddr":candidate.relatedAddress=parts[i+1];break;case"rport":candidate.relatedPort=parseInt(parts[i+1],10);break;case"tcptype":candidate.tcpType=parts[i+1];break;case"ufrag":candidate.ufrag=parts[i+1],candidate.usernameFragment=parts[i+1];break;default:candidate[parts[i]]=parts[i+1]}return candidate},SDPUtils.writeCandidate=function(candidate){var sdp=[];sdp.push(candidate.foundation),sdp.push(candidate.component),sdp.push(candidate.protocol.toUpperCase()),sdp.push(candidate.priority),sdp.push(candidate.address||candidate.ip),sdp.push(candidate.port);var type=candidate.type;return sdp.push("typ"),sdp.push(type),"host"!==type&&candidate.relatedAddress&&candidate.relatedPort&&(sdp.push("raddr"),sdp.push(candidate.relatedAddress),sdp.push("rport"),sdp.push(candidate.relatedPort)),candidate.tcpType&&"tcp"===candidate.protocol.toLowerCase()&&(sdp.push("tcptype"),sdp.push(candidate.tcpType)),(candidate.usernameFragment||candidate.ufrag)&&(sdp.push("ufrag"),sdp.push(candidate.usernameFragment||candidate.ufrag)),"candidate:"+sdp.join(" ")},SDPUtils.parseIceOptions=function(line){return line.substr(14).split(" ")},SDPUtils.parseRtpMap=function(line){var parts=line.substr(9).split(" "),parsed={payloadType:parseInt(parts.shift(),10)};return parts=parts[0].split("/"),parsed.name=parts[0],parsed.clockRate=parseInt(parts[1],10),parsed.channels=3===parts.length?parseInt(parts[2],10):1,parsed.numChannels=parsed.channels,parsed},SDPUtils.writeRtpMap=function(codec){var pt=codec.payloadType;void 0!==codec.preferredPayloadType&&(pt=codec.preferredPayloadType);var channels=codec.channels||codec.numChannels||1;return"a=rtpmap:"+pt+" "+codec.name+"/"+codec.clockRate+(1!==channels?"/"+channels:"")+"\r\n"},SDPUtils.parseExtmap=function(line){var parts=line.substr(9).split(" ");return{id:parseInt(parts[0],10),direction:parts[0].indexOf("/")>0?parts[0].split("/")[1]:"sendrecv",uri:parts[1]}},SDPUtils.writeExtmap=function(headerExtension){return"a=extmap:"+(headerExtension.id||headerExtension.preferredId)+(headerExtension.direction&&"sendrecv"!==headerExtension.direction?"/"+headerExtension.direction:"")+" "+headerExtension.uri+"\r\n"},SDPUtils.parseFmtp=function(line){for(var kv,parsed={},parts=line.substr(line.indexOf(" ")+1).split(";"),j=0;j<parts.length;j++)parsed[(kv=parts[j].trim().split("="))[0].trim()]=kv[1];return parsed},SDPUtils.writeFmtp=function(codec){var line="",pt=codec.payloadType;if(void 0!==codec.preferredPayloadType&&(pt=codec.preferredPayloadType),codec.parameters&&Object.keys(codec.parameters).length){var params=[];Object.keys(codec.parameters).forEach(function(param){codec.parameters[param]?params.push(param+"="+codec.parameters[param]):params.push(param)}),line+="a=fmtp:"+pt+" "+params.join(";")+"\r\n"}return line},SDPUtils.parseRtcpFb=function(line){var parts=line.substr(line.indexOf(" ")+1).split(" ");return{type:parts.shift(),parameter:parts.join(" ")}},SDPUtils.writeRtcpFb=function(codec){var lines="",pt=codec.payloadType;return void 0!==codec.preferredPayloadType&&(pt=codec.preferredPayloadType),codec.rtcpFeedback&&codec.rtcpFeedback.length&&codec.rtcpFeedback.forEach(function(fb){lines+="a=rtcp-fb:"+pt+" "+fb.type+(fb.parameter&&fb.parameter.length?" "+fb.parameter:"")+"\r\n"}),lines},SDPUtils.parseSsrcMedia=function(line){var sp=line.indexOf(" "),parts={ssrc:parseInt(line.substr(7,sp-7),10)},colon=line.indexOf(":",sp);return colon>-1?(parts.attribute=line.substr(sp+1,colon-sp-1),parts.value=line.substr(colon+1)):parts.attribute=line.substr(sp+1),parts},SDPUtils.parseSsrcGroup=function(line){var parts=line.substr(13).split(" ");return{semantics:parts.shift(),ssrcs:parts.map(function(ssrc){return parseInt(ssrc,10)})}},SDPUtils.getMid=function(mediaSection){var mid=SDPUtils.matchPrefix(mediaSection,"a=mid:")[0];if(mid)return mid.substr(6)},SDPUtils.parseFingerprint=function(line){var parts=line.substr(14).split(" ");return{algorithm:parts[0].toLowerCase(),value:parts[1]}},SDPUtils.getDtlsParameters=function(mediaSection,sessionpart){return{role:"auto",fingerprints:SDPUtils.matchPrefix(mediaSection+sessionpart,"a=fingerprint:").map(SDPUtils.parseFingerprint)}},SDPUtils.writeDtlsParameters=function(params,setupType){var sdp="a=setup:"+setupType+"\r\n";return params.fingerprints.forEach(function(fp){sdp+="a=fingerprint:"+fp.algorithm+" "+fp.value+"\r\n"}),sdp},SDPUtils.parseCryptoLine=function(line){var parts=line.substr(9).split(" ");return{tag:parseInt(parts[0],10),cryptoSuite:parts[1],keyParams:parts[2],sessionParams:parts.slice(3)}},SDPUtils.writeCryptoLine=function(parameters){return"a=crypto:"+parameters.tag+" "+parameters.cryptoSuite+" "+("object"==typeof parameters.keyParams?SDPUtils.writeCryptoKeyParams(parameters.keyParams):parameters.keyParams)+(parameters.sessionParams?" "+parameters.sessionParams.join(" "):"")+"\r\n"},SDPUtils.parseCryptoKeyParams=function(keyParams){if(0!==keyParams.indexOf("inline:"))return null;var parts=keyParams.substr(7).split("|");return{keyMethod:"inline",keySalt:parts[0],lifeTime:parts[1],mkiValue:parts[2]?parts[2].split(":")[0]:void 0,mkiLength:parts[2]?parts[2].split(":")[1]:void 0}},SDPUtils.writeCryptoKeyParams=function(keyParams){return keyParams.keyMethod+":"+keyParams.keySalt+(keyParams.lifeTime?"|"+keyParams.lifeTime:"")+(keyParams.mkiValue&&keyParams.mkiLength?"|"+keyParams.mkiValue+":"+keyParams.mkiLength:"")},SDPUtils.getCryptoParameters=function(mediaSection,sessionpart){return SDPUtils.matchPrefix(mediaSection+sessionpart,"a=crypto:").map(SDPUtils.parseCryptoLine)},SDPUtils.getIceParameters=function(mediaSection,sessionpart){var ufrag=SDPUtils.matchPrefix(mediaSection+sessionpart,"a=ice-ufrag:")[0],pwd=SDPUtils.matchPrefix(mediaSection+sessionpart,"a=ice-pwd:")[0];return ufrag&&pwd?{usernameFragment:ufrag.substr(12),password:pwd.substr(10)}:null},SDPUtils.writeIceParameters=function(params){return"a=ice-ufrag:"+params.usernameFragment+"\r\na=ice-pwd:"+params.password+"\r\n"},SDPUtils.parseRtpParameters=function(mediaSection){for(var description={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},mline=SDPUtils.splitLines(mediaSection)[0].split(" "),i=3;i<mline.length;i++){var pt=mline[i],rtpmapline=SDPUtils.matchPrefix(mediaSection,"a=rtpmap:"+pt+" ")[0];if(rtpmapline){var codec=SDPUtils.parseRtpMap(rtpmapline),fmtps=SDPUtils.matchPrefix(mediaSection,"a=fmtp:"+pt+" ");switch(codec.parameters=fmtps.length?SDPUtils.parseFmtp(fmtps[0]):{},codec.rtcpFeedback=SDPUtils.matchPrefix(mediaSection,"a=rtcp-fb:"+pt+" ").map(SDPUtils.parseRtcpFb),description.codecs.push(codec),codec.name.toUpperCase()){case"RED":case"ULPFEC":description.fecMechanisms.push(codec.name.toUpperCase())}}}return SDPUtils.matchPrefix(mediaSection,"a=extmap:").forEach(function(line){description.headerExtensions.push(SDPUtils.parseExtmap(line))}),description},SDPUtils.writeRtpDescription=function(kind,caps){var sdp="";sdp+="m="+kind+" "+(caps.codecs.length>0?"9":"0")+" UDP/TLS/RTP/SAVPF "+caps.codecs.map(function(codec){return void 0!==codec.preferredPayloadType?codec.preferredPayloadType:codec.payloadType}).join(" ")+"\r\nc=IN IP4 0.0.0.0\r\na=rtcp:9 IN IP4 0.0.0.0\r\n",caps.codecs.forEach(function(codec){sdp+=SDPUtils.writeRtpMap(codec)+SDPUtils.writeFmtp(codec)+SDPUtils.writeRtcpFb(codec)});var maxptime=0;return caps.codecs.forEach(function(codec){codec.maxptime>maxptime&&(maxptime=codec.maxptime)}),maxptime>0&&(sdp+="a=maxptime:"+maxptime+"\r\n"),sdp+="a=rtcp-mux\r\n",caps.headerExtensions&&caps.headerExtensions.forEach(function(extension){sdp+=SDPUtils.writeExtmap(extension)}),sdp},SDPUtils.parseRtpEncodingParameters=function(mediaSection){var secondarySsrc,encodingParameters=[],description=SDPUtils.parseRtpParameters(mediaSection),hasRed=-1!==description.fecMechanisms.indexOf("RED"),hasUlpfec=-1!==description.fecMechanisms.indexOf("ULPFEC"),ssrcs=SDPUtils.matchPrefix(mediaSection,"a=ssrc:").map(function(line){return SDPUtils.parseSsrcMedia(line)}).filter(function(parts){return"cname"===parts.attribute}),primarySsrc=ssrcs.length>0&&ssrcs[0].ssrc,flows=SDPUtils.matchPrefix(mediaSection,"a=ssrc-group:FID").map(function(line){return line.substr(17).split(" ").map(function(part){return parseInt(part,10)})});flows.length>0&&flows[0].length>1&&flows[0][0]===primarySsrc&&(secondarySsrc=flows[0][1]),description.codecs.forEach(function(codec){if("RTX"===codec.name.toUpperCase()&&codec.parameters.apt){var encParam={ssrc:primarySsrc,codecPayloadType:parseInt(codec.parameters.apt,10)};primarySsrc&&secondarySsrc&&(encParam.rtx={ssrc:secondarySsrc}),encodingParameters.push(encParam),hasRed&&((encParam=JSON.parse(JSON.stringify(encParam))).fec={ssrc:primarySsrc,mechanism:hasUlpfec?"red+ulpfec":"red"},encodingParameters.push(encParam))}}),0===encodingParameters.length&&primarySsrc&&encodingParameters.push({ssrc:primarySsrc});var bandwidth=SDPUtils.matchPrefix(mediaSection,"b=");return bandwidth.length&&(bandwidth=0===bandwidth[0].indexOf("b=TIAS:")?parseInt(bandwidth[0].substr(7),10):0===bandwidth[0].indexOf("b=AS:")?950*parseInt(bandwidth[0].substr(5),10)-16e3:void 0,encodingParameters.forEach(function(params){params.maxBitrate=bandwidth})),encodingParameters},SDPUtils.parseRtcpParameters=function(mediaSection){var rtcpParameters={},remoteSsrc=SDPUtils.matchPrefix(mediaSection,"a=ssrc:").map(function(line){return SDPUtils.parseSsrcMedia(line)}).filter(function(obj){return"cname"===obj.attribute})[0];remoteSsrc&&(rtcpParameters.cname=remoteSsrc.value,rtcpParameters.ssrc=remoteSsrc.ssrc);var rsize=SDPUtils.matchPrefix(mediaSection,"a=rtcp-rsize");rtcpParameters.reducedSize=rsize.length>0,rtcpParameters.compound=0===rsize.length;var mux=SDPUtils.matchPrefix(mediaSection,"a=rtcp-mux");return rtcpParameters.mux=mux.length>0,rtcpParameters},SDPUtils.parseMsid=function(mediaSection){var parts,spec=SDPUtils.matchPrefix(mediaSection,"a=msid:");if(1===spec.length)return{stream:(parts=spec[0].substr(7).split(" "))[0],track:parts[1]};var planB=SDPUtils.matchPrefix(mediaSection,"a=ssrc:").map(function(line){return SDPUtils.parseSsrcMedia(line)}).filter(function(msidParts){return"msid"===msidParts.attribute});if(planB.length>0)return{stream:(parts=planB[0].value.split(" "))[0],track:parts[1]}},SDPUtils.parseSctpDescription=function(mediaSection){var maxMessageSize,mline=SDPUtils.parseMLine(mediaSection),maxSizeLine=SDPUtils.matchPrefix(mediaSection,"a=max-message-size:");maxSizeLine.length>0&&(maxMessageSize=parseInt(maxSizeLine[0].substr(19),10)),isNaN(maxMessageSize)&&(maxMessageSize=65536);var sctpPort=SDPUtils.matchPrefix(mediaSection,"a=sctp-port:");if(sctpPort.length>0)return{port:parseInt(sctpPort[0].substr(12),10),protocol:mline.fmt,maxMessageSize:maxMessageSize};if(SDPUtils.matchPrefix(mediaSection,"a=sctpmap:").length>0){var parts=SDPUtils.matchPrefix(mediaSection,"a=sctpmap:")[0].substr(10).split(" ");return{port:parseInt(parts[0],10),protocol:parts[1],maxMessageSize:maxMessageSize}}},SDPUtils.writeSctpDescription=function(media,sctp){var output=[];return output="DTLS/SCTP"!==media.protocol?["m="+media.kind+" 9 "+media.protocol+" "+sctp.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+sctp.port+"\r\n"]:["m="+media.kind+" 9 "+media.protocol+" "+sctp.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+sctp.port+" "+sctp.protocol+" 65535\r\n"],void 0!==sctp.maxMessageSize&&output.push("a=max-message-size:"+sctp.maxMessageSize+"\r\n"),output.join("")},SDPUtils.generateSessionId=function(){return Math.random().toString().substr(2,21)},SDPUtils.writeSessionBoilerplate=function(sessId,sessVer,sessUser){return"v=0\r\no="+(sessUser||"thisisadapterortc")+" "+(sessId||SDPUtils.generateSessionId())+" "+(void 0!==sessVer?sessVer:2)+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},SDPUtils.writeMediaSection=function(transceiver,caps,type,stream){var sdp=SDPUtils.writeRtpDescription(transceiver.kind,caps);if(sdp+=SDPUtils.writeIceParameters(transceiver.iceGatherer.getLocalParameters())+SDPUtils.writeDtlsParameters(transceiver.dtlsTransport.getLocalParameters(),"offer"===type?"actpass":"active")+"a=mid:"+transceiver.mid+"\r\n",transceiver.direction?sdp+="a="+transceiver.direction+"\r\n":transceiver.rtpSender&&transceiver.rtpReceiver?sdp+="a=sendrecv\r\n":transceiver.rtpSender?sdp+="a=sendonly\r\n":transceiver.rtpReceiver?sdp+="a=recvonly\r\n":sdp+="a=inactive\r\n",transceiver.rtpSender){var msid="msid:"+stream.id+" "+transceiver.rtpSender.track.id+"\r\n";sdp+="a="+msid+("a=ssrc:"+transceiver.sendEncodingParameters[0].ssrc)+" "+msid,transceiver.sendEncodingParameters[0].rtx&&(sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].rtx.ssrc+" "+msid+("a=ssrc-group:FID "+transceiver.sendEncodingParameters[0].ssrc+" ")+transceiver.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].ssrc+" cname:"+SDPUtils.localCName+"\r\n",transceiver.rtpSender&&transceiver.sendEncodingParameters[0].rtx&&(sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].rtx.ssrc+" cname:"+SDPUtils.localCName+"\r\n"),sdp},SDPUtils.getDirection=function(mediaSection,sessionpart){for(var lines=SDPUtils.splitLines(mediaSection),i=0;i<lines.length;i++)switch(lines[i]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return lines[i].substr(2)}return sessionpart?SDPUtils.getDirection(sessionpart):"sendrecv"},SDPUtils.getKind=function(mediaSection){return SDPUtils.splitLines(mediaSection)[0].split(" ")[0].substr(2)},SDPUtils.isRejected=function(mediaSection){return"0"===mediaSection.split(" ",2)[1]},SDPUtils.parseMLine=function(mediaSection){var parts=SDPUtils.splitLines(mediaSection)[0].substr(2).split(" ");return{kind:parts[0],port:parseInt(parts[1],10),protocol:parts[2],fmt:parts.slice(3).join(" ")}},SDPUtils.parseOLine=function(mediaSection){var parts=SDPUtils.matchPrefix(mediaSection,"o=")[0].substr(2).split(" ");return{username:parts[0],sessionId:parts[1],sessionVersion:parseInt(parts[2],10),netType:parts[3],addressType:parts[4],address:parts[5]}},SDPUtils.isValidSDP=function(blob){if("string"!=typeof blob||0===blob.length)return!1;for(var lines=SDPUtils.splitLines(blob),i=0;i<lines.length;i++)if(lines[i].length<2||"="!==lines[i].charAt(1))return!1;return!0},"object"==typeof module&&(module.exports=SDPUtils)},{}],176:[function(require1,module,exports){module.exports=Stream;var EE=require1("events").EventEmitter;function Stream(){EE.call(this)}require1("inherits")(Stream,EE),Stream.Readable=require1("readable-stream/readable.js"),Stream.Writable=require1("readable-stream/writable.js"),Stream.Duplex=require1("readable-stream/duplex.js"),Stream.Transform=require1("readable-stream/transform.js"),Stream.PassThrough=require1("readable-stream/passthrough.js"),Stream.Stream=Stream,Stream.prototype.pipe=function(dest,options){var source=this;function ondata(chunk){dest.writable&&!1===dest.write(chunk)&&source.pause&&source.pause()}function ondrain(){source.readable&&source.resume&&source.resume()}source.on("data",ondata),dest.on("drain",ondrain),dest._isStdio||options&&!1===options.end||(source.on("end",onend),source.on("close",onclose));var didOnEnd=!1;function onend(){didOnEnd||(didOnEnd=!0,dest.end())}function onclose(){didOnEnd||(didOnEnd=!0,"function"==typeof dest.destroy&&dest.destroy())}function onerror(er){if(cleanup(),0===EE.listenerCount(this,"error"))throw er}function cleanup(){source.removeListener("data",ondata),dest.removeListener("drain",ondrain),source.removeListener("end",onend),source.removeListener("close",onclose),source.removeListener("error",onerror),dest.removeListener("error",onerror),source.removeListener("end",cleanup),source.removeListener("close",cleanup),dest.removeListener("close",cleanup)}return source.on("error",onerror),dest.on("error",onerror),source.on("end",cleanup),source.on("close",cleanup),dest.on("close",cleanup),dest.emit("pipe",source),dest}},{events:80,inherits:85,"readable-stream/duplex.js":177,"readable-stream/passthrough.js":186,"readable-stream/readable.js":187,"readable-stream/transform.js":188,"readable-stream/writable.js":189}],177:[function(require1,module,exports){module.exports=require1("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":178}],178:[function(require1,module,exports){arguments[4][34][0].apply(exports,arguments)},{"./_stream_readable":180,"./_stream_writable":182,"core-util-is":49,dup:34,inherits:85,"process-nextick-args":151}],179:[function(require1,module,exports){arguments[4][35][0].apply(exports,arguments)},{"./_stream_transform":181,"core-util-is":49,dup:35,inherits:85}],180:[function(require1,module,exports){arguments[4][36][0].apply(exports,arguments)},{"./_stream_duplex":178,"./internal/streams/BufferList":183,"./internal/streams/destroy":184,"./internal/streams/stream":185,_process:152,"core-util-is":49,dup:36,events:80,inherits:85,isarray:88,"process-nextick-args":151,"safe-buffer":190,"string_decoder/":191,util:29}],181:[function(require1,module,exports){arguments[4][37][0].apply(exports,arguments)},{"./_stream_duplex":178,"core-util-is":49,dup:37,inherits:85}],182:[function(require1,module,exports){arguments[4][38][0].apply(exports,arguments)},{"./_stream_duplex":178,"./internal/streams/destroy":184,"./internal/streams/stream":185,_process:152,"core-util-is":49,dup:38,inherits:85,"process-nextick-args":151,"safe-buffer":190,timers:210,"util-deprecate":214}],183:[function(require1,module,exports){arguments[4][39][0].apply(exports,arguments)},{dup:39,"safe-buffer":190,util:29}],184:[function(require1,module,exports){arguments[4][40][0].apply(exports,arguments)},{dup:40,"process-nextick-args":151}],185:[function(require1,module,exports){arguments[4][41][0].apply(exports,arguments)},{dup:41,events:80}],186:[function(require1,module,exports){module.exports=require1("./readable").PassThrough},{"./readable":187}],187:[function(require1,module,exports){arguments[4][43][0].apply(exports,arguments)},{"./lib/_stream_duplex.js":178,"./lib/_stream_passthrough.js":179,"./lib/_stream_readable.js":180,"./lib/_stream_transform.js":181,"./lib/_stream_writable.js":182,dup:43}],188:[function(require1,module,exports){arguments[4][44][0].apply(exports,arguments)},{"./readable":187,dup:44}],189:[function(require1,module,exports){module.exports=require1("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":182}],190:[function(require1,module,exports){arguments[4][45][0].apply(exports,arguments)},{buffer:47,dup:45}],191:[function(require1,module,exports){arguments[4][42][0].apply(exports,arguments)},{dup:42,"safe-buffer":190}],192:[function(require1,module,exports){(function(global){(function(){var ClientRequest=require1("./lib/request"),response=require1("./lib/response"),extend=require1("xtend"),statusCodes=require1("builtin-status-codes"),url=require1("url");exports.request=function(opts,cb){opts="string"==typeof opts?url.parse(opts):extend(opts);var defaultProtocol=-1===global.location.protocol.search(/^https?:$/)?"http:":"",protocol=opts.protocol||defaultProtocol,host=opts.hostname||opts.host,port=opts.port,path=opts.path||"/";host&&-1!==host.indexOf(":")&&(host="["+host+"]"),opts.url=(host?protocol+"//"+host:"")+(port?":"+port:"")+path,opts.method=(opts.method||"GET").toUpperCase(),opts.headers=opts.headers||{};var req=new ClientRequest(opts);return cb&&req.on("response",cb),req},exports.get=function get(opts,cb){var req=exports.request(opts,cb);return req.end(),req},exports.ClientRequest=ClientRequest,exports.IncomingMessage=response.IncomingMessage,exports.Agent=function(){},exports.Agent.defaultMaxSockets=4,exports.globalAgent=new exports.Agent,exports.STATUS_CODES=statusCodes,exports.METHODS=["CHECKOUT","CONNECT","COPY","DELETE","GET","HEAD","LOCK","M-SEARCH","MERGE","MKACTIVITY","MKCOL","MOVE","NOTIFY","OPTIONS","PATCH","POST","PROPFIND","PROPPATCH","PURGE","PUT","REPORT","SEARCH","SUBSCRIBE","TRACE","UNLOCK","UNSUBSCRIBE"]}).call(this)}).call(this,void 0!==__webpack_require__.g?__webpack_require__.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./lib/request":194,"./lib/response":195,"builtin-status-codes":48,url:212,xtend:233}],193:[function(require1,module,exports){(function(global){(function(){exports.fetch=isFunction(global.fetch)&&isFunction(global.ReadableStream),exports.writableStream=isFunction(global.WritableStream),exports.abortController=isFunction(global.AbortController),exports.blobConstructor=!1;try{new Blob([new ArrayBuffer(1)]),exports.blobConstructor=!0}catch(e){}function getXHR(){if(void 0!==xhr)return xhr;if(global.XMLHttpRequest){xhr=new global.XMLHttpRequest;try{xhr.open("GET",global.XDomainRequest?"/":"https://example.com")}catch(e){xhr=null}}else xhr=null;return xhr}function checkTypeSupport(type){var xhr=getXHR();if(!xhr)return!1;try{return xhr.responseType=type,xhr.responseType===type}catch(e){}return!1}var xhr,haveArrayBuffer=void 0!==global.ArrayBuffer,haveSlice=haveArrayBuffer&&isFunction(global.ArrayBuffer.prototype.slice);function isFunction(value){return"function"==typeof value}exports.arraybuffer=exports.fetch||haveArrayBuffer&&checkTypeSupport("arraybuffer"),exports.msstream=!exports.fetch&&haveSlice&&checkTypeSupport("ms-stream"),exports.mozchunkedarraybuffer=!exports.fetch&&haveArrayBuffer&&checkTypeSupport("moz-chunked-arraybuffer"),exports.overrideMimeType=exports.fetch||!!getXHR()&&isFunction(getXHR().overrideMimeType),exports.vbArray=isFunction(global.VBArray),xhr=null}).call(this)}).call(this,void 0!==__webpack_require__.g?__webpack_require__.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],194:[function(require1,module,exports){(function(process,global,Buffer){(function(){var capability=require1("./capability"),inherits=require1("inherits"),response=require1("./response"),stream=require1("readable-stream"),toArrayBuffer=require1("to-arraybuffer"),IncomingMessage=response.IncomingMessage,rStates=response.readyStates;function decideMode(preferBinary,useFetch){return capability.fetch&&useFetch?"fetch":capability.mozchunkedarraybuffer?"moz-chunked-arraybuffer":capability.msstream?"ms-stream":capability.arraybuffer&&preferBinary?"arraybuffer":capability.vbArray&&preferBinary?"text:vbarray":"text"}var ClientRequest=module.exports=function(opts){var preferBinary,self1=this;stream.Writable.call(self1),self1._opts=opts,self1._body=[],self1._headers={},opts.auth&&self1.setHeader("Authorization","Basic "+new Buffer(opts.auth).toString("base64")),Object.keys(opts.headers).forEach(function(name){self1.setHeader(name,opts.headers[name])});var useFetch=!0;if("disable-fetch"===opts.mode||"requestTimeout"in opts&&!capability.abortController)useFetch=!1,preferBinary=!0;else if("prefer-streaming"===opts.mode)preferBinary=!1;else if("allow-wrong-content-type"===opts.mode)preferBinary=!capability.overrideMimeType;else if(opts.mode&&"default"!==opts.mode&&"prefer-fast"!==opts.mode)throw Error("Invalid value for opts.mode");else preferBinary=!0;self1._mode=decideMode(preferBinary,useFetch),self1._fetchTimer=null,self1.on("finish",function(){self1._onFinish()})};function statusValid(xhr){try{var status=xhr.status;return null!==status&&0!==status}catch(e){return!1}}inherits(ClientRequest,stream.Writable),ClientRequest.prototype.setHeader=function(name,value){var lowerName=name.toLowerCase();-1===unsafeHeaders.indexOf(lowerName)&&(this._headers[lowerName]={name:name,value:value})},ClientRequest.prototype.getHeader=function(name){var header=this._headers[name.toLowerCase()];return header?header.value:null},ClientRequest.prototype.removeHeader=function(name){delete this._headers[name.toLowerCase()]},ClientRequest.prototype._onFinish=function(){var self1=this;if(!self1._destroyed){var opts=self1._opts,headersObj=self1._headers,body=null;"GET"!==opts.method&&"HEAD"!==opts.method&&(body=capability.arraybuffer?toArrayBuffer(Buffer.concat(self1._body)):capability.blobConstructor?new global.Blob(self1._body.map(function(buffer){return toArrayBuffer(buffer)}),{type:(headersObj["content-type"]||{}).value||""}):Buffer.concat(self1._body).toString());var headersList=[];if(Object.keys(headersObj).forEach(function(keyName){var name=headersObj[keyName].name,value=headersObj[keyName].value;Array.isArray(value)?value.forEach(function(v){headersList.push([name,v])}):headersList.push([name,value])}),"fetch"===self1._mode){var signal=null;if(capability.abortController){var controller=new AbortController;signal=controller.signal,self1._fetchAbortController=controller,"requestTimeout"in opts&&0!==opts.requestTimeout&&(self1._fetchTimer=global.setTimeout(function(){self1.emit("requestTimeout"),self1._fetchAbortController&&self1._fetchAbortController.abort()},opts.requestTimeout))}global.fetch(self1._opts.url,{method:self1._opts.method,headers:headersList,body:body||void 0,mode:"cors",credentials:opts.withCredentials?"include":"same-origin",signal:signal}).then(function(response){self1._fetchResponse=response,self1._connect()},function(reason){global.clearTimeout(self1._fetchTimer),self1._destroyed||self1.emit("error",reason)})}else{var xhr=self1._xhr=new global.XMLHttpRequest;try{xhr.open(self1._opts.method,self1._opts.url,!0)}catch(err){process.nextTick(function(){self1.emit("error",err)});return}"responseType"in xhr&&(xhr.responseType=self1._mode.split(":")[0]),"withCredentials"in xhr&&(xhr.withCredentials=!!opts.withCredentials),"text"===self1._mode&&"overrideMimeType"in xhr&&xhr.overrideMimeType("text/plain; charset=x-user-defined"),"requestTimeout"in opts&&(xhr.timeout=opts.requestTimeout,xhr.ontimeout=function(){self1.emit("requestTimeout")}),headersList.forEach(function(header){xhr.setRequestHeader(header[0],header[1])}),self1._response=null,xhr.onreadystatechange=function(){switch(xhr.readyState){case rStates.LOADING:case rStates.DONE:self1._onXHRProgress()}},"moz-chunked-arraybuffer"===self1._mode&&(xhr.onprogress=function(){self1._onXHRProgress()}),xhr.onerror=function(){self1._destroyed||self1.emit("error",Error("XHR error"))};try{xhr.send(body)}catch(err){process.nextTick(function(){self1.emit("error",err)});return}}}},ClientRequest.prototype._onXHRProgress=function(){statusValid(this._xhr)&&!this._destroyed&&(this._response||this._connect(),this._response._onXHRProgress())},ClientRequest.prototype._connect=function(){var self1=this;self1._destroyed||(self1._response=new IncomingMessage(self1._xhr,self1._fetchResponse,self1._mode,self1._fetchTimer),self1._response.on("error",function(err){self1.emit("error",err)}),self1.emit("response",self1._response))},ClientRequest.prototype._write=function(chunk,encoding,cb){this._body.push(chunk),cb()},ClientRequest.prototype.abort=ClientRequest.prototype.destroy=function(){this._destroyed=!0,global.clearTimeout(this._fetchTimer),this._response&&(this._response._destroyed=!0),this._xhr?this._xhr.abort():this._fetchAbortController&&this._fetchAbortController.abort()},ClientRequest.prototype.end=function(data,encoding,cb){"function"==typeof data&&(cb=data,data=void 0),stream.Writable.prototype.end.call(this,data,encoding,cb)},ClientRequest.prototype.flushHeaders=function(){},ClientRequest.prototype.setTimeout=function(){},ClientRequest.prototype.setNoDelay=function(){},ClientRequest.prototype.setSocketKeepAlive=function(){};var unsafeHeaders=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","cookie","cookie2","date","dnt","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"]}).call(this)}).call(this,require1("_process"),void 0!==__webpack_require__.g?__webpack_require__.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},require1("buffer").Buffer)},{"./capability":193,"./response":195,_process:152,buffer:47,inherits:85,"readable-stream":204,"to-arraybuffer":211}],195:[function(require1,module,exports){(function(process,global,Buffer){(function(){var capability=require1("./capability"),inherits=require1("inherits"),stream=require1("readable-stream"),rStates=exports.readyStates={UNSENT:0,OPENED:1,HEADERS_RECEIVED:2,LOADING:3,DONE:4},IncomingMessage=exports.IncomingMessage=function(xhr,response,mode,fetchTimer){var self1=this;if(stream.Readable.call(self1),self1._mode=mode,self1.headers={},self1.rawHeaders=[],self1.trailers={},self1.rawTrailers=[],self1.on("end",function(){process.nextTick(function(){self1.emit("close")})}),"fetch"===mode){if(self1._fetchResponse=response,self1.url=response.url,self1.statusCode=response.status,self1.statusMessage=response.statusText,response.headers.forEach(function(header,key){self1.headers[key.toLowerCase()]=header,self1.rawHeaders.push(key,header)}),capability.writableStream){var writable=new WritableStream({write:function(chunk){return new Promise(function(resolve,reject){self1._destroyed?reject():self1.push(new Buffer(chunk))?resolve():self1._resumeFetch=resolve})},close:function(){global.clearTimeout(fetchTimer),self1._destroyed||self1.push(null)},abort:function(err){self1._destroyed||self1.emit("error",err)}});try{response.body.pipeTo(writable).catch(function(err){global.clearTimeout(fetchTimer),self1._destroyed||self1.emit("error",err)});return}catch(e){}}var reader=response.body.getReader();function read(){reader.read().then(function(result){if(!self1._destroyed){if(result.done){global.clearTimeout(fetchTimer),self1.push(null);return}self1.push(new Buffer(result.value)),read()}}).catch(function(err){global.clearTimeout(fetchTimer),self1._destroyed||self1.emit("error",err)})}read()}else if(self1._xhr=xhr,self1._pos=0,self1.url=xhr.responseURL,self1.statusCode=xhr.status,self1.statusMessage=xhr.statusText,xhr.getAllResponseHeaders().split(/\r?\n/).forEach(function(header){var matches=header.match(/^([^:]+):\s*(.*)/);if(matches){var key=matches[1].toLowerCase();"set-cookie"===key?(void 0===self1.headers[key]&&(self1.headers[key]=[]),self1.headers[key].push(matches[2])):void 0!==self1.headers[key]?self1.headers[key]+=", "+matches[2]:self1.headers[key]=matches[2],self1.rawHeaders.push(matches[1],matches[2])}}),self1._charset="x-user-defined",!capability.overrideMimeType){var mimeType=self1.rawHeaders["mime-type"];if(mimeType){var charsetMatch=mimeType.match(/;\s*charset=([^;])(;|$)/);charsetMatch&&(self1._charset=charsetMatch[1].toLowerCase())}self1._charset||(self1._charset="utf-8")}};inherits(IncomingMessage,stream.Readable),IncomingMessage.prototype._read=function(){var resolve=this._resumeFetch;resolve&&(this._resumeFetch=null,resolve())},IncomingMessage.prototype._onXHRProgress=function(){var self1=this,xhr=self1._xhr,response=null;switch(self1._mode){case"text:vbarray":if(xhr.readyState!==rStates.DONE)break;try{response=new global.VBArray(xhr.responseBody).toArray()}catch(e){}if(null!==response){self1.push(new Buffer(response));break}case"text":try{response=xhr.responseText}catch(e){self1._mode="text:vbarray";break}if(response.length>self1._pos){var newData=response.substr(self1._pos);if("x-user-defined"===self1._charset){for(var buffer=new Buffer(newData.length),i=0;i<newData.length;i++)buffer[i]=255&newData.charCodeAt(i);self1.push(buffer)}else self1.push(newData,self1._charset);self1._pos=response.length}break;case"arraybuffer":if(xhr.readyState!==rStates.DONE||!xhr.response)break;response=xhr.response,self1.push(new Buffer(new Uint8Array(response)));break;case"moz-chunked-arraybuffer":if(response=xhr.response,xhr.readyState!==rStates.LOADING||!response)break;self1.push(new Buffer(new Uint8Array(response)));break;case"ms-stream":if(response=xhr.response,xhr.readyState!==rStates.LOADING)break;var reader=new global.MSStreamReader;reader.onprogress=function(){reader.result.byteLength>self1._pos&&(self1.push(new Buffer(new Uint8Array(reader.result.slice(self1._pos)))),self1._pos=reader.result.byteLength)},reader.onload=function(){self1.push(null)},reader.readAsArrayBuffer(response)}self1._xhr.readyState===rStates.DONE&&"ms-stream"!==self1._mode&&self1.push(null)}}).call(this)}).call(this,require1("_process"),void 0!==__webpack_require__.g?__webpack_require__.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},require1("buffer").Buffer)},{"./capability":193,_process:152,buffer:47,inherits:85,"readable-stream":204}],196:[function(require1,module,exports){arguments[4][34][0].apply(exports,arguments)},{"./_stream_readable":198,"./_stream_writable":200,"core-util-is":49,dup:34,inherits:85,"process-nextick-args":151}],197:[function(require1,module,exports){arguments[4][35][0].apply(exports,arguments)},{"./_stream_transform":199,"core-util-is":49,dup:35,inherits:85}],198:[function(require1,module,exports){arguments[4][36][0].apply(exports,arguments)},{"./_stream_duplex":196,"./internal/streams/BufferList":201,"./internal/streams/destroy":202,"./internal/streams/stream":203,_process:152,"core-util-is":49,dup:36,events:80,inherits:85,isarray:88,"process-nextick-args":151,"safe-buffer":205,"string_decoder/":206,util:29}],199:[function(require1,module,exports){arguments[4][37][0].apply(exports,arguments)},{"./_stream_duplex":196,"core-util-is":49,dup:37,inherits:85}],200:[function(require1,module,exports){arguments[4][38][0].apply(exports,arguments)},{"./_stream_duplex":196,"./internal/streams/destroy":202,"./internal/streams/stream":203,_process:152,"core-util-is":49,dup:38,inherits:85,"process-nextick-args":151,"safe-buffer":205,timers:210,"util-deprecate":214}],201:[function(require1,module,exports){arguments[4][39][0].apply(exports,arguments)},{dup:39,"safe-buffer":205,util:29}],202:[function(require1,module,exports){arguments[4][40][0].apply(exports,arguments)},{dup:40,"process-nextick-args":151}],203:[function(require1,module,exports){arguments[4][41][0].apply(exports,arguments)},{dup:41,events:80}],204:[function(require1,module,exports){arguments[4][43][0].apply(exports,arguments)},{"./lib/_stream_duplex.js":196,"./lib/_stream_passthrough.js":197,"./lib/_stream_readable.js":198,"./lib/_stream_transform.js":199,"./lib/_stream_writable.js":200,dup:43}],205:[function(require1,module,exports){arguments[4][45][0].apply(exports,arguments)},{buffer:47,dup:45}],206:[function(require1,module,exports){arguments[4][42][0].apply(exports,arguments)},{dup:42,"safe-buffer":205}],207:[function(require1,module,exports){arguments[4][42][0].apply(exports,arguments)},{dup:42,"safe-buffer":173}],208:[function(require1,module,exports){(function(global){(function(){var global1,factory;global1=this,factory=function(exports){"use strict";var global$1=void 0!==global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};let WebSocket=function getWebSocketImplementation(){let WebSocketImplementation=global$1.WebSocket;if(void 0===WebSocketImplementation)try{WebSocketImplementation=require1("ws")}catch(err){throw Error('You must install the "ws" package to use Strophe in nodejs.')}return WebSocketImplementation}(),DOMParser1=function getDOMParserImplementation(){let DOMParserImplementation=global$1.DOMParser;if(void 0===DOMParserImplementation)try{DOMParserImplementation=require1("@xmldom/xmldom").DOMParser}catch(err){throw Error('You must install the "@xmldom/xmldom" package to use Strophe in nodejs.')}return DOMParserImplementation}();function _getIEXmlDom(){let docStrings=["Msxml2.DOMDocument.6.0","Msxml2.DOMDocument.5.0","Msxml2.DOMDocument.4.0","MSXML2.DOMDocument.3.0","MSXML2.DOMDocument","MSXML.DOMDocument","Microsoft.XMLDOM"];for(let d=0;d<docStrings.length;d++)try{return new ActiveXObject(docStrings[d])}catch(e){}}function getDummyXMLDOMDocument(){if("undefined"==typeof document)try{return new(require1("@xmldom/xmldom")).DOMImplementation().createDocument("jabber:client","strophe",null)}catch(err){throw Error('You must install the "@xmldom/xmldom" package to use Strophe in nodejs.')}if(void 0===document.implementation.createDocument||document.implementation.createDocument&&document.documentMode&&document.documentMode<10){let doc=_getIEXmlDom();return doc.appendChild(doc.createElement("strophe")),doc}return document.implementation.createDocument("jabber:client","strophe",null)}let safe_add$1=function(x,y){let lsw=(65535&x)+(65535&y);return(x>>16)+(y>>16)+(lsw>>16)<<16|65535&lsw},str2binl=function(str){if("string"!=typeof str)throw Error("str2binl was passed a non-string");let bin=[];for(let i=0;i<8*str.length;i+=8)bin[i>>5]|=(255&str.charCodeAt(i/8))<<i%32;return bin},binl2str=function(bin){let str="";for(let i=0;i<32*bin.length;i+=8)str+=String.fromCharCode(bin[i>>5]>>>i%32&255);return str},binl2hex=function(binarray){let hex_tab="0123456789abcdef",str="";for(let i=0;i<4*binarray.length;i++)str+=hex_tab.charAt(binarray[i>>2]>>i%4*8+4&15)+hex_tab.charAt(binarray[i>>2]>>i%4*8&15);return str},md5_cmn=function(q,a,b,x,s,t){var num;return safe_add$1((num=safe_add$1(safe_add$1(a,q),safe_add$1(x,t)))<<s|num>>>32-s,b)},md5_ff=function(a,b,c,d,x,s,t){return md5_cmn(b&c|~b&d,a,b,x,s,t)},md5_gg=function(a,b,c,d,x,s,t){return md5_cmn(b&d|c&~d,a,b,x,s,t)},md5_hh=function(a,b,c,d,x,s,t){return md5_cmn(b^c^d,a,b,x,s,t)},md5_ii=function(a,b,c,d,x,s,t){return md5_cmn(c^(b|~d),a,b,x,s,t)},core_md5=function(x,len){let olda,oldb,oldc,oldd;x[len>>5]|=128<<len%32,x[(len+64>>>9<<4)+14]=len;let a=1732584193,b=-271733879,c=-1732584194,d=271733878;for(let i=0;i<x.length;i+=16)olda=a,oldb=b,oldc=c,oldd=d,a=md5_ff(a,b,c,d,x[i+0],7,-680876936),d=md5_ff(d,a,b,c,x[i+1],12,-389564586),c=md5_ff(c,d,a,b,x[i+2],17,606105819),b=md5_ff(b,c,d,a,x[i+3],22,-1044525330),a=md5_ff(a,b,c,d,x[i+4],7,-176418897),d=md5_ff(d,a,b,c,x[i+5],12,1200080426),c=md5_ff(c,d,a,b,x[i+6],17,-1473231341),b=md5_ff(b,c,d,a,x[i+7],22,-45705983),a=md5_ff(a,b,c,d,x[i+8],7,1770035416),d=md5_ff(d,a,b,c,x[i+9],12,-1958414417),c=md5_ff(c,d,a,b,x[i+10],17,-42063),b=md5_ff(b,c,d,a,x[i+11],22,-1990404162),a=md5_ff(a,b,c,d,x[i+12],7,1804603682),d=md5_ff(d,a,b,c,x[i+13],12,-40341101),c=md5_ff(c,d,a,b,x[i+14],17,-1502002290),b=md5_ff(b,c,d,a,x[i+15],22,1236535329),a=md5_gg(a,b,c,d,x[i+1],5,-165796510),d=md5_gg(d,a,b,c,x[i+6],9,-1069501632),c=md5_gg(c,d,a,b,x[i+11],14,643717713),b=md5_gg(b,c,d,a,x[i+0],20,-373897302),a=md5_gg(a,b,c,d,x[i+5],5,-701558691),d=md5_gg(d,a,b,c,x[i+10],9,38016083),c=md5_gg(c,d,a,b,x[i+15],14,-660478335),b=md5_gg(b,c,d,a,x[i+4],20,-405537848),a=md5_gg(a,b,c,d,x[i+9],5,568446438),d=md5_gg(d,a,b,c,x[i+14],9,-1019803690),c=md5_gg(c,d,a,b,x[i+3],14,-187363961),b=md5_gg(b,c,d,a,x[i+8],20,1163531501),a=md5_gg(a,b,c,d,x[i+13],5,-1444681467),d=md5_gg(d,a,b,c,x[i+2],9,-51403784),c=md5_gg(c,d,a,b,x[i+7],14,1735328473),b=md5_gg(b,c,d,a,x[i+12],20,-1926607734),a=md5_hh(a,b,c,d,x[i+5],4,-378558),d=md5_hh(d,a,b,c,x[i+8],11,-2022574463),c=md5_hh(c,d,a,b,x[i+11],16,1839030562),b=md5_hh(b,c,d,a,x[i+14],23,-35309556),a=md5_hh(a,b,c,d,x[i+1],4,-1530992060),d=md5_hh(d,a,b,c,x[i+4],11,1272893353),c=md5_hh(c,d,a,b,x[i+7],16,-155497632),b=md5_hh(b,c,d,a,x[i+10],23,-1094730640),a=md5_hh(a,b,c,d,x[i+13],4,681279174),d=md5_hh(d,a,b,c,x[i+0],11,-358537222),c=md5_hh(c,d,a,b,x[i+3],16,-722521979),b=md5_hh(b,c,d,a,x[i+6],23,76029189),a=md5_hh(a,b,c,d,x[i+9],4,-640364487),d=md5_hh(d,a,b,c,x[i+12],11,-421815835),c=md5_hh(c,d,a,b,x[i+15],16,530742520),b=md5_hh(b,c,d,a,x[i+2],23,-995338651),a=md5_ii(a,b,c,d,x[i+0],6,-198630844),d=md5_ii(d,a,b,c,x[i+7],10,1126891415),c=md5_ii(c,d,a,b,x[i+14],15,-1416354905),b=md5_ii(b,c,d,a,x[i+5],21,-57434055),a=md5_ii(a,b,c,d,x[i+12],6,1700485571),d=md5_ii(d,a,b,c,x[i+3],10,-1894986606),c=md5_ii(c,d,a,b,x[i+10],15,-1051523),b=md5_ii(b,c,d,a,x[i+1],21,-2054922799),a=md5_ii(a,b,c,d,x[i+8],6,1873313359),d=md5_ii(d,a,b,c,x[i+15],10,-30611744),c=md5_ii(c,d,a,b,x[i+6],15,-1560198380),b=md5_ii(b,c,d,a,x[i+13],21,1309151649),a=md5_ii(a,b,c,d,x[i+4],6,-145523070),d=md5_ii(d,a,b,c,x[i+11],10,-1120210379),c=md5_ii(c,d,a,b,x[i+2],15,718787259),b=md5_ii(b,c,d,a,x[i+9],21,-343485551),a=safe_add$1(a,olda),b=safe_add$1(b,oldb),c=safe_add$1(c,oldc),d=safe_add$1(d,oldd);return[a,b,c,d]},MD5={hexdigest:function(s){return binl2hex(core_md5(str2binl(s),8*s.length))},hash:function(s){return binl2str(core_md5(str2binl(s),8*s.length))}};class SASLMechanism{constructor(name,isClientFirst,priority){this.mechname=name,this.isClientFirst=isClientFirst,this.priority=priority}test(){return!0}onStart(connection){this._connection=connection}onChallenge(connection,challenge){throw Error("You should implement challenge handling!")}clientChallenge(connection){if(!this.isClientFirst)throw Error("clientChallenge should not be called if isClientFirst is false!");return this.onChallenge(connection)}onFailure(){this._connection=null}onSuccess(){this._connection=null}}let utils={utf16to8:function(str){var i,c,out="",len=str.length;for(i=0;i<len;i++)(c=str.charCodeAt(i))>=0&&c<=127?out+=str.charAt(i):c>2047?out+=String.fromCharCode(224|c>>12&15)+String.fromCharCode(128|c>>6&63)+String.fromCharCode(128|c>>0&63):out+=String.fromCharCode(192|c>>6&31)+String.fromCharCode(128|c>>0&63);return out},addCookies:function(cookies){for(let cookieName in cookies=cookies||{})if(Object.prototype.hasOwnProperty.call(cookies,cookieName)){let expires="",domain="",path="",cookieObj=cookies[cookieName],isObj="object"==typeof cookieObj,cookieValue=escape(unescape(isObj?cookieObj.value:cookieObj));isObj&&(expires=cookieObj.expires?";expires="+cookieObj.expires:"",domain=cookieObj.domain?";domain="+cookieObj.domain:"",path=cookieObj.path?";path="+cookieObj.path:""),document.cookie=cookieName+"="+cookieValue+expires+domain+path}}};function core_sha1(x,len){x[len>>5]|=128<<24-len%32,x[(len+64>>9<<4)+15]=len;var i,j,t,olda,oldb,oldc,oldd,olde,w=Array(80),a=1732584193,b=-271733879,c=-1732584194,d=271733878,e=-1009589776;for(i=0;i<x.length;i+=16){for(j=0,olda=a,oldb=b,oldc=c,oldd=d,olde=e;j<80;j++)j<16?w[j]=x[i+j]:w[j]=rol(w[j-3]^w[j-8]^w[j-14]^w[j-16],1),t=safe_add(safe_add(rol(a,5),sha1_ft(j,b,c,d)),safe_add(safe_add(e,w[j]),sha1_kt(j))),e=d,d=c,c=rol(b,30),b=a,a=t;a=safe_add(a,olda),b=safe_add(b,oldb),c=safe_add(c,oldc),d=safe_add(d,oldd),e=safe_add(e,olde)}return[a,b,c,d,e]}function sha1_ft(t,b,c,d){return t<20?b&c|~b&d:t<40?b^c^d:t<60?b&c|b&d|c&d:b^c^d}function sha1_kt(t){return t<20?1518500249:t<40?1859775393:t<60?-1894007588:-899497514}function core_hmac_sha1(key,data){var bkey=str2binb(key);bkey.length>16&&(bkey=core_sha1(bkey,8*key.length));for(var ipad=Array(16),opad=Array(16),i=0;i<16;i++)ipad[i]=909522486^bkey[i],opad[i]=1549556828^bkey[i];var hash=core_sha1(ipad.concat(str2binb(data)),512+8*data.length);return core_sha1(opad.concat(hash),672)}function safe_add(x,y){var lsw=(65535&x)+(65535&y);return(x>>16)+(y>>16)+(lsw>>16)<<16|65535&lsw}function rol(num,cnt){return num<<cnt|num>>>32-cnt}function str2binb(str){for(var bin=[],i=0;i<8*str.length;i+=8)bin[i>>5]|=(255&str.charCodeAt(i/8))<<24-i%32;return bin}function binb2b64(binarray){for(var triplet,j,str="",i=0;i<4*binarray.length;i+=3)for(j=0,triplet=(binarray[i>>2]>>8*(3-i%4)&255)<<16|(binarray[i+1>>2]>>8*(3-(i+1)%4)&255)<<8|binarray[i+2>>2]>>8*(3-(i+2)%4)&255;j<4;j++)8*i+6*j>32*binarray.length?str+="=":str+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(triplet>>6*(3-j)&63);return str}function binb2str(bin){for(var str="",i=0;i<32*bin.length;i+=8)str+=String.fromCharCode(bin[i>>5]>>>24-i%32&255);return str}let SHA1={b64_hmac_sha1:function(key,data){return binb2b64(core_hmac_sha1(key,data))},b64_sha1:function(s){return binb2b64(core_sha1(str2binb(s),8*s.length))},binb2str:binb2str,core_hmac_sha1:core_hmac_sha1,str_hmac_sha1:function(key,data){return binb2str(core_hmac_sha1(key,data))},str_sha1:function(s){return binb2str(core_sha1(str2binb(s),8*s.length))}};function atobLookup(chr){let index="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(chr);return index<0?void 0:index}function btoaLookup(index){if(index>=0&&index<64)return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[index]}var abab={atob:function atob$2(data){if(0==arguments.length)throw TypeError("1 argument required, but only 0 present.");if((data=(data=`${data}`).replace(/[ \t\n\f\r]/g,"")).length%4==0&&(data=data.replace(/==?$/,"")),data.length%4==1||/[^+/0-9A-Za-z]/.test(data))return null;let output="",buffer=0,accumulatedBits=0;for(let i=0;i<data.length;i++)buffer<<=6,buffer|=atobLookup(data[i]),24===(accumulatedBits+=6)&&(output+=String.fromCharCode((16711680&buffer)>>16)+String.fromCharCode((65280&buffer)>>8)+String.fromCharCode(255&buffer),buffer=accumulatedBits=0);return 12===accumulatedBits?(buffer>>=4,output+=String.fromCharCode(buffer)):18===accumulatedBits&&(buffer>>=2,output+=String.fromCharCode((65280&buffer)>>8)+String.fromCharCode(255&buffer)),output},btoa:function btoa$2(s){let i;if(0==arguments.length)throw TypeError("1 argument required, but only 0 present.");for(i=0,s=`${s}`;i<s.length;i++)if(s.charCodeAt(i)>255)return null;let out="";for(i=0;i<s.length;i+=3){let groupsOfSix=[void 0,void 0,void 0,void 0];groupsOfSix[0]=s.charCodeAt(i)>>2,groupsOfSix[1]=(3&s.charCodeAt(i))<<4,s.length>i+1&&(groupsOfSix[1]|=s.charCodeAt(i+1)>>4,groupsOfSix[2]=(15&s.charCodeAt(i+1))<<2),s.length>i+2&&(groupsOfSix[2]|=s.charCodeAt(i+2)>>6,groupsOfSix[3]=63&s.charCodeAt(i+2));for(let j=0;j<groupsOfSix.length;j++)void 0===groupsOfSix[j]?out+="=":out+=btoaLookup(groupsOfSix[j])}return out}};function $build1(name,attrs){return new Strophe1.Builder(name,attrs)}function $msg1(attrs){return new Strophe1.Builder("message",attrs)}function $iq1(attrs){return new Strophe1.Builder("iq",attrs)}function $pres1(attrs){return new Strophe1.Builder("presence",attrs)}let Strophe1={VERSION:"1.5.0",NS:{HTTPBIND:"http://jabber.org/protocol/httpbind",BOSH:"urn:xmpp:xbosh",CLIENT:"jabber:client",AUTH:"jabber:iq:auth",ROSTER:"jabber:iq:roster",PROFILE:"jabber:iq:profile",DISCO_INFO:"http://jabber.org/protocol/disco#info",DISCO_ITEMS:"http://jabber.org/protocol/disco#items",MUC:"http://jabber.org/protocol/muc",SASL:"urn:ietf:params:xml:ns:xmpp-sasl",STREAM:"http://etherx.jabber.org/streams",FRAMING:"urn:ietf:params:xml:ns:xmpp-framing",BIND:"urn:ietf:params:xml:ns:xmpp-bind",SESSION:"urn:ietf:params:xml:ns:xmpp-session",VERSION:"jabber:iq:version",STANZAS:"urn:ietf:params:xml:ns:xmpp-stanzas",XHTML_IM:"http://jabber.org/protocol/xhtml-im",XHTML:"http://www.w3.org/1999/xhtml"},XHTML:{tags:["a","blockquote","br","cite","em","img","li","ol","p","span","strong","ul","body"],attributes:{a:["href"],blockquote:["style"],br:[],cite:["style"],em:[],img:["src","alt","style","height","width"],li:["style"],ol:["style"],p:["style"],span:["style"],strong:[],ul:["style"],body:[]},css:["background-color","color","font-family","font-size","font-style","font-weight","margin-left","margin-right","text-align","text-decoration"],validTag(tag){for(let i=0;i<Strophe1.XHTML.tags.length;i++)if(tag===Strophe1.XHTML.tags[i])return!0;return!1},validAttribute(tag,attribute){if(void 0!==Strophe1.XHTML.attributes[tag]&&Strophe1.XHTML.attributes[tag].length>0){for(let i=0;i<Strophe1.XHTML.attributes[tag].length;i++)if(attribute===Strophe1.XHTML.attributes[tag][i])return!0}return!1},validCSS(style){for(let i=0;i<Strophe1.XHTML.css.length;i++)if(style===Strophe1.XHTML.css[i])return!0;return!1}},Status:{ERROR:0,CONNECTING:1,CONNFAIL:2,AUTHENTICATING:3,AUTHFAIL:4,CONNECTED:5,DISCONNECTED:6,DISCONNECTING:7,ATTACHED:8,REDIRECT:9,CONNTIMEOUT:10,BINDREQUIRED:11,ATTACHFAIL:12},ErrorCondition:{BAD_FORMAT:"bad-format",CONFLICT:"conflict",MISSING_JID_NODE:"x-strophe-bad-non-anon-jid",NO_AUTH_MECH:"no-auth-mech",UNKNOWN_REASON:"unknown"},LogLevel:{DEBUG:0,INFO:1,WARN:2,ERROR:3,FATAL:4},ElementType:{NORMAL:1,TEXT:3,CDATA:4,FRAGMENT:11},TIMEOUT:1.1,SECONDARY_TIMEOUT:.1,addNamespace(name,value){Strophe1.NS[name]=value},forEachChild(elem,elemName,func){for(let i=0;i<elem.childNodes.length;i++){let childNode=elem.childNodes[i];childNode.nodeType===Strophe1.ElementType.NORMAL&&(!elemName||this.isTagEqual(childNode,elemName))&&func(childNode)}},isTagEqual:(el,name)=>el.tagName===name,_xmlGenerator:null,xmlGenerator:()=>(Strophe1._xmlGenerator||(Strophe1._xmlGenerator=getDummyXMLDOMDocument()),Strophe1._xmlGenerator),xmlElement(name){if(!name)return null;let node=Strophe1.xmlGenerator().createElement(name);for(let a=1;a<arguments.length;a++){let arg=arguments[a];if(arg){if("string"==typeof arg||"number"==typeof arg)node.appendChild(Strophe1.xmlTextNode(arg));else if("object"==typeof arg&&"function"==typeof arg.sort)for(let i=0;i<arg.length;i++){let attr=arg[i];"object"==typeof attr&&"function"==typeof attr.sort&&void 0!==attr[1]&&null!==attr[1]&&node.setAttribute(attr[0],attr[1])}else if("object"==typeof arg)for(let k in arg)Object.prototype.hasOwnProperty.call(arg,k)&&void 0!==arg[k]&&null!==arg[k]&&node.setAttribute(k,arg[k])}}return node},xmlescape:text=>text=(text=(text=(text=(text=text.replace(/\&/g,"&")).replace(/</g,"<")).replace(/>/g,">")).replace(/'/g,"'")).replace(/"/g,"""),xmlunescape:text=>text=(text=(text=(text=(text=text.replace(/\&/g,"&")).replace(/</g,"<")).replace(/>/g,">")).replace(/'/g,"'")).replace(/"/g,'"'),xmlTextNode:text=>Strophe1.xmlGenerator().createTextNode(text),xmlHtmlNode(html){let node;return DOMParser1?node=new DOMParser1().parseFromString(html,"text/xml"):((node=new ActiveXObject("Microsoft.XMLDOM")).async="false",node.loadXML(html)),node},getText(elem){if(!elem)return null;let str="";0===elem.childNodes.length&&elem.nodeType===Strophe1.ElementType.TEXT&&(str+=elem.nodeValue);for(let i=0;i<elem.childNodes.length;i++)elem.childNodes[i].nodeType===Strophe1.ElementType.TEXT&&(str+=elem.childNodes[i].nodeValue);return Strophe1.xmlescape(str)},copyElement(elem){let el;if(elem.nodeType===Strophe1.ElementType.NORMAL){el=Strophe1.xmlElement(elem.tagName);for(let i=0;i<elem.attributes.length;i++)el.setAttribute(elem.attributes[i].nodeName,elem.attributes[i].value);for(let i=0;i<elem.childNodes.length;i++)el.appendChild(Strophe1.copyElement(elem.childNodes[i]))}else elem.nodeType===Strophe1.ElementType.TEXT&&(el=Strophe1.xmlGenerator().createTextNode(elem.nodeValue));return el},createHtml(elem){let el;if(elem.nodeType===Strophe1.ElementType.NORMAL){let tag=elem.nodeName.toLowerCase();if(Strophe1.XHTML.validTag(tag))try{el=Strophe1.xmlElement(tag);for(let i=0;i<Strophe1.XHTML.attributes[tag].length;i++){let attribute=Strophe1.XHTML.attributes[tag][i],value=elem.getAttribute(attribute);if(null!=value&&""!==value&&!1!==value&&0!==value){if("style"===attribute&&"object"==typeof value&&void 0!==value.cssText&&(value=value.cssText),"style"===attribute){let css=[],cssAttrs=value.split(";");for(let j=0;j<cssAttrs.length;j++){let attr=cssAttrs[j].split(":"),cssName=attr[0].replace(/^\s*/,"").replace(/\s*$/,"").toLowerCase();if(Strophe1.XHTML.validCSS(cssName)){let cssValue=attr[1].replace(/^\s*/,"").replace(/\s*$/,"");css.push(cssName+": "+cssValue)}}css.length>0&&(value=css.join("; "),el.setAttribute(attribute,value))}else el.setAttribute(attribute,value)}}for(let i=0;i<elem.childNodes.length;i++)el.appendChild(Strophe1.createHtml(elem.childNodes[i]))}catch(e){el=Strophe1.xmlTextNode("")}else{el=Strophe1.xmlGenerator().createDocumentFragment();for(let i=0;i<elem.childNodes.length;i++)el.appendChild(Strophe1.createHtml(elem.childNodes[i]))}}else if(elem.nodeType===Strophe1.ElementType.FRAGMENT){el=Strophe1.xmlGenerator().createDocumentFragment();for(let i=0;i<elem.childNodes.length;i++)el.appendChild(Strophe1.createHtml(elem.childNodes[i]))}else elem.nodeType===Strophe1.ElementType.TEXT&&(el=Strophe1.xmlTextNode(elem.nodeValue));return el},escapeNode:node=>"string"!=typeof node?node:node.replace(/^\s+|\s+$/g,"").replace(/\\/g,"\\5c").replace(/ /g,"\\20").replace(/\"/g,"\\22").replace(/\&/g,"\\26").replace(/\'/g,"\\27").replace(/\//g,"\\2f").replace(/:/g,"\\3a").replace(/</g,"\\3c").replace(/>/g,"\\3e").replace(/@/g,"\\40"),unescapeNode:node=>"string"!=typeof node?node:node.replace(/\\20/g," ").replace(/\\22/g,'"').replace(/\\26/g,"&").replace(/\\27/g,"'").replace(/\\2f/g,"/").replace(/\\3a/g,":").replace(/\\3c/g,"<").replace(/\\3e/g,">").replace(/\\40/g,"@").replace(/\\5c/g,"\\"),getNodeFromJid:jid=>0>jid.indexOf("@")?null:jid.split("@")[0],getDomainFromJid(jid){let bare=Strophe1.getBareJidFromJid(jid);if(0>bare.indexOf("@"))return bare;{let parts=bare.split("@");return parts.splice(0,1),parts.join("@")}},getResourceFromJid(jid){if(!jid)return null;let s=jid.split("/");return s.length<2?null:(s.splice(0,1),s.join("/"))},getBareJidFromJid:jid=>jid?jid.split("/")[0]:null,_handleError(e){void 0!==e.stack&&Strophe1.fatal(e.stack),e.sourceURL?Strophe1.fatal("error: "+this.handler+" "+e.sourceURL+":"+e.line+" - "+e.name+": "+e.message):e.fileName?Strophe1.fatal("error: "+this.handler+" "+e.fileName+":"+e.lineNumber+" - "+e.name+": "+e.message):Strophe1.fatal("error: "+e.message)},log(level,msg){if(level===this.LogLevel.FATAL){var _console;null===(_console=console)||void 0===_console||_console.error(msg)}},debug(msg){this.log(this.LogLevel.DEBUG,msg)},info(msg){this.log(this.LogLevel.INFO,msg)},warn(msg){this.log(this.LogLevel.WARN,msg)},error(msg){this.log(this.LogLevel.ERROR,msg)},fatal(msg){this.log(this.LogLevel.FATAL,msg)},serialize(elem){if(!elem)return null;"function"==typeof elem.tree&&(elem=elem.tree());let names=[...Array(elem.attributes.length).keys()].map(i=>elem.attributes[i].nodeName);names.sort();let result=names.reduce((a,n)=>`${a} ${n}="${Strophe1.xmlescape(elem.attributes.getNamedItem(n).value)}"`,`<${elem.nodeName}`);if(elem.childNodes.length>0){result+=">";for(let i=0;i<elem.childNodes.length;i++){let child=elem.childNodes[i];switch(child.nodeType){case Strophe1.ElementType.NORMAL:result+=Strophe1.serialize(child);break;case Strophe1.ElementType.TEXT:result+=Strophe1.xmlescape(child.nodeValue);break;case Strophe1.ElementType.CDATA:result+="<![CDATA["+child.nodeValue+"]]>"}}result+="</"+elem.nodeName+">"}else result+="/>";return result},_requestId:0,_connectionPlugins:{},addConnectionPlugin(name,ptype){Strophe1._connectionPlugins[name]=ptype}};Strophe1.Builder=class{constructor(name,attrs){"presence"!==name&&"message"!==name&&"iq"!==name||(attrs&&!attrs.xmlns?attrs.xmlns=Strophe1.NS.CLIENT:attrs||(attrs={xmlns:Strophe1.NS.CLIENT})),this.nodeTree=Strophe1.xmlElement(name,attrs),this.node=this.nodeTree}tree(){return this.nodeTree}toString(){return Strophe1.serialize(this.nodeTree)}up(){return this.node=this.node.parentNode,this}root(){return this.node=this.nodeTree,this}attrs(moreattrs){for(let k in moreattrs)Object.prototype.hasOwnProperty.call(moreattrs,k)&&(void 0===moreattrs[k]?this.node.removeAttribute(k):this.node.setAttribute(k,moreattrs[k]));return this}c(name,attrs,text){let child=Strophe1.xmlElement(name,attrs,text);return this.node.appendChild(child),"string"!=typeof text&&"number"!=typeof text&&(this.node=child),this}cnode(elem){let impNode;let xmlGen=Strophe1.xmlGenerator();try{impNode=void 0!==xmlGen.importNode}catch(e){impNode=!1}let newElem=impNode?xmlGen.importNode(elem,!0):Strophe1.copyElement(elem);return this.node.appendChild(newElem),this.node=newElem,this}t(text){let child=Strophe1.xmlTextNode(text);return this.node.appendChild(child),this}h(html){let fragment=Strophe1.xmlGenerator().createElement("body");fragment.innerHTML=html;let xhtml=Strophe1.createHtml(fragment);for(;xhtml.childNodes.length>0;)this.node.appendChild(xhtml.childNodes[0]);return this}},Strophe1.Handler=function(handler,ns,name,type,id,from,options){this.handler=handler,this.ns=ns,this.name=name,this.type=type,this.id=id,this.options=options||{matchBareFromJid:!1,ignoreNamespaceFragment:!1},this.options.matchBare&&(Strophe1.warn('The "matchBare" option is deprecated, use "matchBareFromJid" instead.'),this.options.matchBareFromJid=this.options.matchBare,delete this.options.matchBare),this.options.matchBareFromJid?this.from=from?Strophe1.getBareJidFromJid(from):null:this.from=from,this.user=!0},Strophe1.Handler.prototype={getNamespace(elem){let elNamespace=elem.getAttribute("xmlns");return elNamespace&&this.options.ignoreNamespaceFragment&&(elNamespace=elNamespace.split("#")[0]),elNamespace},namespaceMatch(elem){let nsMatch=!1;return!this.ns||(Strophe1.forEachChild(elem,null,elem=>{this.getNamespace(elem)===this.ns&&(nsMatch=!0)}),nsMatch||this.getNamespace(elem)===this.ns)},isMatch(elem){let from=elem.getAttribute("from");this.options.matchBareFromJid&&(from=Strophe1.getBareJidFromJid(from));let elem_type=elem.getAttribute("type");return!!(this.namespaceMatch(elem)&&(!this.name||Strophe1.isTagEqual(elem,this.name)))&&(!this.type||(Array.isArray(this.type)?-1!==this.type.indexOf(elem_type):elem_type===this.type))&&(!this.id||elem.getAttribute("id")===this.id)&&(!this.from||from===this.from)},run(elem){let result=null;try{result=this.handler(elem)}catch(e){throw Strophe1._handleError(e),e}return result},toString(){return"{Handler: "+this.handler+"("+this.name+","+this.id+","+this.ns+")}"}},Strophe1.TimedHandler=class{constructor(period,handler){this.period=period,this.handler=handler,this.lastCalled=new Date().getTime(),this.user=!0}run(){return this.lastCalled=new Date().getTime(),this.handler()}reset(){this.lastCalled=new Date().getTime()}toString(){return"{TimedHandler: "+this.handler+"("+this.period+")}"}},Strophe1.Connection=class{constructor(service,options){for(let k in this.service=service,this.options=options||{},this.setProtocol(),this.jid="",this.domain=null,this.features=null,this._sasl_data={},this.do_bind=!1,this.do_session=!1,this.mechanisms={},this.timedHandlers=[],this.handlers=[],this.removeTimeds=[],this.removeHandlers=[],this.addTimeds=[],this.addHandlers=[],this.protocolErrorHandlers={HTTP:{},websocket:{}},this._idleTimeout=null,this._disconnectTimeout=null,this.authenticated=!1,this.connected=!1,this.disconnecting=!1,this.do_authentication=!0,this.paused=!1,this.restored=!1,this._data=[],this._uniqueId=0,this._sasl_success_handler=null,this._sasl_failure_handler=null,this._sasl_challenge_handler=null,this.maxRetries=5,this._idleTimeout=setTimeout(()=>this._onIdle(),100),utils.addCookies(this.options.cookies),this.registerSASLMechanisms(this.options.mechanisms),this.iqFallbackHandler=new Strophe1.Handler(iq=>this.send($iq1({type:"error",id:iq.getAttribute("id")}).c("error",{type:"cancel"}).c("service-unavailable",{xmlns:Strophe1.NS.STANZAS})),null,"iq",["get","set"]),Strophe1._connectionPlugins)if(Object.prototype.hasOwnProperty.call(Strophe1._connectionPlugins,k)){let F=function(){};F.prototype=Strophe1._connectionPlugins[k],this[k]=new F,this[k].init(this)}}setProtocol(){let proto=this.options.protocol||"";this.options.worker?this._proto=new Strophe1.WorkerWebsocket(this):0===this.service.indexOf("ws:")||0===this.service.indexOf("wss:")||0===proto.indexOf("ws")?this._proto=new Strophe1.Websocket(this):this._proto=new Strophe1.Bosh(this)}reset(){this._proto._reset(),this.do_session=!1,this.do_bind=!1,this.timedHandlers=[],this.handlers=[],this.removeTimeds=[],this.removeHandlers=[],this.addTimeds=[],this.addHandlers=[],this.authenticated=!1,this.connected=!1,this.disconnecting=!1,this.restored=!1,this._data=[],this._requests=[],this._uniqueId=0}pause(){this.paused=!0}resume(){this.paused=!1}getUniqueId(suffix){let uuid="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){let r=16*Math.random()|0;return("x"===c?r:3&r|8).toString(16)});return"string"==typeof suffix||"number"==typeof suffix?uuid+":"+suffix:uuid+""}addProtocolErrorHandler(protocol,status_code,callback){this.protocolErrorHandlers[protocol][status_code]=callback}connect(jid,pass,callback,wait,hold,route,authcid){let disconnection_timeout=arguments.length>7&&void 0!==arguments[7]?arguments[7]:3e3;this.jid=jid,this.authzid=Strophe1.getBareJidFromJid(this.jid),this.authcid=authcid||Strophe1.getNodeFromJid(this.jid),this.pass=pass,this.connect_callback=callback,this.disconnecting=!1,this.connected=!1,this.authenticated=!1,this.restored=!1,this.disconnection_timeout=disconnection_timeout,this.domain=Strophe1.getDomainFromJid(this.jid),this._changeConnectStatus(Strophe1.Status.CONNECTING,null),this._proto._connect(wait,hold,route)}attach(jid,sid,rid,callback,wait,hold,wind){if(this._proto._attach)return this._proto._attach(jid,sid,rid,callback,wait,hold,wind);{let error=Error('The "attach" method is not available for your connection protocol');throw error.name="StropheSessionError",error}}restore(jid,callback,wait,hold,wind){if(this._sessionCachingSupported())this._proto._restore(jid,callback,wait,hold,wind);else{let error=Error('The "restore" method can only be used with a BOSH connection.');throw error.name="StropheSessionError",error}}_sessionCachingSupported(){if(this._proto instanceof Strophe1.Bosh){if(!JSON)return!1;try{sessionStorage.setItem("_strophe_","_strophe_"),sessionStorage.removeItem("_strophe_")}catch(e){return!1}return!0}return!1}xmlInput(elem){}xmlOutput(elem){}rawInput(data){}rawOutput(data){}nextValidRid(rid){}send(elem){if(null!==elem){if("function"==typeof elem.sort)for(let i=0;i<elem.length;i++)this._queueData(elem[i]);else"function"==typeof elem.tree?this._queueData(elem.tree()):this._queueData(elem);this._proto._send()}}flush(){clearTimeout(this._idleTimeout),this._onIdle()}sendPresence(elem,callback,errback,timeout){let timeoutHandler=null;"function"==typeof elem.tree&&(elem=elem.tree());let id=elem.getAttribute("id");if(id||(id=this.getUniqueId("sendPresence"),elem.setAttribute("id",id)),"function"==typeof callback||"function"==typeof errback){let handler=this.addHandler(stanza=>{timeoutHandler&&this.deleteTimedHandler(timeoutHandler),"error"===stanza.getAttribute("type")?errback&&errback(stanza):callback&&callback(stanza)},null,"presence",null,id);timeout&&(timeoutHandler=this.addTimedHandler(timeout,()=>(this.deleteHandler(handler),errback&&errback(null),!1)))}return this.send(elem),id}sendIQ(elem,callback,errback,timeout){let timeoutHandler=null;"function"==typeof elem.tree&&(elem=elem.tree());let id=elem.getAttribute("id");if(id||(id=this.getUniqueId("sendIQ"),elem.setAttribute("id",id)),"function"==typeof callback||"function"==typeof errback){let handler=this.addHandler(stanza=>{timeoutHandler&&this.deleteTimedHandler(timeoutHandler);let iqtype=stanza.getAttribute("type");if("result"===iqtype)callback&&callback(stanza);else if("error"===iqtype)errback&&errback(stanza);else{let error=Error(`Got bad IQ type of ${iqtype}`);throw error.name="StropheError",error}},null,"iq",["error","result"],id);timeout&&(timeoutHandler=this.addTimedHandler(timeout,()=>(this.deleteHandler(handler),errback&&errback(null),!1)))}return this.send(elem),id}_queueData(element){if(null===element||!element.tagName||!element.childNodes){let error=Error("Cannot queue non-DOMElement.");throw error.name="StropheError",error}this._data.push(element)}_sendRestart(){this._data.push("restart"),this._proto._sendRestart(),this._idleTimeout=setTimeout(()=>this._onIdle(),100)}addTimedHandler(period,handler){let thand=new Strophe1.TimedHandler(period,handler);return this.addTimeds.push(thand),thand}deleteTimedHandler(handRef){this.removeTimeds.push(handRef)}addHandler(handler,ns,name,type,id,from,options){let hand=new Strophe1.Handler(handler,ns,name,type,id,from,options);return this.addHandlers.push(hand),hand}deleteHandler(handRef){this.removeHandlers.push(handRef);let i=this.addHandlers.indexOf(handRef);i>=0&&this.addHandlers.splice(i,1)}registerSASLMechanisms(mechanisms){this.mechanisms={},(mechanisms=mechanisms||[Strophe1.SASLAnonymous,Strophe1.SASLExternal,Strophe1.SASLOAuthBearer,Strophe1.SASLXOAuth2,Strophe1.SASLPlain,Strophe1.SASLSHA1]).forEach(m=>this.registerSASLMechanism(m))}registerSASLMechanism(Mechanism){let mechanism=new Mechanism;this.mechanisms[mechanism.mechname]=mechanism}disconnect(reason){if(this._changeConnectStatus(Strophe1.Status.DISCONNECTING,reason),reason?Strophe1.warn("Disconnect was called because: "+reason):Strophe1.info("Disconnect was called"),this.connected){let pres=!1;this.disconnecting=!0,this.authenticated&&(pres=$pres1({xmlns:Strophe1.NS.CLIENT,type:"unavailable"})),this._disconnectTimeout=this._addSysTimedHandler(this.disconnection_timeout,this._onDisconnectTimeout.bind(this)),this._proto._disconnect(pres)}else Strophe1.warn("Disconnect was called before Strophe connected to the server"),this._proto._abortAllRequests(),this._doDisconnect()}_changeConnectStatus(status,condition,elem){for(let k in Strophe1._connectionPlugins)if(Object.prototype.hasOwnProperty.call(Strophe1._connectionPlugins,k)){let plugin=this[k];if(plugin.statusChanged)try{plugin.statusChanged(status,condition)}catch(err){Strophe1.error(`${k} plugin caused an exception changing status: ${err}`)}}if(this.connect_callback)try{this.connect_callback(status,condition,elem)}catch(e){Strophe1._handleError(e),Strophe1.error(`User connection callback caused an exception: ${e}`)}}_doDisconnect(condition){"number"==typeof this._idleTimeout&&clearTimeout(this._idleTimeout),null!==this._disconnectTimeout&&(this.deleteTimedHandler(this._disconnectTimeout),this._disconnectTimeout=null),Strophe1.debug("_doDisconnect was called"),this._proto._doDisconnect(),this.authenticated=!1,this.disconnecting=!1,this.restored=!1,this.handlers=[],this.timedHandlers=[],this.removeTimeds=[],this.removeHandlers=[],this.addTimeds=[],this.addHandlers=[],this._changeConnectStatus(Strophe1.Status.DISCONNECTED,condition),this.connected=!1}_dataRecv(req,raw){let elem=this._proto._reqToData(req);if(null===elem)return;for(this.xmlInput!==Strophe1.Connection.prototype.xmlInput&&(elem.nodeName===this._proto.strip&&elem.childNodes.length?this.xmlInput(elem.childNodes[0]):this.xmlInput(elem)),this.rawInput!==Strophe1.Connection.prototype.rawInput&&(raw?this.rawInput(raw):this.rawInput(Strophe1.serialize(elem)));this.removeHandlers.length>0;){let hand=this.removeHandlers.pop(),i=this.handlers.indexOf(hand);i>=0&&this.handlers.splice(i,1)}for(;this.addHandlers.length>0;)this.handlers.push(this.addHandlers.pop());if(this.disconnecting&&this._proto._emptyQueue()){this._doDisconnect();return}let type=elem.getAttribute("type");if(null!==type&&"terminate"===type){if(this.disconnecting)return;let cond=elem.getAttribute("condition"),conflict=elem.getElementsByTagName("conflict");null!==cond?("remote-stream-error"===cond&&conflict.length>0&&(cond="conflict"),this._changeConnectStatus(Strophe1.Status.CONNFAIL,cond)):this._changeConnectStatus(Strophe1.Status.CONNFAIL,Strophe1.ErrorCondition.UNKOWN_REASON),this._doDisconnect(cond);return}Strophe1.forEachChild(elem,null,child=>{let matches=[];this.handlers=this.handlers.reduce((handlers,handler)=>{try{handler.isMatch(child)&&(this.authenticated||!handler.user)?(handler.run(child)&&handlers.push(handler),matches.push(handler)):handlers.push(handler)}catch(e){Strophe1.warn("Removing Strophe handlers due to uncaught exception: "+e.message)}return handlers},[]),!matches.length&&this.iqFallbackHandler.isMatch(child)&&this.iqFallbackHandler.run(child)})}_connect_cb(req,_callback,raw){let bodyWrap;Strophe1.debug("_connect_cb was called"),this.connected=!0;try{bodyWrap=this._proto._reqToData(req)}catch(e){if(e.name!==Strophe1.ErrorCondition.BAD_FORMAT)throw e;this._changeConnectStatus(Strophe1.Status.CONNFAIL,Strophe1.ErrorCondition.BAD_FORMAT),this._doDisconnect(Strophe1.ErrorCondition.BAD_FORMAT)}if(!bodyWrap||(this.xmlInput!==Strophe1.Connection.prototype.xmlInput&&(bodyWrap.nodeName===this._proto.strip&&bodyWrap.childNodes.length?this.xmlInput(bodyWrap.childNodes[0]):this.xmlInput(bodyWrap)),this.rawInput!==Strophe1.Connection.prototype.rawInput&&(raw?this.rawInput(raw):this.rawInput(Strophe1.serialize(bodyWrap))),this._proto._connect_cb(bodyWrap)===Strophe1.Status.CONNFAIL))return;if(!(bodyWrap.getElementsByTagNameNS?bodyWrap.getElementsByTagNameNS(Strophe1.NS.STREAM,"features").length>0:bodyWrap.getElementsByTagName("stream:features").length>0||bodyWrap.getElementsByTagName("features").length>0)){this._proto._no_auth_received(_callback);return}let matched=Array.from(bodyWrap.getElementsByTagName("mechanism")).map(m=>this.mechanisms[m.textContent]).filter(m=>m);if(0===matched.length&&0===bodyWrap.getElementsByTagName("auth").length){this._proto._no_auth_received(_callback);return}!1!==this.do_authentication&&this.authenticate(matched)}sortMechanismsByPriority(mechanisms){for(let i=0;i<mechanisms.length-1;++i){let higher=i;for(let j=i+1;j<mechanisms.length;++j)mechanisms[j].priority>mechanisms[higher].priority&&(higher=j);if(higher!==i){let swap=mechanisms[i];mechanisms[i]=mechanisms[higher],mechanisms[higher]=swap}}return mechanisms}authenticate(matched){this._attemptSASLAuth(matched)||this._attemptLegacyAuth()}_attemptSASLAuth(mechanisms){mechanisms=this.sortMechanismsByPriority(mechanisms||[]);let mechanism_found=!1;for(let i=0;i<mechanisms.length;++i){if(!mechanisms[i].test(this))continue;this._sasl_success_handler=this._addSysHandler(this._sasl_success_cb.bind(this),null,"success",null,null),this._sasl_failure_handler=this._addSysHandler(this._sasl_failure_cb.bind(this),null,"failure",null,null),this._sasl_challenge_handler=this._addSysHandler(this._sasl_challenge_cb.bind(this),null,"challenge",null,null),this._sasl_mechanism=mechanisms[i],this._sasl_mechanism.onStart(this);let request_auth_exchange=$build1("auth",{xmlns:Strophe1.NS.SASL,mechanism:this._sasl_mechanism.mechname});if(this._sasl_mechanism.isClientFirst){let response=this._sasl_mechanism.clientChallenge(this);request_auth_exchange.t(abab.btoa(response))}this.send(request_auth_exchange.tree()),mechanism_found=!0;break}return mechanism_found}_sasl_challenge_cb(elem){let challenge=abab.atob(Strophe1.getText(elem)),response=this._sasl_mechanism.onChallenge(this,challenge),stanza=$build1("response",{xmlns:Strophe1.NS.SASL});return""!==response&&stanza.t(abab.btoa(response)),this.send(stanza.tree()),!0}_attemptLegacyAuth(){null===Strophe1.getNodeFromJid(this.jid)?(this._changeConnectStatus(Strophe1.Status.CONNFAIL,Strophe1.ErrorCondition.MISSING_JID_NODE),this.disconnect(Strophe1.ErrorCondition.MISSING_JID_NODE)):(this._changeConnectStatus(Strophe1.Status.AUTHENTICATING,null),this._addSysHandler(this._onLegacyAuthIQResult.bind(this),null,null,null,"_auth_1"),this.send($iq1({type:"get",to:this.domain,id:"_auth_1"}).c("query",{xmlns:Strophe1.NS.AUTH}).c("username",{}).t(Strophe1.getNodeFromJid(this.jid)).tree()))}_onLegacyAuthIQResult(elem){let iq=$iq1({type:"set",id:"_auth_2"}).c("query",{xmlns:Strophe1.NS.AUTH}).c("username",{}).t(Strophe1.getNodeFromJid(this.jid)).up().c("password").t(this.pass);return Strophe1.getResourceFromJid(this.jid)||(this.jid=Strophe1.getBareJidFromJid(this.jid)+"/strophe"),iq.up().c("resource",{}).t(Strophe1.getResourceFromJid(this.jid)),this._addSysHandler(this._auth2_cb.bind(this),null,null,null,"_auth_2"),this.send(iq.tree()),!1}_sasl_success_cb(elem){if(this._sasl_data["server-signature"]){let serverSignature;let matches=abab.atob(Strophe1.getText(elem)).match(/([a-z]+)=([^,]+)(,|$)/);if("v"===matches[1]&&(serverSignature=matches[2]),serverSignature!==this._sasl_data["server-signature"])return this.deleteHandler(this._sasl_failure_handler),this._sasl_failure_handler=null,this._sasl_challenge_handler&&(this.deleteHandler(this._sasl_challenge_handler),this._sasl_challenge_handler=null),this._sasl_data={},this._sasl_failure_cb(null)}Strophe1.info("SASL authentication succeeded."),this._sasl_mechanism&&this._sasl_mechanism.onSuccess(),this.deleteHandler(this._sasl_failure_handler),this._sasl_failure_handler=null,this._sasl_challenge_handler&&(this.deleteHandler(this._sasl_challenge_handler),this._sasl_challenge_handler=null);let streamfeature_handlers=[],wrapper=(handlers,elem)=>{for(;handlers.length;)this.deleteHandler(handlers.pop());return this._onStreamFeaturesAfterSASL(elem),!1};return streamfeature_handlers.push(this._addSysHandler(elem=>wrapper(streamfeature_handlers,elem),null,"stream:features",null,null)),streamfeature_handlers.push(this._addSysHandler(elem=>wrapper(streamfeature_handlers,elem),Strophe1.NS.STREAM,"features",null,null)),this._sendRestart(),!1}_onStreamFeaturesAfterSASL(elem){this.features=elem;for(let i=0;i<elem.childNodes.length;i++){let child=elem.childNodes[i];"bind"===child.nodeName&&(this.do_bind=!0),"session"===child.nodeName&&(this.do_session=!0)}return this.do_bind?this.options.explicitResourceBinding?this._changeConnectStatus(Strophe1.Status.BINDREQUIRED,null):this.bind():this._changeConnectStatus(Strophe1.Status.AUTHFAIL,null),!1}bind(){if(!this.do_bind){Strophe1.log(Strophe1.LogLevel.INFO,'Strophe.Connection.prototype.bind called but "do_bind" is false');return}this._addSysHandler(this._onResourceBindResultIQ.bind(this),null,null,null,"_bind_auth_2");let resource=Strophe1.getResourceFromJid(this.jid);resource?this.send($iq1({type:"set",id:"_bind_auth_2"}).c("bind",{xmlns:Strophe1.NS.BIND}).c("resource",{}).t(resource).tree()):this.send($iq1({type:"set",id:"_bind_auth_2"}).c("bind",{xmlns:Strophe1.NS.BIND}).tree())}_onResourceBindResultIQ(elem){if("error"===elem.getAttribute("type")){let condition;return Strophe1.warn("Resource binding failed."),elem.getElementsByTagName("conflict").length>0&&(condition=Strophe1.ErrorCondition.CONFLICT),this._changeConnectStatus(Strophe1.Status.AUTHFAIL,condition,elem),!1}let bind=elem.getElementsByTagName("bind");if(!(bind.length>0))return Strophe1.warn("Resource binding failed."),this._changeConnectStatus(Strophe1.Status.AUTHFAIL,null,elem),!1;{let jidNode=bind[0].getElementsByTagName("jid");jidNode.length>0&&(this.authenticated=!0,this.jid=Strophe1.getText(jidNode[0]),this.do_session?this._establishSession():this._changeConnectStatus(Strophe1.Status.CONNECTED,null))}}_establishSession(){if(!this.do_session)throw Error(`Strophe.Connection.prototype._establishSession called but apparently ${Strophe1.NS.SESSION} wasn't advertised by the server`);this._addSysHandler(this._onSessionResultIQ.bind(this),null,null,null,"_session_auth_2"),this.send($iq1({type:"set",id:"_session_auth_2"}).c("session",{xmlns:Strophe1.NS.SESSION}).tree())}_onSessionResultIQ(elem){return"result"===elem.getAttribute("type")?(this.authenticated=!0,this._changeConnectStatus(Strophe1.Status.CONNECTED,null)):"error"===elem.getAttribute("type")&&(this.authenticated=!1,Strophe1.warn("Session creation failed."),this._changeConnectStatus(Strophe1.Status.AUTHFAIL,null,elem)),!1}_sasl_failure_cb(elem){return this._sasl_success_handler&&(this.deleteHandler(this._sasl_success_handler),this._sasl_success_handler=null),this._sasl_challenge_handler&&(this.deleteHandler(this._sasl_challenge_handler),this._sasl_challenge_handler=null),this._sasl_mechanism&&this._sasl_mechanism.onFailure(),this._changeConnectStatus(Strophe1.Status.AUTHFAIL,null,elem),!1}_auth2_cb(elem){return"result"===elem.getAttribute("type")?(this.authenticated=!0,this._changeConnectStatus(Strophe1.Status.CONNECTED,null)):"error"===elem.getAttribute("type")&&(this._changeConnectStatus(Strophe1.Status.AUTHFAIL,null,elem),this.disconnect("authentication failed")),!1}_addSysTimedHandler(period,handler){let thand=new Strophe1.TimedHandler(period,handler);return thand.user=!1,this.addTimeds.push(thand),thand}_addSysHandler(handler,ns,name,type,id){let hand=new Strophe1.Handler(handler,ns,name,type,id);return hand.user=!1,this.addHandlers.push(hand),hand}_onDisconnectTimeout(){return Strophe1.debug("_onDisconnectTimeout was called"),this._changeConnectStatus(Strophe1.Status.CONNTIMEOUT,null),this._proto._onDisconnectTimeout(),this._doDisconnect(),!1}_onIdle(){for(;this.addTimeds.length>0;)this.timedHandlers.push(this.addTimeds.pop());for(;this.removeTimeds.length>0;){let thand=this.removeTimeds.pop(),i=this.timedHandlers.indexOf(thand);i>=0&&this.timedHandlers.splice(i,1)}let now=new Date().getTime(),newList=[];for(let i=0;i<this.timedHandlers.length;i++){let thand=this.timedHandlers[i];(this.authenticated||!thand.user)&&(thand.lastCalled+thand.period-now<=0?thand.run()&&newList.push(thand):newList.push(thand))}this.timedHandlers=newList,clearTimeout(this._idleTimeout),this._proto._onIdle(),this.connected&&(this._idleTimeout=setTimeout(()=>this._onIdle(),100))}},Strophe1.SASLMechanism=SASLMechanism,Strophe1.SASLAnonymous=class extends SASLMechanism{constructor(){let mechname=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"ANONYMOUS",isClientFirst=arguments.length>1&&void 0!==arguments[1]&&arguments[1],priority=arguments.length>2&&void 0!==arguments[2]?arguments[2]:20;super(mechname,isClientFirst,priority)}test(connection){return null===connection.authcid}},Strophe1.SASLPlain=class extends SASLMechanism{constructor(){let mechname=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"PLAIN",isClientFirst=!(arguments.length>1)||void 0===arguments[1]||arguments[1],priority=arguments.length>2&&void 0!==arguments[2]?arguments[2]:50;super(mechname,isClientFirst,priority)}test(connection){return null!==connection.authcid}onChallenge(connection){let{authcid,authzid,domain,pass}=connection;if(!domain)throw Error("SASLPlain onChallenge: domain is not defined!");let auth_str=authzid!==`${authcid}@${domain}`?authzid:"";return auth_str+="\0"+authcid+"\0"+pass,utils.utf16to8(auth_str)}},Strophe1.SASLSHA1=class extends SASLMechanism{constructor(){let mechname=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"SCRAM-SHA-1",isClientFirst=!(arguments.length>1)||void 0===arguments[1]||arguments[1],priority=arguments.length>2&&void 0!==arguments[2]?arguments[2]:60;super(mechname,isClientFirst,priority)}test(connection){return null!==connection.authcid}onChallenge(connection,challenge){let nonce,salt,iter,Hi,U,U_old,i,k;let responseText="c=biws,",authMessage=`${connection._sasl_data["client-first-message-bare"]},${challenge},`,cnonce=connection._sasl_data.cnonce,attribMatch=/([a-z]+)=([^,]+)(,|$)/;for(;challenge.match(attribMatch);){let matches=challenge.match(attribMatch);switch(challenge=challenge.replace(matches[0],""),matches[1]){case"r":nonce=matches[2];break;case"s":salt=matches[2];break;case"i":iter=matches[2]}}if(nonce.slice(0,cnonce.length)!==cnonce)return connection._sasl_data={},connection._sasl_failure_cb();responseText+="r="+nonce,authMessage+=responseText,salt=atob(salt)+"\0\0\0\x01";let pass=utils.utf16to8(connection.pass);for(i=1,Hi=U_old=SHA1.core_hmac_sha1(pass,salt);i<iter;i++){for(k=0,U=SHA1.core_hmac_sha1(pass,SHA1.binb2str(U_old));k<5;k++)Hi[k]^=U[k];U_old=U}Hi=SHA1.binb2str(Hi);let clientKey=SHA1.core_hmac_sha1(Hi,"Client Key"),serverKey=SHA1.str_hmac_sha1(Hi,"Server Key"),clientSignature=SHA1.core_hmac_sha1(SHA1.str_sha1(SHA1.binb2str(clientKey)),authMessage);for(k=0,connection._sasl_data["server-signature"]=SHA1.b64_hmac_sha1(serverKey,authMessage);k<5;k++)clientKey[k]^=clientSignature[k];return responseText+",p="+btoa(SHA1.binb2str(clientKey))}clientChallenge(connection,test_cnonce){let cnonce=test_cnonce||MD5.hexdigest(""+1234567890*Math.random()),auth_str="n="+utils.utf16to8(connection.authcid);return auth_str+=",r="+cnonce,connection._sasl_data.cnonce=cnonce,connection._sasl_data["client-first-message-bare"]=auth_str,auth_str="n,,"+auth_str}},Strophe1.SASLOAuthBearer=class extends SASLMechanism{constructor(){let mechname=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"OAUTHBEARER",isClientFirst=!(arguments.length>1)||void 0===arguments[1]||arguments[1],priority=arguments.length>2&&void 0!==arguments[2]?arguments[2]:40;super(mechname,isClientFirst,priority)}test(connection){return null!==connection.pass}onChallenge(connection){let auth_str="n,";return null!==connection.authcid&&(auth_str=auth_str+"a="+connection.authzid),auth_str+=",\x01auth=Bearer "+connection.pass+"\x01\x01",utils.utf16to8(auth_str)}},Strophe1.SASLExternal=class extends SASLMechanism{constructor(){let mechname=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"EXTERNAL",isClientFirst=!(arguments.length>1)||void 0===arguments[1]||arguments[1],priority=arguments.length>2&&void 0!==arguments[2]?arguments[2]:10;super(mechname,isClientFirst,priority)}onChallenge(connection){return connection.authcid===connection.authzid?"":connection.authzid}},Strophe1.SASLXOAuth2=class extends SASLMechanism{constructor(){let mechname=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"X-OAUTH2",isClientFirst=!(arguments.length>1)||void 0===arguments[1]||arguments[1],priority=arguments.length>2&&void 0!==arguments[2]?arguments[2]:30;super(mechname,isClientFirst,priority)}test(connection){return null!==connection.pass}onChallenge(connection){let auth_str="\0";return null!==connection.authcid&&(auth_str+=connection.authzid),auth_str+="\0"+connection.pass,utils.utf16to8(auth_str)}};var core={Strophe:Strophe1,$build:$build1,$iq:$iq1,$msg:$msg1,$pres:$pres1,SHA1:SHA1,MD5:MD5,b64_hmac_sha1:SHA1.b64_hmac_sha1,b64_sha1:SHA1.b64_sha1,str_hmac_sha1:SHA1.str_hmac_sha1,str_sha1:SHA1.str_sha1};Strophe1.Request=class{constructor(elem,func,rid,sends){this.id=++Strophe1._requestId,this.xmlData=elem,this.data=Strophe1.serialize(elem),this.origFunc=func,this.func=func,this.rid=rid,this.date=NaN,this.sends=sends||0,this.abort=!1,this.dead=null,this.age=function(){return this.date?(new Date-this.date)/1e3:0},this.timeDead=function(){return this.dead?(new Date-this.dead)/1e3:0},this.xhr=this._newXHR()}getResponse(){let node=null;if(this.xhr.responseXML&&this.xhr.responseXML.documentElement){if("parsererror"===(node=this.xhr.responseXML.documentElement).tagName)throw Strophe1.error("invalid response received"),Strophe1.error("responseText: "+this.xhr.responseText),Strophe1.error("responseXML: "+Strophe1.serialize(this.xhr.responseXML)),Error("parsererror")}else if(this.xhr.responseText){if(Strophe1.debug("Got responseText but no responseXML; attempting to parse it with DOMParser..."),node=new DOMParser1().parseFromString(this.xhr.responseText,"application/xml").documentElement){if(node.querySelector("parsererror")){Strophe1.error("invalid response received: "+node.querySelector("parsererror").textContent),Strophe1.error("responseText: "+this.xhr.responseText);let error=Error();throw error.name=Strophe1.ErrorCondition.BAD_FORMAT,error}}else throw Error("Parsing produced null node")}return node}_newXHR(){let xhr=null;return window.XMLHttpRequest?(xhr=new XMLHttpRequest).overrideMimeType&&xhr.overrideMimeType("text/xml; charset=utf-8"):window.ActiveXObject&&(xhr=new ActiveXObject("Microsoft.XMLHTTP")),xhr.onreadystatechange=this.func.bind(null,this),xhr}},Strophe1.Bosh=class Bosh{constructor(connection){this._conn=connection,this.rid=Math.floor(4294967295*Math.random()),this.sid=null,this.hold=1,this.wait=60,this.window=5,this.errors=0,this.inactivity=null,this.lastResponseHeaders=null,this._requests=[]}_buildBody(){let bodyWrap=$build1("body",{rid:this.rid++,xmlns:Strophe1.NS.HTTPBIND});return null!==this.sid&&bodyWrap.attrs({sid:this.sid}),this._conn.options.keepalive&&this._conn._sessionCachingSupported()&&this._cacheSession(),bodyWrap}_reset(){this.rid=Math.floor(4294967295*Math.random()),this.sid=null,this.errors=0,this._conn._sessionCachingSupported()&&window.sessionStorage.removeItem("strophe-bosh-session"),this._conn.nextValidRid(this.rid)}_connect(wait,hold,route){this.wait=wait||this.wait,this.hold=hold||this.hold,this.errors=0;let body=this._buildBody().attrs({to:this._conn.domain,"xml:lang":"en",wait:this.wait,hold:this.hold,content:"text/xml; charset=utf-8",ver:"1.6","xmpp:version":"1.0","xmlns:xmpp":Strophe1.NS.BOSH});route&&body.attrs({route:route});let _connect_cb=this._conn._connect_cb;this._requests.push(new Strophe1.Request(body.tree(),this._onRequestStateChange.bind(this,_connect_cb.bind(this._conn)),body.tree().getAttribute("rid"))),this._throttledRequestHandler()}_attach(jid,sid,rid,callback,wait,hold,wind){this._conn.jid=jid,this.sid=sid,this.rid=rid,this._conn.connect_callback=callback,this._conn.domain=Strophe1.getDomainFromJid(this._conn.jid),this._conn.authenticated=!0,this._conn.connected=!0,this.wait=wait||this.wait,this.hold=hold||this.hold,this.window=wind||this.window,this._conn._changeConnectStatus(Strophe1.Status.ATTACHED,null)}_restore(jid,callback,wait,hold,wind){let session=JSON.parse(window.sessionStorage.getItem("strophe-bosh-session"));if(null!=session&&session.rid&&session.sid&&session.jid&&(null==jid||Strophe1.getBareJidFromJid(session.jid)===Strophe1.getBareJidFromJid(jid)||null===Strophe1.getNodeFromJid(jid)&&Strophe1.getDomainFromJid(session.jid)===jid))this._conn.restored=!0,this._attach(session.jid,session.sid,session.rid,callback,wait,hold,wind);else{let error=Error("_restore: no restoreable session.");throw error.name="StropheSessionError",error}}_cacheSession(){this._conn.authenticated?this._conn.jid&&this.rid&&this.sid&&window.sessionStorage.setItem("strophe-bosh-session",JSON.stringify({jid:this._conn.jid,rid:this.rid,sid:this.sid})):window.sessionStorage.removeItem("strophe-bosh-session")}_connect_cb(bodyWrap){let typ=bodyWrap.getAttribute("type");if(null!==typ&&"terminate"===typ){let cond=bodyWrap.getAttribute("condition");Strophe1.error("BOSH-Connection failed: "+cond);let conflict=bodyWrap.getElementsByTagName("conflict");return null!==cond?("remote-stream-error"===cond&&conflict.length>0&&(cond="conflict"),this._conn._changeConnectStatus(Strophe1.Status.CONNFAIL,cond)):this._conn._changeConnectStatus(Strophe1.Status.CONNFAIL,"unknown"),this._conn._doDisconnect(cond),Strophe1.Status.CONNFAIL}this.sid||(this.sid=bodyWrap.getAttribute("sid"));let wind=bodyWrap.getAttribute("requests");wind&&(this.window=parseInt(wind,10));let hold=bodyWrap.getAttribute("hold");hold&&(this.hold=parseInt(hold,10));let wait=bodyWrap.getAttribute("wait");wait&&(this.wait=parseInt(wait,10));let inactivity=bodyWrap.getAttribute("inactivity");inactivity&&(this.inactivity=parseInt(inactivity,10))}_disconnect(pres){this._sendTerminate(pres)}_doDisconnect(){this.sid=null,this.rid=Math.floor(4294967295*Math.random()),this._conn._sessionCachingSupported()&&window.sessionStorage.removeItem("strophe-bosh-session"),this._conn.nextValidRid(this.rid)}_emptyQueue(){return 0===this._requests.length}_callProtocolErrorHandlers(req){let reqStatus=Bosh._getRequestStatus(req),err_callback=this._conn.protocolErrorHandlers.HTTP[reqStatus];err_callback&&err_callback.call(this,reqStatus)}_hitError(reqStatus){this.errors++,Strophe1.warn("request errored, status: "+reqStatus+", number of errors: "+this.errors),this.errors>4&&this._conn._onDisconnectTimeout()}_no_auth_received(callback){Strophe1.warn("Server did not yet offer a supported authentication mechanism. Sending a blank poll request."),callback=callback?callback.bind(this._conn):this._conn._connect_cb.bind(this._conn);let body=this._buildBody();this._requests.push(new Strophe1.Request(body.tree(),this._onRequestStateChange.bind(this,callback),body.tree().getAttribute("rid"))),this._throttledRequestHandler()}_onDisconnectTimeout(){this._abortAllRequests()}_abortAllRequests(){for(;this._requests.length>0;){let req=this._requests.pop();req.abort=!0,req.xhr.abort(),req.xhr.onreadystatechange=function(){}}}_onIdle(){let data=this._conn._data;if(this._conn.authenticated&&0===this._requests.length&&0===data.length&&!this._conn.disconnecting&&(Strophe1.debug("no requests during idle cycle, sending blank request"),data.push(null)),!this._conn.paused){if(this._requests.length<2&&data.length>0){let body=this._buildBody();for(let i=0;i<data.length;i++)null!==data[i]&&("restart"===data[i]?body.attrs({to:this._conn.domain,"xml:lang":"en","xmpp:restart":"true","xmlns:xmpp":Strophe1.NS.BOSH}):body.cnode(data[i]).up());delete this._conn._data,this._conn._data=[],this._requests.push(new Strophe1.Request(body.tree(),this._onRequestStateChange.bind(this,this._conn._dataRecv.bind(this._conn)),body.tree().getAttribute("rid"))),this._throttledRequestHandler()}if(this._requests.length>0){let time_elapsed=this._requests[0].age();null!==this._requests[0].dead&&this._requests[0].timeDead()>Math.floor(Strophe1.SECONDARY_TIMEOUT*this.wait)&&this._throttledRequestHandler(),time_elapsed>Math.floor(Strophe1.TIMEOUT*this.wait)&&(Strophe1.warn("Request "+this._requests[0].id+" timed out, over "+Math.floor(Strophe1.TIMEOUT*this.wait)+" seconds since last activity"),this._throttledRequestHandler())}}}static _getRequestStatus(req,def){let reqStatus;if(4===req.xhr.readyState)try{reqStatus=req.xhr.status}catch(e){Strophe1.error("Caught an error while retrieving a request's status, reqStatus: "+reqStatus)}return void 0===reqStatus&&(reqStatus="number"==typeof def?def:0),reqStatus}_onRequestStateChange(func,req){if(Strophe1.debug("request id "+req.id+"."+req.sends+" state changed to "+req.xhr.readyState),req.abort){req.abort=!1;return}if(4!==req.xhr.readyState)return;let reqStatus=Bosh._getRequestStatus(req);if(this.lastResponseHeaders=req.xhr.getAllResponseHeaders(),this._conn.disconnecting&&reqStatus>=400){this._hitError(reqStatus),this._callProtocolErrorHandlers(req);return}let reqIs0=this._requests[0]===req,reqIs1=this._requests[1]===req,valid_request=reqStatus>0&&reqStatus<500,too_many_retries=req.sends>this._conn.maxRetries;(valid_request||too_many_retries)&&(this._removeRequest(req),Strophe1.debug("request id "+req.id+" should now be removed")),200===reqStatus?((reqIs1||reqIs0&&this._requests.length>0&&this._requests[0].age()>Math.floor(Strophe1.SECONDARY_TIMEOUT*this.wait))&&this._restartRequest(0),this._conn.nextValidRid(Number(req.rid)+1),Strophe1.debug("request id "+req.id+"."+req.sends+" got 200"),func(req),this.errors=0):0===reqStatus||reqStatus>=400&&reqStatus<600||reqStatus>=12e3?(Strophe1.error("request id "+req.id+"."+req.sends+" error "+reqStatus+" happened"),this._hitError(reqStatus),this._callProtocolErrorHandlers(req),reqStatus>=400&&reqStatus<500&&(this._conn._changeConnectStatus(Strophe1.Status.DISCONNECTING,null),this._conn._doDisconnect())):Strophe1.error("request id "+req.id+"."+req.sends+" error "+reqStatus+" happened"),valid_request||too_many_retries?too_many_retries&&!this._conn.connected&&this._conn._changeConnectStatus(Strophe1.Status.CONNFAIL,"giving-up"):this._throttledRequestHandler()}_processRequest(i){let req=this._requests[i],reqStatus=Bosh._getRequestStatus(req,-1);if(req.sends>this._conn.maxRetries){this._conn._onDisconnectTimeout();return}let time_elapsed=req.age(),primary_timeout=!isNaN(time_elapsed)&&time_elapsed>Math.floor(Strophe1.TIMEOUT*this.wait),secondary_timeout=null!==req.dead&&req.timeDead()>Math.floor(Strophe1.SECONDARY_TIMEOUT*this.wait),server_error=4===req.xhr.readyState&&(reqStatus<1||reqStatus>=500);if((primary_timeout||secondary_timeout||server_error)&&(secondary_timeout&&Strophe1.error(`Request ${this._requests[i].id} timed out (secondary), restarting`),req.abort=!0,req.xhr.abort(),req.xhr.onreadystatechange=function(){},this._requests[i]=new Strophe1.Request(req.xmlData,req.origFunc,req.rid,req.sends),req=this._requests[i]),0===req.xhr.readyState){Strophe1.debug("request id "+req.id+"."+req.sends+" posting");try{let content_type=this._conn.options.contentType||"text/xml; charset=utf-8";req.xhr.open("POST",this._conn.service,!this._conn.options.sync),void 0!==req.xhr.setRequestHeader&&req.xhr.setRequestHeader("Content-Type",content_type),this._conn.options.withCredentials&&(req.xhr.withCredentials=!0)}catch(e2){Strophe1.error("XHR open failed: "+e2.toString()),this._conn.connected||this._conn._changeConnectStatus(Strophe1.Status.CONNFAIL,"bad-service"),this._conn.disconnect();return}let sendFunc=()=>{if(req.date=new Date,this._conn.options.customHeaders){let headers=this._conn.options.customHeaders;for(let header in headers)Object.prototype.hasOwnProperty.call(headers,header)&&req.xhr.setRequestHeader(header,headers[header])}req.xhr.send(req.data)};req.sends>1?setTimeout(function(){sendFunc()},1e3*Math.min(Math.floor(Strophe1.TIMEOUT*this.wait),Math.pow(req.sends,3))):sendFunc(),req.sends++,this._conn.xmlOutput!==Strophe1.Connection.prototype.xmlOutput&&(req.xmlData.nodeName===this.strip&&req.xmlData.childNodes.length?this._conn.xmlOutput(req.xmlData.childNodes[0]):this._conn.xmlOutput(req.xmlData)),this._conn.rawOutput!==Strophe1.Connection.prototype.rawOutput&&this._conn.rawOutput(req.data)}else Strophe1.debug("_processRequest: "+(0===i?"first":"second")+" request has readyState of "+req.xhr.readyState)}_removeRequest(req){Strophe1.debug("removing request");for(let i=this._requests.length-1;i>=0;i--)req===this._requests[i]&&this._requests.splice(i,1);req.xhr.onreadystatechange=function(){},this._throttledRequestHandler()}_restartRequest(i){let req=this._requests[i];null===req.dead&&(req.dead=new Date),this._processRequest(i)}_reqToData(req){try{return req.getResponse()}catch(e){if("parsererror"!==e.message)throw e;this._conn.disconnect("strophe-parsererror")}}_sendTerminate(pres){Strophe1.debug("_sendTerminate was called");let body=this._buildBody().attrs({type:"terminate"});pres&&body.cnode(pres.tree());let req=new Strophe1.Request(body.tree(),this._onRequestStateChange.bind(this,this._conn._dataRecv.bind(this._conn)),body.tree().getAttribute("rid"));this._requests.push(req),this._throttledRequestHandler()}_send(){clearTimeout(this._conn._idleTimeout),this._throttledRequestHandler(),this._conn._idleTimeout=setTimeout(()=>this._conn._onIdle(),100)}_sendRestart(){this._throttledRequestHandler(),clearTimeout(this._conn._idleTimeout)}_throttledRequestHandler(){this._requests?Strophe1.debug("_throttledRequestHandler called with "+this._requests.length+" requests"):Strophe1.debug("_throttledRequestHandler called with undefined requests"),this._requests&&0!==this._requests.length&&(this._requests.length>0&&this._processRequest(0),this._requests.length>1&&Math.abs(this._requests[0].rid-this._requests[1].rid)<this.window&&this._processRequest(1))}},Strophe1.Bosh.prototype.strip=null,Strophe1.Websocket=class{constructor(connection){this._conn=connection,this.strip="wrapper";let service=connection.service;if(0!==service.indexOf("ws:")&&0!==service.indexOf("wss:")){let new_service="";"ws"===connection.options.protocol&&"https:"!==window.location.protocol?new_service+="ws":new_service+="wss",new_service+="://"+window.location.host,0!==service.indexOf("/")?new_service+=window.location.pathname+service:new_service+=service,connection.service=new_service}}_buildStream(){return $build1("open",{xmlns:Strophe1.NS.FRAMING,to:this._conn.domain,version:"1.0"})}_checkStreamError(bodyWrap,connectstatus){let errors;if(0===(errors=bodyWrap.getElementsByTagNameNS?bodyWrap.getElementsByTagNameNS(Strophe1.NS.STREAM,"error"):bodyWrap.getElementsByTagName("stream:error")).length)return!1;let error=errors[0],condition="",text="";for(let i=0;i<error.childNodes.length;i++){let e=error.childNodes[i];if("urn:ietf:params:xml:ns:xmpp-streams"!==e.getAttribute("xmlns"))break;"text"===e.nodeName?text=e.textContent:condition=e.nodeName}let errorString="WebSocket stream error: ";return condition?errorString+=condition:errorString+="unknown",text&&(errorString+=" - "+text),Strophe1.error(errorString),this._conn._changeConnectStatus(connectstatus,condition),this._conn._doDisconnect(),!0}_reset(){}_connect(){this._closeSocket(),this.socket=new WebSocket(this._conn.service,"xmpp"),this.socket.onopen=()=>this._onOpen(),this.socket.onerror=e=>this._onError(e),this.socket.onclose=e=>this._onClose(e),this.socket.onmessage=message=>this._onInitialMessage(message)}_connect_cb(bodyWrap){if(this._checkStreamError(bodyWrap,Strophe1.Status.CONNFAIL))return Strophe1.Status.CONNFAIL}_handleStreamStart(message){let error=!1,ns=message.getAttribute("xmlns");"string"!=typeof ns?error="Missing xmlns in <open />":ns!==Strophe1.NS.FRAMING&&(error="Wrong xmlns in <open />: "+ns);let ver=message.getAttribute("version");return"string"!=typeof ver?error="Missing version in <open />":"1.0"!==ver&&(error="Wrong version in <open />: "+ver),!error||(this._conn._changeConnectStatus(Strophe1.Status.CONNFAIL,error),this._conn._doDisconnect(),!1)}_onInitialMessage(message){if(0===message.data.indexOf("<open ")||0===message.data.indexOf("<?xml")){let data=message.data.replace(/^(<\?.*?\?>\s*)*/,"");if(""===data)return;let streamStart=new DOMParser1().parseFromString(data,"text/xml").documentElement;this._conn.xmlInput(streamStart),this._conn.rawInput(message.data),this._handleStreamStart(streamStart)&&this._connect_cb(streamStart)}else if(0===message.data.indexOf("<close ")){let parsedMessage=new DOMParser1().parseFromString(message.data,"text/xml").documentElement;this._conn.xmlInput(parsedMessage),this._conn.rawInput(message.data);let see_uri=parsedMessage.getAttribute("see-other-uri");if(see_uri){let service=this._conn.service;(service.indexOf("wss:")>=0&&see_uri.indexOf("wss:")>=0||service.indexOf("ws:")>=0)&&(this._conn._changeConnectStatus(Strophe1.Status.REDIRECT,"Received see-other-uri, resetting connection"),this._conn.reset(),this._conn.service=see_uri,this._connect())}else this._conn._changeConnectStatus(Strophe1.Status.CONNFAIL,"Received closing stream"),this._conn._doDisconnect()}else{this._replaceMessageHandler();let string=this._streamWrap(message.data),elem=new DOMParser1().parseFromString(string,"text/xml").documentElement;this._conn._connect_cb(elem,null,message.data)}}_replaceMessageHandler(){this.socket.onmessage=m=>this._onMessage(m)}_disconnect(pres){if(this.socket&&this.socket.readyState!==WebSocket.CLOSED){pres&&this._conn.send(pres);let close=$build1("close",{xmlns:Strophe1.NS.FRAMING});this._conn.xmlOutput(close.tree());let closeString=Strophe1.serialize(close);this._conn.rawOutput(closeString);try{this.socket.send(closeString)}catch(e){Strophe1.warn("Couldn't send <close /> tag.")}}setTimeout(()=>this._conn._doDisconnect,0)}_doDisconnect(){Strophe1.debug("WebSockets _doDisconnect was called"),this._closeSocket()}_streamWrap(stanza){return"<wrapper>"+stanza+"</wrapper>"}_closeSocket(){if(this.socket)try{this.socket.onclose=null,this.socket.onerror=null,this.socket.onmessage=null,this.socket.close()}catch(e){Strophe1.debug(e.message)}this.socket=null}_emptyQueue(){return!0}_onClose(e){this._conn.connected&&!this._conn.disconnecting?(Strophe1.error("Websocket closed unexpectedly"),this._conn._doDisconnect()):e&&1006===e.code&&!this._conn.connected&&this.socket?(Strophe1.error("Websocket closed unexcectedly"),this._conn._changeConnectStatus(Strophe1.Status.CONNFAIL,"The WebSocket connection could not be established or was disconnected."),this._conn._doDisconnect()):Strophe1.debug("Websocket closed")}_no_auth_received(callback){Strophe1.error("Server did not offer a supported authentication mechanism"),this._conn._changeConnectStatus(Strophe1.Status.CONNFAIL,Strophe1.ErrorCondition.NO_AUTH_MECH),callback&&callback.call(this._conn),this._conn._doDisconnect()}_onDisconnectTimeout(){}_abortAllRequests(){}_onError(error){Strophe1.error("Websocket error "+JSON.stringify(error)),this._conn._changeConnectStatus(Strophe1.Status.CONNFAIL,"The WebSocket connection could not be established or was disconnected."),this._disconnect()}_onIdle(){let data=this._conn._data;if(data.length>0&&!this._conn.paused){for(let i=0;i<data.length;i++)if(null!==data[i]){let stanza;stanza="restart"===data[i]?this._buildStream().tree():data[i];let rawStanza=Strophe1.serialize(stanza);this._conn.xmlOutput(stanza),this._conn.rawOutput(rawStanza),this.socket.send(rawStanza)}this._conn._data=[]}}_onMessage(message){let elem;let close='<close xmlns="urn:ietf:params:xml:ns:xmpp-framing" />';if(message.data===close){this._conn.rawInput(close),this._conn.xmlInput(message),this._conn.disconnecting||this._conn._doDisconnect();return}if(0===message.data.search("<open ")){if(elem=new DOMParser1().parseFromString(message.data,"text/xml").documentElement,!this._handleStreamStart(elem))return}else{let data=this._streamWrap(message.data);elem=new DOMParser1().parseFromString(data,"text/xml").documentElement}if(!this._checkStreamError(elem,Strophe1.Status.ERROR)){if(this._conn.disconnecting&&"presence"===elem.firstChild.nodeName&&"unavailable"===elem.firstChild.getAttribute("type")){this._conn.xmlInput(elem),this._conn.rawInput(Strophe1.serialize(elem));return}this._conn._dataRecv(elem,message.data)}}_onOpen(){Strophe1.debug("Websocket open");let start=this._buildStream();this._conn.xmlOutput(start.tree());let startString=Strophe1.serialize(start);this._conn.rawOutput(startString),this.socket.send(startString)}_reqToData(stanza){return stanza}_send(){this._conn.flush()}_sendRestart(){clearTimeout(this._conn._idleTimeout),this._conn._onIdle.bind(this._conn)()}};let lmap={};lmap.debug=Strophe1.LogLevel.DEBUG,lmap.info=Strophe1.LogLevel.INFO,lmap.warn=Strophe1.LogLevel.WARN,lmap.error=Strophe1.LogLevel.ERROR,lmap.fatal=Strophe1.LogLevel.FATAL,Strophe1.WorkerWebsocket=class extends Strophe1.Websocket{constructor(connection){super(connection),this._conn=connection,this.worker=new SharedWorker(this._conn.options.worker,"Strophe XMPP Connection"),this.worker.onerror=e=>{var _console;null===(_console=console)||void 0===_console||_console.error(e),Strophe1.log(Strophe1.LogLevel.ERROR,`Shared Worker Error: ${e}`)}}get socket(){return{send:str=>this.worker.port.postMessage(["send",str])}}_connect(){this._messageHandler=m=>this._onInitialMessage(m),this.worker.port.start(),this.worker.port.onmessage=ev=>this._onWorkerMessage(ev),this.worker.port.postMessage(["_connect",this._conn.service,this._conn.jid])}_attach(callback){this._messageHandler=m=>this._onMessage(m),this._conn.connect_callback=callback,this.worker.port.start(),this.worker.port.onmessage=ev=>this._onWorkerMessage(ev),this.worker.port.postMessage(["_attach",this._conn.service])}_attachCallback(status,jid){status===Strophe1.Status.ATTACHED?(this._conn.jid=jid,this._conn.authenticated=!0,this._conn.connected=!0,this._conn.restored=!0,this._conn._changeConnectStatus(Strophe1.Status.ATTACHED)):status===Strophe1.Status.ATTACHFAIL&&(this._conn.authenticated=!1,this._conn.connected=!1,this._conn.restored=!1,this._conn._changeConnectStatus(Strophe1.Status.ATTACHFAIL))}_disconnect(readyState,pres){pres&&this._conn.send(pres);let close=$build1("close",{xmlns:Strophe1.NS.FRAMING});this._conn.xmlOutput(close.tree());let closeString=Strophe1.serialize(close);this._conn.rawOutput(closeString),this.worker.port.postMessage(["send",closeString]),this._conn._doDisconnect()}_onClose(e){this._conn.connected&&!this._conn.disconnecting?(Strophe1.error("Websocket closed unexpectedly"),this._conn._doDisconnect()):e&&1006===e.code&&!this._conn.connected?(Strophe1.error("Websocket closed unexcectedly"),this._conn._changeConnectStatus(Strophe1.Status.CONNFAIL,"The WebSocket connection could not be established or was disconnected."),this._conn._doDisconnect()):Strophe1.debug("Websocket closed")}_closeSocket(){this.worker.port.postMessage(["_closeSocket"])}_replaceMessageHandler(){this._messageHandler=m=>this._onMessage(m)}_onWorkerMessage(ev){let{data}=ev,method_name=data[0];if("_onMessage"===method_name)this._messageHandler(data[1]);else if(method_name in this)try{this[method_name].apply(this,ev.data.slice(1))}catch(e){Strophe1.log(Strophe1.LogLevel.ERROR,e)}else if("log"===method_name){let level=data[1],msg=data[2];Strophe1.log(lmap[level],msg)}else Strophe1.log(Strophe1.LogLevel.ERROR,`Found unhandled service worker message: ${data}`)}},global$1.$build=core.$build,global$1.$iq=core.$iq,global$1.$msg=core.$msg,global$1.$pres=core.$pres,global$1.Strophe=core.Strophe;let{b64_sha1}=SHA1;exports.$build=$build1,exports.$iq=$iq1,exports.$msg=$msg1,exports.$pres=$pres1,exports.Strophe=Strophe1,exports.b64_sha1=b64_sha1,Object.defineProperty(exports,"__esModule",{value:!0})},"object"==typeof exports&&void 0!==module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global1="undefined"!=typeof globalThis?globalThis:global1||self).strophe={})}).call(this)}).call(this,void 0!==__webpack_require__.g?__webpack_require__.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"@xmldom/xmldom":5,ws:209}],209:[function(require1,module,exports){"use strict";module.exports=function(){throw Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}},{}],210:[function(require1,module,exports){(function(setImmediate,clearImmediate){(function(){var nextTick=require1("process/browser.js").nextTick,apply=Function.prototype.apply,slice=Array.prototype.slice,immediateIds={},nextImmediateId=0;function Timeout(id,clearFn){this._id=id,this._clearFn=clearFn}exports.setTimeout=function(){return new Timeout(apply.call(setTimeout,window,arguments),clearTimeout)},exports.setInterval=function(){return new Timeout(apply.call(setInterval,window,arguments),clearInterval)},exports.clearTimeout=exports.clearInterval=function(timeout){timeout.close()},Timeout.prototype.unref=Timeout.prototype.ref=function(){},Timeout.prototype.close=function(){this._clearFn.call(window,this._id)},exports.enroll=function(item,msecs){clearTimeout(item._idleTimeoutId),item._idleTimeout=msecs},exports.unenroll=function(item){clearTimeout(item._idleTimeoutId),item._idleTimeout=-1},exports._unrefActive=exports.active=function(item){clearTimeout(item._idleTimeoutId);var msecs=item._idleTimeout;msecs>=0&&(item._idleTimeoutId=setTimeout(function onTimeout(){item._onTimeout&&item._onTimeout()},msecs))},exports.setImmediate="function"==typeof setImmediate?setImmediate:function(fn){var id=nextImmediateId++,args=!(arguments.length<2)&&slice.call(arguments,1);return immediateIds[id]=!0,nextTick(function onNextTick(){immediateIds[id]&&(args?fn.apply(null,args):fn.call(null),exports.clearImmediate(id))}),id},exports.clearImmediate="function"==typeof clearImmediate?clearImmediate:function(id){delete immediateIds[id]}}).call(this)}).call(this,require1("timers").setImmediate,require1("timers").clearImmediate)},{"process/browser.js":152,timers:210}],211:[function(require1,module,exports){var Buffer=require1("buffer").Buffer;module.exports=function(buf){if(buf instanceof Uint8Array){if(0===buf.byteOffset&&buf.byteLength===buf.buffer.byteLength)return buf.buffer;if("function"==typeof buf.buffer.slice)return buf.buffer.slice(buf.byteOffset,buf.byteOffset+buf.byteLength)}if(Buffer.isBuffer(buf)){for(var arrayCopy=new Uint8Array(buf.length),len=buf.length,i=0;i<len;i++)arrayCopy[i]=buf[i];return arrayCopy.buffer}throw Error("Argument must be a Buffer")}},{buffer:47}],212:[function(require1,module,exports){"use strict";var punycode=require1("punycode"),util=require1("./util");function Url(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}exports.parse=urlParse,exports.resolve=urlResolve,exports.resolveObject=urlResolveObject,exports.format=urlFormat,exports.Url=Url;var protocolPattern=/^([a-z0-9.+-]+:)/i,portPattern=/:[0-9]*$/,simplePathPattern=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,autoEscape=["'"].concat(["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n"," "])),nonHostChars=["%","/","?",";","#"].concat(autoEscape),hostEndingChars=["/","?","#"],hostnamePartPattern=/^[+a-z0-9A-Z_-]{0,63}$/,hostnamePartStart=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,unsafeProtocol={javascript:!0,"javascript:":!0},hostlessProtocol={javascript:!0,"javascript:":!0},slashedProtocol={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},querystring=require1("querystring");function urlParse(url,parseQueryString,slashesDenoteHost){if(url&&util.isObject(url)&&url instanceof Url)return url;var u=new Url;return u.parse(url,parseQueryString,slashesDenoteHost),u}function urlFormat(obj){return(util.isString(obj)&&(obj=urlParse(obj)),obj instanceof Url)?obj.format():Url.prototype.format.call(obj)}function urlResolve(source,relative){return urlParse(source,!1,!0).resolve(relative)}function urlResolveObject(source,relative){return source?urlParse(source,!1,!0).resolveObject(relative):relative}Url.prototype.parse=function(url,parseQueryString,slashesDenoteHost){if(!util.isString(url))throw TypeError("Parameter 'url' must be a string, not "+typeof url);var queryIndex=url.indexOf("?"),splitter=-1!==queryIndex&&queryIndex<url.indexOf("#")?"?":"#",uSplit=url.split(splitter);uSplit[0]=uSplit[0].replace(/\\/g,"/");var rest=url=uSplit.join(splitter);if(rest=rest.trim(),!slashesDenoteHost&&1===url.split("#").length){var simplePath=simplePathPattern.exec(rest);if(simplePath)return this.path=rest,this.href=rest,this.pathname=simplePath[1],simplePath[2]?(this.search=simplePath[2],parseQueryString?this.query=querystring.parse(this.search.substr(1)):this.query=this.search.substr(1)):parseQueryString&&(this.search="",this.query={}),this}var proto=protocolPattern.exec(rest);if(proto){var lowerProto=(proto=proto[0]).toLowerCase();this.protocol=lowerProto,rest=rest.substr(proto.length)}if(slashesDenoteHost||proto||rest.match(/^\/\/[^@\/]+@[^@\/]+/)){var slashes="//"===rest.substr(0,2);slashes&&!(proto&&hostlessProtocol[proto])&&(rest=rest.substr(2),this.slashes=!0)}if(!hostlessProtocol[proto]&&(slashes||proto&&!slashedProtocol[proto])){for(var auth,atSign,hostEnd=-1,i=0;i<hostEndingChars.length;i++){var hec=rest.indexOf(hostEndingChars[i]);-1!==hec&&(-1===hostEnd||hec<hostEnd)&&(hostEnd=hec)}-1!==(atSign=-1===hostEnd?rest.lastIndexOf("@"):rest.lastIndexOf("@",hostEnd))&&(auth=rest.slice(0,atSign),rest=rest.slice(atSign+1),this.auth=decodeURIComponent(auth)),hostEnd=-1;for(var i=0;i<nonHostChars.length;i++){var hec=rest.indexOf(nonHostChars[i]);-1!==hec&&(-1===hostEnd||hec<hostEnd)&&(hostEnd=hec)}-1===hostEnd&&(hostEnd=rest.length),this.host=rest.slice(0,hostEnd),rest=rest.slice(hostEnd),this.parseHost(),this.hostname=this.hostname||"";var ipv6Hostname="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!ipv6Hostname)for(var hostparts=this.hostname.split(/\./),i=0,l=hostparts.length;i<l;i++){var part=hostparts[i];if(part&&!part.match(hostnamePartPattern)){for(var newpart="",j=0,k=part.length;j<k;j++)part.charCodeAt(j)>127?newpart+="x":newpart+=part[j];if(!newpart.match(hostnamePartPattern)){var validParts=hostparts.slice(0,i),notHost=hostparts.slice(i+1),bit=part.match(hostnamePartStart);bit&&(validParts.push(bit[1]),notHost.unshift(bit[2])),notHost.length&&(rest="/"+notHost.join(".")+rest),this.hostname=validParts.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),ipv6Hostname||(this.hostname=punycode.toASCII(this.hostname));var p=this.port?":"+this.port:"",h=this.hostname||"";this.host=h+p,this.href+=this.host,ipv6Hostname&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==rest[0]&&(rest="/"+rest))}if(!unsafeProtocol[lowerProto])for(var i=0,l=autoEscape.length;i<l;i++){var ae=autoEscape[i];if(-1!==rest.indexOf(ae)){var esc=encodeURIComponent(ae);esc===ae&&(esc=escape(ae)),rest=rest.split(ae).join(esc)}}var hash=rest.indexOf("#");-1!==hash&&(this.hash=rest.substr(hash),rest=rest.slice(0,hash));var qm=rest.indexOf("?");if(-1!==qm?(this.search=rest.substr(qm),this.query=rest.substr(qm+1),parseQueryString&&(this.query=querystring.parse(this.query)),rest=rest.slice(0,qm)):parseQueryString&&(this.search="",this.query={}),rest&&(this.pathname=rest),slashedProtocol[lowerProto]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var p=this.pathname||"",s=this.search||"";this.path=p+s}return this.href=this.format(),this},Url.prototype.format=function(){var auth=this.auth||"";auth&&(auth=(auth=encodeURIComponent(auth)).replace(/%3A/i,":")+"@");var protocol=this.protocol||"",pathname=this.pathname||"",hash=this.hash||"",host=!1,query="";this.host?host=auth+this.host:this.hostname&&(host=auth+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(host+=":"+this.port)),this.query&&util.isObject(this.query)&&Object.keys(this.query).length&&(query=querystring.stringify(this.query));var search=this.search||query&&"?"+query||"";return protocol&&":"!==protocol.substr(-1)&&(protocol+=":"),this.slashes||(!protocol||slashedProtocol[protocol])&&!1!==host?(host="//"+(host||""),pathname&&"/"!==pathname.charAt(0)&&(pathname="/"+pathname)):host||(host=""),hash&&"#"!==hash.charAt(0)&&(hash="#"+hash),search&&"?"!==search.charAt(0)&&(search="?"+search),protocol+host+(pathname=pathname.replace(/[?#]/g,function(match){return encodeURIComponent(match)}))+(search=search.replace("#","%23"))+hash},Url.prototype.resolve=function(relative){return this.resolveObject(urlParse(relative,!1,!0)).format()},Url.prototype.resolveObject=function(relative){if(util.isString(relative)){var rel=new Url;rel.parse(relative,!1,!0),relative=rel}for(var result=new Url,tkeys=Object.keys(this),tk=0;tk<tkeys.length;tk++){var tkey=tkeys[tk];result[tkey]=this[tkey]}if(result.hash=relative.hash,""===relative.href)return result.href=result.format(),result;if(relative.slashes&&!relative.protocol){for(var rkeys=Object.keys(relative),rk=0;rk<rkeys.length;rk++){var rkey=rkeys[rk];"protocol"!==rkey&&(result[rkey]=relative[rkey])}return slashedProtocol[result.protocol]&&result.hostname&&!result.pathname&&(result.path=result.pathname="/"),result.href=result.format(),result}if(relative.protocol&&relative.protocol!==result.protocol){if(!slashedProtocol[relative.protocol]){for(var keys=Object.keys(relative),v=0;v<keys.length;v++){var k=keys[v];result[k]=relative[k]}return result.href=result.format(),result}if(result.protocol=relative.protocol,relative.host||hostlessProtocol[relative.protocol])result.pathname=relative.pathname;else{for(var relPath=(relative.pathname||"").split("/");relPath.length&&!(relative.host=relPath.shift()););relative.host||(relative.host=""),relative.hostname||(relative.hostname=""),""!==relPath[0]&&relPath.unshift(""),relPath.length<2&&relPath.unshift(""),result.pathname=relPath.join("/")}if(result.search=relative.search,result.query=relative.query,result.host=relative.host||"",result.auth=relative.auth,result.hostname=relative.hostname||relative.host,result.port=relative.port,result.pathname||result.search){var p=result.pathname||"",s=result.search||"";result.path=p+s}return result.slashes=result.slashes||relative.slashes,result.href=result.format(),result}var isSourceAbs=result.pathname&&"/"===result.pathname.charAt(0),isRelAbs=relative.host||relative.pathname&&"/"===relative.pathname.charAt(0),mustEndAbs=isRelAbs||isSourceAbs||result.host&&relative.pathname,removeAllDots=mustEndAbs,srcPath=result.pathname&&result.pathname.split("/")||[],relPath=relative.pathname&&relative.pathname.split("/")||[],psychotic=result.protocol&&!slashedProtocol[result.protocol];if(psychotic&&(result.hostname="",result.port=null,result.host&&(""===srcPath[0]?srcPath[0]=result.host:srcPath.unshift(result.host)),result.host="",relative.protocol&&(relative.hostname=null,relative.port=null,relative.host&&(""===relPath[0]?relPath[0]=relative.host:relPath.unshift(relative.host)),relative.host=null),mustEndAbs=mustEndAbs&&(""===relPath[0]||""===srcPath[0])),isRelAbs)result.host=relative.host||""===relative.host?relative.host:result.host,result.hostname=relative.hostname||""===relative.hostname?relative.hostname:result.hostname,result.search=relative.search,result.query=relative.query,srcPath=relPath;else if(relPath.length)srcPath||(srcPath=[]),srcPath.pop(),srcPath=srcPath.concat(relPath),result.search=relative.search,result.query=relative.query;else if(!util.isNullOrUndefined(relative.search)){if(psychotic){result.hostname=result.host=srcPath.shift();var authInHost=!!(result.host&&result.host.indexOf("@")>0)&&result.host.split("@");authInHost&&(result.auth=authInHost.shift(),result.host=result.hostname=authInHost.shift())}return result.search=relative.search,result.query=relative.query,util.isNull(result.pathname)&&util.isNull(result.search)||(result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")),result.href=result.format(),result}if(!srcPath.length)return result.pathname=null,result.search?result.path="/"+result.search:result.path=null,result.href=result.format(),result;for(var last=srcPath.slice(-1)[0],hasTrailingSlash=(result.host||relative.host||srcPath.length>1)&&("."===last||".."===last)||""===last,up=0,i=srcPath.length;i>=0;i--)"."===(last=srcPath[i])?srcPath.splice(i,1):".."===last?(srcPath.splice(i,1),up++):up&&(srcPath.splice(i,1),up--);if(!mustEndAbs&&!removeAllDots)for(;up--;up)srcPath.unshift("..");mustEndAbs&&""!==srcPath[0]&&(!srcPath[0]||"/"!==srcPath[0].charAt(0))&&srcPath.unshift(""),hasTrailingSlash&&"/"!==srcPath.join("/").substr(-1)&&srcPath.push("");var isAbsolute=""===srcPath[0]||srcPath[0]&&"/"===srcPath[0].charAt(0);if(psychotic){result.hostname=result.host=isAbsolute?"":srcPath.length?srcPath.shift():"";var authInHost=!!(result.host&&result.host.indexOf("@")>0)&&result.host.split("@");authInHost&&(result.auth=authInHost.shift(),result.host=result.hostname=authInHost.shift())}return(mustEndAbs=mustEndAbs||result.host&&srcPath.length)&&!isAbsolute&&srcPath.unshift(""),srcPath.length?result.pathname=srcPath.join("/"):(result.pathname=null,result.path=null),util.isNull(result.pathname)&&util.isNull(result.search)||(result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")),result.auth=relative.auth||result.auth,result.slashes=result.slashes||relative.slashes,result.href=result.format(),result},Url.prototype.parseHost=function(){var host=this.host,port=portPattern.exec(host);port&&(":"!==(port=port[0])&&(this.port=port.substr(1)),host=host.substr(0,host.length-port.length)),host&&(this.hostname=host)}},{"./util":213,punycode:33,querystring:155}],213:[function(require1,module,exports){"use strict";module.exports={isString:function(arg){return"string"==typeof arg},isObject:function(arg){return"object"==typeof arg&&null!==arg},isNull:function(arg){return null===arg},isNullOrUndefined:function(arg){return null==arg}}},{}],214:[function(require1,module,exports){(function(global){(function(){function deprecate(fn,msg){if(config("noDeprecation"))return fn;var warned=!1;return function deprecated(){if(!warned){if(config("throwDeprecation"))throw Error(msg);config("traceDeprecation")?console.trace(msg):console.warn(msg),warned=!0}return fn.apply(this,arguments)}}function config(name){try{if(!global.localStorage)return!1}catch(_){return!1}var val=global.localStorage[name];return null!=val&&"true"===String(val).toLowerCase()}module.exports=deprecate}).call(this)}).call(this,void 0!==__webpack_require__.g?__webpack_require__.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],215:[function(require1,module,exports){arguments[4][18][0].apply(exports,arguments)},{dup:18}],216:[function(require1,module,exports){arguments[4][19][0].apply(exports,arguments)},{dup:19}],217:[function(require1,module,exports){arguments[4][20][0].apply(exports,arguments)},{"./support/isBuffer":216,_process:152,dup:20,inherits:215}],218:[function(require1,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var adapter=(0,require1("./adapter_factory.js").adapterFactory)({window:"undefined"==typeof window?void 0:window});exports.default=adapter},{"./adapter_factory.js":219}],219:[function(require1,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.adapterFactory=adapterFactory;var utils=_interopRequireWildcard(require1("./utils")),chromeShim=_interopRequireWildcard(require1("./chrome/chrome_shim")),edgeShim=_interopRequireWildcard(require1("./edge/edge_shim")),firefoxShim=_interopRequireWildcard(require1("./firefox/firefox_shim")),safariShim=_interopRequireWildcard(require1("./safari/safari_shim")),commonShim=_interopRequireWildcard(require1("./common_shim"));function _interopRequireWildcard(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}function adapterFactory(){var _ref=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},window1=_ref.window,options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0},logging=utils.log,browserDetails=utils.detectBrowser(window1),adapter={browserDetails:browserDetails,commonShim:commonShim,extractVersion:utils.extractVersion,disableLog:utils.disableLog,disableWarnings:utils.disableWarnings};switch(browserDetails.browser){case"chrome":if(!chromeShim||!chromeShim.shimPeerConnection||!options.shimChrome){logging("Chrome shim is not included in this adapter release.");break}if(null===browserDetails.version){logging("Chrome shim can not determine version, not shimming.");break}logging("adapter.js shimming chrome."),adapter.browserShim=chromeShim,commonShim.shimAddIceCandidateNullOrEmpty(window1,browserDetails),chromeShim.shimGetUserMedia(window1,browserDetails),chromeShim.shimMediaStream(window1,browserDetails),chromeShim.shimPeerConnection(window1,browserDetails),chromeShim.shimOnTrack(window1,browserDetails),chromeShim.shimAddTrackRemoveTrack(window1,browserDetails),chromeShim.shimGetSendersWithDtmf(window1,browserDetails),chromeShim.shimGetStats(window1,browserDetails),chromeShim.shimSenderReceiverGetStats(window1,browserDetails),chromeShim.fixNegotiationNeeded(window1,browserDetails),commonShim.shimRTCIceCandidate(window1,browserDetails),commonShim.shimConnectionState(window1,browserDetails),commonShim.shimMaxMessageSize(window1,browserDetails),commonShim.shimSendThrowTypeError(window1,browserDetails),commonShim.removeExtmapAllowMixed(window1,browserDetails);break;case"firefox":if(!firefoxShim||!firefoxShim.shimPeerConnection||!options.shimFirefox){logging("Firefox shim is not included in this adapter release.");break}logging("adapter.js shimming firefox."),adapter.browserShim=firefoxShim,commonShim.shimAddIceCandidateNullOrEmpty(window1,browserDetails),firefoxShim.shimGetUserMedia(window1,browserDetails),firefoxShim.shimPeerConnection(window1,browserDetails),firefoxShim.shimOnTrack(window1,browserDetails),firefoxShim.shimRemoveStream(window1,browserDetails),firefoxShim.shimSenderGetStats(window1,browserDetails),firefoxShim.shimReceiverGetStats(window1,browserDetails),firefoxShim.shimRTCDataChannel(window1,browserDetails),firefoxShim.shimAddTransceiver(window1,browserDetails),firefoxShim.shimGetParameters(window1,browserDetails),firefoxShim.shimCreateOffer(window1,browserDetails),firefoxShim.shimCreateAnswer(window1,browserDetails),commonShim.shimRTCIceCandidate(window1,browserDetails),commonShim.shimConnectionState(window1,browserDetails),commonShim.shimMaxMessageSize(window1,browserDetails),commonShim.shimSendThrowTypeError(window1,browserDetails);break;case"edge":if(!edgeShim||!edgeShim.shimPeerConnection||!options.shimEdge){logging("MS edge shim is not included in this adapter release.");break}logging("adapter.js shimming edge."),adapter.browserShim=edgeShim,edgeShim.shimGetUserMedia(window1,browserDetails),edgeShim.shimGetDisplayMedia(window1,browserDetails),edgeShim.shimPeerConnection(window1,browserDetails),edgeShim.shimReplaceTrack(window1,browserDetails),commonShim.shimMaxMessageSize(window1,browserDetails),commonShim.shimSendThrowTypeError(window1,browserDetails);break;case"safari":if(!safariShim||!options.shimSafari){logging("Safari shim is not included in this adapter release.");break}logging("adapter.js shimming safari."),adapter.browserShim=safariShim,commonShim.shimAddIceCandidateNullOrEmpty(window1,browserDetails),safariShim.shimRTCIceServerUrls(window1,browserDetails),safariShim.shimCreateOfferLegacy(window1,browserDetails),safariShim.shimCallbacksAPI(window1,browserDetails),safariShim.shimLocalStreamsAPI(window1,browserDetails),safariShim.shimRemoteStreamsAPI(window1,browserDetails),safariShim.shimTrackEventTransceiver(window1,browserDetails),safariShim.shimGetUserMedia(window1,browserDetails),safariShim.shimAudioContext(window1,browserDetails),commonShim.shimRTCIceCandidate(window1,browserDetails),commonShim.shimMaxMessageSize(window1,browserDetails),commonShim.shimSendThrowTypeError(window1,browserDetails),commonShim.removeExtmapAllowMixed(window1,browserDetails);break;default:logging("Unsupported browser!")}return adapter}},{"./chrome/chrome_shim":220,"./common_shim":223,"./edge/edge_shim":224,"./firefox/firefox_shim":228,"./safari/safari_shim":231,"./utils":232}],220:[function(require1,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=exports.shimGetUserMedia=void 0;var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},_getusermedia=require1("./getusermedia");Object.defineProperty(exports,"shimGetUserMedia",{enumerable:!0,get:function get(){return _getusermedia.shimGetUserMedia}});var _getdisplaymedia=require1("./getdisplaymedia");Object.defineProperty(exports,"shimGetDisplayMedia",{enumerable:!0,get:function get(){return _getdisplaymedia.shimGetDisplayMedia}}),exports.shimMediaStream=shimMediaStream,exports.shimOnTrack=shimOnTrack,exports.shimGetSendersWithDtmf=shimGetSendersWithDtmf,exports.shimGetStats=shimGetStats,exports.shimSenderReceiverGetStats=shimSenderReceiverGetStats,exports.shimAddTrackRemoveTrackWithNative=shimAddTrackRemoveTrackWithNative,exports.shimAddTrackRemoveTrack=shimAddTrackRemoveTrack,exports.shimPeerConnection=shimPeerConnection,exports.fixNegotiationNeeded=fixNegotiationNeeded;var utils=_interopRequireWildcard(require1("../utils.js"));function _interopRequireWildcard(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function shimMediaStream(window1){window1.MediaStream=window1.MediaStream||window1.webkitMediaStream}function shimOnTrack(window1){if((void 0===window1?"undefined":_typeof(window1))!=="object"||!window1.RTCPeerConnection||"ontrack"in window1.RTCPeerConnection.prototype)utils.wrapPeerConnectionEvent(window1,"track",function(e){return e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e});else{Object.defineProperty(window1.RTCPeerConnection.prototype,"ontrack",{get:function get(){return this._ontrack},set:function set(f){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=f)},enumerable:!0,configurable:!0});var origSetRemoteDescription=window1.RTCPeerConnection.prototype.setRemoteDescription;window1.RTCPeerConnection.prototype.setRemoteDescription=function setRemoteDescription(){var _this=this;return this._ontrackpoly||(this._ontrackpoly=function(e){e.stream.addEventListener("addtrack",function(te){var receiver=void 0;receiver=window1.RTCPeerConnection.prototype.getReceivers?_this.getReceivers().find(function(r){return r.track&&r.track.id===te.track.id}):{track:te.track};var event=new Event("track");event.track=te.track,event.receiver=receiver,event.transceiver={receiver:receiver},event.streams=[e.stream],_this.dispatchEvent(event)}),e.stream.getTracks().forEach(function(track){var receiver=void 0;receiver=window1.RTCPeerConnection.prototype.getReceivers?_this.getReceivers().find(function(r){return r.track&&r.track.id===track.id}):{track:track};var event=new Event("track");event.track=track,event.receiver=receiver,event.transceiver={receiver:receiver},event.streams=[e.stream],_this.dispatchEvent(event)})},this.addEventListener("addstream",this._ontrackpoly)),origSetRemoteDescription.apply(this,arguments)}}}function shimGetSendersWithDtmf(window1){if((void 0===window1?"undefined":_typeof(window1))==="object"&&window1.RTCPeerConnection&&!("getSenders"in window1.RTCPeerConnection.prototype)&&"createDTMFSender"in window1.RTCPeerConnection.prototype){var shimSenderWithDtmf=function(pc,track){return{track:track,get dtmf(){return void 0===this._dtmf&&("audio"===track.kind?this._dtmf=pc.createDTMFSender(track):this._dtmf=null),this._dtmf},_pc:pc}};if(!window1.RTCPeerConnection.prototype.getSenders){window1.RTCPeerConnection.prototype.getSenders=function getSenders(){return this._senders=this._senders||[],this._senders.slice()};var origAddTrack=window1.RTCPeerConnection.prototype.addTrack;window1.RTCPeerConnection.prototype.addTrack=function addTrack(track,stream){var sender=origAddTrack.apply(this,arguments);return sender||(sender=shimSenderWithDtmf(this,track),this._senders.push(sender)),sender};var origRemoveTrack=window1.RTCPeerConnection.prototype.removeTrack;window1.RTCPeerConnection.prototype.removeTrack=function removeTrack(sender){origRemoveTrack.apply(this,arguments);var idx=this._senders.indexOf(sender);-1!==idx&&this._senders.splice(idx,1)}}var origAddStream=window1.RTCPeerConnection.prototype.addStream;window1.RTCPeerConnection.prototype.addStream=function addStream(stream){var _this2=this;this._senders=this._senders||[],origAddStream.apply(this,[stream]),stream.getTracks().forEach(function(track){_this2._senders.push(shimSenderWithDtmf(_this2,track))})};var origRemoveStream=window1.RTCPeerConnection.prototype.removeStream;window1.RTCPeerConnection.prototype.removeStream=function removeStream(stream){var _this3=this;this._senders=this._senders||[],origRemoveStream.apply(this,[stream]),stream.getTracks().forEach(function(track){var sender=_this3._senders.find(function(s){return s.track===track});sender&&_this3._senders.splice(_this3._senders.indexOf(sender),1)})}}else if((void 0===window1?"undefined":_typeof(window1))==="object"&&window1.RTCPeerConnection&&"getSenders"in window1.RTCPeerConnection.prototype&&"createDTMFSender"in window1.RTCPeerConnection.prototype&&window1.RTCRtpSender&&!("dtmf"in window1.RTCRtpSender.prototype)){var origGetSenders=window1.RTCPeerConnection.prototype.getSenders;window1.RTCPeerConnection.prototype.getSenders=function getSenders(){var _this4=this,senders=origGetSenders.apply(this,[]);return senders.forEach(function(sender){return sender._pc=_this4}),senders},Object.defineProperty(window1.RTCRtpSender.prototype,"dtmf",{get:function get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function shimGetStats(window1){if(window1.RTCPeerConnection){var origGetStats=window1.RTCPeerConnection.prototype.getStats;window1.RTCPeerConnection.prototype.getStats=function getStats(){var _this5=this,_arguments=Array.prototype.slice.call(arguments),selector=_arguments[0],onSucc=_arguments[1],onErr=_arguments[2];if(arguments.length>0&&"function"==typeof selector)return origGetStats.apply(this,arguments);if(0===origGetStats.length&&(0==arguments.length||"function"!=typeof selector))return origGetStats.apply(this,[]);var fixChromeStats_=function(response){var standardReport={};return response.result().forEach(function(report){var standardStats={id:report.id,timestamp:report.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[report.type]||report.type};report.names().forEach(function(name){standardStats[name]=report.stat(name)}),standardReport[standardStats.id]=standardStats}),standardReport},makeMapStats=function(stats){return new Map(Object.keys(stats).map(function(key){return[key,stats[key]]}))};return arguments.length>=2?origGetStats.apply(this,[function(response){onSucc(makeMapStats(fixChromeStats_(response)))},selector]):new Promise(function(resolve,reject){origGetStats.apply(_this5,[function(response){resolve(makeMapStats(fixChromeStats_(response)))},reject])}).then(onSucc,onErr)}}}function shimSenderReceiverGetStats(window1){if((void 0===window1?"undefined":_typeof(window1))==="object"&&window1.RTCPeerConnection&&window1.RTCRtpSender&&window1.RTCRtpReceiver){if(!("getStats"in window1.RTCRtpSender.prototype)){var origGetSenders=window1.RTCPeerConnection.prototype.getSenders;origGetSenders&&(window1.RTCPeerConnection.prototype.getSenders=function getSenders(){var _this6=this,senders=origGetSenders.apply(this,[]);return senders.forEach(function(sender){return sender._pc=_this6}),senders});var origAddTrack=window1.RTCPeerConnection.prototype.addTrack;origAddTrack&&(window1.RTCPeerConnection.prototype.addTrack=function addTrack(){var sender=origAddTrack.apply(this,arguments);return sender._pc=this,sender}),window1.RTCRtpSender.prototype.getStats=function getStats(){var sender=this;return this._pc.getStats().then(function(result){return utils.filterStats(result,sender.track,!0)})}}if(!("getStats"in window1.RTCRtpReceiver.prototype)){var origGetReceivers=window1.RTCPeerConnection.prototype.getReceivers;origGetReceivers&&(window1.RTCPeerConnection.prototype.getReceivers=function getReceivers(){var _this7=this,receivers=origGetReceivers.apply(this,[]);return receivers.forEach(function(receiver){return receiver._pc=_this7}),receivers}),utils.wrapPeerConnectionEvent(window1,"track",function(e){return e.receiver._pc=e.srcElement,e}),window1.RTCRtpReceiver.prototype.getStats=function getStats(){var receiver=this;return this._pc.getStats().then(function(result){return utils.filterStats(result,receiver.track,!1)})}}if("getStats"in window1.RTCRtpSender.prototype&&"getStats"in window1.RTCRtpReceiver.prototype){var origGetStats=window1.RTCPeerConnection.prototype.getStats;window1.RTCPeerConnection.prototype.getStats=function getStats(){if(arguments.length>0&&arguments[0]instanceof window1.MediaStreamTrack){var track=arguments[0],sender=void 0,receiver=void 0,err=void 0;return(this.getSenders().forEach(function(s){s.track===track&&(sender?err=!0:sender=s)}),this.getReceivers().forEach(function(r){return r.track===track&&(receiver?err=!0:receiver=r),r.track===track}),err||sender&&receiver)?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):sender?sender.getStats():receiver?receiver.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return origGetStats.apply(this,arguments)}}}}function shimAddTrackRemoveTrackWithNative(window1){window1.RTCPeerConnection.prototype.getLocalStreams=function getLocalStreams(){var _this8=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(function(streamId){return _this8._shimmedLocalStreams[streamId][0]})};var origAddTrack=window1.RTCPeerConnection.prototype.addTrack;window1.RTCPeerConnection.prototype.addTrack=function addTrack(track,stream){if(!stream)return origAddTrack.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};var sender=origAddTrack.apply(this,arguments);return this._shimmedLocalStreams[stream.id]?-1===this._shimmedLocalStreams[stream.id].indexOf(sender)&&this._shimmedLocalStreams[stream.id].push(sender):this._shimmedLocalStreams[stream.id]=[stream,sender],sender};var origAddStream=window1.RTCPeerConnection.prototype.addStream;window1.RTCPeerConnection.prototype.addStream=function addStream(stream){var _this9=this;this._shimmedLocalStreams=this._shimmedLocalStreams||{},stream.getTracks().forEach(function(track){if(_this9.getSenders().find(function(s){return s.track===track}))throw new DOMException("Track already exists.","InvalidAccessError")});var existingSenders=this.getSenders();origAddStream.apply(this,arguments);var newSenders=this.getSenders().filter(function(newSender){return -1===existingSenders.indexOf(newSender)});this._shimmedLocalStreams[stream.id]=[stream].concat(newSenders)};var origRemoveStream=window1.RTCPeerConnection.prototype.removeStream;window1.RTCPeerConnection.prototype.removeStream=function removeStream(stream){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[stream.id],origRemoveStream.apply(this,arguments)};var origRemoveTrack=window1.RTCPeerConnection.prototype.removeTrack;window1.RTCPeerConnection.prototype.removeTrack=function removeTrack(sender){var _this10=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},sender&&Object.keys(this._shimmedLocalStreams).forEach(function(streamId){var idx=_this10._shimmedLocalStreams[streamId].indexOf(sender);-1!==idx&&_this10._shimmedLocalStreams[streamId].splice(idx,1),1===_this10._shimmedLocalStreams[streamId].length&&delete _this10._shimmedLocalStreams[streamId]}),origRemoveTrack.apply(this,arguments)}}function shimAddTrackRemoveTrack(window1,browserDetails){if(window1.RTCPeerConnection){if(window1.RTCPeerConnection.prototype.addTrack&&browserDetails.version>=65)return shimAddTrackRemoveTrackWithNative(window1);var origGetLocalStreams=window1.RTCPeerConnection.prototype.getLocalStreams;window1.RTCPeerConnection.prototype.getLocalStreams=function getLocalStreams(){var _this11=this,nativeStreams=origGetLocalStreams.apply(this);return this._reverseStreams=this._reverseStreams||{},nativeStreams.map(function(stream){return _this11._reverseStreams[stream.id]})};var origAddStream=window1.RTCPeerConnection.prototype.addStream;window1.RTCPeerConnection.prototype.addStream=function addStream(stream){var _this12=this;if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},stream.getTracks().forEach(function(track){if(_this12.getSenders().find(function(s){return s.track===track}))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[stream.id]){var newStream=new window1.MediaStream(stream.getTracks());this._streams[stream.id]=newStream,this._reverseStreams[newStream.id]=stream,stream=newStream}origAddStream.apply(this,[stream])};var origRemoveStream=window1.RTCPeerConnection.prototype.removeStream;window1.RTCPeerConnection.prototype.removeStream=function removeStream(stream){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},origRemoveStream.apply(this,[this._streams[stream.id]||stream]),delete this._reverseStreams[this._streams[stream.id]?this._streams[stream.id].id:stream.id],delete this._streams[stream.id]},window1.RTCPeerConnection.prototype.addTrack=function addTrack(track,stream){var _this13=this;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");var streams=[].slice.call(arguments,1);if(1!==streams.length||!streams[0].getTracks().find(function(t){return t===track}))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(function(s){return s.track===track}))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};var oldStream=this._streams[stream.id];if(oldStream)oldStream.addTrack(track),Promise.resolve().then(function(){_this13.dispatchEvent(new Event("negotiationneeded"))});else{var newStream=new window1.MediaStream([track]);this._streams[stream.id]=newStream,this._reverseStreams[newStream.id]=stream,this.addStream(newStream)}return this.getSenders().find(function(s){return s.track===track})},["createOffer","createAnswer"].forEach(function(method){var nativeMethod=window1.RTCPeerConnection.prototype[method],methodObj=_defineProperty({},method,function(){var _this14=this,args=arguments,isLegacyCall=arguments.length&&"function"==typeof arguments[0];return isLegacyCall?nativeMethod.apply(this,[function(description){var desc=replaceInternalStreamId(_this14,description);args[0].apply(null,[desc])},function(err){args[1]&&args[1].apply(null,err)},arguments[2]]):nativeMethod.apply(this,arguments).then(function(description){return replaceInternalStreamId(_this14,description)})});window1.RTCPeerConnection.prototype[method]=methodObj[method]});var origSetLocalDescription=window1.RTCPeerConnection.prototype.setLocalDescription;window1.RTCPeerConnection.prototype.setLocalDescription=function setLocalDescription(){return arguments.length&&arguments[0].type&&(arguments[0]=replaceExternalStreamId(this,arguments[0])),origSetLocalDescription.apply(this,arguments)};var origLocalDescription=Object.getOwnPropertyDescriptor(window1.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(window1.RTCPeerConnection.prototype,"localDescription",{get:function get(){var description=origLocalDescription.get.apply(this);return""===description.type?description:replaceInternalStreamId(this,description)}}),window1.RTCPeerConnection.prototype.removeTrack=function removeTrack(sender){var _this15=this;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!sender._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(sender._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};var stream=void 0;Object.keys(this._streams).forEach(function(streamid){_this15._streams[streamid].getTracks().find(function(track){return sender.track===track})&&(stream=_this15._streams[streamid])}),stream&&(1===stream.getTracks().length?this.removeStream(this._reverseStreams[stream.id]):stream.removeTrack(sender.track),this.dispatchEvent(new Event("negotiationneeded")))}}function replaceInternalStreamId(pc,description){var sdp=description.sdp;return Object.keys(pc._reverseStreams||[]).forEach(function(internalId){var externalStream=pc._reverseStreams[internalId],internalStream=pc._streams[externalStream.id];sdp=sdp.replace(RegExp(internalStream.id,"g"),externalStream.id)}),new RTCSessionDescription({type:description.type,sdp:sdp})}function replaceExternalStreamId(pc,description){var sdp=description.sdp;return Object.keys(pc._reverseStreams||[]).forEach(function(internalId){var externalStream=pc._reverseStreams[internalId],internalStream=pc._streams[externalStream.id];sdp=sdp.replace(RegExp(externalStream.id,"g"),internalStream.id)}),new RTCSessionDescription({type:description.type,sdp:sdp})}}function shimPeerConnection(window1,browserDetails){!window1.RTCPeerConnection&&window1.webkitRTCPeerConnection&&(window1.RTCPeerConnection=window1.webkitRTCPeerConnection),window1.RTCPeerConnection&&browserDetails.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(method){var nativeMethod=window1.RTCPeerConnection.prototype[method],methodObj=_defineProperty({},method,function(){return arguments[0]=new("addIceCandidate"===method?window1.RTCIceCandidate:window1.RTCSessionDescription)(arguments[0]),nativeMethod.apply(this,arguments)});window1.RTCPeerConnection.prototype[method]=methodObj[method]})}function fixNegotiationNeeded(window1,browserDetails){utils.wrapPeerConnectionEvent(window1,"negotiationneeded",function(e){var pc=e.target;if(!(browserDetails.version<72)&&(!pc.getConfiguration||"plan-b"!==pc.getConfiguration().sdpSemantics)||"stable"===pc.signalingState)return e})}},{"../utils.js":232,"./getdisplaymedia":221,"./getusermedia":222}],221:[function(require1,module,exports){"use strict";function shimGetDisplayMedia(window1,getSourceId){if((!window1.navigator.mediaDevices||!("getDisplayMedia"in window1.navigator.mediaDevices))&&window1.navigator.mediaDevices){if("function"!=typeof getSourceId){console.error("shimGetDisplayMedia: getSourceId argument is not a function");return}window1.navigator.mediaDevices.getDisplayMedia=function getDisplayMedia(constraints){return getSourceId(constraints).then(function(sourceId){var widthSpecified=constraints.video&&constraints.video.width,heightSpecified=constraints.video&&constraints.video.height,frameRateSpecified=constraints.video&&constraints.video.frameRate;return constraints.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:sourceId,maxFrameRate:frameRateSpecified||3}},widthSpecified&&(constraints.video.mandatory.maxWidth=widthSpecified),heightSpecified&&(constraints.video.mandatory.maxHeight=heightSpecified),window1.navigator.mediaDevices.getUserMedia(constraints)})}}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=shimGetDisplayMedia},{}],222:[function(require1,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};exports.shimGetUserMedia=shimGetUserMedia;var logging=function _interopRequireWildcard(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require1("../utils.js")).log;function shimGetUserMedia(window1,browserDetails){var navigator1=window1&&window1.navigator;if(navigator1.mediaDevices){var constraintsToChrome_=function(c){if((void 0===c?"undefined":_typeof(c))!=="object"||c.mandatory||c.optional)return c;var cc={};return Object.keys(c).forEach(function(key){if("require"!==key&&"advanced"!==key&&"mediaSource"!==key){var r="object"===_typeof(c[key])?c[key]:{ideal:c[key]};void 0!==r.exact&&"number"==typeof r.exact&&(r.min=r.max=r.exact);var oldname_=function(prefix,name){return prefix?prefix+name.charAt(0).toUpperCase()+name.slice(1):"deviceId"===name?"sourceId":name};if(void 0!==r.ideal){cc.optional=cc.optional||[];var oc={};"number"==typeof r.ideal?(oc[oldname_("min",key)]=r.ideal,cc.optional.push(oc),(oc={})[oldname_("max",key)]=r.ideal):oc[oldname_("",key)]=r.ideal,cc.optional.push(oc)}void 0!==r.exact&&"number"!=typeof r.exact?(cc.mandatory=cc.mandatory||{},cc.mandatory[oldname_("",key)]=r.exact):["min","max"].forEach(function(mix){void 0!==r[mix]&&(cc.mandatory=cc.mandatory||{},cc.mandatory[oldname_(mix,key)]=r[mix])})}}),c.advanced&&(cc.optional=(cc.optional||[]).concat(c.advanced)),cc},shimConstraints_=function(constraints,func){if(browserDetails.version>=61)return func(constraints);if((constraints=JSON.parse(JSON.stringify(constraints)))&&"object"===_typeof(constraints.audio)){var remap=function(obj,a,b){a in obj&&!(b in obj)&&(obj[b]=obj[a],delete obj[a])};remap((constraints=JSON.parse(JSON.stringify(constraints))).audio,"autoGainControl","googAutoGainControl"),remap(constraints.audio,"noiseSuppression","googNoiseSuppression"),constraints.audio=constraintsToChrome_(constraints.audio)}if(constraints&&"object"===_typeof(constraints.video)){var face=constraints.video.facingMode;face=face&&((void 0===face?"undefined":_typeof(face))==="object"?face:{ideal:face});var getSupportedFacingModeLies=browserDetails.version<66;if(face&&("user"===face.exact||"environment"===face.exact||"user"===face.ideal||"environment"===face.ideal)&&!(navigator1.mediaDevices.getSupportedConstraints&&navigator1.mediaDevices.getSupportedConstraints().facingMode&&!getSupportedFacingModeLies)){delete constraints.video.facingMode;var matches=void 0;if("environment"===face.exact||"environment"===face.ideal?matches=["back","rear"]:("user"===face.exact||"user"===face.ideal)&&(matches=["front"]),matches)return navigator1.mediaDevices.enumerateDevices().then(function(devices){var dev=(devices=devices.filter(function(d){return"videoinput"===d.kind})).find(function(d){return matches.some(function(match){return d.label.toLowerCase().includes(match)})});return!dev&&devices.length&&matches.includes("back")&&(dev=devices[devices.length-1]),dev&&(constraints.video.deviceId=face.exact?{exact:dev.deviceId}:{ideal:dev.deviceId}),constraints.video=constraintsToChrome_(constraints.video),logging("chrome: "+JSON.stringify(constraints)),func(constraints)})}constraints.video=constraintsToChrome_(constraints.video)}return logging("chrome: "+JSON.stringify(constraints)),func(constraints)},shimError_=function(e){return browserDetails.version>=64?e:{name:({PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"})[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString:function toString(){return this.name+(this.message&&": ")+this.message}}};if(navigator1.getUserMedia=(function(constraints,onSuccess,onError){shimConstraints_(constraints,function(c){navigator1.webkitGetUserMedia(c,onSuccess,function(e){onError&&onError(shimError_(e))})})}).bind(navigator1),navigator1.mediaDevices.getUserMedia){var origGetUserMedia=navigator1.mediaDevices.getUserMedia.bind(navigator1.mediaDevices);navigator1.mediaDevices.getUserMedia=function(cs){return shimConstraints_(cs,function(c){return origGetUserMedia(c).then(function(stream){if(c.audio&&!stream.getAudioTracks().length||c.video&&!stream.getVideoTracks().length)throw stream.getTracks().forEach(function(track){track.stop()}),new DOMException("","NotFoundError");return stream},function(e){return Promise.reject(shimError_(e))})})}}}}},{"../utils.js":232}],223:[function(require1,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};exports.shimRTCIceCandidate=shimRTCIceCandidate,exports.shimMaxMessageSize=shimMaxMessageSize,exports.shimSendThrowTypeError=shimSendThrowTypeError,exports.shimConnectionState=shimConnectionState,exports.removeExtmapAllowMixed=removeExtmapAllowMixed,exports.shimAddIceCandidateNullOrEmpty=shimAddIceCandidateNullOrEmpty;var _sdp2=_interopRequireDefault(require1("sdp")),utils=_interopRequireWildcard(require1("./utils"));function _interopRequireWildcard(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function shimRTCIceCandidate(window1){if(window1.RTCIceCandidate&&(!window1.RTCIceCandidate||!("foundation"in window1.RTCIceCandidate.prototype))){var NativeRTCIceCandidate=window1.RTCIceCandidate;window1.RTCIceCandidate=function RTCIceCandidate(args){if((void 0===args?"undefined":_typeof(args))==="object"&&args.candidate&&0===args.candidate.indexOf("a=")&&((args=JSON.parse(JSON.stringify(args))).candidate=args.candidate.substr(2)),args.candidate&&args.candidate.length){var augmentedCandidate=Object.assign(new NativeRTCIceCandidate(args),_sdp2.default.parseCandidate(args.candidate));return augmentedCandidate.toJSON=function toJSON(){return{candidate:augmentedCandidate.candidate,sdpMid:augmentedCandidate.sdpMid,sdpMLineIndex:augmentedCandidate.sdpMLineIndex,usernameFragment:augmentedCandidate.usernameFragment}},augmentedCandidate}return new NativeRTCIceCandidate(args)},window1.RTCIceCandidate.prototype=NativeRTCIceCandidate.prototype,utils.wrapPeerConnectionEvent(window1,"icecandidate",function(e){return e.candidate&&Object.defineProperty(e,"candidate",{value:new window1.RTCIceCandidate(e.candidate),writable:"false"}),e})}}function shimMaxMessageSize(window1,browserDetails){if(window1.RTCPeerConnection){"sctp"in window1.RTCPeerConnection.prototype||Object.defineProperty(window1.RTCPeerConnection.prototype,"sctp",{get:function get(){return void 0===this._sctp?null:this._sctp}});var sctpInDescription=function(description){if(!description||!description.sdp)return!1;var sections=_sdp2.default.splitSections(description.sdp);return sections.shift(),sections.some(function(mediaSection){var mLine=_sdp2.default.parseMLine(mediaSection);return mLine&&"application"===mLine.kind&&-1!==mLine.protocol.indexOf("SCTP")})},getRemoteFirefoxVersion=function(description){var match=description.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===match||match.length<2)return -1;var version=parseInt(match[1],10);return version!=version?-1:version},getCanSendMaxMessageSize=function(remoteIsFirefox){var canSendMaxMessageSize=65536;return"firefox"===browserDetails.browser&&(canSendMaxMessageSize=browserDetails.version<57?-1===remoteIsFirefox?16384:2147483637:browserDetails.version<60?57===browserDetails.version?65535:65536:2147483637),canSendMaxMessageSize},getMaxMessageSize=function(description,remoteIsFirefox){var maxMessageSize=65536;"firefox"===browserDetails.browser&&57===browserDetails.version&&(maxMessageSize=65535);var match=_sdp2.default.matchPrefix(description.sdp,"a=max-message-size:");return match.length>0?maxMessageSize=parseInt(match[0].substr(19),10):"firefox"===browserDetails.browser&&-1!==remoteIsFirefox&&(maxMessageSize=2147483637),maxMessageSize},origSetRemoteDescription=window1.RTCPeerConnection.prototype.setRemoteDescription;window1.RTCPeerConnection.prototype.setRemoteDescription=function setRemoteDescription(){if(this._sctp=null,"chrome"===browserDetails.browser&&browserDetails.version>=76&&"plan-b"===this.getConfiguration().sdpSemantics&&Object.defineProperty(this,"sctp",{get:function get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0}),sctpInDescription(arguments[0])){var isFirefox=getRemoteFirefoxVersion(arguments[0]),canSendMMS=getCanSendMaxMessageSize(isFirefox),remoteMMS=getMaxMessageSize(arguments[0],isFirefox),maxMessageSize=void 0;maxMessageSize=0===canSendMMS&&0===remoteMMS?Number.POSITIVE_INFINITY:0===canSendMMS||0===remoteMMS?Math.max(canSendMMS,remoteMMS):Math.min(canSendMMS,remoteMMS);var sctp={};Object.defineProperty(sctp,"maxMessageSize",{get:function get(){return maxMessageSize}}),this._sctp=sctp}return origSetRemoteDescription.apply(this,arguments)}}}function shimSendThrowTypeError(window1){if(window1.RTCPeerConnection&&"createDataChannel"in window1.RTCPeerConnection.prototype){var origCreateDataChannel=window1.RTCPeerConnection.prototype.createDataChannel;window1.RTCPeerConnection.prototype.createDataChannel=function createDataChannel(){var dataChannel=origCreateDataChannel.apply(this,arguments);return wrapDcSend(dataChannel,this),dataChannel},utils.wrapPeerConnectionEvent(window1,"datachannel",function(e){return wrapDcSend(e.channel,e.target),e})}function wrapDcSend(dc,pc){var origDataChannelSend=dc.send;dc.send=function send(){var data=arguments[0],length=data.length||data.size||data.byteLength;if("open"===dc.readyState&&pc.sctp&&length>pc.sctp.maxMessageSize)throw TypeError("Message too large (can send a maximum of "+pc.sctp.maxMessageSize+" bytes)");return origDataChannelSend.apply(dc,arguments)}}}function shimConnectionState(window1){if(window1.RTCPeerConnection&&!("connectionState"in window1.RTCPeerConnection.prototype)){var proto=window1.RTCPeerConnection.prototype;Object.defineProperty(proto,"connectionState",{get:function get(){return({completed:"connected",checking:"connecting"})[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(proto,"onconnectionstatechange",{get:function get(){return this._onconnectionstatechange||null},set:function set(cb){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),cb&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=cb)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(function(method){var origMethod=proto[method];proto[method]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=function(e){var pc=e.target;if(pc._lastConnectionState!==pc.connectionState){pc._lastConnectionState=pc.connectionState;var newEvent=new Event("connectionstatechange",e);pc.dispatchEvent(newEvent)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),origMethod.apply(this,arguments)}})}}function removeExtmapAllowMixed(window1,browserDetails){if(window1.RTCPeerConnection&&("chrome"!==browserDetails.browser||!(browserDetails.version>=71))&&("safari"!==browserDetails.browser||!(browserDetails.version>=605))){var nativeSRD=window1.RTCPeerConnection.prototype.setRemoteDescription;window1.RTCPeerConnection.prototype.setRemoteDescription=function setRemoteDescription(desc){if(desc&&desc.sdp&&-1!==desc.sdp.indexOf("\na=extmap-allow-mixed")){var sdp=desc.sdp.split("\n").filter(function(line){return"a=extmap-allow-mixed"!==line.trim()}).join("\n");window1.RTCSessionDescription&&desc instanceof window1.RTCSessionDescription?arguments[0]=new window1.RTCSessionDescription({type:desc.type,sdp:sdp}):desc.sdp=sdp}return nativeSRD.apply(this,arguments)}}}function shimAddIceCandidateNullOrEmpty(window1,browserDetails){if(window1.RTCPeerConnection&&window1.RTCPeerConnection.prototype){var nativeAddIceCandidate=window1.RTCPeerConnection.prototype.addIceCandidate;nativeAddIceCandidate&&0!==nativeAddIceCandidate.length&&(window1.RTCPeerConnection.prototype.addIceCandidate=function addIceCandidate(){return arguments[0]?("chrome"===browserDetails.browser&&browserDetails.version<78||"firefox"===browserDetails.browser&&browserDetails.version<68||"safari"===browserDetails.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():nativeAddIceCandidate.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}}},{"./utils":232,sdp:175}],224:[function(require1,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=exports.shimGetUserMedia=void 0;var _getusermedia=require1("./getusermedia");Object.defineProperty(exports,"shimGetUserMedia",{enumerable:!0,get:function get(){return _getusermedia.shimGetUserMedia}});var _getdisplaymedia=require1("./getdisplaymedia");Object.defineProperty(exports,"shimGetDisplayMedia",{enumerable:!0,get:function get(){return _getdisplaymedia.shimGetDisplayMedia}}),exports.shimPeerConnection=shimPeerConnection,exports.shimReplaceTrack=shimReplaceTrack;var utils=_interopRequireWildcard(require1("../utils")),_filtericeservers=require1("./filtericeservers"),_rtcpeerconnectionShim2=_interopRequireDefault(require1("rtcpeerconnection-shim"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _interopRequireWildcard(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}function shimPeerConnection(window1,browserDetails){if(window1.RTCIceGatherer&&(window1.RTCIceCandidate||(window1.RTCIceCandidate=function RTCIceCandidate(args){return args}),window1.RTCSessionDescription||(window1.RTCSessionDescription=function RTCSessionDescription1(args){return args}),browserDetails.version<15025)){var origMSTEnabled=Object.getOwnPropertyDescriptor(window1.MediaStreamTrack.prototype,"enabled");Object.defineProperty(window1.MediaStreamTrack.prototype,"enabled",{set:function set(value){origMSTEnabled.set.call(this,value);var ev=new Event("enabled");ev.enabled=value,this.dispatchEvent(ev)}})}!window1.RTCRtpSender||"dtmf"in window1.RTCRtpSender.prototype||Object.defineProperty(window1.RTCRtpSender.prototype,"dtmf",{get:function get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=new window1.RTCDtmfSender(this):"video"===this.track.kind&&(this._dtmf=null)),this._dtmf}}),window1.RTCDtmfSender&&!window1.RTCDTMFSender&&(window1.RTCDTMFSender=window1.RTCDtmfSender);var RTCPeerConnectionShim=(0,_rtcpeerconnectionShim2.default)(window1,browserDetails.version);window1.RTCPeerConnection=function RTCPeerConnection(config){return config&&config.iceServers&&(config.iceServers=(0,_filtericeservers.filterIceServers)(config.iceServers,browserDetails.version),utils.log("ICE servers after filtering:",config.iceServers)),new RTCPeerConnectionShim(config)},window1.RTCPeerConnection.prototype=RTCPeerConnectionShim.prototype}function shimReplaceTrack(window1){!window1.RTCRtpSender||"replaceTrack"in window1.RTCRtpSender.prototype||(window1.RTCRtpSender.prototype.replaceTrack=window1.RTCRtpSender.prototype.setTrack)}},{"../utils":232,"./filtericeservers":225,"./getdisplaymedia":226,"./getusermedia":227,"rtcpeerconnection-shim":172}],225:[function(require1,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.filterIceServers=filterIceServers;var utils=_interopRequireWildcard(require1("../utils"));function _interopRequireWildcard(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}function filterIceServers(iceServers,edgeVersion){var hasTurn=!1;return(iceServers=JSON.parse(JSON.stringify(iceServers))).filter(function(server){if(server&&(server.urls||server.url)){var urls=server.urls||server.url;server.url&&!server.urls&&utils.deprecated("RTCIceServer.url","RTCIceServer.urls");var isString="string"==typeof urls;return isString&&(urls=[urls]),urls=urls.filter(function(url){if(0===url.indexOf("stun:"))return!1;var validTurn=url.startsWith("turn")&&!url.startsWith("turn:[")&&url.includes("transport=udp");return validTurn&&!hasTurn?(hasTurn=!0,!0):validTurn&&!hasTurn}),delete server.url,server.urls=isString?urls[0]:urls,!!urls.length}})}},{"../utils":232}],226:[function(require1,module,exports){"use strict";function shimGetDisplayMedia(window1){"getDisplayMedia"in window1.navigator&&window1.navigator.mediaDevices&&(!window1.navigator.mediaDevices||!("getDisplayMedia"in window1.navigator.mediaDevices))&&(window1.navigator.mediaDevices.getDisplayMedia=window1.navigator.getDisplayMedia.bind(window1.navigator))}Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=shimGetDisplayMedia},{}],227:[function(require1,module,exports){"use strict";function shimGetUserMedia(window1){var navigator1=window1&&window1.navigator,origGetUserMedia=navigator1.mediaDevices.getUserMedia.bind(navigator1.mediaDevices);navigator1.mediaDevices.getUserMedia=function(c){return origGetUserMedia(c).catch(function(e){return Promise.reject({name:{PermissionDeniedError:"NotAllowedError"}[e.name]||e.name,message:e.message,constraint:e.constraint,toString:function toString(){return this.name}})})}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetUserMedia=shimGetUserMedia},{}],228:[function(require1,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=exports.shimGetUserMedia=void 0;var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},_getusermedia=require1("./getusermedia");Object.defineProperty(exports,"shimGetUserMedia",{enumerable:!0,get:function get(){return _getusermedia.shimGetUserMedia}});var _getdisplaymedia=require1("./getdisplaymedia");Object.defineProperty(exports,"shimGetDisplayMedia",{enumerable:!0,get:function get(){return _getdisplaymedia.shimGetDisplayMedia}}),exports.shimOnTrack=shimOnTrack,exports.shimPeerConnection=shimPeerConnection,exports.shimSenderGetStats=shimSenderGetStats,exports.shimReceiverGetStats=shimReceiverGetStats,exports.shimRemoveStream=shimRemoveStream,exports.shimRTCDataChannel=shimRTCDataChannel,exports.shimAddTransceiver=shimAddTransceiver,exports.shimGetParameters=shimGetParameters,exports.shimCreateOffer=shimCreateOffer,exports.shimCreateAnswer=shimCreateAnswer;var utils=_interopRequireWildcard(require1("../utils"));function _interopRequireWildcard(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function shimOnTrack(window1){(void 0===window1?"undefined":_typeof(window1))==="object"&&window1.RTCTrackEvent&&"receiver"in window1.RTCTrackEvent.prototype&&!("transceiver"in window1.RTCTrackEvent.prototype)&&Object.defineProperty(window1.RTCTrackEvent.prototype,"transceiver",{get:function get(){return{receiver:this.receiver}}})}function shimPeerConnection(window1,browserDetails){if((void 0===window1?"undefined":_typeof(window1))==="object"&&(window1.RTCPeerConnection||window1.mozRTCPeerConnection)){!window1.RTCPeerConnection&&window1.mozRTCPeerConnection&&(window1.RTCPeerConnection=window1.mozRTCPeerConnection),browserDetails.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(method){var nativeMethod=window1.RTCPeerConnection.prototype[method],methodObj=_defineProperty({},method,function(){return arguments[0]=new("addIceCandidate"===method?window1.RTCIceCandidate:window1.RTCSessionDescription)(arguments[0]),nativeMethod.apply(this,arguments)});window1.RTCPeerConnection.prototype[method]=methodObj[method]});var modernStatsTypes={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},nativeGetStats=window1.RTCPeerConnection.prototype.getStats;window1.RTCPeerConnection.prototype.getStats=function getStats(){var _arguments=Array.prototype.slice.call(arguments),selector=_arguments[0],onSucc=_arguments[1],onErr=_arguments[2];return nativeGetStats.apply(this,[selector||null]).then(function(stats){if(browserDetails.version<53&&!onSucc)try{stats.forEach(function(stat){stat.type=modernStatsTypes[stat.type]||stat.type})}catch(e){if("TypeError"!==e.name)throw e;stats.forEach(function(stat,i){stats.set(i,Object.assign({},stat,{type:modernStatsTypes[stat.type]||stat.type}))})}return stats}).then(onSucc,onErr)}}}function shimSenderGetStats(window1){if((void 0===window1?"undefined":_typeof(window1))==="object"&&window1.RTCPeerConnection&&window1.RTCRtpSender&&(!window1.RTCRtpSender||!("getStats"in window1.RTCRtpSender.prototype))){var origGetSenders=window1.RTCPeerConnection.prototype.getSenders;origGetSenders&&(window1.RTCPeerConnection.prototype.getSenders=function getSenders(){var _this=this,senders=origGetSenders.apply(this,[]);return senders.forEach(function(sender){return sender._pc=_this}),senders});var origAddTrack=window1.RTCPeerConnection.prototype.addTrack;origAddTrack&&(window1.RTCPeerConnection.prototype.addTrack=function addTrack(){var sender=origAddTrack.apply(this,arguments);return sender._pc=this,sender}),window1.RTCRtpSender.prototype.getStats=function getStats(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}}function shimReceiverGetStats(window1){if((void 0===window1?"undefined":_typeof(window1))==="object"&&window1.RTCPeerConnection&&window1.RTCRtpSender&&(!window1.RTCRtpSender||!("getStats"in window1.RTCRtpReceiver.prototype))){var origGetReceivers=window1.RTCPeerConnection.prototype.getReceivers;origGetReceivers&&(window1.RTCPeerConnection.prototype.getReceivers=function getReceivers(){var _this2=this,receivers=origGetReceivers.apply(this,[]);return receivers.forEach(function(receiver){return receiver._pc=_this2}),receivers}),utils.wrapPeerConnectionEvent(window1,"track",function(e){return e.receiver._pc=e.srcElement,e}),window1.RTCRtpReceiver.prototype.getStats=function getStats(){return this._pc.getStats(this.track)}}}function shimRemoveStream(window1){!window1.RTCPeerConnection||"removeStream"in window1.RTCPeerConnection.prototype||(window1.RTCPeerConnection.prototype.removeStream=function removeStream(stream){var _this3=this;utils.deprecated("removeStream","removeTrack"),this.getSenders().forEach(function(sender){sender.track&&stream.getTracks().includes(sender.track)&&_this3.removeTrack(sender)})})}function shimRTCDataChannel(window1){window1.DataChannel&&!window1.RTCDataChannel&&(window1.RTCDataChannel=window1.DataChannel)}function shimAddTransceiver(window1){if((void 0===window1?"undefined":_typeof(window1))==="object"&&window1.RTCPeerConnection){var origAddTransceiver=window1.RTCPeerConnection.prototype.addTransceiver;origAddTransceiver&&(window1.RTCPeerConnection.prototype.addTransceiver=function addTransceiver(){this.setParametersPromises=[];var initParameters=arguments[1],shouldPerformCheck=initParameters&&"sendEncodings"in initParameters;shouldPerformCheck&&initParameters.sendEncodings.forEach(function(encodingParam){if("rid"in encodingParam&&!/^[a-z0-9]{0,16}$/i.test(encodingParam.rid))throw TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in encodingParam&&!(parseFloat(encodingParam.scaleResolutionDownBy)>=1))throw RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in encodingParam&&!(parseFloat(encodingParam.maxFramerate)>=0))throw RangeError("max_framerate must be >= 0.0")});var transceiver=origAddTransceiver.apply(this,arguments);if(shouldPerformCheck){var sender=transceiver.sender,params=sender.getParameters();"encodings"in params&&(1!==params.encodings.length||0!==Object.keys(params.encodings[0]).length)||(params.encodings=initParameters.sendEncodings,sender.sendEncodings=initParameters.sendEncodings,this.setParametersPromises.push(sender.setParameters(params).then(function(){delete sender.sendEncodings}).catch(function(){delete sender.sendEncodings})))}return transceiver})}}function shimGetParameters(window1){if((void 0===window1?"undefined":_typeof(window1))==="object"&&window1.RTCRtpSender){var origGetParameters=window1.RTCRtpSender.prototype.getParameters;origGetParameters&&(window1.RTCRtpSender.prototype.getParameters=function getParameters(){var params=origGetParameters.apply(this,arguments);return"encodings"in params||(params.encodings=[].concat(this.sendEncodings||[{}])),params})}}function shimCreateOffer(window1){if((void 0===window1?"undefined":_typeof(window1))==="object"&&window1.RTCPeerConnection){var origCreateOffer=window1.RTCPeerConnection.prototype.createOffer;window1.RTCPeerConnection.prototype.createOffer=function createOffer(){var _this4=this,_arguments2=arguments;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return origCreateOffer.apply(_this4,_arguments2)}).finally(function(){_this4.setParametersPromises=[]}):origCreateOffer.apply(this,arguments)}}}function shimCreateAnswer(window1){if((void 0===window1?"undefined":_typeof(window1))==="object"&&window1.RTCPeerConnection){var origCreateAnswer=window1.RTCPeerConnection.prototype.createAnswer;window1.RTCPeerConnection.prototype.createAnswer=function createAnswer(){var _this5=this,_arguments3=arguments;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return origCreateAnswer.apply(_this5,_arguments3)}).finally(function(){_this5.setParametersPromises=[]}):origCreateAnswer.apply(this,arguments)}}}},{"../utils":232,"./getdisplaymedia":229,"./getusermedia":230}],229:[function(require1,module,exports){"use strict";function shimGetDisplayMedia(window1,preferredMediaSource){window1.navigator.mediaDevices&&"getDisplayMedia"in window1.navigator.mediaDevices||!window1.navigator.mediaDevices||(window1.navigator.mediaDevices.getDisplayMedia=function getDisplayMedia(constraints){if(!(constraints&&constraints.video)){var err=new DOMException("getDisplayMedia without video constraints is undefined");return err.name="NotFoundError",err.code=8,Promise.reject(err)}return!0===constraints.video?constraints.video={mediaSource:preferredMediaSource}:constraints.video.mediaSource=preferredMediaSource,window1.navigator.mediaDevices.getUserMedia(constraints)})}Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=shimGetDisplayMedia},{}],230:[function(require1,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};exports.shimGetUserMedia=shimGetUserMedia;var utils=_interopRequireWildcard(require1("../utils"));function _interopRequireWildcard(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}function shimGetUserMedia(window1,browserDetails){var navigator1=window1&&window1.navigator,MediaStreamTrack=window1&&window1.MediaStreamTrack;if(navigator1.getUserMedia=function(constraints,onSuccess,onError){utils.deprecated("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),navigator1.mediaDevices.getUserMedia(constraints).then(onSuccess,onError)},!(browserDetails.version>55&&"autoGainControl"in navigator1.mediaDevices.getSupportedConstraints())){var remap=function(obj,a,b){a in obj&&!(b in obj)&&(obj[b]=obj[a],delete obj[a])},nativeGetUserMedia=navigator1.mediaDevices.getUserMedia.bind(navigator1.mediaDevices);if(navigator1.mediaDevices.getUserMedia=function(c){return(void 0===c?"undefined":_typeof(c))==="object"&&"object"===_typeof(c.audio)&&(remap((c=JSON.parse(JSON.stringify(c))).audio,"autoGainControl","mozAutoGainControl"),remap(c.audio,"noiseSuppression","mozNoiseSuppression")),nativeGetUserMedia(c)},MediaStreamTrack&&MediaStreamTrack.prototype.getSettings){var nativeGetSettings=MediaStreamTrack.prototype.getSettings;MediaStreamTrack.prototype.getSettings=function(){var obj=nativeGetSettings.apply(this,arguments);return remap(obj,"mozAutoGainControl","autoGainControl"),remap(obj,"mozNoiseSuppression","noiseSuppression"),obj}}if(MediaStreamTrack&&MediaStreamTrack.prototype.applyConstraints){var nativeApplyConstraints=MediaStreamTrack.prototype.applyConstraints;MediaStreamTrack.prototype.applyConstraints=function(c){return"audio"===this.kind&&(void 0===c?"undefined":_typeof(c))==="object"&&(remap(c=JSON.parse(JSON.stringify(c)),"autoGainControl","mozAutoGainControl"),remap(c,"noiseSuppression","mozNoiseSuppression")),nativeApplyConstraints.apply(this,[c])}}}}},{"../utils":232}],231:[function(require1,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};exports.shimLocalStreamsAPI=shimLocalStreamsAPI,exports.shimRemoteStreamsAPI=shimRemoteStreamsAPI,exports.shimCallbacksAPI=shimCallbacksAPI,exports.shimGetUserMedia=shimGetUserMedia,exports.shimConstraints=shimConstraints,exports.shimRTCIceServerUrls=shimRTCIceServerUrls,exports.shimTrackEventTransceiver=shimTrackEventTransceiver,exports.shimCreateOfferLegacy=shimCreateOfferLegacy,exports.shimAudioContext=shimAudioContext;var utils=_interopRequireWildcard(require1("../utils"));function _interopRequireWildcard(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}function shimLocalStreamsAPI(window1){if((void 0===window1?"undefined":_typeof(window1))==="object"&&window1.RTCPeerConnection){if("getLocalStreams"in window1.RTCPeerConnection.prototype||(window1.RTCPeerConnection.prototype.getLocalStreams=function getLocalStreams(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in window1.RTCPeerConnection.prototype)){var _addTrack=window1.RTCPeerConnection.prototype.addTrack;window1.RTCPeerConnection.prototype.addStream=function addStream(stream){var _this=this;this._localStreams||(this._localStreams=[]),this._localStreams.includes(stream)||this._localStreams.push(stream),stream.getAudioTracks().forEach(function(track){return _addTrack.call(_this,track,stream)}),stream.getVideoTracks().forEach(function(track){return _addTrack.call(_this,track,stream)})},window1.RTCPeerConnection.prototype.addTrack=function addTrack(track){for(var _this2=this,_len=arguments.length,streams=Array(_len>1?_len-1:0),_key=1;_key<_len;_key++)streams[_key-1]=arguments[_key];return streams&&streams.forEach(function(stream){_this2._localStreams?_this2._localStreams.includes(stream)||_this2._localStreams.push(stream):_this2._localStreams=[stream]}),_addTrack.apply(this,arguments)}}"removeStream"in window1.RTCPeerConnection.prototype||(window1.RTCPeerConnection.prototype.removeStream=function removeStream(stream){var _this3=this;this._localStreams||(this._localStreams=[]);var index=this._localStreams.indexOf(stream);if(-1!==index){this._localStreams.splice(index,1);var tracks=stream.getTracks();this.getSenders().forEach(function(sender){tracks.includes(sender.track)&&_this3.removeTrack(sender)})}})}}function shimRemoteStreamsAPI(window1){if((void 0===window1?"undefined":_typeof(window1))==="object"&&window1.RTCPeerConnection&&("getRemoteStreams"in window1.RTCPeerConnection.prototype||(window1.RTCPeerConnection.prototype.getRemoteStreams=function getRemoteStreams(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in window1.RTCPeerConnection.prototype))){Object.defineProperty(window1.RTCPeerConnection.prototype,"onaddstream",{get:function get(){return this._onaddstream},set:function set(f){var _this4=this;this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=f),this.addEventListener("track",this._onaddstreampoly=function(e){e.streams.forEach(function(stream){if(_this4._remoteStreams||(_this4._remoteStreams=[]),!_this4._remoteStreams.includes(stream)){_this4._remoteStreams.push(stream);var event=new Event("addstream");event.stream=stream,_this4.dispatchEvent(event)}})})}});var origSetRemoteDescription=window1.RTCPeerConnection.prototype.setRemoteDescription;window1.RTCPeerConnection.prototype.setRemoteDescription=function setRemoteDescription(){var pc=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(e){e.streams.forEach(function(stream){if(pc._remoteStreams||(pc._remoteStreams=[]),!(pc._remoteStreams.indexOf(stream)>=0)){pc._remoteStreams.push(stream);var event=new Event("addstream");event.stream=stream,pc.dispatchEvent(event)}})}),origSetRemoteDescription.apply(pc,arguments)}}}function shimCallbacksAPI(window1){if((void 0===window1?"undefined":_typeof(window1))==="object"&&window1.RTCPeerConnection){var prototype=window1.RTCPeerConnection.prototype,origCreateOffer=prototype.createOffer,origCreateAnswer=prototype.createAnswer,setLocalDescription=prototype.setLocalDescription,setRemoteDescription=prototype.setRemoteDescription,addIceCandidate=prototype.addIceCandidate;prototype.createOffer=function createOffer(successCallback,failureCallback){var options=arguments.length>=2?arguments[2]:arguments[0],promise=origCreateOffer.apply(this,[options]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise},prototype.createAnswer=function createAnswer(successCallback,failureCallback){var options=arguments.length>=2?arguments[2]:arguments[0],promise=origCreateAnswer.apply(this,[options]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise};var withCallback=function(description,successCallback,failureCallback){var promise=setLocalDescription.apply(this,[description]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise};prototype.setLocalDescription=withCallback,withCallback=function withCallback(description,successCallback,failureCallback){var promise=setRemoteDescription.apply(this,[description]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise},prototype.setRemoteDescription=withCallback,withCallback=function withCallback(candidate,successCallback,failureCallback){var promise=addIceCandidate.apply(this,[candidate]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise},prototype.addIceCandidate=withCallback}}function shimGetUserMedia(window1){var navigator1=window1&&window1.navigator;if(navigator1.mediaDevices&&navigator1.mediaDevices.getUserMedia){var mediaDevices=navigator1.mediaDevices,_getUserMedia=mediaDevices.getUserMedia.bind(mediaDevices);navigator1.mediaDevices.getUserMedia=function(constraints){return _getUserMedia(shimConstraints(constraints))}}!navigator1.getUserMedia&&navigator1.mediaDevices&&navigator1.mediaDevices.getUserMedia&&(navigator1.getUserMedia=(function getUserMedia(constraints,cb,errcb){navigator1.mediaDevices.getUserMedia(constraints).then(cb,errcb)}).bind(navigator1))}function shimConstraints(constraints){return constraints&&void 0!==constraints.video?Object.assign({},constraints,{video:utils.compactObject(constraints.video)}):constraints}function shimRTCIceServerUrls(window1){if(window1.RTCPeerConnection){var OrigPeerConnection=window1.RTCPeerConnection;window1.RTCPeerConnection=function RTCPeerConnection(pcConfig,pcConstraints){if(pcConfig&&pcConfig.iceServers){for(var newIceServers=[],i=0;i<pcConfig.iceServers.length;i++){var server=pcConfig.iceServers[i];!server.hasOwnProperty("urls")&&server.hasOwnProperty("url")?(utils.deprecated("RTCIceServer.url","RTCIceServer.urls"),(server=JSON.parse(JSON.stringify(server))).urls=server.url,delete server.url,newIceServers.push(server)):newIceServers.push(pcConfig.iceServers[i])}pcConfig.iceServers=newIceServers}return new OrigPeerConnection(pcConfig,pcConstraints)},window1.RTCPeerConnection.prototype=OrigPeerConnection.prototype,"generateCertificate"in OrigPeerConnection&&Object.defineProperty(window1.RTCPeerConnection,"generateCertificate",{get:function get(){return OrigPeerConnection.generateCertificate}})}}function shimTrackEventTransceiver(window1){(void 0===window1?"undefined":_typeof(window1))==="object"&&window1.RTCTrackEvent&&"receiver"in window1.RTCTrackEvent.prototype&&!("transceiver"in window1.RTCTrackEvent.prototype)&&Object.defineProperty(window1.RTCTrackEvent.prototype,"transceiver",{get:function get(){return{receiver:this.receiver}}})}function shimCreateOfferLegacy(window1){var origCreateOffer=window1.RTCPeerConnection.prototype.createOffer;window1.RTCPeerConnection.prototype.createOffer=function createOffer(offerOptions){if(offerOptions){void 0!==offerOptions.offerToReceiveAudio&&(offerOptions.offerToReceiveAudio=!!offerOptions.offerToReceiveAudio);var audioTransceiver=this.getTransceivers().find(function(transceiver){return"audio"===transceiver.receiver.track.kind});!1===offerOptions.offerToReceiveAudio&&audioTransceiver?"sendrecv"===audioTransceiver.direction?audioTransceiver.setDirection?audioTransceiver.setDirection("sendonly"):audioTransceiver.direction="sendonly":"recvonly"===audioTransceiver.direction&&(audioTransceiver.setDirection?audioTransceiver.setDirection("inactive"):audioTransceiver.direction="inactive"):!0!==offerOptions.offerToReceiveAudio||audioTransceiver||this.addTransceiver("audio"),void 0!==offerOptions.offerToReceiveVideo&&(offerOptions.offerToReceiveVideo=!!offerOptions.offerToReceiveVideo);var videoTransceiver=this.getTransceivers().find(function(transceiver){return"video"===transceiver.receiver.track.kind});!1===offerOptions.offerToReceiveVideo&&videoTransceiver?"sendrecv"===videoTransceiver.direction?videoTransceiver.setDirection?videoTransceiver.setDirection("sendonly"):videoTransceiver.direction="sendonly":"recvonly"===videoTransceiver.direction&&(videoTransceiver.setDirection?videoTransceiver.setDirection("inactive"):videoTransceiver.direction="inactive"):!0!==offerOptions.offerToReceiveVideo||videoTransceiver||this.addTransceiver("video")}return origCreateOffer.apply(this,arguments)}}function shimAudioContext(window1){(void 0===window1?"undefined":_typeof(window1))!=="object"||window1.AudioContext||(window1.AudioContext=window1.webkitAudioContext)}},{"../utils":232}],232:[function(require1,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}exports.extractVersion=extractVersion,exports.wrapPeerConnectionEvent=wrapPeerConnectionEvent,exports.disableLog=disableLog,exports.disableWarnings=disableWarnings,exports.log=log,exports.deprecated=deprecated,exports.detectBrowser=detectBrowser,exports.compactObject=compactObject,exports.walkStats=walkStats,exports.filterStats=filterStats;var logDisabled_=!0,deprecationWarnings_=!0;function extractVersion(uastring,expr,pos){var match=uastring.match(expr);return match&&match.length>=pos&&parseInt(match[pos],10)}function wrapPeerConnectionEvent(window1,eventNameToWrap,wrapper){if(window1.RTCPeerConnection){var proto=window1.RTCPeerConnection.prototype,nativeAddEventListener=proto.addEventListener;proto.addEventListener=function(nativeEventName,cb){if(nativeEventName!==eventNameToWrap)return nativeAddEventListener.apply(this,arguments);var wrappedCallback=function(e){var modifiedEvent=wrapper(e);modifiedEvent&&(cb.handleEvent?cb.handleEvent(modifiedEvent):cb(modifiedEvent))};return this._eventMap=this._eventMap||{},this._eventMap[eventNameToWrap]||(this._eventMap[eventNameToWrap]=new Map),this._eventMap[eventNameToWrap].set(cb,wrappedCallback),nativeAddEventListener.apply(this,[nativeEventName,wrappedCallback])};var nativeRemoveEventListener=proto.removeEventListener;proto.removeEventListener=function(nativeEventName,cb){if(nativeEventName!==eventNameToWrap||!this._eventMap||!this._eventMap[eventNameToWrap]||!this._eventMap[eventNameToWrap].has(cb))return nativeRemoveEventListener.apply(this,arguments);var unwrappedCb=this._eventMap[eventNameToWrap].get(cb);return this._eventMap[eventNameToWrap].delete(cb),0===this._eventMap[eventNameToWrap].size&&delete this._eventMap[eventNameToWrap],0===Object.keys(this._eventMap).length&&delete this._eventMap,nativeRemoveEventListener.apply(this,[nativeEventName,unwrappedCb])},Object.defineProperty(proto,"on"+eventNameToWrap,{get:function get(){return this["_on"+eventNameToWrap]},set:function set(cb){this["_on"+eventNameToWrap]&&(this.removeEventListener(eventNameToWrap,this["_on"+eventNameToWrap]),delete this["_on"+eventNameToWrap]),cb&&this.addEventListener(eventNameToWrap,this["_on"+eventNameToWrap]=cb)},enumerable:!0,configurable:!0})}}function disableLog(bool){return"boolean"!=typeof bool?Error("Argument type: "+(void 0===bool?"undefined":_typeof(bool))+". Please use a boolean."):(logDisabled_=bool,bool?"adapter.js logging disabled":"adapter.js logging enabled")}function disableWarnings(bool){return"boolean"!=typeof bool?Error("Argument type: "+(void 0===bool?"undefined":_typeof(bool))+". Please use a boolean."):(deprecationWarnings_=!bool,"adapter.js deprecation warnings "+(bool?"disabled":"enabled"))}function log(){("undefined"==typeof window?"undefined":_typeof(window))!=="object"||logDisabled_||"undefined"==typeof console||"function"!=typeof console.log||console.log.apply(console,arguments)}function deprecated(oldMethod,newMethod){deprecationWarnings_&&console.warn(oldMethod+" is deprecated, please use "+newMethod+" instead.")}function detectBrowser(window1){var result={browser:null,version:null};if(void 0===window1||!window1.navigator)return result.browser="Not a browser.",result;var navigator1=window1.navigator;return navigator1.mozGetUserMedia?(result.browser="firefox",result.version=extractVersion(navigator1.userAgent,/Firefox\/(\d+)\./,1)):navigator1.webkitGetUserMedia||!1===window1.isSecureContext&&window1.webkitRTCPeerConnection&&!window1.RTCIceGatherer?(result.browser="chrome",result.version=extractVersion(navigator1.userAgent,/Chrom(e|ium)\/(\d+)\./,2)):navigator1.mediaDevices&&navigator1.userAgent.match(/Edge\/(\d+).(\d+)$/)?(result.browser="edge",result.version=extractVersion(navigator1.userAgent,/Edge\/(\d+).(\d+)$/,2)):window1.RTCPeerConnection&&navigator1.userAgent.match(/AppleWebKit\/(\d+)\./)?(result.browser="safari",result.version=extractVersion(navigator1.userAgent,/AppleWebKit\/(\d+)\./,1),result.supportsUnifiedPlan=window1.RTCRtpTransceiver&&"currentDirection"in window1.RTCRtpTransceiver.prototype):result.browser="Not a supported browser.",result}function isObject(val){return"[object Object]"===Object.prototype.toString.call(val)}function compactObject(data){return isObject(data)?Object.keys(data).reduce(function(accumulator,key){var isObj=isObject(data[key]),value=isObj?compactObject(data[key]):data[key],isEmptyObject=isObj&&!Object.keys(value).length;return void 0===value||isEmptyObject?accumulator:Object.assign(accumulator,_defineProperty({},key,value))},{}):data}function walkStats(stats,base,resultSet){!base||resultSet.has(base.id)||(resultSet.set(base.id,base),Object.keys(base).forEach(function(name){name.endsWith("Id")?walkStats(stats,stats.get(base[name]),resultSet):name.endsWith("Ids")&&base[name].forEach(function(id){walkStats(stats,stats.get(id),resultSet)})}))}function filterStats(result,track,outbound){var streamStatsType=outbound?"outbound-rtp":"inbound-rtp",filteredResult=new Map;if(null===track)return filteredResult;var trackStats=[];return result.forEach(function(value){"track"===value.type&&value.trackIdentifier===track.id&&trackStats.push(value)}),trackStats.forEach(function(trackStat){result.forEach(function(stats){stats.type===streamStatsType&&stats.trackId===trackStat.id&&walkStats(result,stats,filteredResult)})}),filteredResult}},{}],233:[function(require1,module,exports){module.exports=extend;var hasOwnProperty=Object.prototype.hasOwnProperty;function extend(){for(var target={},i=0;i<arguments.length;i++){var source=arguments[i];for(var key in source)hasOwnProperty.call(source,key)&&(target[key]=source[key])}return target}},{}],234:[function(require1,module,exports){"use strict";var XMPP,chatUtils=require1("./qbChatHelpers"),config=require1("../../qbConfig"),Utils=require1("../../qbUtils"),StreamManagement=require1("../../plugins/streamManagement"),unsupportedError="This function isn't supported outside of the browser (...yet)";if(Utils.getEnv().browser){var Connection=require1("../../qbStrophe");Strophe.addNamespace("CARBONS",chatUtils.MARKERS.CARBONS),Strophe.addNamespace("CHAT_MARKERS",chatUtils.MARKERS.CHAT),Strophe.addNamespace("PRIVACY_LIST",chatUtils.MARKERS.PRIVACY),Strophe.addNamespace("CHAT_STATES",chatUtils.MARKERS.STATES)}else Utils.getEnv().nativescript?XMPP=require1("nativescript-xmpp-client"):Utils.getEnv().node&&(XMPP=require1("node-xmpp-client"));function ChatProxy(service){var originSendFunction,self1=this;self1.webrtcSignalingProcessor=null,Utils.getEnv().browser?(self1.connection=Connection(),self1.connection.XHandlerReferences=[],self1.connection.XAddTrackedHandler=function(handler,ns,name,type,id,from,options){self1.connection.XHandlerReferences.push(self1.connection.addHandler(handler,ns,name,type,id,from,options))},self1.connection.XDeleteHandlers=function(){for(;self1.connection.XHandlerReferences.length;)self1.connection.deleteHandler(self1.connection.XHandlerReferences.pop())},originSendFunction=self1.connection.send,self1.connection.send=function(stanza){if(!self1.connection.connected)throw new chatUtils.ChatNotConnectedError("Chat is not connected");originSendFunction.call(self1.connection,stanza)}):(Utils.getEnv().nativescript?self1.Client=new XMPP.Client({websocket:{url:config.chatProtocol.websocket},autostart:!1}):Utils.getEnv().node&&(self1.Client=new XMPP({autostart:!1})),originSendFunction=self1.Client.send,self1.Client.send=function(stanza){Utils.QBLog("[QBChat]","SENT:",stanza.toString()),originSendFunction.call(self1.Client,stanza)},self1.nodeStanzasCallbacks={}),this.service=service,this.isConnected=!1,this._isConnecting=!1,this._isLogout=!1,this._checkConnectionTimer=void 0,this._checkConnectionPingTimer=void 0,this._chatPingFailedCounter=0,this._onlineStatus=!0,this._checkExpiredSessionTimer=void 0,this._sessionHasExpired=!1,this._pings={},this.helpers=new Helpers;var options={service:service,helpers:self1.helpers,stropheClient:self1.connection,xmppClient:self1.Client,nodeStanzasCallbacks:self1.nodeStanzasCallbacks};this.roster=new RosterProxy(options),this.privacylist=new PrivacyListProxy(options),this.muc=new MucProxy(options),this.chatUtils=chatUtils,config.streamManagement.enable&&(2===config.chatProtocol.active?(this.streamManagement=new StreamManagement(config.streamManagement),self1._sentMessageCallback=function(messageLost,messageSent){"function"==typeof self1.onSentMessageCallback&&(messageSent?self1.onSentMessageCallback(null,messageSent):self1.onSentMessageCallback(messageLost))}):Utils.QBLog("[QBChat] StreamManagement:",'BOSH protocol doesn\'t support stream management. Set WebSocket as the "chatProtocol" parameter to use this functionality. https://quickblox.com/developers/Javascript#Configuration')),this._onMessage=function(stanza){var extraParamsParsed,recipientId,recipient,jid,from=chatUtils.getAttr(stanza,"from"),type=(chatUtils.getAttr(stanza,"to"),chatUtils.getAttr(stanza,"type")),messageId=chatUtils.getAttr(stanza,"id"),markable=chatUtils.getElement(stanza,"markable"),delivered=chatUtils.getElement(stanza,"received"),read=chatUtils.getElement(stanza,"displayed"),composing=chatUtils.getElement(stanza,"composing"),paused=chatUtils.getElement(stanza,"paused"),invite=chatUtils.getElement(stanza,"invite"),delay=chatUtils.getElement(stanza,"delay"),extraParams=chatUtils.getElement(stanza,"extraParams"),bodyContent=chatUtils.getElementText(stanza,"body"),forwarded=chatUtils.getElement(stanza,"forwarded");if(Utils.getEnv().browser)recipient=stanza.querySelector("forwarded")?stanza.querySelector("forwarded").querySelector("message").getAttribute("to"):null,jid=self1.connection.jid;else{var forwardedMessage=forwarded?chatUtils.getElement(forwarded,"message"):null;recipient=forwardedMessage?chatUtils.getAttr(forwardedMessage,"to"):null,jid=self1.Client.options.jid.user}recipientId=recipient?self1.helpers.getIdFromNode(recipient):null;var dialogId="groupchat"===type?self1.helpers.getDialogIdFromNode(from):null,userId="groupchat"===type?self1.helpers.getIdFromResource(from):self1.helpers.getIdFromNode(from),marker=delivered||read||null;if(invite)return!0;if(extraParams&&(extraParamsParsed=chatUtils.parseExtraParams(extraParams)).dialogId&&(dialogId=extraParamsParsed.dialogId),composing||paused)return"function"!=typeof self1.onMessageTypingListener||"chat"!==type&&"groupchat"!==type&&delay||Utils.safeCallbackCall(self1.onMessageTypingListener,!!composing,userId,dialogId),!0;if(marker)return delivered?"function"==typeof self1.onDeliveredStatusListener&&"chat"===type&&Utils.safeCallbackCall(self1.onDeliveredStatusListener,chatUtils.getAttr(delivered,"id"),dialogId,userId):"function"==typeof self1.onReadStatusListener&&"chat"===type&&Utils.safeCallbackCall(self1.onReadStatusListener,chatUtils.getAttr(read,"id"),dialogId,userId),!0;if(markable&&userId!=self1.helpers.getIdFromNode(jid)){var autoSendReceiveStatusParams={messageId:messageId,userId:userId,dialogId:dialogId};self1.sendDeliveredStatus(autoSendReceiveStatusParams)}var message={id:messageId,dialog_id:dialogId,recipient_id:recipientId,type:type,body:bodyContent,extension:extraParamsParsed?extraParamsParsed.extension:null,delay:delay};return markable&&(message.markable=1),"function"==typeof self1.onMessageListener&&("chat"===type||"groupchat"===type)&&Utils.safeCallbackCall(self1.onMessageListener,userId,message),!0},this._onPresence=function(stanza){var xXMLNS,status,statusCode,dialogId,userId,from=chatUtils.getAttr(stanza,"from"),id=(chatUtils.getAttr(stanza,"to"),chatUtils.getAttr(stanza,"id")),type=chatUtils.getAttr(stanza,"type"),currentUserId=self1.helpers.getIdFromNode(self1.helpers.userCurrentJid(Utils.getEnv().browser?self1.connection:self1.Client)),x=chatUtils.getElement(stanza,"x");if(x&&(xXMLNS=chatUtils.getAttr(x,"xmlns"),(status=chatUtils.getElement(x,"status"))&&(statusCode=chatUtils.getAttr(status,"code"))),xXMLNS&&"http://jabber.org/protocol/muc#user"==xXMLNS){if(dialogId=self1.helpers.getDialogIdFromNode(from),userId=self1.helpers.getUserIdFromRoomJid(from),status&&"301"==statusCode){if("function"==typeof self1.onKickOccupant){var actorElement=chatUtils.getElement(chatUtils.getElement(x,"item"),"actor"),initiatorUserJid=chatUtils.getAttr(actorElement,"jid");Utils.safeCallbackCall(self1.onKickOccupant,dialogId,self1.helpers.getIdFromNode(initiatorUserJid))}return delete self1.muc.joinedRooms[self1.helpers.getRoomJidFromRoomFullJid(from)],!0}if(!status&&userId!=currentUserId)return type&&"unavailable"===type?"function"==typeof self1.onLeaveOccupant&&Utils.safeCallbackCall(self1.onLeaveOccupant,dialogId,parseInt(userId)):"function"==typeof self1.onJoinOccupant&&Utils.safeCallbackCall(self1.onJoinOccupant,dialogId,parseInt(userId)),!0}if(!Utils.getEnv().browser&&xXMLNS){if("http://jabber.org/protocol/muc#user"==xXMLNS){if(type&&"unavailable"===type)return status&&"110"==statusCode&&"function"==typeof self1.nodeStanzasCallbacks["muc:leave"]&&Utils.safeCallbackCall(self1.nodeStanzasCallbacks["muc:leave"],null),!0;if(id.endsWith(":join")&&status&&"110"==statusCode)return"function"==typeof self1.nodeStanzasCallbacks[id]&&self1.nodeStanzasCallbacks[id](stanza),!0}else if(type&&"error"===type&&"http://jabber.org/protocol/muc"==xXMLNS)return id.endsWith(":join")&&"function"==typeof self1.nodeStanzasCallbacks[id]&&self1.nodeStanzasCallbacks[id](stanza),!0}if(userId=self1.helpers.getIdFromNode(from),type)switch(type){case"subscribe":self1.roster.contacts[userId]&&"to"===self1.roster.contacts[userId].subscription?(self1.roster.contacts[userId]={subscription:"both",ask:null},self1.roster._sendSubscriptionPresence({jid:from,type:"subscribed"})):"function"==typeof self1.onSubscribeListener&&Utils.safeCallbackCall(self1.onSubscribeListener,userId);break;case"subscribed":self1.roster.contacts[userId]&&"from"===self1.roster.contacts[userId].subscription?self1.roster.contacts[userId]={subscription:"both",ask:null}:(self1.roster.contacts[userId]={subscription:"to",ask:null},"function"==typeof self1.onConfirmSubscribeListener&&Utils.safeCallbackCall(self1.onConfirmSubscribeListener,userId));break;case"unsubscribed":self1.roster.contacts[userId]={subscription:"none",ask:null},"function"==typeof self1.onRejectSubscribeListener&&Utils.safeCallbackCall(self1.onRejectSubscribeListener,userId);break;case"unsubscribe":self1.roster.contacts[userId]={subscription:"to",ask:null};break;case"unavailable":"function"==typeof self1.onContactListListener&&self1.roster.contacts[userId]&&"none"!==self1.roster.contacts[userId].subscription&&Utils.safeCallbackCall(self1.onContactListListener,userId,type),userId===currentUserId&&(Utils.getEnv().browser?self1.connection.send($pres()):self1.Client.send(chatUtils.createStanza(XMPP.Stanza,null,"presence")))}else"function"==typeof self1.onContactListListener&&self1.roster.contacts[userId]&&"none"!==self1.roster.contacts[userId].subscription&&Utils.safeCallbackCall(self1.onContactListListener,userId);return!0},this._onIQ=function(stanza){var stanzaId=chatUtils.getAttr(stanza,"id"),isLastActivity=stanzaId.indexOf("lastActivity")>-1,isPong=stanzaId.indexOf("ping")>-1,ping=chatUtils.getElement(stanza,"ping"),type=chatUtils.getAttr(stanza,"type"),from=chatUtils.getAttr(stanza,"from"),userId=from?self1.helpers.getIdFromNode(from):null;if("function"==typeof self1.onLastUserActivityListener&&isLastActivity){var query=chatUtils.getElement(stanza,"query"),seconds=chatUtils.getElement(stanza,"error")?void 0:+chatUtils.getAttr(query,"seconds");Utils.safeCallbackCall(self1.onLastUserActivityListener,userId,seconds)}if((ping||isPong)&&type){if("get"===type&&ping&&self1.isConnected){var builder=Utils.getEnv().browser?$iq:XMPP.Stanza,pongParams={from:self1.helpers.getUserCurrentJid(),id:stanzaId,to:from,type:"result"},pongStanza=chatUtils.createStanza(builder,pongParams,"iq");Utils.getEnv().browser?self1.connection.send(pongStanza):self1.Client.send(pongStanza)}else{var pingRequest=self1._pings[stanzaId];pingRequest&&(pingRequest.callback&&pingRequest.callback(null),pingRequest.interval&&clearInterval(pingRequest.interval),self1._pings[stanzaId]=void 0,delete self1._pings[stanzaId])}}return!Utils.getEnv().browser&&self1.nodeStanzasCallbacks[stanzaId]&&(Utils.safeCallbackCall(self1.nodeStanzasCallbacks[stanzaId],stanza),delete self1.nodeStanzasCallbacks[stanzaId]),!0},this._onSystemMessageListener=function(stanza){var message,from=chatUtils.getAttr(stanza,"from"),messageId=(chatUtils.getAttr(stanza,"to"),chatUtils.getAttr(stanza,"id")),extraParams=chatUtils.getElement(stanza,"extraParams"),userId=self1.helpers.getIdFromNode(from),delay=chatUtils.getElement(stanza,"delay"),moduleIdentifier=chatUtils.getElementText(extraParams,"moduleIdentifier"),bodyContent=chatUtils.getElementText(stanza,"body"),extraParamsParsed=chatUtils.parseExtraParams(extraParams);return"SystemNotifications"===moduleIdentifier&&"function"==typeof self1.onSystemMessageListener?(message={id:messageId,userId:userId,body:bodyContent,extension:extraParamsParsed.extension},Utils.safeCallbackCall(self1.onSystemMessageListener,message)):self1.webrtcSignalingProcessor&&!delay&&"WebRTCVideoChat"===moduleIdentifier&&self1.webrtcSignalingProcessor._onMessage(from,extraParams,delay,userId,extraParamsParsed.extension),!0},this._onMessageErrorListener=function(stanza){var messageId=chatUtils.getAttr(stanza,"id"),error=chatUtils.getErrorFromXMLNode(stanza);return"function"==typeof self1.onMessageErrorListener&&Utils.safeCallbackCall(self1.onMessageErrorListener,messageId,error),!0}}function RosterProxy(options){this.service=options.service,this.helpers=options.helpers,this.connection=options.stropheClient,this.Client=options.xmppClient,this.nodeStanzasCallbacks=options.nodeStanzasCallbacks,this.contacts={}}function MucProxy(options){this.service=options.service,this.helpers=options.helpers,this.connection=options.stropheClient,this.Client=options.xmppClient,this.nodeStanzasCallbacks=options.nodeStanzasCallbacks,this.joinedRooms={}}function PrivacyListProxy(options){this.service=options.service,this.helpers=options.helpers,this.connection=options.stropheClient,this.Client=options.xmppClient,this.nodeStanzasCallbacks=options.nodeStanzasCallbacks}function Helpers(){this._userCurrentJid=""}ChatProxy.prototype={connect:function(params,callback){Utils.QBLog("[QBChat]","Connect with parameters "+JSON.stringify(params));var err,self1=this,userJid=chatUtils.buildUserJid(params),isInitialConnect="function"==typeof callback;if(self1._isConnecting){err=Utils.getError(422,"Status.REJECT - The connection is still in the Status.CONNECTING state","QBChat"),isInitialConnect&&callback(err,null);return}if(self1.isConnected){Utils.QBLog("[QBChat]","Status.CONNECTED - You are already connected"),isInitialConnect&&callback(null,self1.roster.contacts);return}self1._isConnecting=!0,self1._isLogout=!1,Utils.getEnv().browser&&(Utils.QBLog("[QBChat]","!!---Browser env - connected--!!"),self1.connection.connect(userJid,params.password,function(status){switch(Utils.QBLog("[QBChat]","self.connection.connect called with status "+status),status){case Strophe.Status.ERROR:self1.isConnected=!1,self1._isConnecting=!1,err=Utils.getError(422,"Status.ERROR - An error has occurred","QBChat"),isInitialConnect&&callback(err,null);break;case Strophe.Status.CONNFAIL:self1.isConnected=!1,self1._isConnecting=!1,err=Utils.getError(422,"Status.CONNFAIL - The connection attempt failed","QBChat"),isInitialConnect&&callback(err,null);break;case Strophe.Status.AUTHENTICATING:Utils.QBLog("[QBChat]","Status.AUTHENTICATING");break;case Strophe.Status.AUTHFAIL:self1.isConnected=!1,self1._isConnecting=!1,err=Utils.getError(401,"Status.AUTHFAIL - The authentication attempt failed","QBChat"),isInitialConnect&&callback(err,null),self1.isConnected||"function"!=typeof self1.onReconnectFailedListener||Utils.safeCallbackCall(self1.onReconnectFailedListener,err);break;case Strophe.Status.CONNECTING:Utils.QBLog("[QBChat]","Status.CONNECTING","(Chat Protocol - "+(1===config.chatProtocol.active?"BOSH":"WebSocket)"));break;case Strophe.Status.CONNECTED:self1.connection.XDeleteHandlers(),self1.connection.XAddTrackedHandler(self1._onMessage,null,"message","chat"),self1.connection.XAddTrackedHandler(self1._onMessage,null,"message","groupchat"),self1.connection.XAddTrackedHandler(self1._onPresence,null,"presence"),self1.connection.XAddTrackedHandler(self1._onIQ,null,"iq"),self1.connection.XAddTrackedHandler(self1._onSystemMessageListener,null,"message","headline"),self1.connection.XAddTrackedHandler(self1._onMessageErrorListener,null,"message","error");var noTimerId=void 0===self1._checkConnectionPingTimer;(noTimerId=0!==config.pingLocalhostTimeInterval&&noTimerId)&&(Utils.QBLog("[QBChat]","Init ping to chat at ",Utils.getCurrentTime()),self1._checkConnectionPingTimer=setInterval(function(){try{self1.pingchat(function(error){error?(Utils.QBLog("[QBChat]","Chat Ping: ","failed, at ",Utils.getCurrentTime(),"_chatPingFailedCounter: ",self1._chatPingFailedCounter," error: ",error),self1._chatPingFailedCounter+=1,self1._chatPingFailedCounter>6&&(self1.isConnected=!1,self1._isConnecting=!1,self1._chatPingFailedCounter=0,self1._establishConnection(params))):(Utils.QBLog("[QBChat]","Chat Ping: ","ok, at ",Utils.getCurrentTime(),"_chatPingFailedCounter: ",self1._chatPingFailedCounter),self1._chatPingFailedCounter=0)})}catch(err){Utils.QBLog("[QBChat]","Chat Ping: ","Exception, at ",Utils.getCurrentTime(),", detail info: ",err)}},1e3*config.pingLocalhostTimeInterval)),"function"==typeof self1.onSessionExpiredListener&&void 0===self1._checkExpiredSessionTimer&&(Utils.QBLog("[QBChat]","Init timer for check session expired at ",new Date().toTimeString().split(" ")[0]),self1._checkExpiredSessionTimer=setInterval(function(){var timeNow=new Date;void 0!==config.qbTokenExpirationDate&&Math.round((timeNow.getTime()-config.qbTokenExpirationDate.getTime())/6e4)>=0&&(self1._sessionHasExpired=!0,Utils.safeCallbackCall(self1.onSessionExpiredListener,null))},5e3)),self1._postConnectActions(function(roster){callback(null,roster)},isInitialConnect);break;case Strophe.Status.DISCONNECTING:Utils.QBLog("[QBChat]","Status.DISCONNECTING");break;case Strophe.Status.DISCONNECTED:Utils.QBLog("[QBChat]","Status.DISCONNECTED at "+chatUtils.getLocalTime()),self1.isConnected&&"function"==typeof self1.onDisconnectedListener&&Utils.safeCallbackCall(self1.onDisconnectedListener),self1.isConnected=!1,self1._isConnecting=!1,self1.connection.reset(),self1._establishConnection(params);break;case Strophe.Status.ATTACHED:Utils.QBLog("[QBChat]","Status.ATTACHED")}})),Utils.getEnv().browser||(Utils.QBLog("[QBChat]","!!--call branch code connect for node--!!"),self1.Client.removeAllListeners(),self1.Client.on("connect",function(){Utils.QBLog("[QBChat]","Status.CONNECTING","(Chat Protocol - "+(1===config.chatProtocol.active?"BOSH":"WebSocket)"))}),self1.Client.on("auth",function(){Utils.QBLog("[QBChat]","Status.AUTHENTICATING")}),self1.Client.on("online",function(){self1._postConnectActions(function(roster){callback(null,roster)},isInitialConnect)}),self1.Client.on("stanza",function(stanza){Utils.QBLog("[QBChat] RECV:",stanza.toString()),stanza.is("presence")?self1._onPresence(stanza):stanza.is("iq")?self1._onIQ(stanza):stanza.is("message")&&("headline"===stanza.attrs.type?self1._onSystemMessageListener(stanza):"error"===stanza.attrs.type?self1._onMessageErrorListener(stanza):self1._onMessage(stanza))}),self1.Client.on("disconnect",function(){Utils.QBLog("[QBChat]","Status.DISCONNECTED - "+chatUtils.getLocalTime()),"function"==typeof self1.onDisconnectedListener&&Utils.safeCallbackCall(self1.onDisconnectedListener),self1.isConnected=!1,self1._isConnecting=!1,self1._establishConnection(params)}),self1.Client.on("error",function(){Utils.QBLog("[QBChat]","Status.ERROR - "+chatUtils.getLocalTime()),err=Utils.getError(422,"Status.ERROR - An error has occurred","QBChat"),isInitialConnect&&callback(err,null),self1.isConnected=!1,self1._isConnecting=!1}),self1.Client.on("end",function(){self1.Client.removeAllListeners()}),self1.Client.options.jid=userJid,self1.Client.options.password=params.password,self1.Client.connect())},_postConnectActions:function(callback,isInitialConnect){Utils.QBLog("[QBChat]","Status.CONNECTED at "+chatUtils.getLocalTime());var self1=this,isBrowser=Utils.getEnv().browser,xmppClient=isBrowser?self1.connection:self1.Client,presence=isBrowser?$pres():chatUtils.createStanza(XMPP.Stanza,null,"presence");if(config.streamManagement.enable&&2===config.chatProtocol.active&&(self1.streamManagement.enable(self1.connection,null),self1.streamManagement.sentMessageCallback=self1._sentMessageCallback),self1.helpers.setUserCurrentJid(self1.helpers.userCurrentJid(xmppClient)),self1.isConnected=!0,self1._isConnecting=!1,self1._sessionHasExpired=!1,self1._enableCarbons(),isInitialConnect)self1.roster.get(function(contacts){xmppClient.send(presence),self1.roster.contacts=contacts,callback(self1.roster.contacts)});else{var rooms=Object.keys(self1.muc.joinedRooms);xmppClient.send(presence),Utils.QBLog("[QBChat]","Re-joining "+rooms.length+" rooms...");for(var i=0,len=rooms.length;i<len;i++)self1.muc.join(rooms[i]);"function"==typeof self1.onReconnectListener&&Utils.safeCallbackCall(self1.onReconnectListener)}},_establishConnection:function(params){var self1=this;if(Utils.QBLog("[QBChat]","_establishConnection called"),self1._isLogout||self1._checkConnectionTimer){Utils.QBLog("[QBChat]","_establishConnection return");return}var _connect=function(){Utils.QBLog("[QBChat]","call _connect() in _establishConnection "),self1.isConnected||self1._isConnecting||self1._sessionHasExpired?(Utils.QBLog("[QBChat]","stop timer in _establishConnection "),clearInterval(self1._checkConnectionTimer),self1._checkConnectionTimer=void 0):(Utils.QBLog("[QBChat]","call connect() again in _establishConnection "),self1.connect(params))};_connect(),self1._checkConnectionTimer=setInterval(function(){Utils.QBLog("[QBChat]","self._checkConnectionTimer called with config.chatReconnectionTimeInterval = "+config.chatReconnectionTimeInterval),_connect()},1e3*config.chatReconnectionTimeInterval)},reconnect:function(){Utils.QBLog("[QBChat]","Call reconnect "),clearInterval(this._checkConnectionTimer),this._checkConnectionTimer=void 0,this.muc.joinedRooms={},this.helpers.setUserCurrentJid(""),Utils.getEnv().browser?(this.connection.flush(),this.connection.disconnect()):this.Client.end()},send:function(jid_or_user_id,message){Utils.QBLog("[QBChat]","Call send "+JSON.stringify(message));var builder=Utils.getEnv().browser?$msg:XMPP.Stanza,paramsCreateMsg={from:this.helpers.getUserCurrentJid(),to:this.helpers.jidOrUserId(jid_or_user_id),type:message.type?message.type:"chat",id:message.id?message.id:Utils.getBsonObjectId()},stanza=chatUtils.createStanza(builder,paramsCreateMsg);return message.body&&stanza.c("body",{xmlns:chatUtils.MARKERS.CLIENT}).t(message.body).up(),message.markable&&stanza.c("markable",{xmlns:chatUtils.MARKERS.CHAT}).up(),message.extension&&(stanza.c("extraParams",{xmlns:chatUtils.MARKERS.CLIENT}),stanza=chatUtils.filledExtraParams(stanza,message.extension)),Utils.getEnv().browser?config.streamManagement.enable?(message.id=paramsCreateMsg.id,message.jid_or_user_id=jid_or_user_id,this.connection.send(stanza,message)):this.connection.send(stanza):config.streamManagement.enable?(message.id=paramsCreateMsg.id,message.jid_or_user_id=jid_or_user_id,this.Client.send(stanza,message)):this.Client.send(stanza),paramsCreateMsg.id},sendSystemMessage:function(jid_or_user_id,message){Utils.QBLog("[QBChat]","Call sendSystemMessage "+JSON.stringify(message));var builder=Utils.getEnv().browser?$msg:XMPP.Stanza,paramsCreateMsg={type:"headline",id:message.id?message.id:Utils.getBsonObjectId(),to:this.helpers.jidOrUserId(jid_or_user_id)},stanza=chatUtils.createStanza(builder,paramsCreateMsg);return message.body&&stanza.c("body",{xmlns:chatUtils.MARKERS.CLIENT}).t(message.body).up(),Utils.getEnv().browser?(message.extension&&(stanza.c("extraParams",{xmlns:chatUtils.MARKERS.CLIENT}).c("moduleIdentifier").t("SystemNotifications").up(),stanza=chatUtils.filledExtraParams(stanza,message.extension)),this.connection.send(stanza)):(message.extension&&(stanza.c("extraParams",{xmlns:chatUtils.MARKERS.CLIENT}).c("moduleIdentifier").t("SystemNotifications"),stanza=chatUtils.filledExtraParams(stanza,message.extension)),this.Client.send(stanza)),paramsCreateMsg.id},sendIsTypingStatus:function(jid_or_user_id){Utils.QBLog("[QBChat]","Call sendIsTypingStatus ");var stanzaParams={from:this.helpers.getUserCurrentJid(),to:this.helpers.jidOrUserId(jid_or_user_id),type:this.helpers.typeChat(jid_or_user_id)},builder=Utils.getEnv().browser?$msg:XMPP.Stanza,stanza=chatUtils.createStanza(builder,stanzaParams);stanza.c("composing",{xmlns:chatUtils.MARKERS.STATES}),Utils.getEnv().browser?this.connection.send(stanza):this.Client.send(stanza)},sendIsStopTypingStatus:function(jid_or_user_id){Utils.QBLog("[QBChat]","Call sendIsStopTypingStatus ");var stanzaParams={from:this.helpers.getUserCurrentJid(),to:this.helpers.jidOrUserId(jid_or_user_id),type:this.helpers.typeChat(jid_or_user_id)},builder=Utils.getEnv().browser?$msg:XMPP.Stanza,stanza=chatUtils.createStanza(builder,stanzaParams);stanza.c("paused",{xmlns:chatUtils.MARKERS.STATES}),Utils.getEnv().browser?this.connection.send(stanza):this.Client.send(stanza)},sendDeliveredStatus:function(params){Utils.QBLog("[QBChat]","Call sendDeliveredStatus ");var stanzaParams={type:"chat",from:this.helpers.getUserCurrentJid(),id:Utils.getBsonObjectId(),to:this.helpers.jidOrUserId(params.userId)},builder=Utils.getEnv().browser?$msg:XMPP.Stanza,stanza=chatUtils.createStanza(builder,stanzaParams);stanza.c("received",{xmlns:chatUtils.MARKERS.MARKERS,id:params.messageId}).up(),stanza.c("extraParams",{xmlns:chatUtils.MARKERS.CLIENT}).c("dialog_id").t(params.dialogId),Utils.getEnv().browser?this.connection.send(stanza):this.Client.send(stanza)},sendReadStatus:function(params){Utils.QBLog("[QBChat]","Call sendReadStatus "+JSON.stringify(params));var stanzaParams={type:"chat",from:this.helpers.getUserCurrentJid(),to:this.helpers.jidOrUserId(params.userId),id:Utils.getBsonObjectId()},builder=Utils.getEnv().browser?$msg:XMPP.Stanza,stanza=chatUtils.createStanza(builder,stanzaParams);stanza.c("displayed",{xmlns:chatUtils.MARKERS.MARKERS,id:params.messageId}).up(),stanza.c("extraParams",{xmlns:chatUtils.MARKERS.CLIENT}).c("dialog_id").t(params.dialogId),Utils.getEnv().browser?this.connection.send(stanza):this.Client.send(stanza)},getLastUserActivity:function(jid_or_user_id){var iqParams,builder,iq;Utils.QBLog("[QBChat]","Call getLastUserActivity "),iqParams={from:this.helpers.getUserCurrentJid(),id:this.helpers.getUniqueId("lastActivity"),to:this.helpers.jidOrUserId(jid_or_user_id),type:"get"},builder=Utils.getEnv().browser?$iq:XMPP.Stanza,(iq=chatUtils.createStanza(builder,iqParams,"iq")).c("query",{xmlns:chatUtils.MARKERS.LAST}),Utils.getEnv().browser?this.connection.sendIQ(iq):this.Client.send(iq)},pingchat:function(callback){Utils.QBLog("[QBChat]","ping chat");var to,stanza,self1=this,id=this.helpers.getUniqueId("ping"),builder=Utils.getEnv().browser?$iq:XMPP.Stanza;to=config.endpoints.chat?config.endpoints.chat:"chat.quickblox.com";var iqParams={from:this.helpers.getUserCurrentJid(),id:id,to:to,type:"get"};return(stanza=chatUtils.createStanza(builder,iqParams,"iq")).c("ping",{xmlns:"urn:xmpp:ping"}),Utils.getEnv().browser?this.connection.send(stanza):this.Client.send(stanza),this._pings[id]={callback:callback,interval:setTimeout(function(){callback("Chat ping No answer"),self1._pings[id]=void 0,delete self1._pings[id]},1e3*config.pingTimeout)},id},ping:function(jid_or_user_id,callback){Utils.QBLog("[QBChat]","Call ping ");var to,_callback,stanza,self1=this,id=this.helpers.getUniqueId("ping"),builder=Utils.getEnv().browser?$iq:XMPP.Stanza;if(("string"==typeof jid_or_user_id||"number"==typeof jid_or_user_id)&&"function"==typeof callback)to=this.helpers.jidOrUserId(jid_or_user_id),_callback=callback;else{if("function"!=typeof jid_or_user_id||callback)throw Error("Invalid arguments provided. Either userId/jid (number/string) and callback or only callback should be provided.");to=config.endpoints.chat,_callback=jid_or_user_id}var iqParams={from:this.helpers.getUserCurrentJid(),id:id,to:to,type:"get"};return(stanza=chatUtils.createStanza(builder,iqParams,"iq")).c("ping",{xmlns:"urn:xmpp:ping"}),Utils.getEnv().browser?this.connection.send(stanza):this.Client.send(stanza),this._pings[id]={callback:_callback,interval:setTimeout(function(){_callback("No answer"),self1._pings[id]=void 0,delete self1._pings[id]},1e3*config.pingTimeout)},id},disconnect:function(){Utils.QBLog("[QBChat]","Call disconnect "),clearInterval(this._checkConnectionTimer),clearInterval(this._checkExpiredSessionTimer),this._checkConnectionTimer=void 0,this._checkExpiredSessionTimer=void 0,this.muc.joinedRooms={},this._isLogout=!0,this.helpers.setUserCurrentJid(""),Utils.getEnv().browser?(this.connection.flush(),this.connection.disconnect(),void 0!==this._checkConnectionPingTimer&&(Utils.QBLog("[QBChat]","Stop ping"),clearInterval(this._checkConnectionPingTimer),this._checkConnectionPingTimer=void 0)):this.Client.end()},addListener:function(params,callback){if(Utils.QBLog("[Deprecated!]","Avoid using it, this feature will be removed in future version."),!Utils.getEnv().browser)throw Error(unsupportedError);return this.connection.XAddTrackedHandler(handler,null,params.name||null,params.type||null,params.id||null,params.from||null);function handler(){return callback(),!1!==params.live}},deleteListener:function(ref){if(Utils.QBLog("[Deprecated!]","Avoid using it, this feature will be removed in future version."),!Utils.getEnv().browser)throw Error(unsupportedError);this.connection.deleteHandler(ref)},_enableCarbons:function(cb){var carbonParams={type:"set",from:this.helpers.getUserCurrentJid(),id:chatUtils.getUniqueId("enableCarbons")},builder=Utils.getEnv().browser?$iq:XMPP.Stanza,iq=chatUtils.createStanza(builder,carbonParams,"iq");iq.c("enable",{xmlns:chatUtils.MARKERS.CARBONS}),Utils.getEnv().browser?this.connection.sendIQ(iq):this.Client.send(iq)}},RosterProxy.prototype={get:function(callback){var self1=this,contacts={},iqParams={type:"get",from:self1.helpers.getUserCurrentJid(),id:chatUtils.getUniqueId("getRoster")},builder=Utils.getEnv().browser?$iq:XMPP.Stanza,iq=chatUtils.createStanza(builder,iqParams,"iq");function _getItems(stanza){return Utils.getEnv().browser?stanza.getElementsByTagName("item"):stanza.getChild("query").children}function _callbackWrap(stanza){for(var items=_getItems(stanza),i=0,len=items.length;i<len;i++){var userId=self1.helpers.getIdFromNode(chatUtils.getAttr(items[i],"jid")),ask=chatUtils.getAttr(items[i],"ask"),subscription=chatUtils.getAttr(items[i],"subscription");contacts[userId]={subscription:subscription,ask:ask||null}}callback(contacts)}iq.c("query",{xmlns:chatUtils.MARKERS.ROSTER}),Utils.getEnv().browser?self1.connection.sendIQ(iq,_callbackWrap):(self1.nodeStanzasCallbacks[iqParams.id]=_callbackWrap,self1.Client.send(iq))},add:function(jidOrUserId,callback){var userJid=this.helpers.jidOrUserId(jidOrUserId),userId=this.helpers.getIdFromNode(userJid).toString();this.contacts[userId]={subscription:"none",ask:"subscribe"},this._sendSubscriptionPresence({jid:userJid,type:"subscribe"}),"function"==typeof callback&&callback()},confirm:function(jidOrUserId,callback){var userJid=this.helpers.jidOrUserId(jidOrUserId),userId=this.helpers.getIdFromNode(userJid).toString();this.contacts[userId]={subscription:"from",ask:"subscribe"},this._sendSubscriptionPresence({jid:userJid,type:"subscribed"}),this._sendSubscriptionPresence({jid:userJid,type:"subscribe"}),"function"==typeof callback&&callback()},reject:function(jidOrUserId,callback){var userJid=this.helpers.jidOrUserId(jidOrUserId),userId=this.helpers.getIdFromNode(userJid).toString();this.contacts[userId]={subscription:"none",ask:null},this._sendSubscriptionPresence({jid:userJid,type:"unsubscribed"}),"function"==typeof callback&&callback()},remove:function(jidOrUserId,callback){var self1=this,userJid=this.helpers.jidOrUserId(jidOrUserId),userId=this.helpers.getIdFromNode(userJid),iqParams={type:"set",from:self1.connection?self1.connection.jid:self1.Client.jid.user,id:chatUtils.getUniqueId("getRoster")},builder=Utils.getEnv().browser?$iq:XMPP.Stanza,iq=chatUtils.createStanza(builder,iqParams,"iq");function _callbackWrap(){delete self1.contacts[userId],"function"==typeof callback&&callback()}iq.c("query",{xmlns:chatUtils.MARKERS.ROSTER}).c("item",{jid:userJid,subscription:"remove"}),Utils.getEnv().browser?self1.connection.sendIQ(iq,_callbackWrap):(self1.nodeStanzasCallbacks[iqParams.id]=_callbackWrap,self1.Client.send(iq))},_sendSubscriptionPresence:function(params){var builder=Utils.getEnv().browser?$pres:XMPP.Stanza,presParams={to:params.jid,type:params.type},pres=chatUtils.createStanza(builder,presParams,"presence");Utils.getEnv().browser?this.connection.send(pres):this.Client.send(pres)}},MucProxy.prototype={join:function(dialogIdOrJid,callback){var self1=this,id=chatUtils.getUniqueId("join"),dialogJid=this.helpers.getDialogJid(dialogIdOrJid),presParams={id:id,from:self1.helpers.getUserCurrentJid(),to:self1.helpers.getRoomJid(dialogJid)},builder=Utils.getEnv().browser?$pres:XMPP.Stanza,pres=chatUtils.createStanza(builder,presParams,"presence");function handleJoinAnswer(stanza){var id=chatUtils.getAttr(stanza,"id"),from=chatUtils.getAttr(stanza,"from"),dialogId=self1.helpers.getDialogIdFromNode(from),x=chatUtils.getElement(stanza,"x"),xXMLNS=chatUtils.getAttr(x,"xmlns"),status=chatUtils.getElement(x,"status"),statusCode=chatUtils.getAttr(status,"code");if(1==callback.length)return Utils.safeCallbackCall(callback,stanza),!0;if(status&&"110"==statusCode)Utils.safeCallbackCall(callback,null,{dialogId:dialogId});else{var type=chatUtils.getAttr(stanza,"type");if(type&&"error"===type&&"http://jabber.org/protocol/muc"==xXMLNS&&id.endsWith(":join")){var errorEl=chatUtils.getElement(stanza,"error"),code=chatUtils.getAttr(errorEl,"code"),errorMessage=chatUtils.getElementText(errorEl,"text");Utils.safeCallbackCall(callback,{code:code||500,message:errorMessage||"Unknown issue"},{dialogId:dialogId})}}}pres.c("x",{xmlns:chatUtils.MARKERS.MUC}).c("history",{maxstanzas:0}),this.joinedRooms[dialogJid]=!0,Utils.getEnv().browser?("function"==typeof callback&&self1.connection.XAddTrackedHandler(handleJoinAnswer,null,"presence",null,id),self1.connection.send(pres)):("function"==typeof callback&&(self1.nodeStanzasCallbacks[id]=handleJoinAnswer),self1.Client.send(pres))},leave:function(jid,callback){var self1=this,presParams={type:"unavailable",from:self1.helpers.getUserCurrentJid(),to:self1.helpers.getRoomJid(jid)},builder=Utils.getEnv().browser?$pres:XMPP.Stanza,pres=chatUtils.createStanza(builder,presParams,"presence");function handleLeaveAnswer(stanza){var id=chatUtils.getAttr(stanza,"id"),from=chatUtils.getAttr(stanza,"from"),dialogId=self1.helpers.getDialogIdFromNode(from),x=chatUtils.getElement(stanza,"x"),xXMLNS=chatUtils.getAttr(x,"xmlns"),status=chatUtils.getElement(x,"status"),statusCode=chatUtils.getAttr(status,"code");if(status&&"110"==statusCode)Utils.safeCallbackCall(callback,null,{dialogId:dialogId});else{var type=chatUtils.getAttr(stanza,"type");if(type&&"error"===type&&"http://jabber.org/protocol/muc"==xXMLNS&&id.endsWith(":join")){var errorEl=chatUtils.getElement(stanza,"error"),code=chatUtils.getAttr(errorEl,"code"),errorMessage=chatUtils.getElementText(errorEl,"text");Utils.safeCallbackCall(callback,{code:code||500,message:errorMessage||"Unknown issue"},null)}}}if(delete this.joinedRooms[jid],Utils.getEnv().browser){var roomJid=self1.helpers.getRoomJid(jid);"function"==typeof callback&&self1.connection.XAddTrackedHandler(handleLeaveAnswer,null,"presence",presParams.type,null,roomJid),self1.connection.send(pres)}else"function"==typeof callback&&(self1.nodeStanzasCallbacks["muc:leave"]=handleLeaveAnswer),self1.Client.send(pres)},listOnlineUsers:function(dialogJID,callback){var self1=this,onlineUsers=[],iqParams={type:"get",to:dialogJID,from:self1.helpers.getUserCurrentJid(),id:chatUtils.getUniqueId("muc_disco_items")},builder=Utils.getEnv().browser?$iq:XMPP.Stanza,iq=chatUtils.createStanza(builder,iqParams,"iq");function _getUsers(stanza){var stanzaId=stanza.attrs.id;if(self1.nodeStanzasCallbacks[stanzaId]){for(var userId,users=[],items=stanza.getChild("query").getChildElements("item"),i=0,len=items.length;i<len;i++)userId=self1.helpers.getUserIdFromRoomJid(items[i].attrs.jid),users.push(parseInt(userId));callback(users)}}iq.c("query",{xmlns:"http://jabber.org/protocol/disco#items"}),Utils.getEnv().browser?self1.connection.sendIQ(iq,function(stanza){for(var userId,items=stanza.getElementsByTagName("item"),i=0,len=items.length;i<len;i++)userId=self1.helpers.getUserIdFromRoomJid(items[i].getAttribute("jid")),onlineUsers.push(parseInt(userId));callback(onlineUsers)}):(self1.Client.send(iq),self1.nodeStanzasCallbacks[iqParams.id]=_getUsers)}},PrivacyListProxy.prototype={create:function(list,callback){for(var userId,userJid,userMuc,userAction,mutualBlock,listPrivacy={},listUserId=[],i=list.items.length-1;i>=0;i--){var user=list.items[i];listPrivacy[user.user_id]={action:user.action,mutualBlock:!0===user.mutualBlock}}listUserId=Object.keys(listPrivacy);var iqParams={type:"set",from:this.helpers.getUserCurrentJid(),id:chatUtils.getUniqueId("edit")},builder=Utils.getEnv().browser?$iq:XMPP.Stanza,iq=chatUtils.createStanza(builder,iqParams,"iq");function createPrivacyItem(iq,params){return Utils.getEnv().browser?iq.c("item",{type:"jid",value:params.jidOrMuc,action:params.userAction,order:params.order}).c("message",{}).up().c("presence-in",{}).up().c("presence-out",{}).up().c("iq",{}).up().up():iq.getChild("query").getChild("list").c("item",{type:"jid",value:params.jidOrMuc,action:params.userAction,order:params.order}).c("message",{}).up().c("presence-in",{}).up().c("presence-out",{}).up().c("iq",{}).up().up(),iq}function createPrivacyItemMutal(iq,params){return Utils.getEnv().browser?iq.c("item",{type:"jid",value:params.jidOrMuc,action:params.userAction,order:params.order}).up():iq.getChild("query").getChild("list").c("item",{type:"jid",value:params.jidOrMuc,action:params.userAction,order:params.order}).up(),iq}iq.c("query",{xmlns:chatUtils.MARKERS.PRIVACY}).c("list",{name:list.name});for(var index=0,j=0,len=listUserId.length;index<len;index++,j+=2)mutualBlock=listPrivacy[userId=listUserId[index]].mutualBlock,userAction=listPrivacy[userId].action,userJid=this.helpers.jidOrUserId(parseInt(userId,10)),userMuc=this.helpers.getUserNickWithMucDomain(userId),mutualBlock&&"deny"===userAction?(iq=createPrivacyItemMutal(iq,{order:j+1,jidOrMuc:userJid,userAction:userAction}),iq=createPrivacyItemMutal(iq,{order:j+2,jidOrMuc:userMuc,userAction:userAction}).up().up()):(iq=createPrivacyItem(iq,{order:j+1,jidOrMuc:userJid,userAction:userAction}),iq=createPrivacyItem(iq,{order:j+2,jidOrMuc:userMuc,userAction:userAction}));Utils.getEnv().browser?this.connection.sendIQ(iq,function(stanzaResult){callback(null)},function(stanzaError){stanzaError?callback(chatUtils.getErrorFromXMLNode(stanzaError)):callback(Utils.getError(408))}):(this.Client.send(iq),this.nodeStanzasCallbacks[iqParams.id]=function(stanza){stanza.getChildElements("error").length?callback(Utils.getError(408)):callback(null)})},getList:function(name,callback){var items,userJid,userId,self1=this,usersList=[],iqParams={type:"get",from:self1.helpers.getUserCurrentJid(),id:chatUtils.getUniqueId("getlist")},builder=Utils.getEnv().browser?$iq:XMPP.Stanza,iq=chatUtils.createStanza(builder,iqParams,"iq");iq.c("query",{xmlns:chatUtils.MARKERS.PRIVACY}).c("list",{name:name}),Utils.getEnv().browser?self1.connection.sendIQ(iq,function(stanzaResult){items=stanzaResult.getElementsByTagName("item");for(var i=0,len=items.length;i<len;i+=2)userJid=items[i].getAttribute("value"),userId=self1.helpers.getIdFromNode(userJid),usersList.push({user_id:userId,action:items[i].getAttribute("action")});callback(null,{name:name,items:usersList})},function(stanzaError){stanzaError?callback(chatUtils.getErrorFromXMLNode(stanzaError),null):callback(Utils.getError(408),null)}):(self1.nodeStanzasCallbacks[iqParams.id]=function(stanza){for(var userJid,stanzaQuery=stanza.getChild("query"),list=stanzaQuery?stanzaQuery.getChild("list"):null,items=list?list.getChildElements("item"):null,usersList=[],i=0,len=items.length;i<len;i+=2)userJid=items[i].attrs.value,usersList.push({user_id:self1.helpers.getIdFromNode(userJid),action:items[i].attrs.action});callback(null,list={name:list.attrs.name,items:usersList}),delete self1.nodeStanzasCallbacks[iqParams.id]},self1.Client.send(iq))},update:function(listWithUpdates,callback){var self1=this;self1.getList(listWithUpdates.name,function(error,existentList){if(error)callback(error,null);else{var updatedList={};updatedList.items=Utils.MergeArrayOfObjects(existentList.items,listWithUpdates.items),updatedList.name=listWithUpdates.name,self1.create(updatedList,function(err,result){error?callback(err,null):callback(null,result)})}})},getNames:function(callback){var iq,stanzaParams={type:"get",from:this.helpers.getUserCurrentJid(),id:chatUtils.getUniqueId("getNames")};Utils.getEnv().browser?(iq=$iq(stanzaParams).c("query",{xmlns:Strophe.NS.PRIVACY_LIST}),this.connection.sendIQ(iq,function(stanzaResult){for(var allNames=[],defaultList=stanzaResult.getElementsByTagName("default"),activeList=stanzaResult.getElementsByTagName("active"),allLists=stanzaResult.getElementsByTagName("list"),defaultName=defaultList&&defaultList.length>0?defaultList[0].getAttribute("name"):null,activeName=activeList&&activeList.length>0?activeList[0].getAttribute("name"):null,i=0,len=allLists.length;i<len;i++)allNames.push(allLists[i].getAttribute("name"));callback(null,{default:defaultName,active:activeName,names:allNames})},function(stanzaError){stanzaError?callback(chatUtils.getErrorFromXMLNode(stanzaError),null):callback(Utils.getError(408),null)})):((iq=new XMPP.Stanza("iq",stanzaParams)).c("query",{xmlns:chatUtils.MARKERS.PRIVACY}),this.nodeStanzasCallbacks[iq.attrs.id]=function(stanza){if("error"!==stanza.attrs.type){for(var allNames=[],query=stanza.getChild("query"),defaultList=query.getChild("default"),activeList=query.getChild("active"),allLists=query.getChildElements("list"),defaultName=defaultList?defaultList.attrs.name:null,activeName=activeList?activeList.attrs.name:null,i=0,len=allLists.length;i<len;i++)allNames.push(allLists[i].attrs.name);callback(null,{default:defaultName,active:activeName,names:allNames})}else callback(Utils.getError(408))},this.Client.send(iq))},delete:function(name,callback){var iq,stanzaParams={from:this.connection?this.connection.jid:this.Client.jid.user,type:"set",id:chatUtils.getUniqueId("remove")};Utils.getEnv().browser?(iq=$iq(stanzaParams).c("query",{xmlns:Strophe.NS.PRIVACY_LIST}).c("list",{name:name||""}),this.connection.sendIQ(iq,function(stanzaResult){callback(null)},function(stanzaError){stanzaError?callback(chatUtils.getErrorFromXMLNode(stanzaError)):callback(Utils.getError(408))})):((iq=new XMPP.Stanza("iq",stanzaParams)).c("query",{xmlns:chatUtils.MARKERS.PRIVACY}).c("list",{name:name||""}),this.nodeStanzasCallbacks[stanzaParams.id]=function(stanza){stanza.getChildElements("error").length?callback(Utils.getError(408)):callback(null)},this.Client.send(iq))},setAsDefault:function(name,callback){var iq,self1=this,stanzaParams={from:this.connection?this.connection.jid:this.Client.jid.user,type:"set",id:chatUtils.getUniqueId("default")};function setAsActive(self1){var setAsActiveIq,setAsActiveStanzaParams={from:self1.connection?self1.connection.jid:self1.Client.jid.user,type:"set",id:chatUtils.getUniqueId("active1")};Utils.getEnv().browser?(setAsActiveIq=$iq(setAsActiveStanzaParams).c("query",{xmlns:Strophe.NS.PRIVACY_LIST}).c("active",name&&name.length>0?{name:name}:{}),self1.connection.sendIQ(setAsActiveIq,function(setAsActiveStanzaResult){callback(null)},function(setAsActiveStanzaError){setAsActiveStanzaError?callback(chatUtils.getErrorFromXMLNode(setAsActiveStanzaError)):callback(Utils.getError(408))})):((setAsActiveIq=new XMPP.Stanza("iq",setAsActiveStanzaParams)).c("query",{xmlns:chatUtils.MARKERS.PRIVACY}).c("active",name&&name.length>0?{name:name}:{}),self1.nodeStanzasCallbacks[setAsActiveStanzaParams.id]=function(setAsActistanza){setAsActistanza.getChildElements("error").length?callback(Utils.getError(408)):callback(null)},self1.Client.send(setAsActiveIq))}Utils.getEnv().browser?(iq=$iq(stanzaParams).c("query",{xmlns:Strophe.NS.PRIVACY_LIST}).c("default",name&&name.length>0?{name:name}:{}),this.connection.sendIQ(iq,function(stanzaResult){setAsActive(self1)},function(stanzaError){stanzaError?callback(chatUtils.getErrorFromXMLNode(stanzaError)):callback(Utils.getError(408))})):((iq=new XMPP.Stanza("iq",stanzaParams)).c("query",{xmlns:chatUtils.MARKERS.PRIVACY}).c("default",name&&name.length>0?{name:name}:{}),this.nodeStanzasCallbacks[stanzaParams.id]=function(stanza){stanza.getChildElements("error").length?callback(Utils.getError(408)):setAsActive(self1)},this.Client.send(iq))}},Helpers.prototype={getUniqueId:chatUtils.getUniqueId,jidOrUserId:function(jid_or_user_id){var jid;if("string"==typeof jid_or_user_id)jid=jid_or_user_id;else if("number"==typeof jid_or_user_id)jid=jid_or_user_id+"-"+config.creds.appId+"@"+config.endpoints.chat;else throw Error('The method "jidOrUserId" may take jid or id');return jid},typeChat:function(jid_or_user_id){var chatType;if("string"==typeof jid_or_user_id)chatType=jid_or_user_id.indexOf("muc")>-1?"groupchat":"chat";else if("number"==typeof jid_or_user_id)chatType="chat";else throw Error(unsupportedError);return chatType},getRecipientId:function(occupantsIds,UserId){var recipient=null;return occupantsIds.forEach(function(item){item!=UserId&&(recipient=item)}),recipient},getUserJid:function(userId,appId){return appId?userId+"-"+appId+"@"+config.endpoints.chat:userId+"-"+config.creds.appId+"@"+config.endpoints.chat},getUserNickWithMucDomain:function(userId){return config.endpoints.muc+"/"+userId},getIdFromNode:function(jid){return 0>jid.indexOf("@")?null:parseInt(jid.split("@")[0].split("-")[0])},getDialogIdFromNode:function(jid){return 0>jid.indexOf("@")?null:jid.split("@")[0].split("_")[1]},getRoomJidFromDialogId:function(dialogId){return config.creds.appId+"_"+dialogId+"@"+config.endpoints.muc},getRoomJid:function(jid){return jid+"/"+this.getIdFromNode(this._userCurrentJid)},getIdFromResource:function(jid){var s=jid.split("/");return s.length<2?null:(s.splice(0,1),parseInt(s.join("/")))},getRoomJidFromRoomFullJid:function(jid){var s=jid.split("/");return s.length<2?null:s[0]},getBsonObjectId:function(){return Utils.getBsonObjectId()},getUserIdFromRoomJid:function(jid){var arrayElements=jid.toString().split("/");return 0===arrayElements.length?null:arrayElements[arrayElements.length-1]},userCurrentJid:function(client){try{if(client instanceof Strophe.Connection)return client.jid;return client.jid.user+"@"+client.jid._domain+"/"+client.jid._resource}catch(e){return client.jid.user+"@"+client.jid._domain+"/"+client.jid._resource}},getUserCurrentJid:function(){return this._userCurrentJid},setUserCurrentJid:function(jid){this._userCurrentJid=jid},getDialogJid:function(identifier){return identifier.indexOf("@")>0?identifier:this.getRoomJidFromDialogId(identifier)}},module.exports=ChatProxy},{"../../plugins/streamManagement":252,"../../qbConfig":253,"../../qbStrophe":256,"../../qbUtils":257,"./qbChatHelpers":235,"nativescript-xmpp-client":void 0,"node-xmpp-client":111}],235:[function(require1,module,exports){"use strict";var utils=require1("../../qbUtils"),config=require1("../../qbConfig"),ERR_UNKNOWN_INTERFACE="Unknown interface. SDK support browser / node env.";function ChatNotConnectedError(message,fileName,lineNumber){var instance=Error(message,fileName,lineNumber);return instance.name="ChatNotConnectedError",Object.setPrototypeOf(instance,Object.getPrototypeOf(this)),Error.captureStackTrace&&Error.captureStackTrace(instance,ChatNotConnectedError),instance}ChatNotConnectedError.prototype=Object.create(Error.prototype,{constructor:{value:Error,enumerable:!1,writable:!0,configurable:!0}}),Object.setPrototypeOf?Object.setPrototypeOf(ChatNotConnectedError,Error):ChatNotConnectedError.__proto__=Error,module.exports={MARKERS:{CLIENT:"jabber:client",CHAT:"urn:xmpp:chat-markers:0",STATES:"http://jabber.org/protocol/chatstates",MARKERS:"urn:xmpp:chat-markers:0",CARBONS:"urn:xmpp:carbons:2",ROSTER:"jabber:iq:roster",MUC:"http://jabber.org/protocol/muc",PRIVACY:"jabber:iq:privacy",LAST:"jabber:iq:last"},ChatNotConnectedError:ChatNotConnectedError,buildUserJid:function(params){var jid;return"userId"in params?(jid=params.userId+"-"+config.creds.appId+"@"+config.endpoints.chat,"resource"in params&&(jid=jid+"/"+params.resource)):"jid"in params&&(jid=params.jid),jid},createStanza:function(builder,params,type){return utils.getEnv().browser?builder(params):new builder(type||"message",params)},getAttr:function(el,attrName){var attr;return el?("function"==typeof el.getAttribute?attr=el.getAttribute(attrName):el.attrs&&(attr=el.attrs[attrName]),attr||null):null},getElement:function(stanza,elName){var el;if("function"==typeof stanza.querySelector)el=stanza.querySelector(elName);else if("function"==typeof stanza.getChild)el=stanza.getChild(elName)||stanza.children.find(child=>"function"==typeof child.getChild&&this.getElement(child,elName));else throw ERR_UNKNOWN_INTERFACE;return el||null},getAllElements:function(stanza,elName){var el;if("function"==typeof stanza.querySelectorAll)el=stanza.querySelectorAll(elName);else if("function"==typeof stanza.getChild)el=stanza.getChild(elName);else throw ERR_UNKNOWN_INTERFACE;return el||null},getElementText:function(stanza,elName){var el,txt;if("function"==typeof stanza.querySelector)txt=(el=stanza.querySelector(elName))?el.textContent:null;else if("function"==typeof stanza.getChildText)txt=stanza.getChildText(elName)||stanza.children.find(child=>"function"==typeof child.getChildText&&this.getElementText(child,elName));else throw ERR_UNKNOWN_INTERFACE;return txt||null},_JStoXML:function(title,obj,msg){var self1=this;msg.c(title),Object.keys(obj).forEach(function(field){"object"==typeof obj[field]?self1._JStoXML(field,obj[field],msg):msg.c(field).t(obj[field]).up()}),msg.up()},_XMLtoJS:function(extension,title,obj){extension[title]={};for(var i=0,len=obj.childNodes.length;i<len;i++)obj.childNodes[i].childNodes.length>1?extension[title]=this._XMLtoJS(extension[title],obj.childNodes[i].tagName,obj.childNodes[i]):extension[title][obj.childNodes[i].tagName]=obj.childNodes[i].textContent;return extension},filledExtraParams:function(stanza,extension){var helper=this;return Object.keys(extension).forEach(function(field){"attachments"===field?extension[field].forEach(function(attach){utils.getEnv().browser?stanza.c("attachment",attach).up():stanza.getChild("extraParams").c("attachment",attach).up()}):"object"==typeof extension[field]?helper._JStoXML(field,extension[field],stanza):utils.getEnv().browser?stanza.c(field).t(extension[field]).up():stanza.getChild("extraParams").c(field).t(extension[field]).up()}),stanza.up(),stanza},parseExtraParams:function(extraParams){if(!extraParams)return null;var dialogId,attach,attributes,extension={},attachments=[];if(utils.getEnv().browser)for(var i=0,len=extraParams.childNodes.length;i<len;i++)if("attachment"===extraParams.childNodes[i].tagName){attach={},attributes=extraParams.childNodes[i].attributes;for(var j=0,len2=attributes.length;j<len2;j++)"size"===attributes[j].name?attach[attributes[j].name]=parseInt(attributes[j].value):attach[attributes[j].name]=attributes[j].value;attachments.push(attach)}else if("dialog_id"===extraParams.childNodes[i].tagName)dialogId=extraParams.childNodes[i].textContent,extension.dialog_id=dialogId;else if(extraParams.childNodes[i].childNodes.length>1){if(extraParams.childNodes[i].textContent.length>4096){for(var wholeNodeContent="",k=0;k<extraParams.childNodes[i].childNodes.length;++k)wholeNodeContent+=extraParams.childNodes[i].childNodes[k].textContent;extension[extraParams.childNodes[i].tagName]=wholeNodeContent}else extension=this._XMLtoJS(extension,extraParams.childNodes[i].tagName,extraParams.childNodes[i])}else extension[extraParams.childNodes[i].tagName]=extraParams.childNodes[i].textContent;else for(var c=0,lenght=extraParams.children.length;c<lenght;c++){if("attachment"===extraParams.children[c].name){attach={};for(var attrKeys=Object.keys(attributes=extraParams.children[c].attrs),l=0;l<attrKeys.length;l++)"size"===attrKeys[l]?attach.size=parseInt(attributes.size):attach[attrKeys[l]]=attributes[attrKeys[l]];attachments.push(attach)}else"dialog_id"===extraParams.children[c].name&&(dialogId=extraParams.getChildText("dialog_id"),extension.dialog_id=dialogId);if(1===extraParams.children[c].children.length){var child=extraParams.children[c];extension[child.name]=child.children[0]}}return attachments.length>0&&(extension.attachments=attachments),extension.moduleIdentifier&&delete extension.moduleIdentifier,{extension:extension,dialogId:dialogId}},getUniqueId:function(suffix){var uuid="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){var r=16*Math.random()|0;return("x"==c?r:3&r|8).toString(16)});return"string"==typeof suffix||"number"==typeof suffix?uuid+":"+suffix:uuid+""},getErrorFromXMLNode:function(stanzaError){var errorElement=this.getElement(stanzaError,"error"),errorCode=parseInt(this.getAttr(errorElement,"code")),errorText=this.getElementText(errorElement,"text");return utils.getError(errorCode,errorText)},getLocalTime:function(){return new Date().toTimeString().split(" ")[0]}}},{"../../qbConfig":253,"../../qbUtils":257}],236:[function(require1,module,exports){"use strict";var config=require1("../../qbConfig"),Utils=require1("../../qbUtils"),DIALOGS_API_URL=config.urls.chat+"/Dialog";function DialogProxy(service){this.service=service}DialogProxy.prototype={list:function(params,callback){"function"==typeof params&&void 0===callback&&(callback=params,params={}),this.service.ajax({url:Utils.getUrl(DIALOGS_API_URL),data:params},callback)},create:function(params,callback){params&¶ms.occupants_ids&&Utils.isArray(params.occupants_ids)&&(params.occupants_ids=params.occupants_ids.join(", ")),this.service.ajax({url:Utils.getUrl(DIALOGS_API_URL),type:"POST",data:params},callback)},update:function(id,params,callback){this.service.ajax({url:Utils.getUrl(DIALOGS_API_URL,id),type:"PUT",contentType:"application/json; charset=utf-8",isNeedStringify:!0,data:params},callback)},delete:function(id,params_or_callback,callback){var ajaxParams={url:Utils.getUrl(DIALOGS_API_URL,id),type:"DELETE",dataType:"text"};2==arguments.length?this.service.ajax(ajaxParams,params_or_callback):3==arguments.length&&(ajaxParams.data=params_or_callback,this.service.ajax(ajaxParams,callback))}},module.exports=DialogProxy},{"../../qbConfig":253,"../../qbUtils":257}],237:[function(require1,module,exports){"use strict";var config=require1("../../qbConfig"),Utils=require1("../../qbUtils"),MESSAGES_API_URL=config.urls.chat+"/Message";function MessageProxy(service){this.service=service}MessageProxy.prototype={list:function(params,callback){this.service.ajax({url:Utils.getUrl(MESSAGES_API_URL),data:params},callback)},create:function(params,callback){this.service.ajax({url:Utils.getUrl(MESSAGES_API_URL),type:"POST",data:params},callback)},update:function(id,params,callback){var attrAjax={type:"PUT",dataType:"text",url:Utils.getUrl(MESSAGES_API_URL,id),data:params};this.service.ajax(attrAjax,callback)},delete:function(id,params_or_callback,callback){var ajaxParams={url:Utils.getUrl(MESSAGES_API_URL,id),type:"DELETE",dataType:"text"};2==arguments.length?this.service.ajax(ajaxParams,params_or_callback):3==arguments.length&&(ajaxParams.data=params_or_callback,this.service.ajax(ajaxParams,callback))},unreadCount:function(params,callback){params&¶ms.chat_dialog_ids&&Utils.isArray(params.chat_dialog_ids)&&(params.chat_dialog_ids=params.chat_dialog_ids.join()),this.service.ajax({url:Utils.getUrl(MESSAGES_API_URL+"/unread"),data:params},callback)}},module.exports=MessageProxy},{"../../qbConfig":253,"../../qbUtils":257}],238:[function(require1,module,exports){"use strict";var Utils=require1("../qbUtils"),AI_API_URL="ai/ai_extensions";function AIProxy(service){this.service=service}AIProxy.prototype={answerAssist:function(smartChatAssistantId,message,history,callback){if(!callback||"function"!=typeof callback)throw Error("Callback function is required and must be a function");if(function validateHistory(history){var AIRole={user:"user",assistant:"assistant"};if(null!=history){if(!Array.isArray(history))throw Error("History must be an array");for(var i=0;i<history.length;i++){var item=history[i];if("object"!=typeof item||null===item||Array.isArray(item))throw Error("Each element of history must be an object");if(!("role"in item)||!("message"in item))throw Error("Each element of history must have an role and message fields");if(!(item.role===AIRole.user||item.role===AIRole.assistant))throw Error("Invalid role in history item");if("string"!=typeof item.message)throw Error("Message of history item must be a string")}}return!0}(history)){var attrAjax={type:"POST",url:Utils.formatUrl(AI_API_URL+"/ai_answer_assist"),data:history?{smart_chat_assistant_id:smartChatAssistantId,message:message,history:history}:{smart_chat_assistant_id:smartChatAssistantId,message:message},contentType:"application/json; charset=utf-8",isNeedStringify:!0};this.service.ajax(attrAjax,callback)}},translate:function(smartChatAssistantId,text,languageCode,callback){if(!callback||"function"!=typeof callback)throw Error("Callback function is required and must be a function");var attrAjax={type:"POST",url:Utils.formatUrl(AI_API_URL+"/ai_translate"),data:{smart_chat_assistant_id:smartChatAssistantId,text:text,to_language:languageCode||"en"}};this.service.ajax(attrAjax,callback)}},module.exports=AIProxy},{"../qbUtils":257}],239:[function(require1,module,exports){"use strict";var Utils=require1("../qbUtils"),config=require1("../qbConfig");function AddressBook(service){this.service=service}function isFunction(func){return!!(func&&func.constructor&&func.call&&func.apply)}AddressBook.prototype={uploadAddressBook:function(list,optionsOrcallback,callback){if(!Array.isArray(list)){Error("First parameter must be an Array.");return}isFunction(optionsOrcallback)?cb=optionsOrcallback:(opts=optionsOrcallback,cb=callback);var opts,cb,data={contacts:list};opts&&(opts.force&&(data.force=opts.force),opts.udid&&(data.udid=opts.udid)),this.service.ajax({type:"POST",url:Utils.getUrl(config.urls.addressbook),data:data,contentType:"application/json; charset=utf-8",isNeedStringify:!0},function(err,res){err?cb(err,null):cb(null,res)})},_isFakeErrorEmptyAddressBook:function(err){var errDetails=err.detail?err.detail:err.message.errors;return 404===err.code&&"Empty address book"===errDetails[0]},get:function(udidOrCallback,callback){var udid,cb,self1=this;if(isFunction(udidOrCallback)?cb=udidOrCallback:(udid=udidOrCallback,cb=callback),!isFunction(cb))throw Error("The QB.addressbook.get accept callback function is required.");var ajaxParams={type:"GET",url:Utils.getUrl(config.urls.addressbook),contentType:"application/json; charset=utf-8",isNeedStringify:!0};udid&&(ajaxParams.data={udid:udid}),this.service.ajax(ajaxParams,function(err,res){err?self1._isFakeErrorEmptyAddressBook(err)?cb(null,[]):cb(err,null):cb(null,res)})},getRegisteredUsers:function(isCompactOrCallback,callback){var isCompact,cb,self1=this;if(isFunction(isCompactOrCallback)?cb=isCompactOrCallback:(isCompact=isCompactOrCallback,cb=callback),!isFunction(cb))throw Error("The QB.addressbook.get accept callback function is required.");var ajaxParams={type:"GET",url:Utils.getUrl(config.urls.addressbookRegistered),contentType:"application/json; charset=utf-8"};isCompact&&(ajaxParams.data={compact:1}),this.service.ajax(ajaxParams,function(err,res){err?self1._isFakeErrorEmptyAddressBook(err)?cb(null,[]):cb(err,null):cb(null,res)})}},module.exports=AddressBook},{"../qbConfig":253,"../qbUtils":257}],240:[function(require1,module,exports){"use strict";var config=require1("../qbConfig"),Utils=require1("../qbUtils"),sha1=require1("crypto-js/hmac-sha1"),sha256=require1("crypto-js/hmac-sha256");function AuthProxy(service){this.service=service}function generateAuthMsg(params){var message={application_id:config.creds.appId,auth_key:config.creds.authKey,nonce:Utils.randomNonce(),timestamp:Utils.unixTime()};return params.login&¶ms.password?message.user={login:params.login,password:params.password}:params.email&¶ms.password?message.user={email:params.email,password:params.password}:params.provider&&(message.provider=params.provider,params.scope&&(message.scope=params.scope),params.keys&¶ms.keys.token&&(message.keys={token:params.keys.token}),params.keys&¶ms.keys.secret&&(message.keys.secret=params.keys.secret)),message}function signMessage(message,secret){var cryptoSessionMsg,sessionMsg=Object.keys(message).map(function(val){return"object"==typeof message[val]?Object.keys(message[val]).map(function(val1){return val+"["+val1+"]="+message[val][val1]}).sort().join("&"):val+"="+message[val]}).sort().join("&");if("sha1"===config.hash)cryptoSessionMsg=sha1(sessionMsg,secret).toString();else if("sha256"===config.hash)cryptoSessionMsg=sha256(sessionMsg,secret).toString();else throw Error("Quickblox SDK: unknown crypto standards, available sha1 or sha256");return cryptoSessionMsg}AuthProxy.prototype={getSession:function(callback){this.service.ajax({url:Utils.getUrl(config.urls.session)},function(err,res){err?callback(err,null):callback(err,res)})},createSession:function(params,callback){if(""===config.creds.appId||""===config.creds.authKey||""===config.creds.authSecret)throw Error("Cannot create a new session without app credentials (app ID, auth key and auth secret)");var message,_this=this;"function"==typeof params&&void 0===callback&&(callback=params,params={}),(message=generateAuthMsg(params)).signature=signMessage(message,config.creds.authSecret),this.service.ajax({url:Utils.getUrl(config.urls.session),type:"POST",data:message},function(err,res){err?callback(err,null):(_this.service.setSession(res.session),callback(null,res.session))})},destroySession:function(callback){var _this=this;this.service.ajax({url:Utils.getUrl(config.urls.session),type:"DELETE",dataType:"text"},function(err,res){err?callback(err,null):(_this.service.setSession(null),callback(null,res))})},login:function(params,callback){var ajaxParams={type:"POST",url:Utils.getUrl(config.urls.login),data:params};function handleResponce(err,res){err?callback(err,null):callback(null,res.user)}this.service.ajax(ajaxParams,handleResponce)},logout:function(callback){this.service.ajax({url:Utils.getUrl(config.urls.login),type:"DELETE",dataType:"text"},callback)}},module.exports=AuthProxy},{"../qbConfig":253,"../qbUtils":257,"crypto-js/hmac-sha1":51,"crypto-js/hmac-sha256":52}],241:[function(require1,module,exports){"use strict";var config=require1("../qbConfig"),Utils=require1("../qbUtils");function ContentProxy(service){this.service=service}function parseUri(str){for(var o=parseUri.options,m=o.parser[o.strictMode?"strict":"loose"].exec(str),uri={},i=14;i--;)uri[o.key[i]]=m[i]||"";return uri[o.q.name]={},uri[o.key[12]].replace(o.q.parser,function($0,$1,$2){$1&&(uri[o.q.name][$1]=$2)}),uri}ContentProxy.prototype={list:function(params,callback){"function"==typeof params&&void 0===callback&&(callback=params,params=null),this.service.ajax({url:Utils.getUrl(config.urls.blobs),data:params,type:"GET"},function(err,result){err?callback(err,null):callback(err,result)})},create:function(params,callback){this.service.ajax({type:"POST",data:{blob:params},url:Utils.getUrl(config.urls.blobs)},function(err,result){err?callback(err,null):callback(err,result.blob)})},delete:function(id,callback){this.service.ajax({url:Utils.getUrl(config.urls.blobs,id),type:"DELETE",dataType:"text"},function(err,result){err?callback(err,null):callback(null,!0)})},createAndUpload:function(params,callback){var file,name,type,size,fileId,_this=this,createParams={};JSON.parse(JSON.stringify(params)).file.data="...",file=params.file,name=params.name||file.name,type=params.type||file.type,size=params.size||file.size,createParams.name=name,createParams.content_type=type,params.public&&(createParams.public=params.public),params.tag_list&&(createParams.tag_list=params.tag_list),this.create(createParams,function(err,createResult){if(err)callback(err,null);else{var uri=parseUri(createResult.blob_object_access.params),uploadParams={url:uri.protocol+"://"+uri.authority+uri.path},data={};fileId=createResult.id,createResult.size=size,Object.keys(uri.queryKey).forEach(function(val){data[val]=decodeURIComponent(uri.queryKey[val])}),data.file=file,uploadParams.data=data,_this.upload(uploadParams,function(err,result){err?callback(err,null):_this.markUploaded({id:fileId,size:size},function(err,result){err?callback(err,null):callback(null,createResult)})})}})},upload:function(params,callback){var uploadParams={type:"POST",dataType:"text",contentType:!1,url:params.url,data:params.data};this.service.ajax(uploadParams,function(err,xmlDoc){err?callback(err,null):callback(null,{})})},markUploaded:function(params,callback){this.service.ajax({url:Utils.getUrl(config.urls.blobs,params.id+"/complete"),type:"PUT",data:{size:params.size},dataType:"text"},function(err,res){err?callback(err,null):callback(null,res)})},getInfo:function(id,callback){this.service.ajax({url:Utils.getUrl(config.urls.blobs,id)},function(err,res){err?callback(err,null):callback(null,res)})},getFile:function(uid,callback){this.service.ajax({url:Utils.getUrl(config.urls.blobs,uid)},function(err,res){err?callback(err,null):callback(null,res)})},update:function(params,callback){var data={};data.blob={},void 0!==params.name&&(data.blob.name=params.name),this.service.ajax({url:Utils.getUrl(config.urls.blobs,params.id),data:data},function(err,res){err?callback(err,null):callback(null,res)})},privateUrl:function(fileUID){return"https://"+config.endpoints.api+"/blobs/"+fileUID+"?token="+this.service.getSession().token},publicUrl:function(fileUID){return"https://"+config.endpoints.api+"/blobs/"+fileUID}},module.exports=ContentProxy,parseUri.options={strictMode:!1,key:["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],q:{name:"queryKey",parser:/(?:^|&)([^&=]*)=?([^&]*)/g},parser:{strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/}}},{"../qbConfig":253,"../qbUtils":257}],242:[function(require1,module,exports){"use strict";var config=require1("../qbConfig"),Utils=require1("../qbUtils");function DataProxy(service){this.service=service}DataProxy.prototype={create:function(className,data,callback){var ajaxParams={type:"POST",data:data,isNeedStringify:!0,contentType:"application/json; charset=utf-8",url:Utils.getUrl(config.urls.data,className)};this.service.ajax(ajaxParams,function(err,res){err?callback(err,null):callback(err,res)})},list:function(className,filters,callback){void 0===callback&&"function"==typeof filters&&(callback=filters,filters=null),this.service.ajax({url:Utils.getUrl(config.urls.data,className),data:filters},function(err,result){err?callback(err,null):callback(err,result)})},update:function(className,data,callback){this.service.ajax({url:Utils.getUrl(config.urls.data,className+"/"+data._id),type:"PUT",contentType:"application/json; charset=utf-8",isNeedStringify:!0,data:data},function(err,result){err?callback(err,null):callback(err,result)})},delete:function(className,requestedData,callback){var requestedTypeOf,typesData={id:1,ids:2,criteria:3},responceNormalized={deleted:[],deletedCount:0},ajaxParams={type:"DELETE",dataType:"text"};function handleDeleteCO(error,result){if(error)callback(error,null);else{var response;requestedTypeOf===typesData.id?(responceNormalized.deleted.push(requestedData),responceNormalized.deletedCount=responceNormalized.deleted.length):requestedTypeOf===typesData.ids?(response=JSON.parse(result),responceNormalized.deleted=response.SuccessfullyDeleted.ids.slice(0),responceNormalized.deletedCount=responceNormalized.deleted.length):requestedTypeOf===typesData.criteria&&(response=JSON.parse(result),responceNormalized.deleted=null,responceNormalized.deletedCount=response.total_deleted),callback(error,responceNormalized)}}"string"==typeof requestedData?requestedTypeOf=typesData.id:Utils.isArray(requestedData)?requestedTypeOf=typesData.ids:Utils.isObject(requestedData)&&(requestedTypeOf=typesData.criteria),requestedTypeOf===typesData.id?ajaxParams.url=Utils.getUrl(config.urls.data,className+"/"+requestedData):requestedTypeOf===typesData.ids?ajaxParams.url=Utils.getUrl(config.urls.data,className+"/"+requestedData.toString()):requestedTypeOf===typesData.criteria&&(ajaxParams.url=Utils.getUrl(config.urls.data,className+"/by_criteria"),ajaxParams.data=requestedData),this.service.ajax(ajaxParams,handleDeleteCO)},uploadFile:function(className,params,callback){var data={field_name:params.field_name,file:{data:params.file,name:params.name}};this.service.ajax({url:Utils.getUrl(config.urls.data,className+"/"+params.id+"/file"),type:"POST",fileToCustomObject:!0,contentType:!1,data:data},function(err,result){err?callback(err,null):callback(err,result)})},downloadFile:function(className,params,callback){var result=Utils.getUrl(config.urls.data,className+"/"+params.id+"/file");callback(null,result+="?field_name="+params.field_name+"&token="+this.service.getSession().token)},fileUrl:function(className,params){return Utils.getUrl(config.urls.data,className+"/"+params.id+"/file")+("?field_name="+params.field_name+"&token=")+this.service.getSession().token},deleteFile:function(className,params,callback){this.service.ajax({url:Utils.getUrl(config.urls.data,className+"/"+params.id+"/file"),data:{field_name:params.field_name},dataType:"text",type:"DELETE"},function(err,result){err?callback(err,null):callback(err,!0)})}},module.exports=DataProxy},{"../qbConfig":253,"../qbUtils":257}],243:[function(require1,module,exports){(function(Buffer){(function(){"use strict";var config=require1("../qbConfig"),Utils=require1("../qbUtils"),isBrowser="undefined"!=typeof window;function PushNotificationsProxy(service){this.service=service,this.subscriptions=new SubscriptionsProxy(service),this.events=new EventsProxy(service),this.base64Encode=function(str){return isBrowser?btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,function(match,p1){return String.fromCharCode("0x"+p1)})):new Buffer(str).toString("base64")}}function SubscriptionsProxy(service){this.service=service}function EventsProxy(service){this.service=service}SubscriptionsProxy.prototype={create:function(params,callback){this.service.ajax({url:Utils.getUrl(config.urls.subscriptions),type:"POST",data:params},callback)},list:function(callback){this.service.ajax({url:Utils.getUrl(config.urls.subscriptions)},callback)},delete:function(id,callback){var attrAjax={type:"DELETE",dataType:"text",url:Utils.getUrl(config.urls.subscriptions,id)};this.service.ajax(attrAjax,function(err,res){err?callback(err,null):callback(null,!0)})}},EventsProxy.prototype={create:function(params,callback){this.service.ajax({url:Utils.getUrl(config.urls.events),type:"POST",contentType:"application/json; charset=utf-8",isNeedStringify:!0,data:{event:params}},callback)},list:function(params,callback){"function"==typeof params&&void 0===callback&&(callback=params,params=null),this.service.ajax({url:Utils.getUrl(config.urls.events),data:params},callback)},get:function(id,callback){this.service.ajax({url:Utils.getUrl(config.urls.events,id)},callback)},delete:function(id,callback){this.service.ajax({url:Utils.getUrl(config.urls.events,id),dataType:"text",type:"DELETE"},callback)},status:function(id,callback){this.service.ajax({url:Utils.getUrl(config.urls.events,id+"/status")},callback)}},module.exports=PushNotificationsProxy}).call(this)}).call(this,require1("buffer").Buffer)},{"../qbConfig":253,"../qbUtils":257,buffer:47}],244:[function(require1,module,exports){"use strict";var config=require1("../qbConfig"),Utils=require1("../qbUtils"),DATE_FIELDS=["created_at","updated_at","last_request_at"],NUMBER_FIELDS=["id","external_user_id"],resetPasswordUrl=config.urls.users+"/password/reset";function UsersProxy(service){this.service=service}function generateFilter(obj){var type=obj.field in DATE_FIELDS?"date":typeof obj.value;return Utils.isArray(obj.value)&&("object"===type&&(type=typeof obj.value[0]),obj.value=obj.value.toString()),[type,obj.field,obj.param,obj.value].join(" ")}function generateOrder(obj){var type=obj.field in DATE_FIELDS?"date":obj.field in NUMBER_FIELDS?"number":"string";return[obj.sort,type,obj.field].join(" ")}UsersProxy.prototype={listUsers:function(params,callback){var item,message={},filters=[];"function"==typeof params&&void 0===callback&&(callback=params,params={}),params&¶ms.filter&&(Utils.isArray(params.filter)?params.filter.forEach(function(el){item=generateFilter(el),filters.push(item)}):(item=generateFilter(params.filter),filters.push(item)),message.filter=filters),params.order&&(message.order=generateOrder(params.order)),params.page&&(message.page=params.page),params.per_page&&(message.per_page=params.per_page),this.service.ajax({url:Utils.getUrl(config.urls.users),data:message},callback)},get:function(params,callback){var url;"number"==typeof params?(url=params,params={}):params.login?url="by_login":params.full_name?url="by_full_name":params.facebook_id?url="by_facebook_id":params.twitter_id?url="by_twitter_id":params.phone?url="phone":params.email?url="by_email":params.tags?url="by_tags":params.external&&(url="external/"+params.external,params={}),this.service.ajax({url:Utils.getUrl(config.urls.users,url),data:params},function(err,res){err?callback(err,null):callback(null,res.user||res)})},create:function(params,callback){this.service.ajax({url:Utils.getUrl(config.urls.users),type:"POST",data:{user:params}},function(err,res){err?callback(err,null):callback(null,res.user)})},update:function(id,params,callback){this.service.ajax({url:Utils.getUrl(config.urls.users,id),type:"PUT",data:{user:params}},function(err,res){err?callback(err,null):callback(null,res.user)})},delete:function(params,callback){var url;"number"==typeof params?url=params:params.external&&(url="external/"+params.external),this.service.ajax({url:Utils.getUrl(config.urls.users,url),type:"DELETE",dataType:"text"},callback)},resetPassword:function(email,callback){this.service.ajax({url:Utils.getUrl(resetPasswordUrl),data:{email:email},dataType:"text"},callback)}},module.exports=UsersProxy},{"../qbConfig":253,"../qbUtils":257}],245:[function(require1,module,exports){"use strict";var config=require1("../../qbConfig"),Helpers=require1("./qbWebRTCHelpers"),qbRTCPeerConnection=function(config){this._pc=new window.RTCPeerConnection(config),this.remoteStream=void 0,this.preferredCodec="VP8"};function _getStats(peer,lastResults,successCallback,errorCallback){var statistic={local:{audio:{},video:{},candidate:{}},remote:{audio:{},video:{},candidate:{}}};if(Helpers.getVersionFirefox()){var localStream=peer.getLocalStreams().length?peer.getLocalStreams()[0]:peer.delegate.localStream,localVideoSettings=localStream.getVideoTracks().length?localStream.getVideoTracks()[0].getSettings():null;statistic.local.video.frameHeight=localVideoSettings&&localVideoSettings.height,statistic.local.video.frameWidth=localVideoSettings&&localVideoSettings.width}function _getBitratePerSecond(result,lastResults,isLocal){var lastResult=lastResults&&lastResults.get(result.id),seconds=lastResult?(result.timestamp-lastResult.timestamp)/1e3:5;return Math.round(lastResult?isLocal?8*(result.bytesSent-lastResult.bytesSent)/(1024*seconds):8*(result.bytesReceived-lastResult.bytesReceived)/(1024*seconds):0)}function _getFramesPerSecond(result,lastResults,isLocal){var lastResult=lastResults&&lastResults.get(result.id),seconds=lastResult?(result.timestamp-lastResult.timestamp)/1e3:5;return Math.round(10*(lastResult?isLocal?(result.framesSent-lastResult.framesSent)/seconds:(result.framesReceived-lastResult.framesReceived)/seconds:0))/10}peer.getStats(null).then(function(results){results.forEach(function(result){var item;result.bytesReceived&&"inbound-rtp"===result.type?((item=statistic.remote[result.mediaType]).bitrate=_getBitratePerSecond(result,lastResults,!1),item.bytesReceived=result.bytesReceived,item.packetsReceived=result.packetsReceived,item.timestamp=result.timestamp,"video"===result.mediaType&&result.framerateMean&&(item.framesPerSecond=Math.round(10*result.framerateMean)/10)):result.bytesSent&&"outbound-rtp"===result.type?((item=statistic.local[result.mediaType]).bitrate=_getBitratePerSecond(result,lastResults,!0),item.bytesSent=result.bytesSent,item.packetsSent=result.packetsSent,item.timestamp=result.timestamp,"video"===result.mediaType&&result.framerateMean&&(item.framesPerSecond=Math.round(10*result.framerateMean)/10)):"local-candidate"===result.type?(item=statistic.local.candidate,"host"===result.candidateType&&"udp"===result.mozLocalTransport&&"udp"===result.transport?(item.protocol=result.transport,item.ip=result.ipAddress,item.port=result.portNumber):Helpers.getVersionFirefox()||(item.protocol=result.protocol,item.ip=result.ip,item.port=result.port)):"remote-candidate"===result.type?((item=statistic.remote.candidate).protocol=result.protocol||result.transport,item.ip=result.ip||result.ipAddress,item.port=result.port||result.portNumber):"track"!==result.type||"video"!==result.kind||Helpers.getVersionFirefox()||(result.remoteSource?((item=statistic.remote.video).frameHeight=result.frameHeight,item.frameWidth=result.frameWidth,item.framesPerSecond=_getFramesPerSecond(result,lastResults,!1)):((item=statistic.local.video).frameHeight=result.frameHeight,item.frameWidth=result.frameWidth,item.framesPerSecond=_getFramesPerSecond(result,lastResults,!0)))}),successCallback(statistic,results)},errorCallback)}function findLineInRange(sdpLines,startLine,endLine,prefix,substr,direction){if(void 0===direction&&(direction="asc"),"asc"===(direction=direction||"asc")){for(var realEndLine=-1!==endLine?endLine:sdpLines.length,i=startLine;i<realEndLine;++i)if(0===sdpLines[i].indexOf(prefix)&&(!substr||-1!==sdpLines[i].toLowerCase().indexOf(substr.toLowerCase())))return i}else for(var realStartLine=-1!==startLine?startLine:sdpLines.length-1,j=realStartLine;j>=0;--j)if(0===sdpLines[j].indexOf(prefix)&&(!substr||-1!==sdpLines[j].toLowerCase().indexOf(substr.toLowerCase())))return j;return null}function getCodecPayloadTypeFromLine(sdpLine){var pattern=RegExp("a=rtpmap:(\\d+) [a-zA-Z0-9-]+\\/\\d+"),result=sdpLine.match(pattern);return result&&2===result.length?result[1]:null}function setDefaultCodec(mLine,payload){var elements=mLine.split(" "),newLine=elements.slice(0,3);newLine.push(payload);for(var i=3;i<elements.length;i++)elements[i]!==payload&&newLine.push(elements[i]);return newLine.join(" ")}function setPreferredCodec(sdp,type,codec){if(!codec)return sdp;var sdpLines=sdp.split("\r\n"),mLineIndex=findLineInRange(sdpLines,0,-1,"m=",type);if(null===mLineIndex)return sdp;for(var payload=null,i=sdpLines.length-1;i>=0;--i){var index=findLineInRange(sdpLines,i,0,"a=rtpmap",codec,"desc");if(null!==index)i=index,(payload=getCodecPayloadTypeFromLine(sdpLines[index]))&&(sdpLines[mLineIndex]=setDefaultCodec(sdpLines[mLineIndex],payload));else break}return sdp=sdpLines.join("\r\n")}function _removeExtmapMixedFromSDP(description){return description&&description.sdp&&-1!==description.sdp.indexOf("\na=extmap-allow-mixed")&&(description.sdp=description.sdp.split("\n").filter(function(line){return"a=extmap-allow-mixed"!==line.trim()}).join("\n")),description}function setMediaBitrate(sdp,media,bitrate){if(!bitrate)return sdp.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"");for(var lines=sdp.split("\n"),line=-1,modifier=Helpers.getVersionFirefox()?"TIAS":"AS",amount=Helpers.getVersionFirefox()?1024*bitrate:bitrate,i=0;i<lines.length;i++)if(0===lines[i].indexOf("m="+media)){line=i;break}if(-1===line)return sdp;for(line++;0===lines[line].indexOf("i=")||0===lines[line].indexOf("c=");)line++;if(0===lines[line].indexOf("b"))return lines[line]="b="+modifier+":"+amount,lines.join("\n");var newLines=lines.slice(0,line);return newLines.push("b="+modifier+":"+amount),(newLines=newLines.concat(lines.slice(line,lines.length))).join("\n")}qbRTCPeerConnection.State={NEW:1,CONNECTING:2,CHECKING:3,CONNECTED:4,DISCONNECTED:5,FAILED:6,CLOSED:7,COMPLETED:8},qbRTCPeerConnection.prototype._init=function(delegate,userID,sessionID,polite){Helpers.trace("RTCPeerConnection init.","userID: ",userID,", sessionID: ",sessionID,", polite: ",polite),this.delegate=delegate,this.localIceCandidates=[],this.remoteIceCandidates=[],this.remoteSDP=void 0,this.sessionID=sessionID,this.polite=polite,this.userID=userID,this._reconnecting=!1,this.state=qbRTCPeerConnection.State.NEW,this._pc.onicecandidate=this.onIceCandidateCallback.bind(this),this._pc.onsignalingstatechange=this.onSignalingStateCallback.bind(this),this._pc.oniceconnectionstatechange=this.onIceConnectionStateCallback.bind(this),this._pc.ontrack=this.onTrackCallback.bind(this),this.dialingTimer=null,this.answerTimeInterval=0,this.statsReportTimer=null},qbRTCPeerConnection.prototype.release=function(){this._clearDialingTimer(),this._clearStatsReportTimer(),this._pc.close(),this.state=qbRTCPeerConnection.State.CLOSED,this._pc.onicecandidate=null,this._pc.onsignalingstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.ontrack=null,navigator.userAgent.includes("Edge")&&(this.connectionState="closed",this.iceConnectionState="closed")},qbRTCPeerConnection.prototype.negotiate=function(){var self1=this;return this.setLocalSessionDescription({type:"offer",options:{iceRestart:!0}},function(error){if(error)return Helpers.traceError("Error in 'negotiate': "+error);var description=self1._pc.localDescription.toJSON();self1.delegate.update({reason:"reconnect",sessionDescription:{offerId:self1.offerId,sdp:description.sdp,type:description.type}},self1.userID)})},qbRTCPeerConnection.prototype.setRemoteSDP=function(newSDP){if(newSDP)this.remoteSDP=newSDP;else throw Error("sdp string can't be empty.")},qbRTCPeerConnection.prototype.getRemoteSDP=function(){return this.remoteSDP},qbRTCPeerConnection.prototype.setLocalSessionDescription=function(params,callback){var self1=this;function successCallback(description){var modifiedDescription=_removeExtmapMixedFromSDP(description);modifiedDescription.sdp=setPreferredCodec(modifiedDescription.sdp,"video",self1.preferredCodec),self1.delegate.bandwidth&&(modifiedDescription.sdp=setMediaBitrate(modifiedDescription.sdp,"video",self1.delegate.bandwidth)),self1._pc.setLocalDescription(modifiedDescription).then(function(){callback(null)}).catch(function(error){Helpers.traceError("Error in 'setLocalSessionDescription': "+error),callback(error)})}self1.state=qbRTCPeerConnection.State.CONNECTING,window.RTCRtpTransceiver&&"setCodecPreferences"in window.RTCRtpTransceiver.prototype&&Helpers.getVersionSafari()&&self1._pc.getTransceivers().forEach(function(transceiver){var kind=transceiver.sender.track.kind,sendCodecs=window.RTCRtpSender.getCapabilities(kind).codecs,recvCodecs=window.RTCRtpReceiver.getCapabilities(kind).codecs;if("video"===kind){var preferredCodecSendIndex=sendCodecs.findIndex(function(codec){return codec.mimeType.toLowerCase().includes(self1.preferredCodec.toLowerCase())});if(-1!==preferredCodecSendIndex){var arrayWithPreferredSendCodec=sendCodecs.splice(preferredCodecSendIndex,1);sendCodecs.unshift(arrayWithPreferredSendCodec[0])}var preferredCodecRecvIndex=recvCodecs.findIndex(function(codec){return codec.mimeType.toLowerCase().includes(self1.preferredCodec.toLowerCase())});if(-1!==preferredCodecRecvIndex){var arrayWithPreferredRecvCodec=recvCodecs.splice(preferredCodecRecvIndex,1);recvCodecs.unshift(arrayWithPreferredRecvCodec[0])}transceiver.setCodecPreferences(sendCodecs.concat(recvCodecs))}}),"answer"===params.type?this._pc.createAnswer(params.options).then(successCallback).catch(callback):this._pc.createOffer(params.options).then(successCallback).catch(callback)},qbRTCPeerConnection.prototype.setRemoteSessionDescription=function(description,callback){var modifiedSDP=this.delegate.bandwidth?{type:description.type,sdp:setMediaBitrate(description.sdp,"video",this.delegate.bandwidth)}:description;this._pc.setRemoteDescription(modifiedSDP).then(function(){callback()}).catch(function(error){Helpers.traceError("Error in 'setRemoteSessionDescription': "+error),callback(error)})},qbRTCPeerConnection.prototype.addLocalStream=function(stream){if(!stream)throw Error("'qbRTCPeerConnection.addLocalStream' error: stream is not defined");var self1=this;stream.getTracks().forEach(function(track){self1._pc.addTrack(track,stream)})},qbRTCPeerConnection.prototype._addIceCandidate=function(iceCandidate){return this._pc.addIceCandidate(iceCandidate).catch(function(error){Helpers.traceError("Error on 'addIceCandidate': "+error)})},qbRTCPeerConnection.prototype.addCandidates=function(iceCandidates){var self1=this;iceCandidates.forEach(function(candidate){self1.remoteIceCandidates.push(candidate)}),this._pc.remoteDescription&&self1.remoteIceCandidates.forEach(function(candidate){self1._addIceCandidate(candidate)})},qbRTCPeerConnection.prototype.toString=function sessionToString(){return"sessionID: "+this.sessionID+", userID: "+this.userID+", state: "+this.state},qbRTCPeerConnection.prototype.onSignalingStateCallback=function(){if("stable"===this._pc.signalingState&&this.localIceCandidates.length>0)for(this.delegate.processIceCandidates(this,this.localIceCandidates);this.localIceCandidates.length;)this.localIceCandidates.pop()},qbRTCPeerConnection.prototype.onIceCandidateCallback=function(event){if(event.candidate){var candidate={candidate:event.candidate.candidate,sdpMid:event.candidate.sdpMid,sdpMLineIndex:event.candidate.sdpMLineIndex};"stable"===this._pc.signalingState?this.delegate.processIceCandidates(this,[candidate]):this.localIceCandidates.push(candidate)}},qbRTCPeerConnection.prototype.onTrackCallback=function(event){this.remoteStream=event.streams[0],"function"==typeof this.delegate._onRemoteStreamListener&&["connected","completed"].includes(this._pc.iceConnectionState)&&this.delegate._onRemoteStreamListener(this.userID,this.remoteStream),this._getStatsWrap()},qbRTCPeerConnection.prototype.onIceConnectionStateCallback=function(){Helpers.trace("onIceConnectionStateCallback: "+this._pc.iceConnectionState);var connectionState=null;switch(this._pc.iceConnectionState){case"checking":this.state=qbRTCPeerConnection.State.CHECKING,connectionState=Helpers.SessionConnectionState.CONNECTING;break;case"connected":this._reconnecting&&this.delegate._stopReconnectTimer(this.userID),this.state=qbRTCPeerConnection.State.CONNECTED,connectionState=Helpers.SessionConnectionState.CONNECTED;break;case"completed":this._reconnecting&&this.delegate._stopReconnectTimer(this.userID),this.state=qbRTCPeerConnection.State.COMPLETED,connectionState=Helpers.SessionConnectionState.COMPLETED;break;case"failed":this.delegate._startReconnectTimer(this.userID),this.state=qbRTCPeerConnection.State.FAILED,connectionState=Helpers.SessionConnectionState.FAILED;break;case"disconnected":this.delegate._startReconnectTimer(this.userID),this.state=qbRTCPeerConnection.State.DISCONNECTED,connectionState=Helpers.SessionConnectionState.DISCONNECTED;break;case"closed":this.delegate._stopReconnectTimer(this.userID),this.state=qbRTCPeerConnection.State.CLOSED,connectionState=Helpers.SessionConnectionState.CLOSED}"function"==typeof this.delegate._onSessionConnectionStateChangedListener&&connectionState&&this.delegate._onSessionConnectionStateChangedListener(this.userID,connectionState),"connected"===this._pc.iceConnectionState&&"function"==typeof this.delegate._onRemoteStreamListener&&this.delegate._onRemoteStreamListener(this.userID,this.remoteStream)},qbRTCPeerConnection.prototype._clearStatsReportTimer=function(){this.statsReportTimer&&(clearInterval(this.statsReportTimer),this.statsReportTimer=null)},qbRTCPeerConnection.prototype._getStatsWrap=function(){var statsReportInterval,lastResult,self1=this;if(config.webrtc&&config.webrtc.statsReportTimeInterval&&!self1.statsReportTimer){if(isNaN(+config.webrtc.statsReportTimeInterval)){Helpers.traceError("statsReportTimeInterval ("+config.webrtc.statsReportTimeInterval+") must be integer.");return}statsReportInterval=1e3*config.webrtc.statsReportTimeInterval,Helpers.trace("Stats tracker has been started."),self1.statsReportTimer=setInterval(function(){_getStats(self1._pc,lastResult,function(results,lastResults){lastResult=lastResults,self1.delegate._onCallStatsReport(self1.userID,results,null)},function errorLog(err){Helpers.traceError("_getStats error. "+err.name+": "+err.message),self1.delegate._onCallStatsReport(self1.userID,null,err)})},statsReportInterval)}},qbRTCPeerConnection.prototype._clearDialingTimer=function(){this.dialingTimer&&(Helpers.trace("_clearDialingTimer"),clearInterval(this.dialingTimer),this.dialingTimer=null,this.answerTimeInterval=0)},qbRTCPeerConnection.prototype._startDialingTimer=function(extension){var self1=this,dialingTimeInterval=1e3*config.webrtc.dialingTimeInterval;Helpers.trace("_startDialingTimer, dialingTimeInterval: "+dialingTimeInterval);var _dialingCallback=function(extension,skipIncrement){skipIncrement||(self1.answerTimeInterval+=dialingTimeInterval),Helpers.trace("_dialingCallback, answerTimeInterval: "+self1.answerTimeInterval),self1.answerTimeInterval>=1e3*config.webrtc.answerTimeInterval?(self1._clearDialingTimer(),self1.delegate.processOnNotAnswer(self1)):self1.delegate.processCall(self1,extension)};self1.dialingTimer=setInterval(_dialingCallback,dialingTimeInterval,extension,!1),_dialingCallback(extension,!0)},module.exports=qbRTCPeerConnection},{"../../qbConfig":253,"./qbWebRTCHelpers":247}],246:[function(require1,module,exports){"use strict";var WebRTCSession=require1("./qbWebRTCSession"),WebRTCSignalingProcessor=require1("./qbWebRTCSignalingProcessor"),WebRTCSignalingProvider=require1("./qbWebRTCSignalingProvider"),Helpers=require1("./qbWebRTCHelpers"),RTCPeerConnection=require1("./qbRTCPeerConnection"),SignalingConstants=require1("./qbWebRTCSignalingConstants"),Utils=require1("../../qbUtils"),config=require1("../../qbConfig"),LiveSessionStates=[WebRTCSession.State.NEW,WebRTCSession.State.CONNECTING,WebRTCSession.State.ACTIVE];function WebRTCClient(service,chat){this.chat=chat,this.signalingProcessor=new WebRTCSignalingProcessor(service,this),this.signalingProvider=new WebRTCSignalingProvider(service,chat),chat.webrtcSignalingProcessor=this.signalingProcessor,this.SessionConnectionState=Helpers.SessionConnectionState,this.CallType=Helpers.CallType,this.PeerConnectionState=RTCPeerConnection.State,this.sessions={},navigator.mediaDevices&&"ondevicechange"in navigator.mediaDevices&&(navigator.mediaDevices.ondevicechange=this._onDevicesChangeListener.bind(this))}function isOpponentsEqual(exOpponents,currentOpponents){var ans=!1,cOpponents=currentOpponents.sort();return exOpponents.length&&exOpponents.forEach(function(i){var array=i.sort();ans=array.length==cOpponents.length&&array.every(function(el,index){return el===cOpponents[index]})}),ans}function getOpponentsIdNASessions(sessions){var opponents=[];return Object.keys(sessions).length>0&&Object.keys(sessions).forEach(function(key,i,arr){var session=sessions[key];(session.state===WebRTCSession.State.NEW||session.state===WebRTCSession.State.ACTIVE)&&opponents.push(session.opponentsIDs)}),opponents}WebRTCClient.prototype.getMediaDevices=function(spec){var specDevices=[],errMsg="Browser does not support output device selection.";return new Promise(function(resolve,reject){navigator.mediaDevices&&navigator.mediaDevices.enumerateDevices?navigator.mediaDevices.enumerateDevices().then(function(devices){spec?(devices.forEach(function(device,i){device.kind===spec&&specDevices.push(device)}),resolve(specDevices)):resolve(devices)}):(reject(errMsg),Helpers.traceWarning(errMsg))})},WebRTCClient.prototype.sessions={},WebRTCClient.prototype.createNewSession=function(opponentsIDs,ct,cID,opts){var opponentsIdNASessions=getOpponentsIdNASessions(this.sessions),callerID=cID||Helpers.getIdFromNode(this.chat.connection.jid),bandwidth=opts&&opts.bandwidth&&!isNaN(opts.bandwidth)?+opts.bandwidth:0;if(!opponentsIDs)throw Error("Can't create a session without the opponentsIDs.");if(!Array.isArray(opponentsIDs))throw Error('"opponentsIDs" should be Array of numbers');if(opponentsIDs.forEach(function(id){var value=parseInt(id);if(isNaN(value))throw Error('"opponentsIDs" should be Array of numbers');id=value}),!isOpponentsEqual(opponentsIdNASessions,opponentsIDs))return this._createAndStoreSession(null,callerID,opponentsIDs,ct||2,bandwidth);throw Error("Can't create a session with the same opponentsIDs. There is a session already in NEW or ACTIVE state.")},WebRTCClient.prototype._createAndStoreSession=function(sessionID,callerID,opponentsIDs,callType,bandwidth){var newSession=new WebRTCSession({sessionID:sessionID,initiatorID:callerID,opIDs:opponentsIDs,callType:callType,signalingProvider:this.signalingProvider,currentUserID:Helpers.getIdFromNode(this.chat.connection.jid),bandwidth:bandwidth});return newSession.onUserNotAnswerListener=this.onUserNotAnswerListener,newSession.onReconnectListener=this.onReconnectListener,newSession.onRemoteStreamListener=this.onRemoteStreamListener,newSession.onSessionConnectionStateChangedListener=this.onSessionConnectionStateChangedListener,newSession.onSessionCloseListener=this.onSessionCloseListener,newSession.onCallStatsReport=this.onCallStatsReport,this.sessions[newSession.ID]=newSession,newSession},WebRTCClient.prototype.clearSession=function(sessionId){delete WebRTCClient.sessions[sessionId]},WebRTCClient.prototype.isExistLiveSessionExceptSessionID=function(sessionID){var exist=!1,sessions=this.sessions;return Object.keys(sessions).length>0&&(exist=Object.keys(sessions).some(function(key){var session=sessions[key];return LiveSessionStates.includes(session.state)&&session.ID!==sessionID})),exist},WebRTCClient.prototype.getNewSessionsCount=function(exceptId){var sessions=this.sessions;return Object.keys(sessions).reduce(function(count,sessionId){var session=sessions[sessionId];return session.ID===exceptId?count:session.state===WebRTCSession.State.NEW?count+1:count},0)},WebRTCClient.prototype._onCallListener=function(userID,sessionID,extension){var userInfo=extension.userInfo||{},currentUserID=Helpers.getIdFromNode(this.chat.connection.jid);if(userID===currentUserID&&!extension.opponentsIDs.includes(currentUserID)){Helpers.trace('Ignore "onCall" signal from current user. userID:'+userID+", sessionID: "+sessionID);return}Helpers.trace("onCall. UserID:"+userID+". SessionID: "+sessionID);var otherActiveSessions=this.isExistLiveSessionExceptSessionID(sessionID),newSessionsCount=this.getNewSessionsCount(sessionID);if(otherActiveSessions&&!this.sessions[sessionID]&&newSessionsCount++,otherActiveSessions&&(config.webrtc.autoReject||newSessionsCount>config.webrtc.incomingLimit))Helpers.trace("User with id "+userID+" is busy at the moment."),delete extension.sessionDescription,delete extension.platform,extension.sessionID=sessionID,this.signalingProvider.sendMessage(userID,extension,SignalingConstants.SignalingType.REJECT),"function"==typeof this.onInvalidEventsListener&&Utils.safeCallbackCall(this.onInvalidEventsListener,"onCall",sessionID,userID,userInfo);else{var session=this.sessions[sessionID],bandwidth=+userInfo.bandwidth||0;session||(session=this._createAndStoreSession(sessionID,extension.callerID,extension.opponentsIDs,extension.callType,bandwidth),"function"==typeof this.onCallListener&&Utils.safeCallbackCall(this.onCallListener,session,userInfo)),session.processOnCall(userID,extension)}},WebRTCClient.prototype._onAcceptListener=function(userID,sessionID,extension){var session=this.sessions[sessionID],userInfo=extension.userInfo||{};Helpers.trace("onAccept. UserID:"+userID+". SessionID: "+sessionID),session?session.state===WebRTCSession.State.CONNECTING||session.state===WebRTCSession.State.ACTIVE?("function"==typeof this.onAcceptCallListener&&Utils.safeCallbackCall(this.onAcceptCallListener,session,userID,userInfo),session.processOnAccept(userID,extension)):("function"==typeof this.onInvalidEventsListener&&Utils.safeCallbackCall(this.onInvalidEventsListener,"onAccept",session,userID,userInfo),Helpers.traceWarning("Ignore 'onAccept', the session( "+sessionID+" ) has invalid state.")):Helpers.traceError("Ignore 'onAccept', there is no information about session "+sessionID+" by some reason.")},WebRTCClient.prototype._onRejectListener=function(userID,sessionID,extension){var session=this.sessions[sessionID];if(Helpers.trace("onReject. UserID:"+userID+". SessionID: "+sessionID),session){var userInfo=extension.userInfo||{};"function"==typeof this.onRejectCallListener&&Utils.safeCallbackCall(this.onRejectCallListener,session,userID,userInfo),session.processOnReject(userID,extension)}else Helpers.traceError("Ignore 'onReject', there is no information about session "+sessionID+" by some reason.")},WebRTCClient.prototype._onStopListener=function(userID,sessionID,extension){Helpers.trace("onStop. UserID:"+userID+". SessionID: "+sessionID);var session=this.sessions[sessionID],userInfo=extension.userInfo||{};session&&LiveSessionStates.includes(session.state)?("function"==typeof this.onStopCallListener&&Utils.safeCallbackCall(this.onStopCallListener,session,userID,userInfo),setTimeout(session.processOnStop.bind(session),10,userID,extension)):("function"==typeof this.onInvalidEventsListener&&Utils.safeCallbackCall(this.onInvalidEventsListener,"onStop",session,userID,userInfo),Helpers.traceError("Ignore 'onStop', there is no information about session "+sessionID+" by some reason."))},WebRTCClient.prototype._onIceCandidatesListener=function(userID,sessionID,extension){var session=this.sessions[sessionID];Helpers.trace("onIceCandidates. UserID:"+userID+". SessionID: "+sessionID+". ICE candidates count: "+extension.iceCandidates.length),session?session.state===WebRTCSession.State.CONNECTING||session.state===WebRTCSession.State.ACTIVE?session.processOnIceCandidates(userID,extension):Helpers.traceWarning("Ignore 'OnIceCandidates', the session ( "+sessionID+" ) has invalid state."):Helpers.traceError("Ignore 'OnIceCandidates', there is no information about session "+sessionID+" by some reason.")},WebRTCClient.prototype._onUpdateListener=function(userID,sessionID,extension){var session=this.sessions[sessionID],userInfo=extension.userInfo||{};Helpers.trace("onUpdate. UserID:"+userID+". SessionID: "+sessionID+". Extension: "+JSON.stringify(userInfo)),session&&(extension.reason&&session.processOnUpdate(userID,extension),"function"==typeof this.onUpdateCallListener&&Utils.safeCallbackCall(this.onUpdateCallListener,session,userID,userInfo))},WebRTCClient.prototype._onDevicesChangeListener=function(){"function"==typeof this.onDevicesChangeListener&&Utils.safeCallbackCall(this.onDevicesChangeListener)},module.exports=WebRTCClient},{"../../qbConfig":253,"../../qbUtils":257,"./qbRTCPeerConnection":245,"./qbWebRTCHelpers":247,"./qbWebRTCSession":248,"./qbWebRTCSignalingConstants":249,"./qbWebRTCSignalingProcessor":250,"./qbWebRTCSignalingProvider":251}],247:[function(require1,module,exports){"use strict";var config=require1("../../qbConfig");module.exports={getUserJid:function(id,appId){return id+"-"+appId+"@"+config.endpoints.chat},getIdFromNode:function(jid){return 0>jid.indexOf("@")?null:parseInt(jid.split("@")[0].split("-")[0])},trace:function(text){config.debug&&console.log("[QBWebRTC]:",text)},traceWarning:function(text){config.debug&&console.warn("[QBWebRTC]:",text)},traceError:function(text){config.debug&&console.error("[QBWebRTC]:",text)},getLocalTime:function(){return new Date().toString().split(" ").slice(1,5).join("-")},isIOS:function(){return!!window&&!!window.navigator&&!!window.navigator.userAgent&&!!window.navigator.userAgent.match(/iP(ad|hone)/i)},isIOSSafari:function(){if(!window||!window.navigator||!window.navigator.userAgent)return!1;var ua=window.navigator.userAgent,iOS=!!ua.match(/iP(ad|hone)/i),isWebkit=!!ua.match(/WebKit/i),isChrome=!!ua.match(/CriOS/i);return iOS&&isWebkit&&!isChrome},isIOSChrome:function(){if(!window||!window.navigator||!window.navigator.userAgent)return!1;var ua=window.navigator.userAgent,iOS=!!ua.match(/iP(ad|hone)/i),isWebkit=!!ua.match(/WebKit/i),isChrome=!!ua.match(/CriOS/i);return iOS&&!isWebkit&&isChrome},getVersionFirefox:function(){var version,ua=!!navigator&&navigator.userAgent;if(ua){var ffInfo=ua.match(/(?:firefox)[ \/](\d+)/i)||[];version=ffInfo[1]?+ffInfo[1]:null}return version},getVersionSafari:function(){var version,ua=!!navigator&&navigator.userAgent;if(ua){if((ua.match(/(?:safari)[ \/](\d+)/i)||[]).length){var sVer=ua.match(/(?:version)[ \/](\d+)/i)||[];version=sVer&&sVer[1]?+sVer[1]:null}else version=null}return version},delay:function(timeout){return timeout="number"==typeof timeout&&timeout>0?timeout:0,new Promise(function(resolve){setTimeout(resolve,timeout)})},SessionConnectionState:{UNDEFINED:0,CONNECTING:1,CONNECTED:2,FAILED:3,DISCONNECTED:4,CLOSED:5,COMPLETED:6},CallType:{VIDEO:1,AUDIO:2}}},{"../../qbConfig":253}],248:[function(require1,module,exports){"use strict";var config=require1("../../qbConfig"),qbRTCPeerConnection=require1("./qbRTCPeerConnection"),Utils=require1("../../qbUtils"),Helpers=require1("./qbWebRTCHelpers"),SignalingConstants=require1("./qbWebRTCSignalingConstants");WebRTCSession.State={NEW:1,ACTIVE:2,HUNGUP:3,REJECTED:4,CLOSED:5};var ReconnectionState={RECONNECTING:"reconnecting",RECONNECTED:"reconnected",FAILED:"failed"};function WebRTCSession(params){this.ID=params.sessionID?params.sessionID:generateUUID(),this.state=WebRTCSession.State.NEW,this.initiatorID=parseInt(params.initiatorID),this.opponentsIDs=params.opIDs,this.callType=parseInt(params.callType),this.peerConnections={},this.mediaParams=null,this.iceConnectTimers={},this.reconnectTimers={},this.signalingProvider=params.signalingProvider,this.currentUserID=params.currentUserID,this.bandwidth=params.bandwidth,this.answerTimer=null,this.startCallTime=0,this.acceptCallTime=0,this.localStream=void 0}function generateUUID(){var d=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){var r=(d+16*Math.random())%16|0;return d=Math.floor(d/16),("x"==c?r:3&r|8).toString(16)})}function _prepareExtension(extension){var ext={};try{if("[object Object]"===({}).toString.call(extension))ext.userInfo=extension,ext=JSON.parse(JSON.stringify(ext).replace(/null/g,'""'));else throw Error('Invalid type of "extension" object.')}catch(err){Helpers.traceWarning(err.message)}return ext}WebRTCSession.prototype.getUserMedia=function(params,callback){if(!navigator.mediaDevices.getUserMedia)throw Error("getUserMedia() is not supported in your browser");var self1=this,mediaConstraints={audio:params.audio||!1,video:params.video||!1};function successCallback(stream){self1.localStream=stream,self1.mediaParams=Object.assign({},params),params.elemId&&self1.attachMediaStream(params.elemId,stream,params.options),callback&&"function"==typeof callback&&callback(void 0,stream)}navigator.mediaDevices.getUserMedia(mediaConstraints).then(successCallback).catch(callback)},WebRTCSession.prototype.connectionStateForUser=function(userID){var peerConnection=this.peerConnections[userID];return peerConnection?peerConnection.state:void 0},WebRTCSession.prototype.attachMediaStream=function(elementId,stream,options){var elem=document.getElementById(elementId);if(elem){if(elem instanceof HTMLMediaElement)"srcObject"in elem?elem.srcObject=stream:elem.src=window.URL.createObjectURL(stream),options&&options.muted&&(elem.muted=!0),options&&options.mirror&&(elem.style.transform="scaleX(-1)"),elem.autoplay||(elem.onloadedmetadata=function(){elem.play()});else throw Error('Cannot attach media stream to element with id "'+elementId+'" because it is not of type HTMLMediaElement')}else throw Error('Unable to attach media stream, cannot find element by Id "'+elementId+'"')},WebRTCSession.prototype.detachMediaStream=function(elementId){var elem=document.getElementById(elementId);elem&&elem instanceof HTMLMediaElement&&(elem.pause(),elem.srcObject&&"object"==typeof elem.srcObject?(elem.srcObject.getTracks().forEach(function(track){track.stop(),track.enabled=!1}),elem.srcObject=null):elem.src="",elem.removeAttribute("src"),elem.removeAttribute("srcObject"))},WebRTCSession.prototype.switchMediaTracks=function(deviceIds,callback){if(!navigator.mediaDevices.getUserMedia)throw Error("getUserMedia() is not supported in your browser");var self1=this;deviceIds&&deviceIds.audio&&(this.mediaParams.audio.deviceId=deviceIds.audio),deviceIds&&deviceIds.video&&(this.mediaParams.video.deviceId=deviceIds.video),this.localStream.getTracks().forEach(function(track){track.stop()}),navigator.mediaDevices.getUserMedia({audio:self1.mediaParams.audio||!1,video:self1.mediaParams.video||!1}).then(function(stream){self1._replaceTracks(stream),callback(null,stream)}).catch(function(error){callback(error,null)})},WebRTCSession.prototype._replaceTracks=function(stream){var localStream=this.localStream,elemId=this.mediaParams.elemId,ops=this.mediaParams.options,currentStreamTracks=localStream.getTracks(),newStreamTracks=stream.getTracks();function _replaceTracksForPeer(peer){return Promise.all(peer.getSenders().map(function(sender){return sender.replaceTrack(newStreamTracks.find(function(track){return track.kind===sender.track.kind}))}))}return this.detachMediaStream(elemId),newStreamTracks.forEach(function(newTrack){let currentTrack=currentStreamTracks.find(function(track){return track.kind===newTrack.kind});currentTrack&&(currentTrack.stop(),localStream.removeTrack(currentTrack),localStream.addTrack(newTrack))}),elemId&&this.attachMediaStream(elemId,stream,ops),Promise.all(Object.values(this.peerConnections).map(function(peerConnection){return peerConnection._pc}).map(_replaceTracksForPeer))},WebRTCSession.prototype.call=function(extension,callback){var self1=this,ext=_prepareExtension(extension);Helpers.trace("Call, extension: "+JSON.stringify(ext.userInfo)),self1.state=WebRTCSession.State.ACTIVE,self1._reconnectToChat(function(){self1.state===WebRTCSession.State.ACTIVE&&self1.opponentsIDs.forEach(function(userID){self1._callInternal(userID,ext)})}),"function"==typeof callback&&callback(null)},WebRTCSession.prototype._callInternal=function(userID,extension){var peer=this._createPeer(userID,this.currentUserID<userID);this.peerConnections[userID]=peer,peer.addLocalStream(this.localStream),peer.setLocalSessionDescription({type:"offer"},function(error){error?Helpers.trace("setLocalSessionDescription error: "+error):(Helpers.trace("setLocalSessionDescription success"),peer._startDialingTimer(extension))})},WebRTCSession.prototype.accept=function(extension){var self1=this,ext=_prepareExtension(extension);if(Helpers.trace("Accept, extension: "+JSON.stringify(ext.userInfo)),self1.state===WebRTCSession.State.ACTIVE){Helpers.traceError("Can't accept, the session is already active, return.");return}if(self1.state===WebRTCSession.State.CLOSED){Helpers.traceError("Can't accept, the session is already closed, return."),self1.stop({});return}self1.state=WebRTCSession.State.ACTIVE,self1.acceptCallTime=new Date,self1._clearAnswerTimer(),self1._acceptInternal(self1.initiatorID,ext);var oppIDs=self1._uniqueOpponentsIDsWithoutInitiator();if(oppIDs.length>0){var offerTime=(self1.acceptCallTime-self1.startCallTime)/1e3;self1._startWaitingOfferOrAnswerTimer(offerTime),oppIDs.forEach(function(opID,i,arr){self1.currentUserID>opID&&self1._callInternal(opID,{},!0)})}},WebRTCSession.prototype._acceptInternal=function(userID,extension){var self1=this,peerConnection=this.peerConnections[userID];if(peerConnection){var remoteSDP=peerConnection.getRemoteSDP();peerConnection.addLocalStream(self1.localStream),peerConnection.setRemoteSessionDescription(remoteSDP,function(error){error?Helpers.traceError("'setRemoteSessionDescription' error: "+error):(Helpers.trace("'setRemoteSessionDescription' success"),peerConnection.setLocalSessionDescription({type:"answer"},function(err){err?Helpers.trace("setLocalSessionDescription error: "+err):(Helpers.trace("'setLocalSessionDescription' success"),extension.sessionID=self1.ID,extension.callType=self1.callType,extension.callerID=self1.initiatorID,extension.opponentsIDs=self1.opponentsIDs,peerConnection._pc.localDescription&&(extension.sdp=peerConnection._pc.localDescription.toJSON().sdp),self1.signalingProvider.sendMessage(userID,extension,SignalingConstants.SignalingType.ACCEPT))}))})}else Helpers.traceError("Can't accept the call, peer connection for userID "+userID+" was not found")},WebRTCSession.prototype.reject=function(extension){var self1=this,ext=_prepareExtension(extension);Helpers.trace("Reject, extension: "+JSON.stringify(ext.userInfo)),self1.state=WebRTCSession.State.REJECTED,self1._clearAnswerTimer(),ext.sessionID=self1.ID,ext.callType=self1.callType,ext.callerID=self1.initiatorID,ext.opponentsIDs=self1.opponentsIDs,Object.keys(self1.peerConnections).forEach(function(key){var peerConnection=self1.peerConnections[key];self1.signalingProvider.sendMessage(peerConnection.userID,ext,SignalingConstants.SignalingType.REJECT)}),self1._close()},WebRTCSession.prototype.stop=function(extension){var self1=this,ext=_prepareExtension(extension);Helpers.trace("Stop, extension: "+JSON.stringify(ext.userInfo)),self1.state=WebRTCSession.State.HUNGUP,self1.answerTimer&&self1._clearAnswerTimer(),ext.sessionID=self1.ID,ext.callType=self1.callType,ext.callerID=self1.initiatorID,ext.opponentsIDs=self1.opponentsIDs,Object.keys(self1.peerConnections).forEach(function(key){var peerConnection=self1.peerConnections[key];self1.signalingProvider.sendMessage(peerConnection.userID,ext,SignalingConstants.SignalingType.STOP)}),self1._close()},WebRTCSession.prototype.closeConnection=function(userId){var peer=this.peerConnections[userId];if(!peer)return Helpers.traceWarn("Not found connection with user ("+userId+")"),!1;try{peer.release()}catch(e){Helpers.traceError(e)}finally{this._closeSessionIfAllConnectionsClosed()}},WebRTCSession.prototype.update=function(extension,userID){var ext="object"==typeof extension?extension:{};if(Helpers.trace("Update, extension: "+JSON.stringify(extension)),null===extension){Helpers.trace("extension is null, no parameters to update");return}if(ext.sessionID=this.ID,ext.callType=this.callType,ext.callerID=this.initiatorID,ext.opponentsIDs=this.opponentsIDs,userID)this.signalingProvider.sendMessage(userID,ext,SignalingConstants.SignalingType.PARAMETERS_CHANGED);else for(var key in this.peerConnections){var peer=this.peerConnections[key];this.signalingProvider.sendMessage(peer.userID,ext,SignalingConstants.SignalingType.PARAMETERS_CHANGED)}},WebRTCSession.prototype.mute=function(type){this._muteStream(0,type)},WebRTCSession.prototype.unmute=function(type){this._muteStream(1,type)},WebRTCSession.prototype.processOnCall=function(callerID,extension){var self1=this;self1._uniqueOpponentsIDs().forEach(function(opponentID){var peer=self1.peerConnections[opponentID];peer||(peer=self1._createPeer(opponentID,self1.currentUserID<opponentID),self1.peerConnections[opponentID]=peer,opponentID==callerID&&self1._startAnswerTimer()),opponentID==callerID&&(peer.setRemoteSDP(new window.RTCSessionDescription({sdp:extension.sdp,type:"offer"})),callerID!=self1.initiatorID&&self1.state===WebRTCSession.State.ACTIVE&&self1._acceptInternal(callerID,{}))})},WebRTCSession.prototype.processOnAccept=function(userID,extension){var self1=this,peerConnection=this.peerConnections[userID];if(peerConnection){if(peerConnection._clearDialingTimer(),"stable"!==peerConnection._pc.signalingState){var remoteSessionDescription=new window.RTCSessionDescription({sdp:extension.sdp,type:"answer"});peerConnection.setRemoteSDP(remoteSessionDescription),peerConnection.setRemoteSessionDescription(remoteSessionDescription,function(error){error?Helpers.traceError("'setRemoteSessionDescription' error: "+error):(Helpers.trace("'setRemoteSessionDescription' success"),self1.state!==WebRTCSession.State.ACTIVE&&(self1.state=WebRTCSession.State.ACTIVE))})}else Helpers.traceError("Ignore 'onAccept', PeerConnection is already in 'stable' state")}else Helpers.traceError("Ignore 'OnAccept': peer connection for user with Id "+userID+" was not found")},WebRTCSession.prototype.processOnReject=function(userID,extension){var peerConnection=this.peerConnections[userID];this._clearWaitingOfferOrAnswerTimer(),peerConnection?peerConnection.release():Helpers.traceError("Ignore 'OnReject', there is no information about peer connection by some reason."),this._closeSessionIfAllConnectionsClosed()},WebRTCSession.prototype.processOnStop=function(userID,extension){this._clearAnswerTimer();var peerConnection=this.peerConnections[userID];peerConnection?(peerConnection.release(),peerConnection._reconnecting&&(peerConnection._reconnecting=!1),this._stopReconnectTimer(userID)):Helpers.traceError("Ignore 'OnStop', there is no information about peer connection by some reason."),this._closeSessionIfAllConnectionsClosed()},WebRTCSession.prototype.processOnIceCandidates=function(userID,extension){var peerConnection=this.peerConnections[userID];peerConnection?peerConnection.addCandidates(extension.iceCandidates):Helpers.traceError("Ignore 'OnIceCandidates', there is no information about peer connection by some reason.")},WebRTCSession.prototype.processOnUpdate=function(userID,extension){var SRD=extension.sessionDescription,reason=extension.reason;this.state===WebRTCSession.State.ACTIVE&&reason&&"reconnect"===reason&&(this.peerConnections[userID]?SRD&&("offer"===SRD.type?this._processReconnectOffer(userID,SRD):this._processReconnectAnswer(userID,SRD)):Helpers.traceError("Ignore 'OnUpdate': peer connection for user with Id "+userID+" was not found"))},WebRTCSession.prototype._processReconnectOffer=function(userID,SRD){var self1=this;if(this.peerConnections[userID].polite){this._reconnect(this.peerConnections[userID]);var peer=this.peerConnections[userID],offerId=SRD.offerId,remoteDescription=new window.RTCSessionDescription({sdp:SRD.sdp,type:SRD.type});peer.setRemoteSDP(remoteDescription),peer.setRemoteSessionDescription(remoteDescription,function(e){e?Helpers.traceError('"setRemoteSessionDescription" error:'+e.message):peer.setLocalSessionDescription({type:"answer"},function(){var description=peer._pc.localDescription.toJSON(),ext={reason:"reconnect",sessionDescription:{offerId:offerId,sdp:description.sdp,type:description.type}};self1.update(ext,userID)})})}else this._reconnect(this.peerConnections[userID],!0)},WebRTCSession.prototype._processReconnectAnswer=function(userID,SRD){var peer=this.peerConnections[userID],offerId=SRD.offerId;if(peer&&peer.offerId&&offerId&&peer.offerId===offerId){var remoteDescription=new window.RTCSessionDescription({sdp:SRD.sdp,type:SRD.type});peer.setRemoteSDP(remoteDescription),peer.setRemoteSessionDescription(remoteDescription,function(e){e&&Helpers.traceError('"setRemoteSessionDescription" error:'+e.message)})}},WebRTCSession.prototype.processCall=function(peerConnection,ext){var extension=ext||{};peerConnection._pc.localDescription&&(extension.sessionID=this.ID,extension.callType=this.callType,extension.callerID=this.initiatorID,extension.opponentsIDs=this.opponentsIDs,extension.sdp=peerConnection._pc.localDescription.sdp,extension.userInfo=ext&&ext.userInfo?ext.userInfo:{},extension.userInfo.bandwidth=this.bandwidth,this.signalingProvider.sendMessage(peerConnection.userID,extension,SignalingConstants.SignalingType.CALL))},WebRTCSession.prototype.processIceCandidates=function(peerConnection,iceCandidates){var extension={};extension.sessionID=this.ID,extension.callType=this.callType,extension.callerID=this.initiatorID,extension.opponentsIDs=this.opponentsIDs,this.signalingProvider.sendCandidate(peerConnection.userID,iceCandidates,extension)},WebRTCSession.prototype.processOnNotAnswer=function(peerConnection){Helpers.trace("Answer timeout callback for session "+this.ID+" for user "+peerConnection.userID),this._clearWaitingOfferOrAnswerTimer(),peerConnection.release(),"function"==typeof this.onUserNotAnswerListener&&Utils.safeCallbackCall(this.onUserNotAnswerListener,this,peerConnection.userID),this._closeSessionIfAllConnectionsClosed()},WebRTCSession.prototype._onRemoteStreamListener=function(userID,stream){"function"==typeof this.onRemoteStreamListener&&Utils.safeCallbackCall(this.onRemoteStreamListener,this,userID,stream)},WebRTCSession.prototype._onCallStatsReport=function(userId,stats,error){"function"==typeof this.onCallStatsReport&&Utils.safeCallbackCall(this.onCallStatsReport,this,userId,stats,error)},WebRTCSession.prototype._onSessionConnectionStateChangedListener=function(userID,connectionState){var StateClosed=Helpers.SessionConnectionState.CLOSED,peer=this.peerConnections[userID];"function"==typeof this.onSessionConnectionStateChangedListener&&Utils.safeCallbackCall(this.onSessionConnectionStateChangedListener,this,userID,connectionState),connectionState===StateClosed&&peer&&(peer._pc.onicecandidate=null,peer._pc.onsignalingstatechange=null,peer._pc.ontrack=null,peer._pc.oniceconnectionstatechange=null,delete this.peerConnections[userID])},WebRTCSession.prototype._createPeer=function(userId,polite){if(!window.RTCPeerConnection)throw Error("_createPeer error: RTCPeerConnection is not supported in your browser");this.startCallTime=new Date;var pcConfig={iceServers:config.webrtc.iceServers};Helpers.trace("_createPeer configuration: "+JSON.stringify(pcConfig));var peer=new qbRTCPeerConnection(pcConfig);return peer._init(this,userId,this.ID,polite),peer},WebRTCSession.prototype._startReconnectTimer=function(userID){var self1=this,delay=1e3*config.webrtc.disconnectTimeInterval,peer=this.peerConnections[userID];peer._reconnecting=!0;var reconnectTimeoutCallback=function(){Helpers.trace("disconnectTimeInterval reached for userID "+userID),self1._stopReconnectTimer(userID),self1.peerConnections[userID].release(),self1._onSessionConnectionStateChangedListener(userID,Helpers.SessionConnectionState.CLOSED),self1._closeSessionIfAllConnectionsClosed()};"function"==typeof this.onReconnectListener&&Utils.safeCallbackCall(this.onReconnectListener,this,userID,ReconnectionState.RECONNECTING),Helpers.trace("_startReconnectTimer for userID:"+userID+", timeout: "+delay),this.iceConnectTimers[userID]||(this.iceConnectTimers[userID]=setTimeout(function(){Helpers.trace("iceConnectTimeout reached for user "+userID),self1.iceConnectTimers[userID]&&(clearTimeout(self1.iceConnectTimers[userID]),self1.iceConnectTimers[userID]=void 0,self1.reconnectTimers[userID]||(self1.reconnectTimers[userID]=setTimeout(reconnectTimeoutCallback,delay-5e3),self1._reconnectToChat(function(){self1.state===WebRTCSession.State.ACTIVE&&self1.reconnectTimers[userID]&&self1._reconnect(peer,!0)})))},5e3))},WebRTCSession.prototype._stopReconnectTimer=function(userID){var peer=this.peerConnections[userID];if(this.iceConnectTimers[userID]&&(clearTimeout(this.iceConnectTimers[userID]),this.iceConnectTimers[userID]=void 0),this.reconnectTimers[userID]&&(Helpers.trace("_stopReconnectTimer for userID: "+userID),clearTimeout(this.reconnectTimers[userID]),this.reconnectTimers[userID]=void 0),peer&&peer._reconnecting&&(peer._reconnecting=!1,"function"==typeof this.onReconnectListener)){var state=peer._pc.iceConnectionState;Utils.safeCallbackCall(this.onReconnectListener,this,userID,"connected"===state?ReconnectionState.RECONNECTED:ReconnectionState.FAILED)}},WebRTCSession.prototype._reconnectToChat=function(callback){var self1=this,signalingProvider=this.signalingProvider,reconnectToChat=function(){var _onReconnectListener=signalingProvider.chat.onReconnectListener;signalingProvider.chat.onReconnectListener=function(){"function"==typeof _onReconnectListener&&_onReconnectListener(),signalingProvider.chat.onReconnectListener=_onReconnectListener,callback()},signalingProvider.chat.reconnect()};if(signalingProvider&&signalingProvider.chat)try{signalingProvider.chat.ping(function(e){self1.state!==WebRTCSession.State.CLOSED&&(e?reconnectToChat():callback())})}catch(e){self1.state!==WebRTCSession.State.CLOSED&&reconnectToChat()}},WebRTCSession.prototype._reconnect=function(peerConnection,negotiate){if(peerConnection&&peerConnection.userID){var userId=peerConnection.userID,polite=peerConnection.polite,_reconnecting=peerConnection._reconnecting;peerConnection.release();var pcConfig={iceServers:config.webrtc.iceServers};Helpers.trace("_reconnect peer configuration: "+JSON.stringify(pcConfig));var peer=new qbRTCPeerConnection(pcConfig);this.peerConnections[userId]=peer,peer._init(this,userId,this.ID,polite),peer._reconnecting=_reconnecting,peer.addLocalStream(this.localStream),negotiate&&(peer.offerId=generateUUID(),peer.negotiate())}},WebRTCSession.prototype._close=function(){for(var key in Helpers.trace("_close"),this.peerConnections){var peer=this.peerConnections[key];this._stopReconnectTimer(peer.userID);try{peer.release()}catch(e){console.warn("Peer close error:",e)}}this._closeLocalMediaStream(),"function"==typeof this._detectSilentAudioTaskCleanup&&(this._detectSilentAudioTaskCleanup(),this._detectSilentAudioTaskCleanup=void 0),"function"==typeof this._detectSilentVideoTaskCleanup&&(this._detectSilentVideoTaskCleanup(),this._detectSilentVideoTaskCleanup=void 0),this.state=WebRTCSession.State.CLOSED,"function"==typeof this.onSessionCloseListener&&Utils.safeCallbackCall(this.onSessionCloseListener,this)},WebRTCSession.prototype._closeSessionIfAllConnectionsClosed=function(){var isAllConnectionsClosed=Object.values(this.peerConnections).every(function(peer){return peer.state===qbRTCPeerConnection.State.CLOSED});Helpers.trace("All peer connections closed: "+isAllConnectionsClosed),isAllConnectionsClosed&&(this._closeLocalMediaStream(),"function"==typeof this.onSessionCloseListener&&this.onSessionCloseListener(this),this.state=WebRTCSession.State.CLOSED)},WebRTCSession.prototype._closeLocalMediaStream=function(){this.localStream&&(this.localStream.getTracks().forEach(function(track){track.stop(),track.enabled=!1}),this.localStream=null)},WebRTCSession.prototype._muteStream=function(bool,type){if("audio"===type&&this.localStream.getAudioTracks().length>0){this.localStream.getAudioTracks().forEach(function(track){track.enabled=!!bool});return}if("video"===type&&this.localStream.getVideoTracks().length>0){this.localStream.getVideoTracks().forEach(function(track){track.enabled=!!bool});return}},WebRTCSession.prototype._clearAnswerTimer=function(){this.answerTimer&&(Helpers.trace("_clearAnswerTimer"),clearTimeout(this.answerTimer),this.answerTimer=null)},WebRTCSession.prototype._startAnswerTimer=function(){Helpers.trace("_startAnswerTimer");var self1=this,answerTimeInterval=1e3*config.webrtc.answerTimeInterval;this.answerTimer=setTimeout(function(){Helpers.trace("_answerTimeoutCallback"),"function"==typeof self1.onSessionCloseListener&&self1._close(),self1.answerTimer=null},answerTimeInterval)},WebRTCSession.prototype._clearWaitingOfferOrAnswerTimer=function(){this.waitingOfferOrAnswerTimer&&(Helpers.trace("_clearWaitingOfferOrAnswerTimer"),clearTimeout(this.waitingOfferOrAnswerTimer),this.waitingOfferOrAnswerTimer=null)},WebRTCSession.prototype._startWaitingOfferOrAnswerTimer=function(time){var self1=this,timeout=config.webrtc.answerTimeInterval-time<0?1:config.webrtc.answerTimeInterval-time;Helpers.trace("_startWaitingOfferOrAnswerTimer, timeout: "+timeout),this.waitingOfferOrAnswerTimer=setTimeout(function(){Helpers.trace("waitingOfferOrAnswerTimeoutCallback"),Object.keys(self1.peerConnections).length>0&&Object.keys(self1.peerConnections).forEach(function(key){var peerConnection=self1.peerConnections[key];(peerConnection.state===qbRTCPeerConnection.State.CONNECTING||peerConnection.state===qbRTCPeerConnection.State.NEW)&&self1.processOnNotAnswer(peerConnection)}),self1.waitingOfferOrAnswerTimer=null},1e3*timeout)},WebRTCSession.prototype._uniqueOpponentsIDs=function(){var self1=this,opponents=[];return this.initiatorID!==this.currentUserID&&opponents.push(this.initiatorID),this.opponentsIDs.forEach(function(userID,i,arr){userID!=self1.currentUserID&&opponents.push(parseInt(userID))}),opponents},WebRTCSession.prototype._uniqueOpponentsIDsWithoutInitiator=function(){var self1=this,opponents=[];return this.opponentsIDs.forEach(function(userID,i,arr){userID!=self1.currentUserID&&opponents.push(parseInt(userID))}),opponents},WebRTCSession.prototype.toString=function sessionToString(){return"ID: "+this.ID+", initiatorID: "+this.initiatorID+", opponentsIDs: "+this.opponentsIDs+", state: "+this.state+", callType: "+this.callType},module.exports=WebRTCSession},{"../../qbConfig":253,"../../qbUtils":257,"./qbRTCPeerConnection":245,"./qbWebRTCHelpers":247,"./qbWebRTCSignalingConstants":249}],249:[function(require1,module,exports){"use strict";function WebRTCSignalingConstants(){}WebRTCSignalingConstants.MODULE_ID="WebRTCVideoChat",WebRTCSignalingConstants.SignalingType={CALL:"call",ACCEPT:"accept",REJECT:"reject",STOP:"hangUp",CANDIDATE:"iceCandidates",PARAMETERS_CHANGED:"update"},module.exports=WebRTCSignalingConstants},{}],250:[function(require1,module,exports){"use strict";require1("strophe.js");var SignalingConstants=require1("./qbWebRTCSignalingConstants");function WebRTCSignalingProcessor(service,delegate){var self1=this;self1.service=service,self1.delegate=delegate,this._onMessage=function(from,extraParams,delay,userId){var extension=self1._getExtension(extraParams),sessionId=extension.sessionID,signalType=extension.signalType;switch(delete extension.moduleIdentifier,delete extension.sessionID,delete extension.signalType,signalType){case SignalingConstants.SignalingType.CALL:"function"==typeof self1.delegate._onCallListener&&self1.delegate._onCallListener(userId,sessionId,extension);break;case SignalingConstants.SignalingType.ACCEPT:"function"==typeof self1.delegate._onAcceptListener&&self1.delegate._onAcceptListener(userId,sessionId,extension);break;case SignalingConstants.SignalingType.REJECT:"function"==typeof self1.delegate._onRejectListener&&self1.delegate._onRejectListener(userId,sessionId,extension);break;case SignalingConstants.SignalingType.STOP:"function"==typeof self1.delegate._onStopListener&&self1.delegate._onStopListener(userId,sessionId,extension);break;case SignalingConstants.SignalingType.CANDIDATE:"function"==typeof self1.delegate._onIceCandidatesListener&&self1.delegate._onIceCandidatesListener(userId,sessionId,extension);break;case SignalingConstants.SignalingType.PARAMETERS_CHANGED:"function"==typeof self1.delegate._onUpdateListener&&self1.delegate._onUpdateListener(userId,sessionId,extension)}},this._getExtension=function(extraParams){if(!extraParams)return{};var extension={},iceCandidates=[],opponents=[];return extraParams.childNodes.forEach(function(childNode){"iceCandidates"===childNode.nodeName?childNode.childNodes.forEach(function(candidateNode){var candidate={};candidateNode.childNodes.forEach(function(node){candidate[node.nodeName]=node.textContent}),iceCandidates.push(candidate)}):"opponentsIDs"===childNode.nodeName?childNode.childNodes.forEach(function(opponentNode){var opponentId=opponentNode.textContent;opponents.push(parseInt(opponentId))}):childNode.childNodes.length>1?extension=self1._XMLtoJS(extension,childNode.nodeName,childNode):"userInfo"===childNode.nodeName?extension=self1._XMLtoJS(extension,childNode.nodeName,childNode):extension[childNode.nodeName]=childNode.textContent}),iceCandidates.length>0&&(extension.iceCandidates=iceCandidates),opponents.length>0&&(extension.opponentsIDs=opponents),extension},this._XMLtoJS=function(extension,title,element){var self1=this;return extension[title]={},element.childNodes.forEach(function(childNode){childNode.childNodes.length>1?extension[title]=self1._XMLtoJS(extension[title],childNode.nodeName,childNode):extension[title][childNode.nodeName]=childNode.textContent}),extension}}module.exports=WebRTCSignalingProcessor},{"./qbWebRTCSignalingConstants":249,"strophe.js":208}],251:[function(require1,module,exports){"use strict";require1("strophe.js");var Helpers=require1("./qbWebRTCHelpers"),SignalingConstants=require1("./qbWebRTCSignalingConstants"),Utils=require1("../../qbUtils"),config=require1("../../qbConfig");function WebRTCSignalingProvider(service,chat){this.service=service,this.chat=chat}WebRTCSignalingProvider.prototype.sendCandidate=function(userId,iceCandidates,ext){var extension=ext||{};extension.iceCandidates=iceCandidates,this.sendMessage(userId,extension,SignalingConstants.SignalingType.CANDIDATE)},WebRTCSignalingProvider.prototype.sendMessage=function(userId,ext,signalingType){var extension=ext||{},self1=this;extension.moduleIdentifier=SignalingConstants.MODULE_ID,extension.signalType=signalingType,extension.platform="web",extension.userInfo&&!Object.keys(extension.userInfo).length&&delete extension.userInfo;var msg=$msg({to:Helpers.getUserJid(userId,config.creds.appId),type:"headline",id:Utils.getBsonObjectId()}).c("extraParams",{xmlns:Strophe.NS.CLIENT});Object.keys(extension).forEach(function(field){"iceCandidates"===field?(msg.c("iceCandidates"),extension[field].forEach(function(candidate){msg.c("iceCandidate"),Object.keys(candidate).forEach(function(key){msg.c(key).t(candidate[key]).up()}),msg.up()}),msg.up()):"opponentsIDs"===field?(msg.c("opponentsIDs"),extension[field].forEach(function(opponentId){msg.c("opponentID").t(opponentId).up()}),msg.up()):"object"==typeof extension[field]?self1._JStoXML(field,extension[field],msg):msg.c(field).t(extension[field]).up()}),this.chat.connection.send(msg)},WebRTCSignalingProvider.prototype._JStoXML=function(title,obj,msg){var self1=this;msg.c(title),Object.keys(obj).forEach(function(field){"object"==typeof obj[field]?self1._JStoXML(field,obj[field],msg):msg.c(field).t(obj[field]).up()}),msg.up()},module.exports=WebRTCSignalingProvider},{"../../qbConfig":253,"../../qbUtils":257,"./qbWebRTCHelpers":247,"./qbWebRTCSignalingConstants":249,"strophe.js":208}],252:[function(require1,module,exports){"use strict";var Utils=require1("../qbUtils"),chatUtils=require1("../modules/chat/qbChatHelpers");function StreamManagement(options){this._NS="urn:xmpp:sm:3",this._isStreamManagementEnabled=!1,this._clientProcessedStanzasCounter=null,this._clientSentStanzasCounter=null,this._intervalId=null,this._timeInterval=Utils.getTimeIntervalForCallBackMessage(),this.sentMessageCallback=null,Utils.getEnv().browser&&(this._parser=new DOMParser),this._c=null,this._nodeBuilder=null,this._originalSend=null,this._stanzasQueue=[]}StreamManagement.prototype.enable=function(connection,client){var stanza,enableParams={xmlns:this._NS};this._isStreamManagementEnabled||(this._c=connection,this._originalSend=this._c.send,this._c.send=this.send.bind(this)),Utils.getEnv().browser?(this._clientProcessedStanzasCounter=null,this._clientSentStanzasCounter=null,this._addEnableHandlers(),stanza=$build("enable",enableParams)):(this._nodeBuilder=client.Stanza,this._addEnableHandlers(),stanza=chatUtils.createStanza(this._nodeBuilder,enableParams,"enable")),this._c.send(stanza)},StreamManagement.prototype._timeoutCallback=function(){var now=Date.now(),updatedStanzasQueue=[];if(this._stanzasQueue.length){for(var i=0;i<this._stanzasQueue.length;i++)this._stanzasQueue[i]&&this._stanzasQueue[i].time<now?this.sentMessageCallback(this._stanzasQueue[i].message):updatedStanzasQueue.push(this._stanzasQueue[i]);this._stanzasQueue=updatedStanzasQueue}},StreamManagement.prototype._addEnableHandlers=function(){var self1=this;function _incomingStanzaHandler(stanza){var tagName=stanza.name||stanza.tagName||stanza.nodeTree.tagName;if("enabled"===tagName)return self1._isStreamManagementEnabled=!0,!0;if(self1._isStreamManagementEnabled&&"message"===tagName)return clearInterval(self1._intervalId),self1._intervalId=setInterval(self1._timeoutCallback.bind(self1),self1._timeInterval),!0;if(chatUtils.getAttr(stanza,"xmlns")!==self1._NS&&self1._increaseReceivedStanzasCounter(),"r"===tagName){var params={xmlns:self1._NS,h:self1._clientProcessedStanzasCounter},answerStanza=Utils.getEnv().browser?$build("a",params):chatUtils.createStanza(self1._nodeBuilder,params,"a");return self1._originalSend.call(self1._c,answerStanza),!0}if("a"===tagName){var h=parseInt(chatUtils.getAttr(stanza,"h"));self1._checkCounterOnIncomeStanza(h)}return!0}Utils.getEnv().browser?self1._c.XAddTrackedHandler(_incomingStanzaHandler.bind(self1)):self1._c.on("stanza",_incomingStanzaHandler.bind(self1))},StreamManagement.prototype.send=function(stanza,message){var stanzaXML=stanza.nodeTree?this._parser.parseFromString(stanza.nodeTree.outerHTML,"application/xml").childNodes[0]:stanza,tagName=stanzaXML.name||stanzaXML.tagName||stanzaXML.nodeTree.tagName,type=chatUtils.getAttr(stanzaXML,"type"),bodyContent=chatUtils.getElementText(stanzaXML,"body")||"",attachments=chatUtils.getAllElements(stanzaXML,"attachment")||"";try{this._originalSend.call(this._c,stanza)}catch(e){Utils.QBLog("[QBChat]",e.message)}finally{"message"===tagName&&("chat"===type||"groupchat"===type)&&(bodyContent||attachments.length)&&this._sendStanzasRequest({message:message,time:Date.now()+this._timeInterval,expect:this._clientSentStanzasCounter}),this._clientSentStanzasCounter++}},StreamManagement.prototype._sendStanzasRequest=function(data){if(this._isStreamManagementEnabled){this._stanzasQueue.push(data);var stanza=Utils.getEnv().browser?$build("r",{xmlns:this._NS}):chatUtils.createStanza(this._nodeBuilder,{xmlns:this._NS},"r");this._c.connected?this._originalSend.call(this._c,stanza):this._checkCounterOnIncomeStanza()}},StreamManagement.prototype.getClientSentStanzasCounter=function(){return this._clientSentStanzasCounter},StreamManagement.prototype._checkCounterOnIncomeStanza=function(count){var updatedStanzasQueue=[];if(this._stanzasQueue.length){for(var i=0;i<this._stanzasQueue.length;i++)this._stanzasQueue[i].expect==count?this.sentMessageCallback(null,this._stanzasQueue[i].message):updatedStanzasQueue.push(this._stanzasQueue[i]);this._stanzasQueue=updatedStanzasQueue}},StreamManagement.prototype._increaseReceivedStanzasCounter=function(){this._clientProcessedStanzasCounter++},module.exports=StreamManagement},{"../modules/chat/qbChatHelpers":235,"../qbUtils":257}],253:[function(require1,module,exports){"use strict";var config={version:"2.17.0",buildNumber:"1160",creds:{appId:0,authKey:"",authSecret:"",accountKey:""},endpoints:{api:"api.quickblox.com",chat:"chat.quickblox.com",muc:"muc.chat.quickblox.com"},hash:"sha1",streamManagement:{enable:!1},chatProtocol:{bosh:"https://chat.quickblox.com:5281",websocket:"wss://chat.quickblox.com:5291",active:2},pingTimeout:1,pingLocalhostTimeInterval:5,chatReconnectionTimeInterval:3,webrtc:{answerTimeInterval:60,autoReject:!0,incomingLimit:1,dialingTimeInterval:5,disconnectTimeInterval:30,statsReportTimeInterval:!1,iceServers:[{urls:["turn:turn.quickblox.com","stun:turn.quickblox.com"],username:"quickblox",credential:"baccb97ba2d92d71e26eb9886da5f1e0"}]},urls:{account:"account_settings",session:"session",login:"login",users:"users",chat:"chat",blobs:"blobs",geodata:"geodata",pushtokens:"push_tokens",subscriptions:"subscriptions",events:"events",data:"data",addressbook:"address_book",addressbookRegistered:"address_book/registered_users",type:".json"},on:{sessionExpired:null},timeout:null,debug:{mode:0,file:null},addISOTime:!1,qbTokenExpirationDate:null,liveSessionInterval:120,callBackInterval:30};config.set=function(options){"object"==typeof options.endpoints&&options.endpoints.chat&&(config.endpoints.muc="muc."+options.endpoints.chat,config.chatProtocol.bosh="https://"+options.endpoints.chat+":5281",config.chatProtocol.websocket="wss://"+options.endpoints.chat+":5291"),Object.keys(options).forEach(function(key){"set"!==key&&config.hasOwnProperty(key)&&("object"!=typeof options[key]?config[key]=options[key]:Object.keys(options[key]).forEach(function(nextkey){config[key].hasOwnProperty(nextkey)&&(config[key][nextkey]=options[key][nextkey])})),"iceServers"===key&&(config.webrtc.iceServers=options[key])})},config.updateSessionExpirationDate=function(tokenExpirationDate,headerHasToken=!1){var newDate;headerHasToken?(newDate=new Date(tokenExpirationDate.replaceAll("-","/"))).setMinutes(newDate.getMinutes()-1):((newDate=new Date(tokenExpirationDate)).setMinutes(newDate.getMinutes()-1),newDate.setMinutes(newDate.getMinutes()+config.liveSessionInterval)),config.qbTokenExpirationDate=newDate},module.exports=config},{}],254:[function(require1,module,exports){"use strict";var config=require1("./qbConfig"),Utils=require1("./qbUtils");function QuickBlox(){}require1("./modules/chat/qbMessage"),QuickBlox.prototype={version:config.version,buildNumber:config.buildNumber,_getOS:Utils.getOS.bind(Utils),init:function(appIdOrToken,authKeyOrAppId,authSecret,accountKey,configMap){console.log("current platform: ",Utils.getEnv()),"string"==typeof accountKey&&accountKey.length?(configMap&&"object"==typeof configMap&&config.set(configMap),config.creds.accountKey=accountKey):(console.warn('Parameter "accountKey" is missing. This will lead to error in next major release'),console.warn('NOTE: Account migration will not work without "accountKey"'),"object"==typeof accountKey&&config.set(accountKey));var SHARED_API_ENDPOINT="api.quickblox.com",Proxy=require1("./qbProxy"),Auth=require1("./modules/qbAuth"),Users=require1("./modules/qbUsers"),Content=require1("./modules/qbContent"),PushNotifications=require1("./modules/qbPushNotifications"),Data=require1("./modules/qbData"),AddressBook=require1("./modules/qbAddressBook"),Chat=require1("./modules/chat/qbChat"),DialogProxy=require1("./modules/chat/qbDialog"),MessageProxy=require1("./modules/chat/qbMessage"),AIProxy=require1("./modules/qbAI");if(this.service=new Proxy,this.auth=new Auth(this.service),this.users=new Users(this.service),this.content=new Content(this.service),this.pushnotifications=new PushNotifications(this.service),this.data=new Data(this.service),this.addressbook=new AddressBook(this.service),this.chat=new Chat(this.service),this.chat.dialog=new DialogProxy(this.service),this.chat.message=new MessageProxy(this.service),this.ai=new AIProxy(this.service),Utils.getEnv().browser){if(require1("webrtc-adapter"),Utils.isWebRTCAvailble()){var WebRTCClient=require1("./modules/webrtc/qbWebRTCClient");this.webrtc=new WebRTCClient(this.service,this.chat)}else this.webrtc=!1}else this.webrtc=!1;if("string"!=typeof appIdOrToken||authKeyOrAppId&&"number"!=typeof authKeyOrAppId||authSecret?(config.creds.appId=appIdOrToken,config.creds.authKey=authKeyOrAppId,config.creds.authSecret=authSecret):("number"==typeof authKeyOrAppId&&(config.creds.appId=authKeyOrAppId),this.service.setSession({token:appIdOrToken})),config.creds.accountKey&&(!config.endpoints.api||config.endpoints.api===SHARED_API_ENDPOINT||!config.endpoints.chat||"chat.quickblox.com"===config.endpoints.chat)){var accountSettingsUrl=["https://",SHARED_API_ENDPOINT,"/",config.urls.account,config.urls.type].join("");this.service.ajax({url:accountSettingsUrl},function(err,response){if(!err&&"object"==typeof response){var update={endpoints:{api:response.api_endpoint.replace(/^https?:\/\//,""),chat:response.chat_endpoint}};config.set(update)}})}},initWithAppId:function(appId,accountKey,configMap){if("number"!=typeof appId)throw Error("Type of appId must be a number");if(""===appId||null==appId||""===accountKey||null==accountKey)throw Error("Cannot init QuickBlox without app credentials (app ID, auth key)");this.init("",appId,null,accountKey,configMap)},getSession:function(callback){this.auth.getSession(callback)},startSessionWithToken:function(token,callback){if(void 0===token)throw Error("Cannot start session with undefined token");if(""===token)throw Error("Cannot start session with empty string token");if(null===token)throw Error("Cannot start session with null value token");if("function"!=typeof callback)throw Error("Cannot start session without callback function");try{this.service.setSession({token:token})}catch(err){callback(err,null)}if("function"==typeof callback)try{this.auth.getSession(callback)}catch(er){callback(er,null)}},createSession:function(params,callback){this.auth.createSession(params,callback)},destroySession:function(callback){this.auth.destroySession(callback)},login:function(params,callback){this.auth.login(params,callback)},logout:function(callback){this.auth.logout(callback)}};var QB=new QuickBlox;QB.QuickBlox=QuickBlox,module.exports=QB},{"./modules/chat/qbChat":234,"./modules/chat/qbDialog":236,"./modules/chat/qbMessage":237,"./modules/qbAI":238,"./modules/qbAddressBook":239,"./modules/qbAuth":240,"./modules/qbContent":241,"./modules/qbData":242,"./modules/qbPushNotifications":243,"./modules/qbUsers":244,"./modules/webrtc/qbWebRTCClient":246,"./qbConfig":253,"./qbProxy":255,"./qbUtils":257,"webrtc-adapter":218}],255:[function(require1,module,exports){"use strict";var qbFetch,qbFormData,config=require1("./qbConfig"),Utils=require1("./qbUtils");function ServiceProxy(){this.qbInst={config:config,session:null},this.reqCount=0}Utils.getEnv().node?(qbFetch=require1("node-fetch"),qbFormData=require1("form-data")):(qbFetch=fetch,qbFormData=FormData),ServiceProxy.prototype={_fetchingSettings:!1,_queue:[],setSession:function(session){this.qbInst.session=session},getSession:function(){return this.qbInst.session},handleResponse:function(error,response,next,retry){if(error){let errorMsg=JSON.stringify(error.message).toLowerCase();"function"==typeof config.on.sessionExpired&&401===error.code&&errorMsg.indexOf("session does not exist")>-1?config.on.sessionExpired(function(){next(error,response)},retry):next(error,null)}else config.addISOTime&&(response=Utils.injectISOTimes(response)),next(null,response)},startLogger:function(params){var clonedData;++this.reqCount,params.data&¶ms.data.file?(clonedData=JSON.parse(JSON.stringify(params.data))).file="...":clonedData=Utils.getEnv().nativescript?JSON.stringify(params.data):params.data,Utils.QBLog("[Request]["+this.reqCount+"]",(params.type||"GET")+" "+params.url,clonedData||"")},ajax:function(params,callback){if(this._fetchingSettings){this._queue.push([params,callback]);return}this.startLogger(params);var qbRequestBody,qbResponse,self1=this,isGetOrHeadType=!params.type||"GET"===params.type||"HEAD"===params.type,qbSessionToken=self1.qbInst&&self1.qbInst.session&&self1.qbInst.session.token,isQBRequest=-1===params.url.indexOf("s3.amazonaws.com"),isMultipartFormData=!1===params.contentType,qbDataType=params.dataType||"json",qbUrl=params.url,qbRequest={};function _fixedEncodeURIComponent(str){return encodeURIComponent(str).replace(/[#$&+,/:;=?@\[\]]/g,function(c){return"%"+c.charCodeAt(0).toString(16)})}function _getBodyRequest(){var qbData,data=params.data;return isMultipartFormData?(qbData=new qbFormData,Object.keys(data).forEach(function(item){params.fileToCustomObject&&"file"===item?qbData.append(item,data[item].data,data[item].name):qbData.append(item,params.data[item])})):qbData=params.isNeedStringify?JSON.stringify(data):Object.keys(data).map(function(k){return Utils.isObject(data[k])?Object.keys(data[k]).map(function(v){return _fixedEncodeURIComponent(k)+"["+(Utils.isArray(data[k])?"":v)+"]="+_fixedEncodeURIComponent(data[k][v])}).sort().join("&"):_fixedEncodeURIComponent(k)+(Utils.isArray(data[k])?"[]":"")+"="+_fixedEncodeURIComponent(data[k])}).sort().join("&"),qbData}function _requestCallback(error,response,body){var errorMsg,responseMessage,responseBody,statusCode=response&&(response.status||response.statusCode);if(error||200!==statusCode&&201!==statusCode&&202!==statusCode){try{errorMsg={code:response&&statusCode||error&&error.code,status:response&&response.headers&&response.headers.status||"error",message:body||error&&error.errno,detail:body&&body.errors||error&&error.syscall}}catch(e){errorMsg=error}responseBody=body||error||body.errors,responseMessage=Utils.getEnv().nativescript?JSON.stringify(responseBody):responseBody,Utils.QBLog("[Response]["+self1.reqCount+"]","error",statusCode,responseMessage),self1.handleResponse(errorMsg,null,callback,retry)}else responseBody=body&&" "!==body?body:"empty body",responseMessage=Utils.getEnv().nativescript?JSON.stringify(responseBody):responseBody,Utils.QBLog("[Response]["+self1.reqCount+"]",responseMessage),self1.handleResponse(null,body,callback,retry);if(self1._fetchingSettings)for(self1._fetchingSettings=!1;self1._queue.length;){var args=self1._queue.shift();self1.ajax.apply(self1,args)}}function retry(session){session&&(self1.setSession(session),self1.ajax(params,callback))}qbRequest.method=params.type||"GET",params.data&&(qbRequestBody=_getBodyRequest(),isGetOrHeadType?qbUrl+="?"+qbRequestBody:qbRequest.body=qbRequestBody),isMultipartFormData||(qbRequest.headers={"Content-Type":params.contentType||"application/x-www-form-urlencoded; charset=UTF-8"}),isQBRequest&&(qbRequest.headers||(qbRequest.headers={}),qbRequest.headers["QB-OS"]=Utils.getOS(),qbRequest.headers["QB-SDK"]="JS "+config.version+" - Client",qbSessionToken&&(qbRequest.headers["QB-Token"]=qbSessionToken),params.url.indexOf(config.urls.account)>-1&&(qbRequest.headers["QB-Account-Key"]=config.creds.accountKey,this._fetchingSettings=!0)),config.timeout&&(qbRequest.timeout=config.timeout),qbFetch(qbUrl,qbRequest).then(function(response){if(qbResponse=response,"GET"===qbRequest.method||"POST"===qbRequest.method){var qbTokenExpirationDate=qbResponse.headers.get("qb-token-expirationdate"),headerHasToken=null!=qbTokenExpirationDate;qbTokenExpirationDate=headerHasToken?qbTokenExpirationDate:new Date,self1.qbInst.config.updateSessionExpirationDate(qbTokenExpirationDate,headerHasToken),Utils.QBLog("[Request][ajax]","header has token:",headerHasToken),Utils.QBLog("[Request][ajax]","updateSessionExpirationDate ... Set value: ",self1.qbInst.config.qbTokenExpirationDate)}return"text"===qbDataType?response.text():response.json()},function(){return qbResponse={status:200}," "}).then(function(body){_requestCallback(null,qbResponse,body)},function(error){_requestCallback(error)}).catch(error=>{console.log("qbProxy fetch ... catch, error: ",error),_requestCallback(error)})}},module.exports=ServiceProxy},{"./qbConfig":253,"./qbUtils":257,"form-data":81,"node-fetch":105}],256:[function(require1,module,exports){"use strict";require1("strophe.js");var chatPRTCL=require1("./qbConfig").chatProtocol,Utils=require1("./qbUtils");function Connection(){var protocol=1===chatPRTCL.active?chatPRTCL.bosh:chatPRTCL.websocket,conn=new Strophe.Connection(protocol);return 1===chatPRTCL.active?(conn.xmlInput=function(data){if(data.childNodes[0])for(var i=0,len=data.childNodes.length;i<len;i++)Utils.QBLog("[QBChat]","RECV:",data.childNodes[i])},conn.xmlOutput=function(data){if(data.childNodes[0])for(var i=0,len=data.childNodes.length;i<len;i++)Utils.QBLog("[QBChat]","SENT:",data.childNodes[i])}):(conn.xmlInput=function(data){Utils.QBLog("[QBChat]","RECV:",data)},conn.xmlOutput=function(data){Utils.QBLog("[QBChat]","SENT:",data)}),conn}module.exports=Connection},{"./qbConfig":253,"./qbUtils":257,"strophe.js":208}],257:[function(require1,module,exports){(function(global){(function(){"use strict";var config=require1("./qbConfig"),isNativeScript="object"==typeof global&&(global.hasOwnProperty("android")||global.hasOwnProperty("NSObject")),isNode="undefined"==typeof window&&"object"==typeof exports&&!isNativeScript,isBrowser="undefined"!=typeof window;if(isNode)var fs=require1("fs"),os=require1("os");var ObjectId={machine:Math.floor(16777216*Math.random()).toString(16),pid:Math.floor(32767*Math.random()).toString(16),increment:0};module.exports={getEnv:function(){return{nativescript:isNativeScript,browser:isBrowser,node:isNode}},_getOSInfoFromNodeJS:function(){return os.platform()},_getOSInfoFromBrowser:function(){return window.navigator.userAgent},_getOSInfoFromNativeScript:function(){return(global&&global.hasOwnProperty("android")?"Android":"iOS")+" - NativeScript"},getOS:function(){var platformInfo,osName="An unknown OS";if(this.getEnv().browser)platformInfo=this._getOSInfoFromBrowser();else if(this.getEnv().node)platformInfo=this._getOSInfoFromNodeJS();else if(this.getEnv().nativescript)return this._getOSInfoFromNativeScript();return[{osName:"Windows",codeNames:["Windows","win32"]},{osName:"Linux",codeNames:["Linux","linux"]},{osName:"macOS",codeNames:["Mac OS","darwin"]}].forEach(function(osInfo){osInfo.codeNames.forEach(function(codeName){-1!==platformInfo.indexOf(codeName)&&(osName=osInfo.osName)})}),osName},safeCallbackCall:function(){for(var listenerCall,listenerString=arguments[0].toString(),listenerName=listenerString.split("(")[0].split(" ")[1],argumentsCopy=[],i=0;i<arguments.length;i++)argumentsCopy.push(arguments[i]);listenerCall=argumentsCopy.shift();try{listenerCall.apply(null,argumentsCopy)}catch(err){""===listenerName?console.error("Error: "+err):console.error("Error in listener "+listenerName+": "+err)}},randomNonce:function(){return Math.floor(1e4*Math.random())},unixTime:function(){return Math.floor(Date.now()/1e3)},getUrl:function(base,id){return"https://"+config.endpoints.api+"/"+base+(id?"/"+id:"")+config.urls.type},formatUrl:function(base,id){return"https://"+config.endpoints.api+"/"+base+(id?"/"+id:"")},isArray:function(arg){return"[object Array]"===Object.prototype.toString.call(arg)},isObject:function(arg){return"[object Object]"===Object.prototype.toString.call(arg)},getBsonObjectId:function(){var timestamp=this.unixTime().toString(16),increment=(ObjectId.increment++).toString(16);return increment>16777215&&(ObjectId.increment=0),"00000000".substr(0,8-timestamp.length)+timestamp+"000000".substr(0,6-ObjectId.machine.length)+ObjectId.machine+"0000".substr(0,4-ObjectId.pid.length)+ObjectId.pid+"000000".substr(0,6-increment.length)+increment},getCurrentTime:function(){return new Date().toTimeString().split(" ")[0]},injectISOTimes:function(data){if(data.created_at)"number"==typeof data.created_at&&(data.iso_created_at=new Date(1e3*data.created_at).toISOString()),"number"==typeof data.updated_at&&(data.iso_updated_at=new Date(1e3*data.updated_at).toISOString());else if(data.items)for(var i=0,len=data.items.length;i<len;++i)"number"==typeof data.items[i].created_at&&(data.items[i].iso_created_at=new Date(1e3*data.items[i].created_at).toISOString()),"number"==typeof data.items[i].updated_at&&(data.items[i].iso_updated_at=new Date(1e3*data.items[i].updated_at).toISOString());return data},QBLog:function(){if(this.loggers){for(var logger,i=0;i<this.loggers.length;++i)this.loggers[i](arguments);return}this.loggers=[];var consoleLoggerFunction=function(){return function(args){console.log.apply(console,Array.prototype.slice.call(args))}},fileLoggerFunction=function(){return function(args){if(fs){for(var data=[],i=0;i<args.length;i++)data.push(JSON.stringify(args[i]));data=data.join(" ");var toLog="\n"+new Date+". "+data;fs.appendFile(config.debug.file,toLog,function(err){if(err)return console.error("Error while writing log to file. Error: "+err)})}else throw"This function isn't supported outside of the browser (...yet)"}};if("object"==typeof config.debug){if("number"==typeof config.debug.mode)1==config.debug.mode?(logger=consoleLoggerFunction(),this.loggers.push(logger)):2==config.debug.mode&&(logger=fileLoggerFunction(),this.loggers.push(logger));else if("object"==typeof config.debug.mode){var self1=this;config.debug.mode.forEach(function(mode){1===mode?(logger=consoleLoggerFunction(),self1.loggers.push(logger)):2===mode&&(logger=fileLoggerFunction(),self1.loggers.push(logger))})}}else"boolean"==typeof config.debug&&config.debug&&(logger=consoleLoggerFunction(),this.loggers.push(logger));if(this.loggers)for(var j=0;j<this.loggers.length;++j)this.loggers[j](arguments)},isWebRTCAvailble:function(){var RTCPeerConnection=window.RTCPeerConnection,IceCandidate=window.RTCIceCandidate,SessionDescription=window.RTCSessionDescription,MediaDevices=window.navigator.mediaDevices;return!!RTCPeerConnection&&!!IceCandidate&&!!SessionDescription&&!!MediaDevices},getError:function(code,detail,moduleName){var errorMsg={code:code,status:"error",detail:detail};switch(code){case 401:errorMsg.message="Unauthorized";break;case 403:errorMsg.message="Forbidden";break;case 408:errorMsg.message="Request Timeout";break;case 422:errorMsg.message="Unprocessable Entity";break;case 502:errorMsg.message="Bad Gateway";break;default:errorMsg.message="Unknown error"}return this.QBLog("["+moduleName+"]","Error:",detail),errorMsg},MergeArrayOfObjects:function(arrayTo,arrayFrom){var merged=JSON.parse(JSON.stringify(arrayTo));firstLevel:for(var i=0;i<arrayFrom.length;i++){for(var newItem=arrayFrom[i],j=0;j<merged.length;j++)if(newItem.user_id===merged[j].user_id){merged[j]=newItem;continue firstLevel}merged.push(newItem)}return merged},getTimeIntervalForCallBackMessage:function(){return 1e3*(void 0===config.callBackInterval?2:config.callBackInterval)}}}).call(this)}).call(this,void 0!==__webpack_require__.g?__webpack_require__.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./qbConfig":253,fs:32,os:139}]},{},[254])(254)},module.exports=f()},"./node_modules/react/cjs/react-jsx-runtime.production.min.js":(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";/**
|
|
25
25
|
* @license React
|
|
26
26
|
* react-jsx-runtime.production.min.js
|
|
27
27
|
*
|
|
@@ -30,4 +30,4 @@ object-assign
|
|
|
30
30
|
* This source code is licensed under the MIT license found in the
|
|
31
31
|
* LICENSE file in the root directory of this source tree.
|
|
32
32
|
*/var f=__webpack_require__("./node_modules/react/index.js"),k=Symbol.for("react.element"),l=Symbol.for("react.fragment"),m=Object.prototype.hasOwnProperty,n=f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,p={key:!0,ref:!0,__self:!0,__source:!0};function q(c,a,g){var b,d={},e=null,h=null;for(b in void 0!==g&&(e=""+g),void 0!==a.key&&(e=""+a.key),void 0!==a.ref&&(h=a.ref),a)m.call(a,b)&&!p.hasOwnProperty(b)&&(d[b]=a[b]);if(c&&c.defaultProps)for(b in a=c.defaultProps)void 0===d[b]&&(d[b]=a[b]);return{$$typeof:k,type:c,key:e,ref:h,props:d,_owner:n.current}}exports.Fragment=l,exports.jsx=q,exports.jsxs=q},"./node_modules/react/jsx-runtime.js":(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";module.exports=__webpack_require__("./node_modules/react/cjs/react-jsx-runtime.production.min.js")}}]);
|
|
33
|
-
//# sourceMappingURL=703.
|
|
33
|
+
//# sourceMappingURL=703.f12f2e71.iframe.bundle.js.map
|