text: (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.REX=f()}})(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){module.exports={name:"REX HMI",version:"2.50.7-9228",created:"2018-03-28 17:56"}},{}],2:[function(require,module,exports){module.exports.Init=require("./src/index.js");module.exports.UTIL={};module.exports.UTIL.Logger=require("./src/utils/Logger.js");module.exports.WS={Group:require("./src/group-management/Group.js"),Item:require("./src/group-management/RWItem.js"),Trend:require("./src/group-management/Trend.js")};module.exports.WS.Client=require("./src/ws-client/Client.js");module.exports.Watch={};module.exports.Watch.Engine=require("./src/webwatch/Engine.js");module.exports.HMI=require("./src/hmi.js");module.exports.WebBuDi=require("./src/webbudi/WebBuDi.js");module.exports.WebWatch=require("./src/webwatch/Engine.js");module.exports.UI={COLORS:require("./src/utils/Constants.js").COLORS,SVG:{SVGManager:require("./src/ui/svg/SVGManager.js"),Component:require("./src/ui/svg/SVGComponent.js"),HTMLComponent:require("./src/ui/svg/HTMLComponent"),Modules:{HMIConfig:require("./src/ui/svg/HMIConfig.js"),Trend:require("./src/ui/svg/SVGGraph.js"),TRND:require("./src/ui/svg/TRND.js")}}};module.exports.HELPERS=require("./src/utils/utils.js");module.exports.VERSION=require("./build-version.js")},{"./build-version.js":1,"./src/group-management/Group.js":40,"./src/group-management/RWItem.js":43,"./src/group-management/Trend.js":44,"./src/hmi.js":46,"./src/index.js":47,"./src/ui/svg/HMIConfig.js":55,"./src/ui/svg/HTMLComponent":56,"./src/ui/svg/SVGComponent.js":57,"./src/ui/svg/SVGGraph.js":58,"./src/ui/svg/SVGManager.js":59,"./src/ui/svg/TRND.js":60,"./src/utils/Constants.js":61,"./src/utils/Logger.js":65,"./src/utils/utils.js":67,"./src/webbudi/WebBuDi.js":71,"./src/webwatch/Engine.js":84,"./src/ws-client/Client.js":91}],3:[function(require,module,exports){(function(global){"use strict";function compare(a,b){if(a===b){return 0}var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i<len;++i){if(a[i]!==b[i]){x=a[i];y=b[i];break}}if(x<y){return-1}if(y<x){return 1}return 0}function isBuffer(b){if(global.Buffer&&typeof global.Buffer.isBuffer==="function"){return global.Buffer.isBuffer(b)}return!!(b!=null&&b._isBuffer)}var util=require("util/");var hasOwn=Object.prototype.hasOwnProperty;var pSlice=Array.prototype.slice;var functionsHaveNames=function(){return function foo(){}.name==="foo"}();function pToString(obj){return Object.prototype.toString.call(obj)}function isView(arrbuf){if(isBuffer(arrbuf)){return false}if(typeof global.ArrayBuffer!=="function"){return false}if(typeof ArrayBuffer.isView==="function"){return ArrayBuffer.isView(arrbuf)}if(!arrbuf){return false}if(arrbuf instanceof DataView){return true}if(arrbuf.buffer&&arrbuf.buffer instanceof ArrayBuffer){return true}return false}var assert=module.exports=ok;var regex=/\s*function\s+([^\(\s]*)\s*/;function getName(func){if(!util.isFunction(func)){return}if(functionsHaveNames){return func.name}var str=func.toString();var match=str.match(regex);return match&&match[1]}assert.AssertionError=function AssertionError(options){this.name="AssertionError";this.actual=options.actual;this.expected=options.expected;this.operator=options.operator;if(options.message){this.message=options.message;this.generatedMessage=false}else{this.message=getMessage(this);this.generatedMessage=true}var stackStartFunction=options.stackStartFunction||fail;if(Error.captureStackTrace){Error.captureStackTrace(this,stackStartFunction)}else{var err=new Error;if(err.stack){var out=err.stack;var fn_name=getName(stackStartFunction);var idx=out.indexOf("\n"+fn_name);if(idx>=0){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}};util.inherits(assert.AssertionError,Error);function truncate(s,n){if(typeof s==="string"){return s.length<n?s:s.slice(0,n)}else{return s}}function inspect(something){if(functionsHaveNames||!util.isFunction(something)){return util.inspect(something)}var rawname=getName(something);var name=rawname?": "+rawname:"";return"[Function"+name+"]"}function getMessage(self){return truncate(inspect(self.actual),128)+" "+self.operator+" "+truncate(inspect(self.expected),128)}function fail(actual,expected,message,operator,stackStartFunction){throw new assert.AssertionError({message:message,actual:actual,expected:expected,operator:operator,stackStartFunction:stackStartFunction})}assert.fail=fail;function ok(value,message){if(!value)fail(value,true,message,"==",assert.ok)}assert.ok=ok;assert.equal=function equal(actual,expected,message){if(actual!=expected)fail(actual,expected,message,"==",assert.equal)};assert.notEqual=function notEqual(actual,expected,message){if(actual==expected){fail(actual,expected,message,"!=",assert.notEqual)}};assert.deepEqual=function deepEqual(actual,expected,message){if(!_deepEqual(actual,expected,false)){fail(actual,expected,message,"deepEqual",assert.deepEqual)}};assert.deepStrictEqual=function deepStrictEqual(actual,expected,message){if(!_deepEqual(actual,expected,true)){fail(actual,expected,message,"deepStrictEqual",assert.deepStrictEqual)}};function _deepEqual(actual,expected,strict,memos){if(actual===expected){return true}else if(isBuffer(actual)&&isBuffer(expected)){return compare(actual,expected)===0}else if(util.isDate(actual)&&util.isDate(expected)){return actual.getTime()===expected.getTime()}else if(util.isRegExp(actual)&&util.isRegExp(expected)){return actual.source===expected.source&&actual.global===expected.global&&actual.multiline===expected.multiline&&actual.lastIndex===expected.lastIndex&&actual.ignoreCase===expected.ignoreCase}else if((actual===null||typeof actual!=="object")&&(expected===null||typeof expected!=="object")){return strict?actual===expected:actual==expected}else if(isView(actual)&&isView(expected)&&pToString(actual)===pToString(expected)&&!(actual instanceof Float32Array||actual instanceof Float64Array)){return compare(new Uint8Array(actual.buffer),new Uint8Array(expected.buffer))===0}else if(isBuffer(actual)!==isBuffer(expected)){return false}else{memos=memos||{actual:[],expected:[]};var actualIndex=memos.actual.indexOf(actual);if(actualIndex!==-1){if(actualIndex===memos.expected.indexOf(expected)){return true}}memos.actual.push(actual);memos.expected.push(expected);return objEquiv(actual,expected,strict,memos)}}function isArguments(object){return Object.prototype.toString.call(object)=="[object Arguments]"}function objEquiv(a,b,strict,actualVisitedObjects){if(a===null||a===undefined||b===null||b===undefined)return false;if(util.isPrimitive(a)||util.isPrimitive(b))return a===b;if(strict&&Object.getPrototypeOf(a)!==Object.getPrototypeOf(b))return false;var aIsArgs=isArguments(a);var bIsArgs=isArguments(b);if(aIsArgs&&!bIsArgs||!aIsArgs&&bIsArgs)return false;if(aIsArgs){a=pSlice.call(a);b=pSlice.call(b);return _deepEqual(a,b,strict)}var ka=objectKeys(a);var kb=objectKeys(b);var key,i;if(ka.length!==kb.length)return false;ka.sort();kb.sort();for(i=ka.length-1;i>=0;i--){if(ka[i]!==kb[i])return false}for(i=ka.length-1;i>=0;i--){key=ka[i];if(!_deepEqual(a[key],b[key],strict,actualVisitedObjects))return false}return true}assert.notDeepEqual=function notDeepEqual(actual,expected,message){if(_deepEqual(actual,expected,false)){fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)}};assert.notDeepStrictEqual=notDeepStrictEqual;function notDeepStrictEqual(actual,expected,message){if(_deepEqual(actual,expected,true)){fail(actual,expected,message,"notDeepStrictEqual",notDeepStrictEqual)}}assert.strictEqual=function strictEqual(actual,expected,message){if(actual!==expected){fail(actual,expected,message,"===",assert.strictEqual)}};assert.notStrictEqual=function notStrictEqual(actual,expected,message){if(actual===expected){fail(actual,expected,message,"!==",assert.notStrictEqual)}};function expectedException(actual,expected){if(!actual||!expected){return false}if(Object.prototype.toString.call(expected)=="[object RegExp]"){return expected.test(actual)}try{if(actual instanceof expected){return true}}catch(e){}if(Error.isPrototypeOf(expected)){return false}return expected.call({},actual)===true}function _tryBlock(block){var error;try{block()}catch(e){error=e}return error}function _throws(shouldThrow,block,expected,message){var actual;if(typeof block!=="function"){throw new TypeError('"block" argument must be a function')}if(typeof expected==="string"){message=expected;expected=null}actual=_tryBlock(block);message=(expected&&expected.name?" ("+expected.name+").":".")+(message?" "+message:".");if(shouldThrow&&!actual){fail(actual,expected,"Missing expected exception"+message)}var userProvidedMessage=typeof message==="string";var isUnwantedException=!shouldThrow&&util.isError(actual);var isUnexpectedException=!shouldThrow&&actual&&!expected;if(isUnwantedException&&userProvidedMessage&&expectedException(actual,expected)||isUnexpectedException){fail(actual,expected,"Got unwanted exception"+message)}if(shouldThrow&&actual&&expected&&!expectedException(actual,expected)||!shouldThrow&&actual){throw actual}}assert.throws=function(block,error,message){_throws(true,block,error,message)};assert.doesNotThrow=function(block,error,message){_throws(false,block,error,message)};assert.ifError=function(err){if(err)throw err};var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj){if(hasOwn.call(obj,key))keys.push(key)}return keys}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"util/":38}],4:[function(require,module,exports){"use strict";exports.byteLength=byteLength;exports.toByteArray=toByteArray;exports.fromByteArray=fromByteArray;var lookup=[];var revLookup=[];var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;var code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var i=0,len=code.length;i<len;++i){lookup[i]=code[i];revLookup[code.charCodeAt(i)]=i}revLookup["-".charCodeAt(0)]=62;revLookup["_".charCodeAt(0)]=63;function placeHoldersCount(b64){var len=b64.length;if(len%4>0){throw new Error("Invalid string. Length must be a multiple of 4")}return b64[len-2]==="="?2:b64[len-1]==="="?1:0}function byteLength(b64){return b64.length*3/4-placeHoldersCount(b64)}function toByteArray(b64){var i,j,l,tmp,placeHolders,arr;var len=b64.length;placeHolders=placeHoldersCount(b64);arr=new Arr(len*3/4-placeHolders);l=placeHolders>0?len-4:len;var L=0;for(i=0,j=0;i<l;i+=4,j+=3){tmp=revLookup[b64.charCodeAt(i)]<<18|revLookup[b64.charCodeAt(i+1)]<<12|revLookup[b64.charCodeAt(i+2)]<<6|revLookup[b64.charCodeAt(i+3)];arr[L++]=tmp>>16&255;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}if(placeHolders===2){tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4;arr[L++]=tmp&255}else if(placeHolders===1){tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}return arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[num&63]}function encodeChunk(uint8,start,end){var tmp;var output=[];for(var i=start;i<end;i+=3){tmp=(uint8[i]<<16)+(uint8[i+1]<<8)+uint8[i+2];output.push(tripletToBase64(tmp))}return output.join("")}function fromByteArray(uint8){var tmp;var len=uint8.length;var extraBytes=len%3;var output="";var parts=[];var maxChunkLength=16383;for(var i=0,len2=len-extraBytes;i<len2;i+=maxChunkLength){parts.push(encodeChunk(uint8,i,i+maxChunkLength>len2?len2:i+maxChunkLength))}if(extraBytes===1){tmp=uint8[len-1];output+=lookup[tmp>>2];output+=lookup[tmp<<4&63];output+="=="}else if(extraBytes===2){tmp=(uint8[len-2]<<8)+uint8[len-1];output+=lookup[tmp>>10];output+=lookup[tmp>>4&63];output+=lookup[tmp<<2&63];output+="="}parts.push(output);return parts.join("")}},{}],5:[function(require,module,exports){},{}],6:[function(require,module,exports){arguments[4][5][0].apply(exports,arguments)},{dup:5}],7:[function(require,module,exports){(function(global){"use strict";var buffer=require("buffer");var Buffer=buffer.Buffer;var SlowBuffer=buffer.SlowBuffer;var MAX_LEN=buffer.kMaxLength||2147483647;exports.alloc=function alloc(size,fill,encoding){if(typeof Buffer.alloc==="function"){return Buffer.alloc(size,fill,encoding)}if(typeof encoding==="number"){throw new TypeError("encoding must not be number")}if(typeof size!=="number"){throw new TypeError("size must be a number")}if(size>MAX_LEN){throw new RangeError("size is too large")}var enc=encoding;var _fill=fill;if(_fill===undefined){enc=undefined;_fill=0}var buf=new Buffer(size);if(typeof _fill==="string"){var fillBuf=new Buffer(_fill,enc);var flen=fillBuf.length;var i=-1;while(++i<size){buf[i]=fillBuf[i%flen]}}else{buf.fill(_fill)}return buf};exports.allocUnsafe=function allocUnsafe(size){if(typeof Buffer.allocUnsafe==="function"){return Buffer.allocUnsafe(size)}if(typeof size!=="number"){throw new TypeError("size must be a number")}if(size>MAX_LEN){throw new RangeError("size is too large")}return new Buffer(size)};exports.from=function from(value,encodingOrOffset,length){if(typeof Buffer.from==="function"&&(!global.Uint8Array||Uint8Array.from!==Buffer.from)){return Buffer.from(value,encodingOrOffset,length)}if(typeof value==="number"){throw new TypeError('"value" argument must not be a number')}if(typeof value==="string"){return new Buffer(value,encodingOrOffset)}if(typeof ArrayBuffer!=="undefined"&&value instanceof ArrayBuffer){var offset=encodingOrOffset;if(arguments.length===1){return new Buffer(value)}if(typeof offset==="undefined"){offset=0}var len=length;if(typeof len==="undefined"){len=value.byteLength-offset}if(offset>=value.byteLength){throw new RangeError("'offset' is out of bounds")}if(len>value.byteLength-offset){throw new RangeError("'length' is out of bounds")}return new Buffer(value.slice(offset,offset+len))}if(Buffer.isBuffer(value)){var out=new Buffer(value.length);value.copy(out,0,0,value.length);return out}if(value){if(Array.isArray(value)||typeof ArrayBuffer!=="undefined"&&value.buffer instanceof ArrayBuffer||"length"in value){return new Buffer(value)}if(value.type==="Buffer"&&Array.isArray(value.data)){return new Buffer(value.data)}}throw new TypeError("First argument must be a string, Buffer, "+"ArrayBuffer, Array, or array-like object.")};exports.allocUnsafeSlow=function allocUnsafeSlow(size){if(typeof Buffer.allocUnsafeSlow==="function"){return Buffer.allocUnsafeSlow(size)}if(typeof size!=="number"){throw new TypeError("size must be a number")}if(size>=MAX_LEN){throw new RangeError("size is too large")}return new SlowBuffer(size)}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{buffer:8}],8:[function(require,module,exports){"use strict";var base64=require("base64-js");var ieee754=require("ieee754");exports.Buffer=Buffer;exports.SlowBuffer=SlowBuffer;exports.INSPECT_MAX_BYTES=50;var K_MAX_LENGTH=2147483647;exports.kMaxLength=K_MAX_LENGTH;Buffer.TYPED_ARRAY_SUPPORT=typedArraySupport();if(!Buffer.TYPED_ARRAY_SUPPORT&&typeof console!=="undefined"&&typeof console.error==="function"){console.error("This browser lacks typed array (Uint8Array) support which is required by "+"`buffer` v5.x. Use `buffer` v4.x if you require old browser support.")}function typedArraySupport(){try{var arr=new Uint8Array(1);arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}};return arr.foo()===42}catch(e){return false}}function createBuffer(length){if(length>K_MAX_LENGTH){throw new RangeError("Invalid typed array length")}var buf=new Uint8Array(length);buf.__proto__=Buffer.prototype;return buf}function Buffer(arg,encodingOrOffset,length){if(typeof arg==="number"){if(typeof encodingOrOffset==="string"){throw new Error("If encoding is specified then the first argument must be a string")}return allocUnsafe(arg)}return from(arg,encodingOrOffset,length)}if(typeof Symbol!=="undefined"&&Symbol.species&&Buffer[Symbol.species]===Buffer){Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:true,enumerable:false,writable:false})}Buffer.poolSize=8192;function from(value,encodingOrOffset,length){if(typeof value==="number"){throw new TypeError('"value" argument must not be a number')}if(isArrayBuffer(value)){return fromArrayBuffer(value,encodingOrOffset,length)}if(typeof value==="string"){return fromString(value,encodingOrOffset)}return fromObject(value)}Buffer.from=function(value,encodingOrOffset,length){return from(value,encodingOrOffset,length)};Buffer.prototype.__proto__=Uint8Array.prototype;Buffer.__proto__=Uint8Array;function assertSize(size){if(typeof size!=="number"){throw new TypeError('"size" argument must be a number')}else if(size<0){throw new RangeError('"size" argument must not be negative')}}function alloc(size,fill,encoding){assertSize(size);if(size<=0){return createBuffer(size)}if(fill!==undefined){return typeof encoding==="string"?createBuffer(size).fill(fill,encoding):createBuffer(size).fill(fill)}return createBuffer(size)}Buffer.alloc=function(size,fill,encoding){return alloc(size,fill,encoding)};function allocUnsafe(size){assertSize(size);return createBuffer(size<0?0:checked(size)|0)}Buffer.allocUnsafe=function(size){return allocUnsafe(size)};Buffer.allocUnsafeSlow=function(size){return allocUnsafe(size)};function fromString(string,encoding){if(typeof encoding!=="string"||encoding===""){encoding="utf8"}if(!Buffer.isEncoding(encoding)){throw new TypeError('"encoding" must be a valid string encoding')}var length=byteLength(string,encoding)|0;var buf=createBuffer(length);var actual=buf.write(string,encoding);if(actual!==length){buf=buf.slice(0,actual)}return buf}function fromArrayLike(array){var length=array.length<0?0:checked(array.length)|0;var buf=createBuffer(length);for(var i=0;i<length;i+=1){buf[i]=array[i]&255}return buf}function fromArrayBuffer(array,byteOffset,length){if(byteOffset<0||array.byteLength<byteOffset){throw new RangeError("'offset' is out of bounds")}if(array.byteLength<byteOffset+(length||0)){throw new RangeError("'length' is out of bounds")}var buf;if(byteOffset===undefined&&length===undefined){buf=new Uint8Array(array)}else if(length===undefined){buf=new Uint8Array(array,byteOffset)}else{buf=new Uint8Array(array,byteOffset,length)}buf.__proto__=Buffer.prototype;return buf}function fromObject(obj){if(Buffer.isBuffer(obj)){var len=checked(obj.length)|0;var buf=createBuffer(len);if(buf.length===0){return buf}obj.copy(buf,0,0,len);return buf}if(obj){if(isArrayBufferView(obj)||"length"in obj){if(typeof obj.length!=="number"||numberIsNaN(obj.length)){return createBuffer(0)}return fromArrayLike(obj)}if(obj.type==="Buffer"&&Array.isArray(obj.data)){return fromArrayLike(obj.data)}}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}function checked(length){if(length>=K_MAX_LENGTH){throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+K_MAX_LENGTH.toString(16)+" bytes")}return length|0}function SlowBuffer(length){if(+length!=length){length=0}return Buffer.alloc(+length)}Buffer.isBuffer=function isBuffer(b){return b!=null&&b._isBuffer===true};Buffer.compare=function compare(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b)){throw new TypeError("Arguments must be Buffers")}if(a===b)return 0;var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i<len;++i){if(a[i]!==b[i]){x=a[i];y=b[i];break}}if(x<y)return-1;if(y<x)return 1;return 0};Buffer.isEncoding=function isEncoding(encoding){switch(String(encoding).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return true;default:return false}};Buffer.concat=function concat(list,length){if(!Array.isArray(list)){throw new TypeError('"list" argument must be an Array of Buffers')}if(list.length===0){return Buffer.alloc(0)}var i;if(length===undefined){length=0;for(i=0;i<list.length;++i){length+=list[i].length}}var buffer=Buffer.allocUnsafe(length);var pos=0;for(i=0;i<list.length;++i){var buf=list[i];if(!Buffer.isBuffer(buf)){throw new TypeError('"list" argument must be an Array of Buffers')}buf.copy(buffer,pos);pos+=buf.length}return buffer};function byteLength(string,encoding){if(Buffer.isBuffer(string)){return string.length}if(isArrayBufferView(string)||isArrayBuffer(string)){return string.byteLength}if(typeof string!=="string"){string=""+string}var len=string.length;if(len===0)return 0;var loweredCase=false;for(;;){switch(encoding){case"ascii":case"latin1":case"binary":return len;case"utf8":case"utf-8":case undefined:return utf8ToBytes(string).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return len*2;case"hex":return len>>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase();loweredCase=true}}}Buffer.byteLength=byteLength;function slowToString(encoding,start,end){var loweredCase=false;if(start===undefined||start<0){start=0}if(start>this.length){return""}if(end===undefined||end>this.length){end=this.length}if(end<=0){return""}end>>>=0;start>>>=0;if(end<=start){return""}if(!encoding)encoding="utf8";while(true){switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}}Buffer.prototype._isBuffer=true;function swap(b,n,m){var i=b[n];b[n]=b[m];b[m]=i}Buffer.prototype.swap16=function swap16(){var len=this.length;if(len%2!==0){throw new RangeError("Buffer size must be a multiple of 16-bits")}for(var i=0;i<len;i+=2){swap(this,i,i+1)}return this};Buffer.prototype.swap32=function swap32(){var len=this.length;if(len%4!==0){throw new RangeError("Buffer size must be a multiple of 32-bits")}for(var i=0;i<len;i+=4){swap(this,i,i+3);swap(this,i+1,i+2)}return this};Buffer.prototype.swap64=function swap64(){var len=this.length;if(len%8!==0){throw new RangeError("Buffer size must be a multiple of 64-bits")}for(var i=0;i<len;i+=8){swap(this,i,i+7);swap(this,i+1,i+6);swap(this,i+2,i+5);swap(this,i+3,i+4)}return this};Buffer.prototype.toString=function toString(){var length=this.length;if(length===0)return"";if(arguments.length===0)return utf8Slice(this,0,length);return slowToString.apply(this,arguments)};Buffer.prototype.equals=function equals(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");if(this===b)return true;return Buffer.compare(this,b)===0};Buffer.prototype.inspect=function inspect(){var str="";var max=exports.INSPECT_MAX_BYTES;if(this.length>0){str=this.toString("hex",0,max).match(/.{2}/g).join(" ");if(this.length>max)str+=" ... "}return"<Buffer "+str+">"};Buffer.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(!Buffer.isBuffer(target)){throw new TypeError("Argument must be a Buffer")}if(start===undefined){start=0}if(end===undefined){end=target?target.length:0}if(thisStart===undefined){thisStart=0}if(thisEnd===undefined){thisEnd=this.length}if(start<0||end>target.length||thisStart<0||thisEnd>this.length){throw new RangeError("out of range index")}if(thisStart>=thisEnd&&start>=end){return 0}if(thisStart>=thisEnd){return-1}if(start>=end){return 1}start>>>=0;end>>>=0;thisStart>>>=0;thisEnd>>>=0;if(this===target)return 0;var x=thisEnd-thisStart;var y=end-start;var len=Math.min(x,y);var thisCopy=this.slice(thisStart,thisEnd);var targetCopy=target.slice(start,end);for(var i=0;i<len;++i){if(thisCopy[i]!==targetCopy[i]){x=thisCopy[i];y=targetCopy[i];break}}if(x<y)return-1;if(y<x)return 1;return 0};function bidirectionalIndexOf(buffer,val,byteOffset,encoding,dir){if(buffer.length===0)return-1;if(typeof byteOffset==="string"){encoding=byteOffset;byteOffset=0}else if(byteOffset>2147483647){byteOffset=2147483647}else if(byteOffset<-2147483648){byteOffset=-2147483648}byteOffset=+byteOffset;if(numberIsNaN(byteOffset)){byteOffset=dir?0:buffer.length-1}if(byteOffset<0)byteOffset=buffer.length+byteOffset;if(byteOffset>=buffer.length){if(dir)return-1;else byteOffset=buffer.length-1}else if(byteOffset<0){if(dir)byteOffset=0;else return-1}if(typeof val==="string"){val=Buffer.from(val,encoding)}if(Buffer.isBuffer(val)){if(val.length===0){return-1}return arrayIndexOf(buffer,val,byteOffset,encoding,dir)}else if(typeof val==="number"){val=val&255;if(typeof Uint8Array.prototype.indexOf==="function"){if(dir){return Uint8Array.prototype.indexOf.call(buffer,val,byteOffset)}else{return Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset)}}return arrayIndexOf(buffer,[val],byteOffset,encoding,dir)}throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){var indexSize=1;var arrLength=arr.length;var valLength=val.length;if(encoding!==undefined){encoding=String(encoding).toLowerCase();if(encoding==="ucs2"||encoding==="ucs-2"||encoding==="utf16le"||encoding==="utf-16le"){if(arr.length<2||val.length<2){return-1}indexSize=2;arrLength/=2;valLength/=2;byteOffset/=2}}function read(buf,i){if(indexSize===1){return buf[i]}else{return buf.readUInt16BE(i*indexSize)}}var i;if(dir){var foundIndex=-1;for(i=byteOffset;i<arrLength;i++){if(read(arr,i)===read(val,foundIndex===-1?0:i-foundIndex)){if(foundIndex===-1)foundIndex=i;if(i-foundIndex+1===valLength)return foundIndex*indexSize}else{if(foundIndex!==-1)i-=i-foundIndex;foundIndex=-1}}}else{if(byteOffset+valLength>arrLength)byteOffset=arrLength-valLength;for(i=byteOffset;i>=0;i--){var found=true;for(var j=0;j<valLength;j++){if(read(arr,i+j)!==read(val,j)){found=false;break}}if(found)return i}}return-1}Buffer.prototype.includes=function includes(val,byteOffset,encoding){return this.indexOf(val,byteOffset,encoding)!==-1};Buffer.prototype.indexOf=function indexOf(val,byteOffset,encoding){return bidirectionalIndexOf(this,val,byteOffset,encoding,true)};Buffer.prototype.lastIndexOf=function lastIndexOf(val,byteOffset,encoding){return bidirectionalIndexOf(this,val,byteOffset,encoding,false)};function hexWrite(buf,string,offset,length){offset=Number(offset)||0;var remaining=buf.length-offset;if(!length){length=remaining}else{length=Number(length);if(length>remaining){length=remaining}}var strLen=string.length;if(strLen%2!==0)throw new TypeError("Invalid hex string");if(length>strLen/2){length=strLen/2}for(var i=0;i<length;++i){var parsed=parseInt(string.substr(i*2,2),16);if(numberIsNaN(parsed))return i;buf[offset+i]=parsed}return i}function utf8Write(buf,string,offset,length){return blitBuffer(utf8ToBytes(string,buf.length-offset),buf,offset,length)}function asciiWrite(buf,string,offset,length){return blitBuffer(asciiToBytes(string),buf,offset,length)}function latin1Write(buf,string,offset,length){return asciiWrite(buf,string,offset,length)}function base64Write(buf,string,offset,length){return blitBuffer(base64ToBytes(string),buf,offset,length)}function ucs2Write(buf,string,offset,length){return blitBuffer(utf16leToBytes(string,buf.length-offset),buf,offset,length)}Buffer.prototype.write=function write(string,offset,length,encoding){if(offset===undefined){encoding="utf8";length=this.length;offset=0}else if(length===undefined&&typeof offset==="string"){encoding=offset;length=this.length;offset=0}else if(isFinite(offset)){offset=offset>>>0;if(isFinite(length)){length=length>>>0;if(encoding===undefined)encoding="utf8"}else{encoding=length;length=undefined}}else{throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported")}var remaining=this.length-offset;if(length===undefined||length>remaining)length=remaining;if(string.length>0&&(length<0||offset<0)||offset>this.length){throw new RangeError("Attempt to write outside buffer bounds")}if(!encoding)encoding="utf8";var loweredCase=false;for(;;){switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return latin1Write(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase();loweredCase=true}}};Buffer.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);var res=[];var i=start;while(i<end){var firstByte=buf[i];var codePoint=null;var bytesPerSequence=firstByte>239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte<128){codePoint=firstByte}break;case 2:secondByte=buf[i+1];if((secondByte&192)===128){tempCodePoint=(firstByte&31)<<6|secondByte&63;if(tempCodePoint>127){codePoint=tempCodePoint}}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&192)===128&&(thirdByte&192)===128){tempCodePoint=(firstByte&15)<<12|(secondByte&63)<<6|thirdByte&63;if(tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)){codePoint=tempCodePoint}}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+3];if((secondByte&192)===128&&(thirdByte&192)===128&&(fourthByte&192)===128){tempCodePoint=(firstByte&15)<<18|(secondByte&63)<<12|(thirdByte&63)<<6|fourthByte&63;if(tempCodePoint>65535&&tempCodePoint<1114112){codePoint=tempCodePoint}}}}if(codePoint===null){codePoint=65533;bytesPerSequence=1}else if(codePoint>65535){codePoint-=65536;res.push(codePoint>>>10&1023|55296);codePoint=56320|codePoint&1023}res.push(codePoint);i+=bytesPerSequence}return decodeCodePointsArray(res)}var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH){return String.fromCharCode.apply(String,codePoints)}var res="";var i=0;while(i<len){res+=String.fromCharCode.apply(String,codePoints.slice(i,i+=MAX_ARGUMENTS_LENGTH))}return res}function asciiSlice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;i<end;++i){ret+=String.fromCharCode(buf[i]&127)}return ret}function latin1Slice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;i<end;++i){ret+=String.fromCharCode(buf[i])}return ret}function hexSlice(buf,start,end){var len=buf.length;if(!start||start<0)start=0;if(!end||end<0||end>len)end=len;var out="";for(var i=start;i<end;++i){out+=toHex(buf[i])}return out}function utf16leSlice(buf,start,end){var bytes=buf.slice(start,end);var res="";for(var i=0;i<bytes.length;i+=2){res+=String.fromCharCode(bytes[i]+bytes[i+1]*256)}return res}Buffer.prototype.slice=function slice(start,end){var len=this.length;start=~~start;end=end===undefined?len:~~end;if(start<0){start+=len;if(start<0)start=0}else if(start>len){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(end<start)end=start;var newBuf=this.subarray(start,end);newBuf.__proto__=Buffer.prototype;return newBuf};function checkOffset(offset,ext,length){if(offset%1!==0||offset<0)throw new RangeError("offset is not uint");if(offset+ext>length)throw new RangeError("Trying to access beyond buffer length")}Buffer.prototype.readUIntLE=function readUIntLE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i<byteLength&&(mul*=256)){val+=this[offset+i]*mul}return val};Buffer.prototype.readUIntBE=function readUIntBE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert){checkOffset(offset,byteLength,this.length)}var val=this[offset+--byteLength];var mul=1;while(byteLength>0&&(mul*=256)){val+=this[offset+--byteLength]*mul}return val};Buffer.prototype.readUInt8=function readUInt8(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer.prototype.readIntLE=function readIntLE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i<byteLength&&(mul*=256)){val+=this[offset+i]*mul}mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readIntBE=function readIntBE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var i=byteLength;var mul=1;var val=this[offset+--i];while(i>0&&(mul*=256)){val+=this[offset+--i]*mul}mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readInt8=function readInt8(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer.prototype.readInt16LE=function readInt16LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt16BE=function readInt16BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt32LE=function readInt32LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer.prototype.readInt32BE=function readInt32BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer.prototype.readFloatLE=function readFloatLE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer.prototype.readFloatBE=function readFloatBE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||value<min)throw new RangeError('"value" argument is out of bounds');if(offset+ext>buf.length)throw new RangeError("Index out of range")}Buffer.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var mul=1;var i=0;this[offset]=value&255;while(++i<byteLength&&(mul*=256)){this[offset+i]=value/mul&255}return offset+byteLength};Buffer.prototype.writeUIntBE=function writeUIntBE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var i=byteLength-1;var mul=1;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){this[offset+i]=value/mul&255}return offset+byteLength};Buffer.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,255,0);this[offset]=value&255;return offset+1};Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);this[offset]=value&255;this[offset+1]=value>>>8;return offset+2};Buffer.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);this[offset]=value>>>8;this[offset+1]=value&255;return offset+2};Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&255;return offset+4};Buffer.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255;return offset+4};Buffer.prototype.writeIntLE=function writeIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0;var mul=1;var sub=0;this[offset]=value&255;while(++i<byteLength&&(mul*=256)){if(value<0&&sub===0&&this[offset+i-1]!==0){sub=1}this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength};Buffer.prototype.writeIntBE=function writeIntBE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1;var mul=1;var sub=0;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){if(value<0&&sub===0&&this[offset+i+1]!==0){sub=1}this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength};Buffer.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(value<0)value=255+value+1;this[offset]=value&255;return offset+1};Buffer.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);this[offset]=value&255;this[offset+1]=value>>>8;return offset+2};Buffer.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);this[offset]=value>>>8;this[offset+1]=value&255;return offset+2};Buffer.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);this[offset]=value&255;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24;return offset+4};Buffer.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255;return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38)}ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkIEEE754(buf,value,offset,8,1.7976931348623157e308,-1.7976931348623157e308)}ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer.prototype.copy=function copy(target,targetStart,start,end){if(!start)start=0;if(!end&&end!==0)end=this.length;if(targetStart>=target.length)targetStart=target.length;if(!targetStart)targetStart=0;if(end>0&&end<start)end=start;if(end===start)return 0;if(target.length===0||this.length===0)return 0;if(targetStart<0){throw new RangeError("targetStart out of bounds")}if(start<0||start>=this.length)throw new RangeError("sourceStart out of bounds");if(end<0)throw new RangeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-targetStart<end-start){end=target.length-targetStart+start}var len=end-start;var i;if(this===target&&start<targetStart&&targetStart<end){for(i=len-1;i>=0;--i){target[i+targetStart]=this[i+start]}}else if(len<1e3){for(i=0;i<len;++i){target[i+targetStart]=this[i+start]}}else{Uint8Array.prototype.set.call(target,this.subarray(start,start+len),targetStart)}return len};Buffer.prototype.fill=function fill(val,start,end,encoding){if(typeof val==="string"){if(typeof start==="string"){encoding=start;start=0;end=this.length}else if(typeof end==="string"){encoding=end;end=this.length}if(val.length===1){var code=val.charCodeAt(0);if(code<256){val=code}}if(encoding!==undefined&&typeof encoding!=="string"){throw new TypeError("encoding must be a string")}if(typeof encoding==="string"&&!Buffer.isEncoding(encoding)){throw new TypeError("Unknown encoding: "+encoding)}}else if(typeof val==="number"){val=val&255}if(start<0||this.length<start||this.length<end){throw new RangeError("Out of range index")}if(end<=start){return this}start=start>>>0;end=end===undefined?this.length:end>>>0;if(!val)val=0;var i;if(typeof val==="number"){for(i=start;i<end;++i){this[i]=val}}else{var bytes=Buffer.isBuffer(val)?val:new Buffer(val,encoding);var len=bytes.length;for(i=0;i<end-start;++i){this[i+start]=bytes[i%len]}}return this};var INVALID_BASE64_RE=/[^+/0-9A-Za-z-_]/g;function base64clean(str){str=str.trim().replace(INVALID_BASE64_RE,"");if(str.length<2)return"";while(str.length%4!==0){str=str+"="}return str}function toHex(n){if(n<16)return"0"+n.toString(16);return n.toString(16)}function utf8ToBytes(string,units){units=units||Infinity;var codePoint;var length=string.length;var leadSurrogate=null;var bytes=[];for(var i=0;i<length;++i){codePoint=string.charCodeAt(i);if(codePoint>55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else if(leadSurrogate){if((units-=3)>-1)bytes.push(239,191,189)}leadSurrogate=null;if(codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<1114112){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else{throw new Error("Invalid code point")}}return bytes}function asciiToBytes(str){var byteArray=[];for(var i=0;i<str.length;++i){byteArray.push(str.charCodeAt(i)&255)}return byteArray}function utf16leToBytes(str,units){var c,hi,lo;var byteArray=[];for(var i=0;i<str.length;++i){if((units-=2)<0)break;c=str.charCodeAt(i);hi=c>>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i<length;++i){if(i+offset>=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function isArrayBuffer(obj){return obj instanceof ArrayBuffer||obj!=null&&obj.constructor!=null&&obj.constructor.name==="ArrayBuffer"&&typeof obj.byteLength==="number"}function isArrayBufferView(obj){return typeof ArrayBuffer.isView==="function"&&ArrayBuffer.isView(obj)}function numberIsNaN(obj){return obj!==obj}},{"base64-js":4,ieee754:12}],9:[function(require,module,exports){(function(Buffer,process){var VERSION="1.8.10";var LOG_VERSION=0;var xxx=function xxx(s){var args=["XX"+"X: "+s].concat(Array.prototype.slice.call(arguments,1));console.error.apply(this,args)};var xxx=function xxx(){};var runtimeEnv;if(typeof process!=="undefined"&&process.versions){if(process.versions.nw){runtimeEnv="nw"}else if(process.versions.node){runtimeEnv="node"}}if(!runtimeEnv&&typeof window!=="undefined"&&window.window===window){runtimeEnv="browser"}if(!runtimeEnv){throw new Error("unknown runtime environment")}var os,fs,dtrace;if(runtimeEnv==="browser"){os={hostname:function(){return window.location.host}};fs={};dtrace=null}else{os=require("os");fs=require("fs");try{dtrace=require("dtrace-provider"+"")}catch(e){dtrace=null}}var util=require("util");var assert=require("assert");var EventEmitter=require("events").EventEmitter;var stream=require("stream");try{var safeJsonStringify=require("safe-json-stringify")}catch(e){safeJsonStringify=null}if(process.env.BUNYAN_TEST_NO_SAFE_JSON_STRINGIFY){safeJsonStringify=null}try{var mv=require("mv"+"")}catch(e){mv=null}try{var sourceMapSupport=require("source-map-support"+"")}catch(_){sourceMapSupport=null}function objCopy(obj){if(obj==null){return obj}else if(Array.isArray(obj)){return obj.slice()}else if(typeof obj==="object"){var copy={};Object.keys(obj).forEach(function(k){copy[k]=obj[k]});return copy}else{return obj}}var format=util.format;if(!format){var inspect=util.inspect;var formatRegExp=/%[sdj%]/g;format=function format(f){if(typeof f!=="string"){var objects=[];for(var i=0;i<arguments.length;i++){objects.push(inspect(arguments[i]))}return objects.join(" ")}var i=1;var args=arguments;var len=args.length;var str=String(f).replace(formatRegExp,function(x){if(i>=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":return fastAndSafeJsonStringify(args[i++]);case"%%":return"%";default:return x}});for(var x=args[i];i<len;x=args[++i]){if(x===null||typeof x!=="object"){str+=" "+x}else{str+=" "+inspect(x)}}return str}}function getCaller3Info(){if(this===undefined){return}var obj={};var saveLimit=Error.stackTraceLimit;var savePrepare=Error.prepareStackTrace;Error.stackTraceLimit=3;Error.prepareStackTrace=function(_,stack){var caller=stack[2];if(sourceMapSupport){caller=sourceMapSupport.wrapCallSite(caller)}obj.file=caller.getFileName();obj.line=caller.getLineNumber();var func=caller.getFunctionName();if(func)obj.func=func};Error.captureStackTrace(this,getCaller3Info);this.stack;Error.stackTraceLimit=saveLimit;Error.prepareStackTrace=savePrepare;return obj}function _indent(s,indent){if(!indent)indent="    ";var lines=s.split(/\r?\n/g);return indent+lines.join("\n"+indent)}function _warn(msg,dedupKey){assert.ok(msg);if(dedupKey){if(_warned[dedupKey]){return}_warned[dedupKey]=true}process.stderr.write(msg+"\n")}function _haveWarned(dedupKey){return _warned[dedupKey]}var _warned={};function ConsoleRawStream(){}ConsoleRawStream.prototype.write=function(rec){if(rec.level<INFO){console.log(rec)}else if(rec.level<WARN){console.info(rec)}else if(rec.level<ERROR){console.warn(rec)}else{console.error(rec)}};var TRACE=10;var DEBUG=20;var INFO=30;var WARN=40;var ERROR=50;var FATAL=60;var levelFromName={trace:TRACE,debug:DEBUG,info:INFO,warn:WARN,error:ERROR,fatal:FATAL};var nameFromLevel={};Object.keys(levelFromName).forEach(function(name){nameFromLevel[levelFromName[name]]=name});var dtp=undefined;var probes=dtrace&&{};function resolveLevel(nameOrNum){var level;var type=typeof nameOrNum;if(type==="string"){level=levelFromName[nameOrNum.toLowerCase()];if(!level){throw new Error(format('unknown level name: "%s"',nameOrNum))}}else if(type!=="number"){throw new TypeError(format("cannot resolve level: invalid arg (%s):",type,nameOrNum))}else if(nameOrNum<0||Math.floor(nameOrNum)!==nameOrNum){throw new TypeError(format("level is not a positive integer: %s",nameOrNum))}else{level=nameOrNum}return level}function isWritable(obj){if(obj instanceof stream.Writable){return true}return typeof obj.write==="function"}function Logger(options,_childOptions,_childSimple){xxx("Logger start:",options);if(!(this instanceof Logger)){return new Logger(options,_childOptions)}var parent;if(_childOptions!==undefined){parent=options;options=_childOptions;if(!(parent instanceof Logger)){throw new TypeError("invalid Logger creation: do not pass a second arg")}}if(!options){throw new TypeError("options (object) is required")}if(!parent){if(!options.name){throw new TypeError("options.name (string) is required")}}else{if(options.name){throw new TypeError("invalid options.name: child cannot set logger name")}}if(options.stream&&options.streams){throw new TypeError('cannot mix "streams" and "stream" options')}if(options.streams&&!Array.isArray(options.streams)){throw new TypeError("invalid options.streams: must be an array")}if(options.serializers&&(typeof options.serializers!=="object"||Array.isArray(options.serializers))){throw new TypeError("invalid options.serializers: must be an object")}EventEmitter.call(this);if(parent&&_childSimple){this._isSimpleChild=true;this._level=parent._level;this.streams=parent.streams;this.serializers=parent.serializers;this.src=parent.src;var fields=this.fields={};var parentFieldNames=Object.keys(parent.fields);for(var i=0;i<parentFieldNames.length;i++){var name=parentFieldNames[i];fields[name]=parent.fields[name]}var names=Object.keys(options);for(var i=0;i<names.length;i++){var name=names[i];fields[name]=options[name]}return}var self=this;if(parent){this._level=parent._level;this.streams=[];for(var i=0;i<parent.streams.length;i++){var s=objCopy(parent.streams[i]);s.closeOnExit=false;this.streams.push(s)}this.serializers=objCopy(parent.serializers);this.src=parent.src;this.fields=objCopy(parent.fields);if(options.level){this.level(options.level)}}else{this._level=Number.POSITIVE_INFINITY;this.streams=[];this.serializers=null;this.src=false;this.fields={}}if(!dtp&&dtrace){dtp=dtrace.createDTraceProvider("bunyan");for(var level in levelFromName){var probe;probes[levelFromName[level]]=probe=dtp.addProbe("log-"+level,"char *");probe.dtp=dtp}dtp.enable()}if(options.stream){self.addStream({type:"stream",stream:options.stream,closeOnExit:false,level:options.level})}else if(options.streams){options.streams.forEach(function(s){self.addStream(s,options.level)})}else if(parent&&options.level){this.level(options.level)}else if(!parent){if(runtimeEnv==="browser"){self.addStream({type:"raw",stream:new ConsoleRawStream,closeOnExit:false,level:options.level})}else{self.addStream({type:"stream",stream:process.stdout,closeOnExit:false,level:options.level})}}if(options.serializers){self.addSerializers(options.serializers)}if(options.src){this.src=true}xxx("Logger: ",self);var fields=objCopy(options);delete fields.stream;delete fields.level;delete fields.streams;delete fields.serializers;delete fields.src;if(this.serializers){this._applySerializers(fields)}if(!fields.hostname&&!self.fields.hostname){fields.hostname=os.hostname()}if(!fields.pid){fields.pid=process.pid}Object.keys(fields).forEach(function(k){self.fields[k]=fields[k]})}util.inherits(Logger,EventEmitter);Logger.prototype.addStream=function addStream(s,defaultLevel){var self=this;if(defaultLevel===null||defaultLevel===undefined){defaultLevel=INFO}s=objCopy(s);if(!s.type){if(s.stream){s.type="stream"}else if(s.path){s.type="file"}}s.raw=s.type==="raw";if(s.level!==undefined){s.level=resolveLevel(s.level)}else{s.level=resolveLevel(defaultLevel)}if(s.level<self._level){self._level=s.level}switch(s.type){case"stream":assert.ok(isWritable(s.stream),'"stream" stream is not writable: '+util.inspect(s.stream));if(!s.closeOnExit){s.closeOnExit=false}break;case"file":if(s.reemitErrorEvents===undefined){s.reemitErrorEvents=true}if(!s.stream){s.stream=fs.createWriteStream(s.path,{flags:"a",encoding:"utf8"});if(!s.closeOnExit){s.closeOnExit=true}}else{if(!s.closeOnExit){s.closeOnExit=false}}break;case"rotating-file":assert.ok(!s.stream,'"rotating-file" stream should not give a "stream"');assert.ok(s.path);assert.ok(mv,'"rotating-file" stream type is not supported: '+'missing "mv" module');s.stream=new RotatingFileStream(s);if(!s.closeOnExit){s.closeOnExit=true}break;case"raw":if(!s.closeOnExit){s.closeOnExit=false}break;default:throw new TypeError('unknown stream type "'+s.type+'"')}if(s.reemitErrorEvents&&typeof s.stream.on==="function"){s.stream.on("error",function onStreamError(err){self.emit("error",err,s)})}self.streams.push(s);delete self.haveNonRawStreams};Logger.prototype.addSerializers=function addSerializers(serializers){var self=this;if(!self.serializers){self.serializers={}}Object.keys(serializers).forEach(function(field){var serializer=serializers[field];if(typeof serializer!=="function"){throw new TypeError(format('invalid serializer for "%s" field: must be a function',field))}else{self.serializers[field]=serializer}})};Logger.prototype.child=function(options,simple){return new this.constructor(this,options||{},simple)};Logger.prototype.reopenFileStreams=function(){var self=this;self.streams.forEach(function(s){if(s.type==="file"){if(s.stream){s.stream.end();s.stream.destroySoon();delete s.stream}s.stream=fs.createWriteStream(s.path,{flags:"a",encoding:"utf8"});s.stream.on("error",function(err){self.emit("error",err,s)})}})};Logger.prototype.level=function level(value){if(value===undefined){return this._level}var newLevel=resolveLevel(value);var len=this.streams.length;for(var i=0;i<len;i++){this.streams[i].level=newLevel}this._level=newLevel};Logger.prototype.levels=function levels(name,value){if(name===undefined){assert.equal(value,undefined);return this.streams.map(function(s){return s.level})}var stream;if(typeof name==="number"){stream=this.streams[name];if(stream===undefined){throw new Error("invalid stream index: "+name)}}else{var len=this.streams.length;for(var i=0;i<len;i++){var s=this.streams[i];if(s.name===name){stream=s;break}}if(!stream){throw new Error(format('no stream with name "%s"',name))}}if(value===undefined){return stream.level}else{var newLevel=resolveLevel(value);stream.level=newLevel;if(newLevel<this._level){this._level=newLevel}}};Logger.prototype._applySerializers=function(fields,excludeFields){var self=this;xxx("_applySerializers: excludeFields",excludeFields);Object.keys(this.serializers).forEach(function(name){if(fields[name]===undefined||excludeFields&&excludeFields[name]){return}xxx('_applySerializers; apply to "%s" key',name);try{fields[name]=self.serializers[name](fields[name])}catch(err){_warn(format('bunyan: ERROR: Exception thrown from the "%s" '+"Bunyan serializer. This should never happen. This is a bug "+"in that serializer function.\n%s",name,err.stack||err));fields[name]=format('(Error in Bunyan log "%s" serializer '+"broke field. See stderr for details.)",name)}})};Logger.prototype._emit=function(rec,noemit){var i;if(this.haveNonRawStreams===undefined){this.haveNonRawStreams=false;for(i=0;i<this.streams.length;i++){if(!this.streams[i].raw){this.haveNonRawStreams=true;break}}}var str;if(noemit||this.haveNonRawStreams){str=fastAndSafeJsonStringify(rec)+"\n"}if(noemit)return str;var level=rec.level;for(i=0;i<this.streams.length;i++){var s=this.streams[i];if(s.level<=level){xxx('writing log rec "%s" to "%s" stream (%d <= %d): %j',rec.msg,s.type,s.level,level,rec);s.stream.write(s.raw?rec:str)}}return str};function mkRecord(log,minLevel,args){var excludeFields,fields,msgArgs;if(args[0]instanceof Error){fields={err:log.serializers&&log.serializers.err?log.serializers.err(args[0]):Logger.stdSerializers.err(args[0])};excludeFields={err:true};if(args.length===1){msgArgs=[fields.err.message]}else{msgArgs=args.slice(1)}}else if(typeof args[0]!=="object"||Array.isArray(args[0])){fields=null;msgArgs=args.slice()}else if(Buffer.isBuffer(args[0])){fields=null;msgArgs=args.slice();msgArgs[0]=util.inspect(msgArgs[0])}else{fields=args[0];if(fields&&args.length===1&&fields.err&&fields.err instanceof Error){msgArgs=[fields.err.message]}else{msgArgs=args.slice(1)}}var rec=objCopy(log.fields);var level=rec.level=minLevel;var recFields=fields?objCopy(fields):null;if(recFields){if(log.serializers){log._applySerializers(recFields,excludeFields)}Object.keys(recFields).forEach(function(k){rec[k]=recFields[k]})}rec.msg=format.apply(log,msgArgs);if(!rec.time){rec.time=new Date}if(log.src&&!rec.src){rec.src=getCaller3Info()}rec.v=LOG_VERSION;return rec}function mkProbeArgs(str,log,minLevel,msgArgs){return[str||log._emit(mkRecord(log,minLevel,msgArgs),true)]}function mkLogEmitter(minLevel){return function(){var log=this;var str=null;var rec=null;if(!this._emit){var dedupKey="unbound";if(!_haveWarned[dedupKey]){var caller=getCaller3Info();_warn(format("bunyan usage error: %s:%s: attempt to log "+"with an unbound log method: `this` is: %s",caller.file,caller.line,util.inspect(this)),dedupKey)}return}else if(arguments.length===0){return this._level<=minLevel}var msgArgs=new Array(arguments.length);for(var i=0;i<msgArgs.length;++i){msgArgs[i]=arguments[i]}if(this._level<=minLevel){rec=mkRecord(log,minLevel,msgArgs);str=this._emit(rec)}if(probes){probes[minLevel].fire(mkProbeArgs,str,log,minLevel,msgArgs)}}}Logger.prototype.trace=mkLogEmitter(TRACE);Logger.prototype.debug=mkLogEmitter(DEBUG);Logger.prototype.info=mkLogEmitter(INFO);Logger.prototype.warn=mkLogEmitter(WARN);Logger.prototype.error=mkLogEmitter(ERROR);Logger.prototype.fatal=mkLogEmitter(FATAL);Logger.stdSerializers={};Logger.stdSerializers.req=function(req){if(!req||!req.connection)return req;return{method:req.method,url:req.url,headers:req.headers,remoteAddress:req.connection.remoteAddress,remotePort:req.connection.remotePort}};Logger.stdSerializers.res=function(res){if(!res||!res.statusCode)return res;return{statusCode:res.statusCode,header:res._header}};function getFullErrorStack(ex){var ret=ex.stack||ex.toString();if(ex.cause&&typeof ex.cause==="function"){var cex=ex.cause();if(cex){ret+="\nCaused by: "+getFullErrorStack(cex)}}return ret}var errSerializer=Logger.stdSerializers.err=function(err){if(!err||!err.stack)return err;var obj={message:err.message,name:err.name,stack:getFullErrorStack(err),code:err.code,signal:err.signal};return obj};function safeCyclesSet(){var seen=new Set;return function(key,val){if(!val||typeof val!=="object"){return val}if(seen.has(val)){return"[Circular]"}seen.add(val);return val}}function safeCyclesArray(){var seen=[];return function(key,val){if(!val||typeof val!=="object"){return val}if(seen.indexOf(val)!==-1){return"[Circular]"}seen.push(val);return val}}var safeCycles=typeof Set!=="undefined"?safeCyclesSet:safeCyclesArray;function fastAndSafeJsonStringify(rec){try{return JSON.stringify(rec)}catch(ex){try{return JSON.stringify(rec,safeCycles())}catch(e){if(safeJsonStringify){return safeJsonStringify(rec)}else{var dedupKey=e.stack.split(/\n/g,3).join("\n");_warn("bunyan: ERROR: Exception in "+"`JSON.stringify(rec)`. You can install the "+'"safe-json-stringify" module to have Bunyan fallback '+"to safer stringification. Record:\n"+_indent(format("%s\n%s",util.inspect(rec),e.stack)),dedupKey);return format("(Exception in JSON.stringify(rec): %j. "+"See stderr for details.)",e.message)}}}}var RotatingFileStream=null;if(mv){RotatingFileStream=function RotatingFileStream(options){this.path=options.path;this.count=options.count==null?10:options.count;assert.equal(typeof this.count,"number",format('rotating-file stream "count" is not a number: %j (%s) in %j',this.count,typeof this.count,this));assert.ok(this.count>=0,format('rotating-file stream "count" is not >= 0: %j in %j',this.count,this));if(options.period){var period={hourly:"1h",daily:"1d",weekly:"1w",monthly:"1m",yearly:"1y"}[options.period]||options.period;var m=/^([1-9][0-9]*)([hdwmy]|ms)$/.exec(period);if(!m){throw new Error(format('invalid period: "%s"',options.period))}this.periodNum=Number(m[1]);this.periodScope=m[2]}else{this.periodNum=1;this.periodScope="d"}var lastModified=null;try{var fileInfo=fs.statSync(this.path);lastModified=fileInfo.mtime.getTime()}catch(err){}var rotateAfterOpen=false;if(lastModified){var lastRotTime=this._calcRotTime(0);if(lastModified<lastRotTime){rotateAfterOpen=true}}this.stream=fs.createWriteStream(this.path,{flags:"a",encoding:"utf8"});this.rotQueue=[];this.rotating=false;if(rotateAfterOpen){this._debug("rotateAfterOpen -> call rotate()");this.rotate()}else{this._setupNextRot()}};util.inherits(RotatingFileStream,EventEmitter);RotatingFileStream.prototype._debug=function(){if(false){if(arguments.length===0){return true}var args=Array.prototype.slice.call(arguments);args[0]="["+(new Date).toISOString()+", "+this.path+"] "+args[0];console.log.apply(this,args)}else{return false}};RotatingFileStream.prototype._setupNextRot=function(){this.rotAt=this._calcRotTime(1);this._setRotationTimer()};RotatingFileStream.prototype._setRotationTimer=function(){var self=this;var delay=this.rotAt-Date.now();var TIMEOUT_MAX=2147483647;if(delay>TIMEOUT_MAX){delay=TIMEOUT_MAX}this.timeout=setTimeout(function(){self._debug("_setRotationTimer timeout -> call rotate()");self.rotate()},delay);if(typeof this.timeout.unref==="function"){this.timeout.unref()}};RotatingFileStream.prototype._calcRotTime=function _calcRotTime(periodOffset){this._debug("_calcRotTime: %s%s",this.periodNum,this.periodScope);var d=new Date;this._debug("  now local: %s",d);this._debug("    now utc: %s",d.toISOString());var rotAt;switch(this.periodScope){case"ms":if(this.rotAt){rotAt=this.rotAt+this.periodNum*periodOffset}else{rotAt=Date.now()+this.periodNum*periodOffset}break;case"h":if(this.rotAt){rotAt=this.rotAt+this.periodNum*60*60*1e3*periodOffset}else{rotAt=Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate(),d.getUTCHours()+periodOffset)}break;case"d":if(this.rotAt){rotAt=this.rotAt+this.periodNum*24*60*60*1e3*periodOffset}else{rotAt=Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate()+periodOffset)}break;case"w":if(this.rotAt){rotAt=this.rotAt+this.periodNum*7*24*60*60*1e3*periodOffset}else{var dayOffset=7-d.getUTCDay();if(periodOffset<1){dayOffset=-d.getUTCDay()}if(periodOffset>1||periodOffset<-1){dayOffset+=7*periodOffset}rotAt=Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate()+dayOffset)}break;case"m":if(this.rotAt){rotAt=Date.UTC(d.getUTCFullYear(),d.getUTCMonth()+this.periodNum*periodOffset,1)}else{rotAt=Date.UTC(d.getUTCFullYear(),d.getUTCMonth()+periodOffset,1)}break;case"y":if(this.rotAt){rotAt=Date.UTC(d.getUTCFullYear()+this.periodNum*periodOffset,0,1)}else{rotAt=Date.UTC(d.getUTCFullYear()+periodOffset,0,1)}break;default:assert.fail(format('invalid period scope: "%s"',this.periodScope))}if(this._debug()){this._debug("  **rotAt**: %s (utc: %s)",rotAt,new Date(rotAt).toUTCString());var now=Date.now();this._debug("        now: %s (%sms == %smin == %sh to go)",now,rotAt-now,(rotAt-now)/1e3/60,(rotAt-now)/1e3/60/60)}return rotAt};RotatingFileStream.prototype.rotate=function rotate(){var self=this;if(self.rotAt&&self.rotAt>Date.now()){return self._setRotationTimer()}this._debug("rotate");if(self.rotating){throw new TypeError("cannot start a rotation when already rotating")}self.rotating=true;self.stream.end();function del(){var toDel=self.path+"."+String(n-1);if(n===0){toDel=self.path}n-=1;self._debug("  rm %s",toDel);fs.unlink(toDel,function(delErr){moves()})}function moves(){if(self.count===0||n<0){return finish()}var before=self.path;var after=self.path+"."+String(n);if(n>0){before+="."+String(n-1)}n-=1;fs.exists(before,function(exists){if(!exists){moves()}else{self._debug("  mv %s %s",before,after);mv(before,after,function(mvErr){if(mvErr){self.emit("error",mvErr);finish()}else{moves()}})}})}function finish(){self._debug("  open %s",self.path);self.stream=fs.createWriteStream(self.path,{flags:"a",encoding:"utf8"});var q=self.rotQueue,len=q.length;for(var i=0;i<len;i++){self.stream.write(q[i])}self.rotQueue=[];self.rotating=false;self.emit("drain");self._setupNextRot()}var n=this.count;del()};RotatingFileStream.prototype.write=function write(s){if(this.rotating){this.rotQueue.push(s);return false}else{return this.stream.write(s)}};RotatingFileStream.prototype.end=function end(s){this.stream.end()};RotatingFileStream.prototype.destroy=function destroy(s){this.stream.destroy()};RotatingFileStream.prototype.destroySoon=function destroySoon(s){this.stream.destroySoon()}}function RingBuffer(options){this.limit=options&&options.limit?options.limit:100;this.writable=true;this.records=[];EventEmitter.call(this)}util.inherits(RingBuffer,EventEmitter);RingBuffer.prototype.write=function(record){if(!this.writable)throw new Error("RingBuffer has been ended already");this.records.push(record);if(this.records.length>this.limit)this.records.shift();return true};RingBuffer.prototype.end=function(){if(arguments.length>0)this.write.apply(this,Array.prototype.slice.call(arguments));this.writable=false};RingBuffer.prototype.destroy=function(){this.writable=false;this.emit("close")};RingBuffer.prototype.destroySoon=function(){this.destroy()};module.exports=Logger;module.exports.TRACE=TRACE;module.exports.DEBUG=DEBUG;module.exports.INFO=INFO;module.exports.WARN=WARN;module.exports.ERROR=ERROR;module.exports.FATAL=FATAL;module.exports.resolveLevel=resolveLevel;module.exports.levelFromName=levelFromName;module.exports.nameFromLevel=nameFromLevel;module.exports.VERSION=VERSION;module.exports.LOG_VERSION=LOG_VERSION;module.exports.createLogger=function createLogger(options){return new Logger(options)};module.exports.RingBuffer=RingBuffer;module.exports.RotatingFileStream=RotatingFileStream;module.exports.safeCycles=safeCycles}).call(this,{isBuffer:require("../../is-buffer/index.js")},require("_process"))},{"../../is-buffer/index.js":14,_process:19,assert:3,events:11,fs:6,os:17,"safe-json-stringify":32,stream:33,util:38}],10:[function(require,module,exports){(function(Buffer){function isArray(arg){if(Array.isArray){return Array.isArray(arg)}return objectToString(arg)==="[object Array]"}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return objectToString(e)==="[object Error]"||e instanceof Error}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=Buffer.isBuffer;function objectToString(o){return Object.prototype.toString.call(o)}}).call(this,{isBuffer:require("../../is-buffer/index.js")})},{"../../is-buffer/index.js":14}],11:[function(require,module,exports){function EventEmitter(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined}module.exports=EventEmitter;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;EventEmitter.defaultMaxListeners=10;EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError("n must be a positive number");this._maxListeners=n;return this};EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(!this._events)this._events={};if(type==="error"){if(!this._events.error||isObject(this._events.error)&&!this._events.error.length){er=arguments[1];if(er instanceof Error){throw er}else{var err=new Error('Uncaught, unspecified "error" event. ('+er+")");err.context=er;throw err}}}handler=this._events[type];if(isUndefined(handler))return false;if(isFunction(handler)){switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:args=Array.prototype.slice.call(arguments,1);handler.apply(this,args)}}else if(isObject(handler)){args=Array.prototype.slice.call(arguments,1);listeners=handler.slice();len=listeners.length;for(i=0;i<len;i++)listeners[i].apply(this,args)}return true};EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events)this._events={};if(this._events.newListener)this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener);if(!this._events[type])this._events[type]=listener;else if(isObject(this._events[type]))this._events[type].push(listener);else this._events[type]=[this._events[type],listener];if(isObject(this._events[type])&&!this._events[type].warned){if(!isUndefined(this._maxListeners)){m=this._maxListeners}else{m=EventEmitter.defaultMaxListeners}if(m&&m>0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[type].length);if(typeof console.trace==="function"){console.trace()}}}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError("listener must be a function");var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments)}}g.listener=listener;this.on(type,g);return this};EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit("removeListener",type,listener)}else if(isObject(list)){for(i=length;i-- >0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type]}else{list.splice(position,1)}if(this._events.removeListener)this.emit("removeListener",type,listener)}return this};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}if(arguments.length===0){for(key in this._events){if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events={};return this}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners)}else if(listeners){while(listeners.length)this.removeListener(type,listeners[listeners.length-1])}delete this._events[type];return this};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret};EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;else if(evlistener)return evlistener.length}return 0};EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type)};function isFunction(arg){return typeof arg==="function"}function isNumber(arg){return typeof arg==="number"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isUndefined(arg){return arg===void 0}},{}],12:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m;var eLen=nBytes*8-mLen-1;var eMax=(1<<eLen)-1;var eBias=eMax>>1;var nBits=-7;var i=isLE?nBytes-1:0;var d=isLE?-1:1;var s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8){}m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8){}if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c;var eLen=nBytes*8-mLen-1;var eMax=(1<<eLen)-1;var eBias=eMax>>1;var rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0;var i=isLE?0:nBytes-1;var d=isLE?1:-1;var s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8){}e=e<<mLen|m;eLen+=mLen;for(;eLen>0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128}},{}],13:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},{}],14:[function(require,module,exports){module.exports=function(obj){return obj!=null&&(isBuffer(obj)||isSlowBuffer(obj)||!!obj._isBuffer)};function isBuffer(obj){return!!obj.constructor&&typeof obj.constructor.isBuffer==="function"&&obj.constructor.isBuffer(obj)}function isSlowBuffer(obj){return typeof obj.readFloatLE==="function"&&typeof obj.slice==="function"&&isBuffer(obj.slice(0,0))}},{}],15:[function(require,module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return toString.call(arr)=="[object Array]"}},{}],16:[function(require,module,exports){(function(global,factory){typeof exports==="object"&&typeof module!=="undefined"?module.exports=factory():typeof define==="function"&&define.amd?define(factory):global.moment=factory()})(this,function(){"use strict";var hookCallback;function hooks(){return hookCallback.apply(null,arguments)}function setHookCallback(callback){hookCallback=callback}function isArray(input){return input instanceof Array||Object.prototype.toString.call(input)==="[object Array]"}function isObject(input){return input!=null&&Object.prototype.toString.call(input)==="[object Object]"}function isObjectEmpty(obj){var k;for(k in obj){return false}return true}function isUndefined(input){return input===void 0}function isNumber(input){return typeof input==="number"||Object.prototype.toString.call(input)==="[object Number]"}function isDate(input){return input instanceof Date||Object.prototype.toString.call(input)==="[object Date]"}function map(arr,fn){var res=[],i;for(i=0;i<arr.length;++i){res.push(fn(arr[i],i))}return res}function hasOwnProp(a,b){return Object.prototype.hasOwnProperty.call(a,b)}function extend(a,b){for(var i in b){if(hasOwnProp(b,i)){a[i]=b[i]}}if(hasOwnProp(b,"toString")){a.toString=b.toString}if(hasOwnProp(b,"valueOf")){a.valueOf=b.valueOf}return a}function createUTC(input,format,locale,strict){return createLocalOrUTC(input,format,locale,strict,true).utc()}function defaultParsingFlags(){return{empty:false,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:false,invalidMonth:null,invalidFormat:false,userInvalidated:false,iso:false,parsedDateParts:[],meridiem:null,rfc2822:false,weekdayMismatch:false}}function getParsingFlags(m){if(m._pf==null){m._pf=defaultParsingFlags()}return m._pf}var some;if(Array.prototype.some){some=Array.prototype.some}else{some=function(fun){var t=Object(this);var len=t.length>>>0;for(var i=0;i<len;i++){if(i in t&&fun.call(this,t[i],i,t)){return true}}return false}}var some$1=some;function isValid(m){if(m._isValid==null){var flags=getParsingFlags(m);var parsedParts=some$1.call(flags.parsedDateParts,function(i){return i!=null});var isNowValid=!isNaN(m._d.getTime())&&flags.overflow<0&&!flags.empty&&!flags.invalidMonth&&!flags.invalidWeekday&&!flags.nullInput&&!flags.invalidFormat&&!flags.userInvalidated&&(!flags.meridiem||flags.meridiem&&parsedParts);if(m._strict){isNowValid=isNowValid&&flags.charsLeftOver===0&&flags.unusedTokens.length===0&&flags.bigHour===undefined}if(Object.isFrozen==null||!Object.isFrozen(m)){m._isValid=isNowValid}else{return isNowValid}}return m._isValid}function createInvalid(flags){var m=createUTC(NaN);if(flags!=null){extend(getParsingFlags(m),flags)}else{getParsingFlags(m).userInvalidated=true}return m}var momentProperties=hooks.momentProperties=[];function copyConfig(to,from){var i,prop,val;if(!isUndefined(from._isAMomentObject)){to._isAMomentObject=from._isAMomentObject}if(!isUndefined(from._i)){to._i=from._i}if(!isUndefined(from._f)){to._f=from._f}if(!isUndefined(from._l)){to._l=from._l}if(!isUndefined(from._strict)){to._strict=from._strict}if(!isUndefined(from._tzm)){to._tzm=from._tzm}if(!isUndefined(from._isUTC)){to._isUTC=from._isUTC}if(!isUndefined(from._offset)){to._offset=from._offset}if(!isUndefined(from._pf)){to._pf=getParsingFlags(from)}if(!isUndefined(from._locale)){to._locale=from._locale}if(momentProperties.length>0){for(i=0;i<momentProperties.length;i++){prop=momentProperties[i];val=from[prop];if(!isUndefined(val)){to[prop]=val}}}return to}var updateInProgress=false;function Moment(config){copyConfig(this,config);this._d=new Date(config._d!=null?config._d.getTime():NaN);if(!this.isValid()){this._d=new Date(NaN)}if(updateInProgress===false){updateInProgress=true;hooks.updateOffset(this);updateInProgress=false}}function isMoment(obj){return obj instanceof Moment||obj!=null&&obj._isAMomentObject!=null}function absFloor(number){if(number<0){return Math.ceil(number)||0}else{return Math.floor(number)}}function toInt(argumentForCoercion){var coercedNumber=+argumentForCoercion,value=0;if(coercedNumber!==0&&isFinite(coercedNumber)){value=absFloor(coercedNumber)}return value}function compareArrays(array1,array2,dontConvert){var len=Math.min(array1.length,array2.length),lengthDiff=Math.abs(array1.length-array2.length),diffs=0,i;for(i=0;i<len;i++){if(dontConvert&&array1[i]!==array2[i]||!dontConvert&&toInt(array1[i])!==toInt(array2[i])){diffs++}}return diffs+lengthDiff}function warn(msg){if(hooks.suppressDeprecationWarnings===false&&typeof console!=="undefined"&&console.warn){console.warn("Deprecation warning: "+msg)}}function deprecate(msg,fn){var firstTime=true;return extend(function(){if(hooks.deprecationHandler!=null){hooks.deprecationHandler(null,msg)}if(firstTime){var args=[];var arg;for(var i=0;i<arguments.length;i++){arg="";if(typeof arguments[i]==="object"){arg+="\n["+i+"] ";for(var key in arguments[0]){arg+=key+": "+arguments[0][key]+", "}arg=arg.slice(0,-2)}else{arg=arguments[i]}args.push(arg)}warn(msg+"\nArguments: "+Array.prototype.slice.call(args).join("")+"\n"+(new Error).stack);firstTime=false}return fn.apply(this,arguments)},fn)}var deprecations={};function deprecateSimple(name,msg){if(hooks.deprecationHandler!=null){hooks.deprecationHandler(name,msg)}if(!deprecations[name]){warn(msg);deprecations[name]=true}}hooks.suppressDeprecationWarnings=false;hooks.deprecationHandler=null;function isFunction(input){return input instanceof Function||Object.prototype.toString.call(input)==="[object Function]"}function set(config){var prop,i;for(i in config){prop=config[i];if(isFunction(prop)){this[i]=prop}else{this["_"+i]=prop}}this._config=config;this._dayOfMonthOrdinalParseLenient=new RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+"|"+/\d{1,2}/.source)}function mergeConfigs(parentConfig,childConfig){var res=extend({},parentConfig),prop;for(prop in childConfig){if(hasOwnProp(childConfig,prop)){if(isObject(parentConfig[prop])&&isObject(childConfig[prop])){res[prop]={};extend(res[prop],parentConfig[prop]);extend(res[prop],childConfig[prop])}else if(childConfig[prop]!=null){res[prop]=childConfig[prop]}else{delete res[prop]}}}for(prop in parentConfig){if(hasOwnProp(parentConfig,prop)&&!hasOwnProp(childConfig,prop)&&isObject(parentConfig[prop])){res[prop]=extend({},res[prop])}}return res}function Locale(config){if(config!=null){this.set(config)}}var keys;if(Object.keys){keys=Object.keys}else{keys=function(obj){var i,res=[];for(i in obj){if(hasOwnProp(obj,i)){res.push(i)}}return res}}var keys$1=keys;var defaultCalendar={sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"};function calendar(key,mom,now){var output=this._calendar[key]||this._calendar["sameElse"];return isFunction(output)?output.call(mom,now):output}var defaultLongDateFormat={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"};function longDateFormat(key){var format=this._longDateFormat[key],formatUpper=this._longDateFormat[key.toUpperCase()];if(format||!formatUpper){return format}this._longDateFormat[key]=formatUpper.replace(/MMMM|MM|DD|dddd/g,function(val){return val.slice(1)});return this._longDateFormat[key]}var defaultInvalidDate="Invalid date";function invalidDate(){return this._invalidDate}var defaultOrdinal="%d";var defaultDayOfMonthOrdinalParse=/\d{1,2}/;function ordinal(number){return this._ordinal.replace("%d",number)}var defaultRelativeTime={future:"in %s",past:"%s ago",s:"a few seconds",ss:"%d seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"};function relativeTime(number,withoutSuffix,string,isFuture){var output=this._relativeTime[string];return isFunction(output)?output(number,withoutSuffix,string,isFuture):output.replace(/%d/i,number)}function pastFuture(diff,output){var format=this._relativeTime[diff>0?"future":"past"];return isFunction(format)?format(output):format.replace(/%s/i,output)}var aliases={};function addUnitAlias(unit,shorthand){var lowerCase=unit.toLowerCase();aliases[lowerCase]=aliases[lowerCase+"s"]=aliases[shorthand]=unit}function normalizeUnits(units){return typeof units==="string"?aliases[units]||aliases[units.toLowerCase()]:undefined}function normalizeObjectUnits(inputObject){var normalizedInput={},normalizedProp,prop;for(prop in inputObject){if(hasOwnProp(inputObject,prop)){normalizedProp=normalizeUnits(prop);if(normalizedProp){normalizedInput[normalizedProp]=inputObject[prop]}}}return normalizedInput}var priorities={};function addUnitPriority(unit,priority){priorities[unit]=priority}function getPrioritizedUnits(unitsObj){var units=[];for(var u in unitsObj){units.push({unit:u,priority:priorities[u]})}units.sort(function(a,b){return a.priority-b.priority});return units}function makeGetSet(unit,keepTime){return function(value){if(value!=null){set$1(this,unit,value);hooks.updateOffset(this,keepTime);return this}else{return get(this,unit)}}}function get(mom,unit){return mom.isValid()?mom._d["get"+(mom._isUTC?"UTC":"")+unit]():NaN}function set$1(mom,unit,value){if(mom.isValid()){mom._d["set"+(mom._isUTC?"UTC":"")+unit](value)}}function stringGet(units){units=normalizeUnits(units);if(isFunction(this[units])){return this[units]()}return this}function stringSet(units,value){if(typeof units==="object"){units=normalizeObjectUnits(units);var prioritized=getPrioritizedUnits(units);for(var i=0;i<prioritized.length;i++){this[prioritized[i].unit](units[prioritized[i].unit])}}else{units=normalizeUnits(units);if(isFunction(this[units])){return this[units](value)}}return this}function zeroFill(number,targetLength,forceSign){var absNumber=""+Math.abs(number),zerosToFill=targetLength-absNumber.length,sign=number>=0;return(sign?forceSign?"+":"":"-")+Math.pow(10,Math.max(0,zerosToFill)).toString().substr(1)+absNumber}var formattingTokens=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g;var localFormattingTokens=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g;var formatFunctions={};var formatTokenFunctions={};function addFormatToken(token,padded,ordinal,callback){var func=callback;if(typeof callback==="string"){func=function(){return this[callback]()}}if(token){formatTokenFunctions[token]=func}if(padded){formatTokenFunctions[padded[0]]=function(){return zeroFill(func.apply(this,arguments),padded[1],padded[2])}}if(ordinal){formatTokenFunctions[ordinal]=function(){return this.localeData().ordinal(func.apply(this,arguments),token)}}}function removeFormattingTokens(input){if(input.match(/\[[\s\S]/)){return input.replace(/^\[|\]$/g,"")}return input.replace(/\\/g,"")}function makeFormatFunction(format){var array=format.match(formattingTokens),i,length;for(i=0,length=array.length;i<length;i++){if(formatTokenFunctions[array[i]]){array[i]=formatTokenFunctions[array[i]]}else{array[i]=removeFormattingTokens(array[i])}}return function(mom){var output="",i;for(i=0;i<length;i++){output+=isFunction(array[i])?array[i].call(mom,format):array[i]}return output}}function formatMoment(m,format){if(!m.isValid()){return m.localeData().invalidDate()}format=expandFormat(format,m.localeData());formatFunctions[format]=formatFunctions[format]||makeFormatFunction(format);return formatFunctions[format](m)}function expandFormat(format,locale){var i=5;function replaceLongDateFormatTokens(input){return locale.longDateFormat(input)||input}localFormattingTokens.lastIndex=0;while(i>=0&&localFormattingTokens.test(format)){format=format.replace(localFormattingTokens,replaceLongDateFormatTokens);localFormattingTokens.lastIndex=0;i-=1}return format}var match1=/\d/;var match2=/\d\d/;var match3=/\d{3}/;var match4=/\d{4}/;var match6=/[+-]?\d{6}/;var match1to2=/\d\d?/;var match3to4=/\d\d\d\d?/;var match5to6=/\d\d\d\d\d\d?/;var match1to3=/\d{1,3}/;var match1to4=/\d{1,4}/;var match1to6=/[+-]?\d{1,6}/;var matchUnsigned=/\d+/;var matchSigned=/[+-]?\d+/;var matchOffset=/Z|[+-]\d\d:?\d\d/gi;var matchShortOffset=/Z|[+-]\d\d(?::?\d\d)?/gi;var matchTimestamp=/[+-]?\d+(\.\d{1,3})?/;var matchWord=/[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i;var regexes={};function addRegexToken(token,regex,strictRegex){regexes[token]=isFunction(regex)?regex:function(isStrict,localeData){return isStrict&&strictRegex?strictRegex:regex}}function getParseRegexForToken(token,config){if(!hasOwnProp(regexes,token)){return new RegExp(unescapeFormat(token))}return regexes[token](config._strict,config._locale)}function unescapeFormat(s){return regexEscape(s.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(matched,p1,p2,p3,p4){return p1||p2||p3||p4}))}function regexEscape(s){return s.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}var tokens={};function addParseToken(token,callback){var i,func=callback;if(typeof token==="string"){token=[token]}if(isNumber(callback)){func=function(input,array){array[callback]=toInt(input)}}for(i=0;i<token.length;i++){tokens[token[i]]=func}}function addWeekParseToken(token,callback){addParseToken(token,function(input,array,config,token){config._w=config._w||{};callback(input,config._w,config,token)})}function addTimeToArrayFromToken(token,input,config){if(input!=null&&hasOwnProp(tokens,token)){tokens[token](input,config._a,config,token)}}var YEAR=0;var MONTH=1;var DATE=2;var HOUR=3;var MINUTE=4;var SECOND=5;var MILLISECOND=6;var WEEK=7;var WEEKDAY=8;var indexOf;if(Array.prototype.indexOf){indexOf=Array.prototype.indexOf}else{indexOf=function(o){var i;for(i=0;i<this.length;++i){if(this[i]===o){return i}}return-1}}var indexOf$1=indexOf;function daysInMonth(year,month){return new Date(Date.UTC(year,month+1,0)).getUTCDate()}addFormatToken("M",["MM",2],"Mo",function(){return this.month()+1});addFormatToken("MMM",0,0,function(format){return this.localeData().monthsShort(this,format)});addFormatToken("MMMM",0,0,function(format){return this.localeData().months(this,format)});addUnitAlias("month","M");addUnitPriority("month",8);addRegexToken("M",match1to2);addRegexToken("MM",match1to2,match2);addRegexToken("MMM",function(isStrict,locale){return locale.monthsShortRegex(isStrict)});addRegexToken("MMMM",function(isStrict,locale){return locale.monthsRegex(isStrict)});addParseToken(["M","MM"],function(input,array){array[MONTH]=toInt(input)-1});addParseToken(["MMM","MMMM"],function(input,array,config,token){var month=config._locale.monthsParse(input,token,config._strict);if(month!=null){array[MONTH]=month}else{getParsingFlags(config).invalidMonth=input}});var MONTHS_IN_FORMAT=/D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/;var defaultLocaleMonths="January_February_March_April_May_June_July_August_September_October_November_December".split("_");function localeMonths(m,format){if(!m){return isArray(this._months)?this._months:this._months["standalone"]}return isArray(this._months)?this._months[m.month()]:this._months[(this._months.isFormat||MONTHS_IN_FORMAT).test(format)?"format":"standalone"][m.month()]}var defaultLocaleMonthsShort="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_");function localeMonthsShort(m,format){if(!m){return isArray(this._monthsShort)?this._monthsShort:this._monthsShort["standalone"]}return isArray(this._monthsShort)?this._monthsShort[m.month()]:this._monthsShort[MONTHS_IN_FORMAT.test(format)?"format":"standalone"][m.month()]}function handleStrictParse(monthName,format,strict){var i,ii,mom,llc=monthName.toLocaleLowerCase();if(!this._monthsParse){this._monthsParse=[];this._longMonthsParse=[];this._shortMonthsParse=[];for(i=0;i<12;++i){mom=createUTC([2e3,i]);this._shortMonthsParse[i]=this.monthsShort(mom,"").toLocaleLowerCase();this._longMonthsParse[i]=this.months(mom,"").toLocaleLowerCase()}}if(strict){if(format==="MMM"){ii=indexOf$1.call(this._shortMonthsParse,llc);return ii!==-1?ii:null}else{ii=indexOf$1.call(this._longMonthsParse,llc);return ii!==-1?ii:null}}else{if(format==="MMM"){ii=indexOf$1.call(this._shortMonthsParse,llc);if(ii!==-1){return ii}ii=indexOf$1.call(this._longMonthsParse,llc);return ii!==-1?ii:null}else{ii=indexOf$1.call(this._longMonthsParse,llc);if(ii!==-1){return ii}ii=indexOf$1.call(this._shortMonthsParse,llc);return ii!==-1?ii:null}}}function localeMonthsParse(monthName,format,strict){var i,mom,regex;if(this._monthsParseExact){return handleStrictParse.call(this,monthName,format,strict)}if(!this._monthsParse){this._monthsParse=[];this._longMonthsParse=[];this._shortMonthsParse=[]}for(i=0;i<12;i++){mom=createUTC([2e3,i]);if(strict&&!this._longMonthsParse[i]){this._longMonthsParse[i]=new RegExp("^"+this.months(mom,"").replace(".","")+"$","i");this._shortMonthsParse[i]=new RegExp("^"+this.monthsShort(mom,"").replace(".","")+"$","i")}if(!strict&&!this._monthsParse[i]){regex="^"+this.months(mom,"")+"|^"+this.monthsShort(mom,"");this._monthsParse[i]=new RegExp(regex.replace(".",""),"i")}if(strict&&format==="MMMM"&&this._longMonthsParse[i].test(monthName)){return i}else if(strict&&format==="MMM"&&this._shortMonthsParse[i].test(monthName)){return i}else if(!strict&&this._monthsParse[i].test(monthName)){return i}}}function setMonth(mom,value){var dayOfMonth;if(!mom.isValid()){return mom}if(typeof value==="string"){if(/^\d+$/.test(value)){value=toInt(value)}else{value=mom.localeData().monthsParse(value);if(!isNumber(value)){return mom}}}dayOfMonth=Math.min(mom.date(),daysInMonth(mom.year(),value));mom._d["set"+(mom._isUTC?"UTC":"")+"Month"](value,dayOfMonth);return mom}function getSetMonth(value){if(value!=null){setMonth(this,value);hooks.updateOffset(this,true);return this}else{return get(this,"Month")}}function getDaysInMonth(){return daysInMonth(this.year(),this.month())}var defaultMonthsShortRegex=matchWord;function monthsShortRegex(isStrict){if(this._monthsParseExact){if(!hasOwnProp(this,"_monthsRegex")){computeMonthsParse.call(this)}if(isStrict){return this._monthsShortStrictRegex}else{return this._monthsShortRegex}}else{if(!hasOwnProp(this,"_monthsShortRegex")){this._monthsShortRegex=defaultMonthsShortRegex}return this._monthsShortStrictRegex&&isStrict?this._monthsShortStrictRegex:this._monthsShortRegex}}var defaultMonthsRegex=matchWord;function monthsRegex(isStrict){if(this._monthsParseExact){if(!hasOwnProp(this,"_monthsRegex")){computeMonthsParse.call(this)}if(isStrict){return this._monthsStrictRegex}else{return this._monthsRegex}}else{if(!hasOwnProp(this,"_monthsRegex")){this._monthsRegex=defaultMonthsRegex}return this._monthsStrictRegex&&isStrict?this._monthsStrictRegex:this._monthsRegex}}function computeMonthsParse(){function cmpLenRev(a,b){return b.length-a.length}var shortPieces=[],longPieces=[],mixedPieces=[],i,mom;for(i=0;i<12;i++){mom=createUTC([2e3,i]);shortPieces.push(this.monthsShort(mom,""));longPieces.push(this.months(mom,""));mixedPieces.push(this.months(mom,""));mixedPieces.push(this.monthsShort(mom,""))}shortPieces.sort(cmpLenRev);longPieces.sort(cmpLenRev);mixedPieces.sort(cmpLenRev);for(i=0;i<12;i++){shortPieces[i]=regexEscape(shortPieces[i]);longPieces[i]=regexEscape(longPieces[i])}for(i=0;i<24;i++){mixedPieces[i]=regexEscape(mixedPieces[i])}this._monthsRegex=new RegExp("^("+mixedPieces.join("|")+")","i");this._monthsShortRegex=this._monthsRegex;this._monthsStrictRegex=new RegExp("^("+longPieces.join("|")+")","i");this._monthsShortStrictRegex=new RegExp("^("+shortPieces.join("|")+")","i")}addFormatToken("Y",0,0,function(){var y=this.year();return y<=9999?""+y:"+"+y});addFormatToken(0,["YY",2],0,function(){return this.year()%100});addFormatToken(0,["YYYY",4],0,"year");addFormatToken(0,["YYYYY",5],0,"year");addFormatToken(0,["YYYYYY",6,true],0,"year");addUnitAlias("year","y");addUnitPriority("year",1);addRegexToken("Y",matchSigned);addRegexToken("YY",match1to2,match2);addRegexToken("YYYY",match1to4,match4);addRegexToken("YYYYY",match1to6,match6);addRegexToken("YYYYYY",match1to6,match6);addParseToken(["YYYYY","YYYYYY"],YEAR);addParseToken("YYYY",function(input,array){array[YEAR]=input.length===2?hooks.parseTwoDigitYear(input):toInt(input)});addParseToken("YY",function(input,array){array[YEAR]=hooks.parseTwoDigitYear(input)});addParseToken("Y",function(input,array){array[YEAR]=parseInt(input,10)});function daysInYear(year){return isLeapYear(year)?366:365}function isLeapYear(year){return year%4===0&&year%100!==0||year%400===0}hooks.parseTwoDigitYear=function(input){return toInt(input)+(toInt(input)>68?1900:2e3)};var getSetYear=makeGetSet("FullYear",true);function getIsLeapYear(){return isLeapYear(this.year())}function createDate(y,m,d,h,M,s,ms){var date=new Date(y,m,d,h,M,s,ms);if(y<100&&y>=0&&isFinite(date.getFullYear())){date.setFullYear(y)}return date}function createUTCDate(y){var date=new Date(Date.UTC.apply(null,arguments));if(y<100&&y>=0&&isFinite(date.getUTCFullYear())){date.setUTCFullYear(y)}return date}function firstWeekOffset(year,dow,doy){var fwd=7+dow-doy,fwdlw=(7+createUTCDate(year,0,fwd).getUTCDay()-dow)%7;return-fwdlw+fwd-1}function dayOfYearFromWeeks(year,week,weekday,dow,doy){var localWeekday=(7+weekday-dow)%7,weekOffset=firstWeekOffset(year,dow,doy),dayOfYear=1+7*(week-1)+localWeekday+weekOffset,resYear,resDayOfYear;if(dayOfYear<=0){resYear=year-1;resDayOfYear=daysInYear(resYear)+dayOfYear}else if(dayOfYear>daysInYear(year)){resYear=year+1;resDayOfYear=dayOfYear-daysInYear(year)}else{resYear=year;resDayOfYear=dayOfYear}return{year:resYear,dayOfYear:resDayOfYear}}function weekOfYear(mom,dow,doy){var weekOffset=firstWeekOffset(mom.year(),dow,doy),week=Math.floor((mom.dayOfYear()-weekOffset-1)/7)+1,resWeek,resYear;if(week<1){resYear=mom.year()-1;resWeek=week+weeksInYear(resYear,dow,doy)}else if(week>weeksInYear(mom.year(),dow,doy)){resWeek=week-weeksInYear(mom.year(),dow,doy);resYear=mom.year()+1}else{resYear=mom.year();resWeek=week}return{week:resWeek,year:resYear}}function weeksInYear(year,dow,doy){var weekOffset=firstWeekOffset(year,dow,doy),weekOffsetNext=firstWeekOffset(year+1,dow,doy);return(daysInYear(year)-weekOffset+weekOffsetNext)/7}addFormatToken("w",["ww",2],"wo","week");addFormatToken("W",["WW",2],"Wo","isoWeek");addUnitAlias("week","w");addUnitAlias("isoWeek","W");addUnitPriority("week",5);addUnitPriority("isoWeek",5);addRegexToken("w",match1to2);addRegexToken("ww",match1to2,match2);addRegexToken("W",match1to2);addRegexToken("WW",match1to2,match2);addWeekParseToken(["w","ww","W","WW"],function(input,week,config,token){week[token.substr(0,1)]=toInt(input)});function localeWeek(mom){return weekOfYear(mom,this._week.dow,this._week.doy).week}var defaultLocaleWeek={dow:0,doy:6};function localeFirstDayOfWeek(){return this._week.dow}function localeFirstDayOfYear(){return this._week.doy}function getSetWeek(input){var week=this.localeData().week(this);return input==null?week:this.add((input-week)*7,"d")}function getSetISOWeek(input){var week=weekOfYear(this,1,4).week;return input==null?week:this.add((input-week)*7,"d")}addFormatToken("d",0,"do","day");addFormatToken("dd",0,0,function(format){return this.localeData().weekdaysMin(this,format)});addFormatToken("ddd",0,0,function(format){return this.localeData().weekdaysShort(this,format)});addFormatToken("dddd",0,0,function(format){return this.localeData().weekdays(this,format)});addFormatToken("e",0,0,"weekday");addFormatToken("E",0,0,"isoWeekday");addUnitAlias("day","d");addUnitAlias("weekday","e");addUnitAlias("isoWeekday","E");addUnitPriority("day",11);addUnitPriority("weekday",11);addUnitPriority("isoWeekday",11);addRegexToken("d",match1to2);addRegexToken("e",match1to2);addRegexToken("E",match1to2);addRegexToken("dd",function(isStrict,locale){return locale.weekdaysMinRegex(isStrict)});addRegexToken("ddd",function(isStrict,locale){return locale.weekdaysShortRegex(isStrict)});addRegexToken("dddd",function(isStrict,locale){return locale.weekdaysRegex(isStrict)});addWeekParseToken(["dd","ddd","dddd"],function(input,week,config,token){var weekday=config._locale.weekdaysParse(input,token,config._strict);if(weekday!=null){week.d=weekday}else{getParsingFlags(config).invalidWeekday=input}});addWeekParseToken(["d","e","E"],function(input,week,config,token){week[token]=toInt(input)});function parseWeekday(input,locale){if(typeof input!=="string"){return input}if(!isNaN(input)){return parseInt(input,10)}input=locale.weekdaysParse(input);if(typeof input==="number"){return input}return null}function parseIsoWeekday(input,locale){if(typeof input==="string"){return locale.weekdaysParse(input)%7||7}return isNaN(input)?null:input}var defaultLocaleWeekdays="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_");function localeWeekdays(m,format){if(!m){return isArray(this._weekdays)?this._weekdays:this._weekdays["standalone"]}return isArray(this._weekdays)?this._weekdays[m.day()]:this._weekdays[this._weekdays.isFormat.test(format)?"format":"standalone"][m.day()]}var defaultLocaleWeekdaysShort="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_");function localeWeekdaysShort(m){return m?this._weekdaysShort[m.day()]:this._weekdaysShort}var defaultLocaleWeekdaysMin="Su_Mo_Tu_We_Th_Fr_Sa".split("_");function localeWeekdaysMin(m){return m?this._weekdaysMin[m.day()]:this._weekdaysMin}function handleStrictParse$1(weekdayName,format,strict){var i,ii,mom,llc=weekdayName.toLocaleLowerCase();if(!this._weekdaysParse){this._weekdaysParse=[];this._shortWeekdaysParse=[];this._minWeekdaysParse=[];for(i=0;i<7;++i){mom=createUTC([2e3,1]).day(i);this._minWeekdaysParse[i]=this.weekdaysMin(mom,"").toLocaleLowerCase();this._shortWeekdaysParse[i]=this.weekdaysShort(mom,"").toLocaleLowerCase();this._weekdaysParse[i]=this.weekdays(mom,"").toLocaleLowerCase()}}if(strict){if(format==="dddd"){ii=indexOf$1.call(this._weekdaysParse,llc);return ii!==-1?ii:null}else if(format==="ddd"){ii=indexOf$1.call(this._shortWeekdaysParse,llc);return ii!==-1?ii:null}else{ii=indexOf$1.call(this._minWeekdaysParse,llc);return ii!==-1?ii:null}}else{if(format==="dddd"){ii=indexOf$1.call(this._weekdaysParse,llc);if(ii!==-1){return ii}ii=indexOf$1.call(this._shortWeekdaysParse,llc);if(ii!==-1){return ii}ii=indexOf$1.call(this._minWeekdaysParse,llc);return ii!==-1?ii:null}else if(format==="ddd"){ii=indexOf$1.call(this._shortWeekdaysParse,llc);if(ii!==-1){return ii}ii=indexOf$1.call(this._weekdaysParse,llc);if(ii!==-1){return ii}ii=indexOf$1.call(this._minWeekdaysParse,llc);return ii!==-1?ii:null}else{ii=indexOf$1.call(this._minWeekdaysParse,llc);if(ii!==-1){return ii}ii=indexOf$1.call(this._weekdaysParse,llc);if(ii!==-1){return ii}ii=indexOf$1.call(this._shortWeekdaysParse,llc);return ii!==-1?ii:null}}}function localeWeekdaysParse(weekdayName,format,strict){var i,mom,regex;if(this._weekdaysParseExact){return handleStrictParse$1.call(this,weekdayName,format,strict)}if(!this._weekdaysParse){this._weekdaysParse=[];this._minWeekdaysParse=[];this._shortWeekdaysParse=[];this._fullWeekdaysParse=[]}for(i=0;i<7;i++){mom=createUTC([2e3,1]).day(i);if(strict&&!this._fullWeekdaysParse[i]){this._fullWeekdaysParse[i]=new RegExp("^"+this.weekdays(mom,"").replace(".",".?")+"$","i");this._shortWeekdaysParse[i]=new RegExp("^"+this.weekdaysShort(mom,"").replace(".",".?")+"$","i");this._minWeekdaysParse[i]=new RegExp("^"+this.weekdaysMin(mom,"").replace(".",".?")+"$","i")}if(!this._weekdaysParse[i]){regex="^"+this.weekdays(mom,"")+"|^"+this.weekdaysShort(mom,"")+"|^"+this.weekdaysMin(mom,"");this._weekdaysParse[i]=new RegExp(regex.replace(".",""),"i")}if(strict&&format==="dddd"&&this._fullWeekdaysParse[i].test(weekdayName)){return i}else if(strict&&format==="ddd"&&this._shortWeekdaysParse[i].test(weekdayName)){return i}else if(strict&&format==="dd"&&this._minWeekdaysParse[i].test(weekdayName)){return i}else if(!strict&&this._weekdaysParse[i].test(weekdayName)){return i}}}function getSetDayOfWeek(input){if(!this.isValid()){return input!=null?this:NaN}var day=this._isUTC?this._d.getUTCDay():this._d.getDay();if(input!=null){input=parseWeekday(input,this.localeData());return this.add(input-day,"d")}else{return day}}function getSetLocaleDayOfWeek(input){if(!this.isValid()){return input!=null?this:NaN}var weekday=(this.day()+7-this.localeData()._week.dow)%7;return input==null?weekday:this.add(input-weekday,"d")}function getSetISODayOfWeek(input){if(!this.isValid()){return input!=null?this:NaN}if(input!=null){var weekday=parseIsoWeekday(input,this.localeData());return this.day(this.day()%7?weekday:weekday-7)}else{return this.day()||7}}var defaultWeekdaysRegex=matchWord;function weekdaysRegex(isStrict){if(this._weekdaysParseExact){if(!hasOwnProp(this,"_weekdaysRegex")){computeWeekdaysParse.call(this)}if(isStrict){return this._weekdaysStrictRegex}else{return this._weekdaysRegex}}else{if(!hasOwnProp(this,"_weekdaysRegex")){this._weekdaysRegex=defaultWeekdaysRegex}return this._weekdaysStrictRegex&&isStrict?this._weekdaysStrictRegex:this._weekdaysRegex}}var defaultWeekdaysShortRegex=matchWord;function weekdaysShortRegex(isStrict){if(this._weekdaysParseExact){if(!hasOwnProp(this,"_weekdaysRegex")){computeWeekdaysParse.call(this)}if(isStrict){return this._weekdaysShortStrictRegex}else{return this._weekdaysShortRegex}}else{if(!hasOwnProp(this,"_weekdaysShortRegex")){this._weekdaysShortRegex=defaultWeekdaysShortRegex}return this._weekdaysShortStrictRegex&&isStrict?this._weekdaysShortStrictRegex:this._weekdaysShortRegex}}var defaultWeekdaysMinRegex=matchWord;function weekdaysMinRegex(isStrict){if(this._weekdaysParseExact){if(!hasOwnProp(this,"_weekdaysRegex")){computeWeekdaysParse.call(this)}if(isStrict){return this._weekdaysMinStrictRegex}else{return this._weekdaysMinRegex}}else{if(!hasOwnProp(this,"_weekdaysMinRegex")){this._weekdaysMinRegex=defaultWeekdaysMinRegex}return this._weekdaysMinStrictRegex&&isStrict?this._weekdaysMinStrictRegex:this._weekdaysMinRegex}}function computeWeekdaysParse(){function cmpLenRev(a,b){return b.length-a.length}var minPieces=[],shortPieces=[],longPieces=[],mixedPieces=[],i,mom,minp,shortp,longp;for(i=0;i<7;i++){mom=createUTC([2e3,1]).day(i);minp=this.weekdaysMin(mom,"");shortp=this.weekdaysShort(mom,"");longp=this.weekdays(mom,"");minPieces.push(minp);shortPieces.push(shortp);longPieces.push(longp);mixedPieces.push(minp);mixedPieces.push(shortp);mixedPieces.push(longp)}minPieces.sort(cmpLenRev);shortPieces.sort(cmpLenRev);longPieces.sort(cmpLenRev);mixedPieces.sort(cmpLenRev);for(i=0;i<7;i++){shortPieces[i]=regexEscape(shortPieces[i]);longPieces[i]=regexEscape(longPieces[i]);mixedPieces[i]=regexEscape(mixedPieces[i])}this._weekdaysRegex=new RegExp("^("+mixedPieces.join("|")+")","i");this._weekdaysShortRegex=this._weekdaysRegex;this._weekdaysMinRegex=this._weekdaysRegex;this._weekdaysStrictRegex=new RegExp("^("+longPieces.join("|")+")","i");this._weekdaysShortStrictRegex=new RegExp("^("+shortPieces.join("|")+")","i");this._weekdaysMinStrictRegex=new RegExp("^("+minPieces.join("|")+")","i")}function hFormat(){return this.hours()%12||12}function kFormat(){return this.hours()||24}addFormatToken("H",["HH",2],0,"hour");addFormatToken("h",["hh",2],0,hFormat);addFormatToken("k",["kk",2],0,kFormat);addFormatToken("hmm",0,0,function(){return""+hFormat.apply(this)+zeroFill(this.minutes(),2)});addFormatToken("hmmss",0,0,function(){return""+hFormat.apply(this)+zeroFill(this.minutes(),2)+zeroFill(this.seconds(),2)});addFormatToken("Hmm",0,0,function(){return""+this.hours()+zeroFill(this.minutes(),2)});addFormatToken("Hmmss",0,0,function(){return""+this.hours()+zeroFill(this.minutes(),2)+zeroFill(this.seconds(),2)});function meridiem(token,lowercase){addFormatToken(token,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),lowercase)})}meridiem("a",true);meridiem("A",false);addUnitAlias("hour","h");addUnitPriority("hour",13);function matchMeridiem(isStrict,locale){return locale._meridiemParse}addRegexToken("a",matchMeridiem);addRegexToken("A",matchMeridiem);addRegexToken("H",match1to2);addRegexToken("h",match1to2);addRegexToken("k",match1to2);addRegexToken("HH",match1to2,match2);addRegexToken("hh",match1to2,match2);addRegexToken("kk",match1to2,match2);addRegexToken("hmm",match3to4);addRegexToken("hmmss",match5to6);addRegexToken("Hmm",match3to4);addRegexToken("Hmmss",match5to6);addParseToken(["H","HH"],HOUR);addParseToken(["k","kk"],function(input,array,config){var kInput=toInt(input);array[HOUR]=kInput===24?0:kInput});addParseToken(["a","A"],function(input,array,config){config._isPm=config._locale.isPM(input);config._meridiem=input});addParseToken(["h","hh"],function(input,array,config){array[HOUR]=toInt(input);getParsingFlags(config).bigHour=true});addParseToken("hmm",function(input,array,config){var pos=input.length-2;array[HOUR]=toInt(input.substr(0,pos));array[MINUTE]=toInt(input.substr(pos));getParsingFlags(config).bigHour=true});addParseToken("hmmss",function(input,array,config){var pos1=input.length-4;var pos2=input.length-2;array[HOUR]=toInt(input.substr(0,pos1));array[MINUTE]=toInt(input.substr(pos1,2));array[SECOND]=toInt(input.substr(pos2));getParsingFlags(config).bigHour=true});addParseToken("Hmm",function(input,array,config){var pos=input.length-2;array[HOUR]=toInt(input.substr(0,pos));array[MINUTE]=toInt(input.substr(pos))});addParseToken("Hmmss",function(input,array,config){var pos1=input.length-4;var pos2=input.length-2;array[HOUR]=toInt(input.substr(0,pos1));array[MINUTE]=toInt(input.substr(pos1,2));array[SECOND]=toInt(input.substr(pos2))});function localeIsPM(input){return(input+"").toLowerCase().charAt(0)==="p"}var defaultLocaleMeridiemParse=/[ap]\.?m?\.?/i;function localeMeridiem(hours,minutes,isLower){if(hours>11){return isLower?"pm":"PM"}else{return isLower?"am":"AM"}}var getSetHour=makeGetSet("Hours",true);var baseConfig={calendar:defaultCalendar,longDateFormat:defaultLongDateFormat,invalidDate:defaultInvalidDate,ordinal:defaultOrdinal,dayOfMonthOrdinalParse:defaultDayOfMonthOrdinalParse,relativeTime:defaultRelativeTime,months:defaultLocaleMonths,monthsShort:defaultLocaleMonthsShort,week:defaultLocaleWeek,weekdays:defaultLocaleWeekdays,weekdaysMin:defaultLocaleWeekdaysMin,weekdaysShort:defaultLocaleWeekdaysShort,meridiemParse:defaultLocaleMeridiemParse};var locales={};var localeFamilies={};var globalLocale;function normalizeLocale(key){return key?key.toLowerCase().replace("_","-"):key}function chooseLocale(names){var i=0,j,next,locale,split;while(i<names.length){split=normalizeLocale(names[i]).split("-");j=split.length;next=normalizeLocale(names[i+1]);next=next?next.split("-"):null;while(j>0){locale=loadLocale(split.slice(0,j).join("-"));if(locale){return locale}if(next&&next.length>=j&&compareArrays(split,next,true)>=j-1){break}j--}i++}return null}function loadLocale(name){var oldLocale=null;if(!locales[name]&&typeof module!=="undefined"&&module&&module.exports){try{oldLocale=globalLocale._abbr;require("./locale/"+name);getSetGlobalLocale(oldLocale)}catch(e){}}return locales[name]}function getSetGlobalLocale(key,values){var data;if(key){if(isUndefined(values)){data=getLocale(key)}else{data=defineLocale(key,values)}if(data){globalLocale=data}}return globalLocale._abbr}function defineLocale(name,config){if(config!==null){var parentConfig=baseConfig;config.abbr=name;if(locales[name]!=null){deprecateSimple("defineLocaleOverride","use moment.updateLocale(localeName, config) to change "+"an existing locale. moment.defineLocale(localeName, "+"config) should only be used for creating a new locale "+"See http://momentjs.com/guides/#/warnings/define-locale/ for more info.");parentConfig=locales[name]._config}else if(config.parentLocale!=null){if(locales[config.parentLocale]!=null){parentConfig=locales[config.parentLocale]._config}else{if(!localeFamilies[config.parentLocale]){localeFamilies[config.parentLocale]=[]}localeFamilies[config.parentLocale].push({name:name,config:config});return null}}locales[name]=new Locale(mergeConfigs(parentConfig,config));if(localeFamilies[name]){localeFamilies[name].forEach(function(x){defineLocale(x.name,x.config)})}getSetGlobalLocale(name);return locales[name]}else{delete locales[name];return null}}function updateLocale(name,config){if(config!=null){var locale,parentConfig=baseConfig;if(locales[name]!=null){parentConfig=locales[name]._config}config=mergeConfigs(parentConfig,config);locale=new Locale(config);locale.parentLocale=locales[name];locales[name]=locale;getSetGlobalLocale(name)}else{if(locales[name]!=null){if(locales[name].parentLocale!=null){locales[name]=locales[name].parentLocale}else if(locales[name]!=null){delete locales[name]}}}return locales[name]}function getLocale(key){var locale;if(key&&key._locale&&key._locale._abbr){key=key._locale._abbr}if(!key){return globalLocale}if(!isArray(key)){locale=loadLocale(key);if(locale){return locale}key=[key]}return chooseLocale(key)}function listLocales(){return keys$1(locales)}function checkOverflow(m){var overflow;var a=m._a;if(a&&getParsingFlags(m).overflow===-2){overflow=a[MONTH]<0||a[MONTH]>11?MONTH:a[DATE]<1||a[DATE]>daysInMonth(a[YEAR],a[MONTH])?DATE:a[HOUR]<0||a[HOUR]>24||a[HOUR]===24&&(a[MINUTE]!==0||a[SECOND]!==0||a[MILLISECOND]!==0)?HOUR:a[MINUTE]<0||a[MINUTE]>59?MINUTE:a[SECOND]<0||a[SECOND]>59?SECOND:a[MILLISECOND]<0||a[MILLISECOND]>999?MILLISECOND:-1;if(getParsingFlags(m)._overflowDayOfYear&&(overflow<YEAR||overflow>DATE)){overflow=DATE}if(getParsingFlags(m)._overflowWeeks&&overflow===-1){overflow=WEEK}if(getParsingFlags(m)._overflowWeekday&&overflow===-1){overflow=WEEKDAY}getParsingFlags(m).overflow=overflow}return m}var extendedIsoRegex=/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;var basicIsoRegex=/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;var tzRegex=/Z|[+-]\d\d(?::?\d\d)?/;var isoDates=[["YYYYYY-MM-DD",/[+-]\d{6}-\d\d-\d\d/],["YYYY-MM-DD",/\d{4}-\d\d-\d\d/],["GGGG-[W]WW-E",/\d{4}-W\d\d-\d/],["GGGG-[W]WW",/\d{4}-W\d\d/,false],["YYYY-DDD",/\d{4}-\d{3}/],["YYYY-MM",/\d{4}-\d\d/,false],["YYYYYYMMDD",/[+-]\d{10}/],["YYYYMMDD",/\d{8}/],["GGGG[W]WWE",/\d{4}W\d{3}/],["GGGG[W]WW",/\d{4}W\d{2}/,false],["YYYYDDD",/\d{7}/]];var isoTimes=[["HH:mm:ss.SSSS",/\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss,SSSS",/\d\d:\d\d:\d\d,\d+/],["HH:mm:ss",/\d\d:\d\d:\d\d/],["HH:mm",/\d\d:\d\d/],["HHmmss.SSSS",/\d\d\d\d\d\d\.\d+/],["HHmmss,SSSS",/\d\d\d\d\d\d,\d+/],["HHmmss",/\d\d\d\d\d\d/],["HHmm",/\d\d\d\d/],["HH",/\d\d/]];var aspNetJsonRegex=/^\/?Date\((\-?\d+)/i;function configFromISO(config){var i,l,string=config._i,match=extendedIsoRegex.exec(string)||basicIsoRegex.exec(string),allowTime,dateFormat,timeFormat,tzFormat;if(match){getParsingFlags(config).iso=true;for(i=0,l=isoDates.length;i<l;i++){if(isoDates[i][1].exec(match[1])){dateFormat=isoDates[i][0];allowTime=isoDates[i][2]!==false;break}}if(dateFormat==null){config._isValid=false;return}if(match[3]){for(i=0,l=isoTimes.length;i<l;i++){if(isoTimes[i][1].exec(match[3])){timeFormat=(match[2]||" ")+isoTimes[i][0];break}}if(timeFormat==null){config._isValid=false;return}}if(!allowTime&&timeFormat!=null){config._isValid=false;return}if(match[4]){if(tzRegex.exec(match[4])){tzFormat="Z"}else{config._isValid=false;return}}config._f=dateFormat+(timeFormat||"")+(tzFormat||"");configFromStringAndFormat(config)}else{config._isValid=false}}var basicRfcRegex=/^((?:Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d?\d\s(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(?:\d\d)?\d\d\s)(\d\d:\d\d)(\:\d\d)?(\s(?:UT|GMT|[ECMP][SD]T|[A-IK-Za-ik-z]|[+-]\d{4}))$/;function configFromRFC2822(config){var string,match,dayFormat,dateFormat,timeFormat,tzFormat;var timezones={" GMT":" +0000"," EDT":" -0400"," EST":" -0500"," CDT":" -0500"," CST":" -0600"," MDT":" -0600"," MST":" -0700"," PDT":" -0700"," PST":" -0800"};var military="YXWVUTSRQPONZABCDEFGHIKLM";var timezone,timezoneIndex;string=config._i.replace(/\([^\)]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").replace(/^\s|\s$/g,"");match=basicRfcRegex.exec(string);if(match){dayFormat=match[1]?"ddd"+(match[1].length===5?", ":" "):"";dateFormat="D MMM "+(match[2].length>10?"YYYY ":"YY ");timeFormat="HH:mm"+(match[4]?":ss":"");if(match[1]){var momentDate=new Date(match[2]);var momentDay=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][momentDate.getDay()];if(match[1].substr(0,3)!==momentDay){getParsingFlags(config).weekdayMismatch=true;config._isValid=false;return}}switch(match[5].length){case 2:if(timezoneIndex===0){timezone=" +0000"}else{timezoneIndex=military.indexOf(match[5][1].toUpperCase())-12;timezone=(timezoneIndex<0?" -":" +")+(""+timezoneIndex).replace(/^-?/,"0").match(/..$/)[0]+"00"}break;case 4:timezone=timezones[match[5]];break;default:timezone=timezones[" GMT"]}match[5]=timezone;config._i=match.splice(1).join("");tzFormat=" ZZ";config._f=dayFormat+dateFormat+timeFormat+tzFormat;configFromStringAndFormat(config);getParsingFlags(config).rfc2822=true}else{config._isValid=false}}function configFromString(config){var matched=aspNetJsonRegex.exec(config._i);if(matched!==null){config._d=new Date(+matched[1]);return}configFromISO(config);if(config._isValid===false){delete config._isValid}else{return}configFromRFC2822(config);if(config._isValid===false){delete config._isValid}else{return}hooks.createFromInputFallback(config)}hooks.createFromInputFallback=deprecate("value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), "+"which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are "+"discouraged and will be removed in an upcoming major release. Please refer to "+"http://momentjs.com/guides/#/warnings/js-date/ for more info.",function(config){config._d=new Date(config._i+(config._useUTC?" UTC":""))});function defaults(a,b,c){if(a!=null){return a}if(b!=null){return b}return c}function currentDateArray(config){var nowValue=new Date(hooks.now());if(config._useUTC){return[nowValue.getUTCFullYear(),nowValue.getUTCMonth(),nowValue.getUTCDate()]}return[nowValue.getFullYear(),nowValue.getMonth(),nowValue.getDate()]}function configFromArray(config){var i,date,input=[],currentDate,yearToUse;if(config._d){return}currentDate=currentDateArray(config);if(config._w&&config._a[DATE]==null&&config._a[MONTH]==null){dayOfYearFromWeekInfo(config)}if(config._dayOfYear!=null){yearToUse=defaults(config._a[YEAR],currentDate[YEAR]);if(config._dayOfYear>daysInYear(yearToUse)||config._dayOfYear===0){getParsingFlags(config)._overflowDayOfYear=true}date=createUTCDate(yearToUse,0,config._dayOfYear);config._a[MONTH]=date.getUTCMonth();config._a[DATE]=date.getUTCDate()}for(i=0;i<3&&config._a[i]==null;++i){config._a[i]=input[i]=currentDate[i]}for(;i<7;i++){config._a[i]=input[i]=config._a[i]==null?i===2?1:0:config._a[i]}if(config._a[HOUR]===24&&config._a[MINUTE]===0&&config._a[SECOND]===0&&config._a[MILLISECOND]===0){config._nextDay=true;config._a[HOUR]=0}config._d=(config._useUTC?createUTCDate:createDate).apply(null,input);if(config._tzm!=null){config._d.setUTCMinutes(config._d.getUTCMinutes()-config._tzm)}if(config._nextDay){config._a[HOUR]=24}}function dayOfYearFromWeekInfo(config){var w,weekYear,week,weekday,dow,doy,temp,weekdayOverflow;w=config._w;if(w.GG!=null||w.W!=null||w.E!=null){dow=1;doy=4;weekYear=defaults(w.GG,config._a[YEAR],weekOfYear(createLocal(),1,4).year);week=defaults(w.W,1);weekday=defaults(w.E,1);if(weekday<1||weekday>7){weekdayOverflow=true}}else{dow=config._locale._week.dow;doy=config._locale._week.doy;var curWeek=weekOfYear(createLocal(),dow,doy);weekYear=defaults(w.gg,config._a[YEAR],curWeek.year);week=defaults(w.w,curWeek.week);if(w.d!=null){weekday=w.d;if(weekday<0||weekday>6){weekdayOverflow=true}}else if(w.e!=null){weekday=w.e+dow;if(w.e<0||w.e>6){weekdayOverflow=true}}else{weekday=dow}}if(week<1||week>weeksInYear(weekYear,dow,doy)){getParsingFlags(config)._overflowWeeks=true}else if(weekdayOverflow!=null){getParsingFlags(config)._overflowWeekday=true}else{temp=dayOfYearFromWeeks(weekYear,week,weekday,dow,doy);config._a[YEAR]=temp.year;config._dayOfYear=temp.dayOfYear}}hooks.ISO_8601=function(){};hooks.RFC_2822=function(){};function configFromStringAndFormat(config){if(config._f===hooks.ISO_8601){configFromISO(config);return}if(config._f===hooks.RFC_2822){configFromRFC2822(config);return}config._a=[];getParsingFlags(config).empty=true;var string=""+config._i,i,parsedInput,tokens,token,skipped,stringLength=string.length,totalParsedInputLength=0;tokens=expandFormat(config._f,config._locale).match(formattingTokens)||[];for(i=0;i<tokens.length;i++){token=tokens[i];parsedInput=(string.match(getParseRegexForToken(token,config))||[])[0];if(parsedInput){skipped=string.substr(0,string.indexOf(parsedInput));if(skipped.length>0){getParsingFlags(config).unusedInput.push(skipped)}string=string.slice(string.indexOf(parsedInput)+parsedInput.length);totalParsedInputLength+=parsedInput.length}if(formatTokenFunctions[token]){if(parsedInput){getParsingFlags(config).empty=false}else{getParsingFlags(config).unusedTokens.push(token)}addTimeToArrayFromToken(token,parsedInput,config)}else if(config._strict&&!parsedInput){getParsingFlags(config).unusedTokens.push(token)}}getParsingFlags(config).charsLeftOver=stringLength-totalParsedInputLength;if(string.length>0){getParsingFlags(config).unusedInput.push(string)}if(config._a[HOUR]<=12&&getParsingFlags(config).bigHour===true&&config._a[HOUR]>0){getParsingFlags(config).bigHour=undefined}getParsingFlags(config).parsedDateParts=config._a.slice(0);getParsingFlags(config).meridiem=config._meridiem;config._a[HOUR]=meridiemFixWrap(config._locale,config._a[HOUR],config._meridiem);configFromArray(config);checkOverflow(config)}function meridiemFixWrap(locale,hour,meridiem){var isPm;if(meridiem==null){return hour}if(locale.meridiemHour!=null){return locale.meridiemHour(hour,meridiem)}else if(locale.isPM!=null){isPm=locale.isPM(meridiem);if(isPm&&hour<12){hour+=12}if(!isPm&&hour===12){hour=0}return hour}else{return hour}}function configFromStringAndArray(config){var tempConfig,bestMoment,scoreToBeat,i,currentScore;if(config._f.length===0){getParsingFlags(config).invalidFormat=true;config._d=new Date(NaN);return}for(i=0;i<config._f.length;i++){currentScore=0;tempConfig=copyConfig({},config);if(config._useUTC!=null){tempConfig._useUTC=config._useUTC}tempConfig._f=config._f[i];configFromStringAndFormat(tempConfig);if(!isValid(tempConfig)){continue}currentScore+=getParsingFlags(tempConfig).charsLeftOver;currentScore+=getParsingFlags(tempConfig).unusedTokens.length*10;getParsingFlags(tempConfig).score=currentScore;if(scoreToBeat==null||currentScore<scoreToBeat){scoreToBeat=currentScore;bestMoment=tempConfig}}extend(config,bestMoment||tempConfig)}function configFromObject(config){if(config._d){return}var i=normalizeObjectUnits(config._i);config._a=map([i.year,i.month,i.day||i.date,i.hour,i.minute,i.second,i.millisecond],function(obj){return obj&&parseInt(obj,10)});configFromArray(config)}function createFromConfig(config){var res=new Moment(checkOverflow(prepareConfig(config)));if(res._nextDay){res.add(1,"d");res._nextDay=undefined}return res}function prepareConfig(config){var input=config._i,format=config._f;config._locale=config._locale||getLocale(config._l);if(input===null||format===undefined&&input===""){return createInvalid({nullInput:true})}if(typeof input==="string"){config._i=input=config._locale.preparse(input)}if(isMoment(input)){return new Moment(checkOverflow(input))}else if(isDate(input)){config._d=input}else if(isArray(format)){configFromStringAndArray(config)}else if(format){configFromStringAndFormat(config)}else{configFromInput(config)}if(!isValid(config)){config._d=null}return config}function configFromInput(config){var input=config._i;if(isUndefined(input)){config._d=new Date(hooks.now())}else if(isDate(input)){config._d=new Date(input.valueOf())}else if(typeof input==="string"){configFromString(config)}else if(isArray(input)){config._a=map(input.slice(0),function(obj){return parseInt(obj,10)});configFromArray(config)}else if(isObject(input)){configFromObject(config)}else if(isNumber(input)){config._d=new Date(input)}else{hooks.createFromInputFallback(config)}}function createLocalOrUTC(input,format,locale,strict,isUTC){var c={};if(locale===true||locale===false){strict=locale;locale=undefined}if(isObject(input)&&isObjectEmpty(input)||isArray(input)&&input.length===0){input=undefined}c._isAMomentObject=true;c._useUTC=c._isUTC=isUTC;c._l=locale;c._i=input;c._f=format;c._strict=strict;return createFromConfig(c)}function createLocal(input,format,locale,strict){return createLocalOrUTC(input,format,locale,strict,false)}var prototypeMin=deprecate("moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var other=createLocal.apply(null,arguments);if(this.isValid()&&other.isValid()){return other<this?this:other}else{return createInvalid()}});var prototypeMax=deprecate("moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var other=createLocal.apply(null,arguments);if(this.isValid()&&other.isValid()){return other>this?this:other}else{return createInvalid()}});function pickBy(fn,moments){var res,i;if(moments.length===1&&isArray(moments[0])){moments=moments[0]}if(!moments.length){return createLocal()}res=moments[0];for(i=1;i<moments.length;++i){if(!moments[i].isValid()||moments[i][fn](res)){res=moments[i]}}return res}function min(){var args=[].slice.call(arguments,0);return pickBy("isBefore",args)}function max(){var args=[].slice.call(arguments,0);return pickBy("isAfter",args)}var now=function(){return Date.now?Date.now():+new Date};var ordering=["year","quarter","month","week","day","hour","minute","second","millisecond"];function isDurationValid(m){for(var key in m){if(!(ordering.indexOf(key)!==-1&&(m[key]==null||!isNaN(m[key])))){return false}}var unitHasDecimal=false;for(var i=0;i<ordering.length;++i){if(m[ordering[i]]){if(unitHasDecimal){return false}if(parseFloat(m[ordering[i]])!==toInt(m[ordering[i]])){unitHasDecimal=true}}}return true}function isValid$1(){return this._isValid}function createInvalid$1(){return createDuration(NaN)}function Duration(duration){var normalizedInput=normalizeObjectUnits(duration),years=normalizedInput.year||0,quarters=normalizedInput.quarter||0,months=normalizedInput.month||0,weeks=normalizedInput.week||0,days=normalizedInput.day||0,hours=normalizedInput.hour||0,minutes=normalizedInput.minute||0,seconds=normalizedInput.second||0,milliseconds=normalizedInput.millisecond||0;this._isValid=isDurationValid(normalizedInput);this._milliseconds=+milliseconds+seconds*1e3+minutes*6e4+hours*1e3*60*60;this._days=+days+weeks*7;this._months=+months+quarters*3+years*12;this._data={};this._locale=getLocale();this._bubble()}function isDuration(obj){return obj instanceof Duration}function absRound(number){if(number<0){return Math.round(-1*number)*-1}else{return Math.round(number)}}function offset(token,separator){addFormatToken(token,0,0,function(){var offset=this.utcOffset();var sign="+";if(offset<0){offset=-offset;sign="-"}return sign+zeroFill(~~(offset/60),2)+separator+zeroFill(~~offset%60,2)})}offset("Z",":");offset("ZZ","");addRegexToken("Z",matchShortOffset);addRegexToken("ZZ",matchShortOffset);addParseToken(["Z","ZZ"],function(input,array,config){config._useUTC=true;config._tzm=offsetFromString(matchShortOffset,input)});var chunkOffset=/([\+\-]|\d\d)/gi;function offsetFromString(matcher,string){var matches=(string||"").match(matcher);if(matches===null){return null}var chunk=matches[matches.length-1]||[];var parts=(chunk+"").match(chunkOffset)||["-",0,0];var minutes=+(parts[1]*60)+toInt(parts[2]);return minutes===0?0:parts[0]==="+"?minutes:-minutes}function cloneWithOffset(input,model){var res,diff;if(model._isUTC){res=model.clone();diff=(isMoment(input)||isDate(input)?input.valueOf():createLocal(input).valueOf())-res.valueOf();res._d.setTime(res._d.valueOf()+diff);hooks.updateOffset(res,false);return res}else{return createLocal(input).local()}}function getDateOffset(m){return-Math.round(m._d.getTimezoneOffset()/15)*15}hooks.updateOffset=function(){};function getSetOffset(input,keepLocalTime,keepMinutes){var offset=this._offset||0,localAdjust;if(!this.isValid()){return input!=null?this:NaN}if(input!=null){if(typeof input==="string"){input=offsetFromString(matchShortOffset,input);if(input===null){return this}}else if(Math.abs(input)<16&&!keepMinutes){input=input*60}if(!this._isUTC&&keepLocalTime){localAdjust=getDateOffset(this)}this._offset=input;this._isUTC=true;if(localAdjust!=null){this.add(localAdjust,"m")}if(offset!==input){if(!keepLocalTime||this._changeInProgress){addSubtract(this,createDuration(input-offset,"m"),1,false)}else if(!this._changeInProgress){this._changeInProgress=true;hooks.updateOffset(this,true);this._changeInProgress=null}}return this}else{return this._isUTC?offset:getDateOffset(this)}}function getSetZone(input,keepLocalTime){if(input!=null){if(typeof input!=="string"){input=-input}this.utcOffset(input,keepLocalTime);return this}else{return-this.utcOffset()}}function setOffsetToUTC(keepLocalTime){return this.utcOffset(0,keepLocalTime)}function setOffsetToLocal(keepLocalTime){if(this._isUTC){this.utcOffset(0,keepLocalTime);this._isUTC=false;if(keepLocalTime){this.subtract(getDateOffset(this),"m")}}return this}function setOffsetToParsedOffset(){if(this._tzm!=null){this.utcOffset(this._tzm,false,true)}else if(typeof this._i==="string"){var tZone=offsetFromString(matchOffset,this._i);if(tZone!=null){this.utcOffset(tZone)}else{this.utcOffset(0,true)}}return this}function hasAlignedHourOffset(input){if(!this.isValid()){return false}input=input?createLocal(input).utcOffset():0;return(this.utcOffset()-input)%60===0}function isDaylightSavingTime(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()}function isDaylightSavingTimeShifted(){if(!isUndefined(this._isDSTShifted)){return this._isDSTShifted}var c={};copyConfig(c,this);c=prepareConfig(c);if(c._a){var other=c._isUTC?createUTC(c._a):createLocal(c._a);this._isDSTShifted=this.isValid()&&compareArrays(c._a,other.toArray())>0}else{this._isDSTShifted=false}return this._isDSTShifted}function isLocal(){return this.isValid()?!this._isUTC:false}function isUtcOffset(){return this.isValid()?this._isUTC:false}function isUtc(){return this.isValid()?this._isUTC&&this._offset===0:false}var aspNetRegex=/^(\-)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/;var isoRegex=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/;function createDuration(input,key){var duration=input,match=null,sign,ret,diffRes;if(isDuration(input)){duration={ms:input._milliseconds,d:input._days,M:input._months}}else if(isNumber(input)){duration={};if(key){duration[key]=input}else{duration.milliseconds=input}}else if(!!(match=aspNetRegex.exec(input))){sign=match[1]==="-"?-1:1;duration={y:0,d:toInt(match[DATE])*sign,h:toInt(match[HOUR])*sign,m:toInt(match[MINUTE])*sign,s:toInt(match[SECOND])*sign,ms:toInt(absRound(match[MILLISECOND]*1e3))*sign}}else if(!!(match=isoRegex.exec(input))){sign=match[1]==="-"?-1:1;duration={y:parseIso(match[2],sign),M:parseIso(match[3],sign),w:parseIso(match[4],sign),d:parseIso(match[5],sign),h:parseIso(match[6],sign),m:parseIso(match[7],sign),s:parseIso(match[8],sign)}}else if(duration==null){duration={}}else if(typeof duration==="object"&&("from"in duration||"to"in duration)){diffRes=momentsDifference(createLocal(duration.from),createLocal(duration.to));duration={};duration.ms=diffRes.milliseconds;duration.M=diffRes.months}ret=new Duration(duration);if(isDuration(input)&&hasOwnProp(input,"_locale")){ret._locale=input._locale}return ret}createDuration.fn=Duration.prototype;createDuration.invalid=createInvalid$1;function parseIso(inp,sign){var res=inp&&parseFloat(inp.replace(",","."));return(isNaN(res)?0:res)*sign}function positiveMomentsDifference(base,other){var res={milliseconds:0,months:0};res.months=other.month()-base.month()+(other.year()-base.year())*12;if(base.clone().add(res.months,"M").isAfter(other)){--res.months}res.milliseconds=+other-+base.clone().add(res.months,"M");return res}function momentsDifference(base,other){var res;if(!(base.isValid()&&other.isValid())){return{milliseconds:0,months:0}}other=cloneWithOffset(other,base);if(base.isBefore(other)){res=positiveMomentsDifference(base,other)}else{res=positiveMomentsDifference(other,base);res.milliseconds=-res.milliseconds;res.months=-res.months}return res}function createAdder(direction,name){return function(val,period){var dur,tmp;if(period!==null&&!isNaN(+period)){deprecateSimple(name,"moment()."+name+"(period, number) is deprecated. Please use moment()."+name+"(number, period). "+"See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.");tmp=val;val=period;period=tmp}val=typeof val==="string"?+val:val;dur=createDuration(val,period);addSubtract(this,dur,direction);return this}}function addSubtract(mom,duration,isAdding,updateOffset){var milliseconds=duration._milliseconds,days=absRound(duration._days),months=absRound(duration._months);if(!mom.isValid()){return}updateOffset=updateOffset==null?true:updateOffset;if(milliseconds){mom._d.setTime(mom._d.valueOf()+milliseconds*isAdding)}if(days){set$1(mom,"Date",get(mom,"Date")+days*isAdding)}if(months){setMonth(mom,get(mom,"Month")+months*isAdding)}if(updateOffset){hooks.updateOffset(mom,days||months)}}var add=createAdder(1,"add");var subtract=createAdder(-1,"subtract");function getCalendarFormat(myMoment,now){var diff=myMoment.diff(now,"days",true);return diff<-6?"sameElse":diff<-1?"lastWeek":diff<0?"lastDay":diff<1?"sameDay":diff<2?"nextDay":diff<7?"nextWeek":"sameElse"}function calendar$1(time,formats){var now=time||createLocal(),sod=cloneWithOffset(now,this).startOf("day"),format=hooks.calendarFormat(this,sod)||"sameElse";var output=formats&&(isFunction(formats[format])?formats[format].call(this,now):formats[format]);return this.format(output||this.localeData().calendar(format,this,createLocal(now)))}function clone(){return new Moment(this)}function isAfter(input,units){var localInput=isMoment(input)?input:createLocal(input);if(!(this.isValid()&&localInput.isValid())){return false}units=normalizeUnits(!isUndefined(units)?units:"millisecond");if(units==="millisecond"){return this.valueOf()>localInput.valueOf()}else{return localInput.valueOf()<this.clone().startOf(units).valueOf()}}function isBefore(input,units){var localInput=isMoment(input)?input:createLocal(input);if(!(this.isValid()&&localInput.isValid())){return false}units=normalizeUnits(!isUndefined(units)?units:"millisecond");if(units==="millisecond"){return this.valueOf()<localInput.valueOf()}else{return this.clone().endOf(units).valueOf()<localInput.valueOf()}}function isBetween(from,to,units,inclusivity){inclusivity=inclusivity||"()";return(inclusivity[0]==="("?this.isAfter(from,units):!this.isBefore(from,units))&&(inclusivity[1]===")"?this.isBefore(to,units):!this.isAfter(to,units))}function isSame(input,units){var localInput=isMoment(input)?input:createLocal(input),inputMs;if(!(this.isValid()&&localInput.isValid())){return false}units=normalizeUnits(units||"millisecond");if(units==="millisecond"){return this.valueOf()===localInput.valueOf()}else{inputMs=localInput.valueOf();return this.clone().startOf(units).valueOf()<=inputMs&&inputMs<=this.clone().endOf(units).valueOf()}}function isSameOrAfter(input,units){return this.isSame(input,units)||this.isAfter(input,units)}function isSameOrBefore(input,units){return this.isSame(input,units)||this.isBefore(input,units)}function diff(input,units,asFloat){var that,zoneDelta,delta,output;if(!this.isValid()){return NaN}that=cloneWithOffset(input,this);if(!that.isValid()){return NaN}zoneDelta=(that.utcOffset()-this.utcOffset())*6e4;units=normalizeUnits(units);if(units==="year"||units==="month"||units==="quarter"){output=monthDiff(this,that);if(units==="quarter"){output=output/3}else if(units==="year"){output=output/12}}else{delta=this-that;output=units==="second"?delta/1e3:units==="minute"?delta/6e4:units==="hour"?delta/36e5:units==="day"?(delta-zoneDelta)/864e5:units==="week"?(delta-zoneDelta)/6048e5:delta}return asFloat?output:absFloor(output)}function monthDiff(a,b){var wholeMonthDiff=(b.year()-a.year())*12+(b.month()-a.month()),anchor=a.clone().add(wholeMonthDiff,"months"),anchor2,adjust;if(b-anchor<0){anchor2=a.clone().add(wholeMonthDiff-1,"months");adjust=(b-anchor)/(anchor-anchor2)}else{anchor2=a.clone().add(wholeMonthDiff+1,"months");adjust=(b-anchor)/(anchor2-anchor)}return-(wholeMonthDiff+adjust)||0}hooks.defaultFormat="YYYY-MM-DDTHH:mm:ssZ";hooks.defaultFormatUtc="YYYY-MM-DDTHH:mm:ss[Z]";function toString(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")}function toISOString(){if(!this.isValid()){return null}var m=this.clone().utc();if(m.year()<0||m.year()>9999){return formatMoment(m,"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]")}if(isFunction(Date.prototype.toISOString)){return this.toDate().toISOString()}return formatMoment(m,"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]")}function inspect(){if(!this.isValid()){return"moment.invalid(/* "+this._i+" */)"}var func="moment";var zone="";if(!this.isLocal()){func=this.utcOffset()===0?"moment.utc":"moment.parseZone";zone="Z"}var prefix="["+func+'("]';var year=0<=this.year()&&this.year()<=9999?"YYYY":"YYYYYY";var datetime="-MM-DD[T]HH:mm:ss.SSS";var suffix=zone+'[")]';return this.format(prefix+year+datetime+suffix)}function format(inputString){if(!inputString){inputString=this.isUtc()?hooks.defaultFormatUtc:hooks.defaultFormat}var output=formatMoment(this,inputString);return this.localeData().postformat(output)}function from(time,withoutSuffix){if(this.isValid()&&(isMoment(time)&&time.isValid()||createLocal(time).isValid())){return createDuration({to:this,from:time}).locale(this.locale()).humanize(!withoutSuffix)}else{return this.localeData().invalidDate()}}function fromNow(withoutSuffix){return this.from(createLocal(),withoutSuffix)}function to(time,withoutSuffix){if(this.isValid()&&(isMoment(time)&&time.isValid()||createLocal(time).isValid())){return createDuration({from:this,to:time}).locale(this.locale()).humanize(!withoutSuffix)}else{return this.localeData().invalidDate()}}function toNow(withoutSuffix){return this.to(createLocal(),withoutSuffix)}function locale(key){var newLocaleData;if(key===undefined){return this._locale._abbr}else{newLocaleData=getLocale(key);if(newLocaleData!=null){this._locale=newLocaleData}return this}}var lang=deprecate("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(key){if(key===undefined){return this.localeData()}else{return this.locale(key)}});function localeData(){return this._locale}function startOf(units){units=normalizeUnits(units);switch(units){case"year":this.month(0);case"quarter":case"month":this.date(1);case"week":case"isoWeek":case"day":case"date":this.hours(0);case"hour":this.minutes(0);case"minute":this.seconds(0);case"second":this.milliseconds(0)}if(units==="week"){this.weekday(0)}if(units==="isoWeek"){this.isoWeekday(1)}if(units==="quarter"){this.month(Math.floor(this.month()/3)*3)}return this}function endOf(units){units=normalizeUnits(units);if(units===undefined||units==="millisecond"){return this}if(units==="date"){units="day"}return this.startOf(units).add(1,units==="isoWeek"?"week":units).subtract(1,"ms")}function valueOf(){return this._d.valueOf()-(this._offset||0)*6e4}function unix(){return Math.floor(this.valueOf()/1e3)}function toDate(){return new Date(this.valueOf())}function toArray(){var m=this;return[m.year(),m.month(),m.date(),m.hour(),m.minute(),m.second(),m.millisecond()]}function toObject(){var m=this;return{years:m.year(),months:m.month(),date:m.date(),hours:m.hours(),minutes:m.minutes(),seconds:m.seconds(),milliseconds:m.milliseconds()}}function toJSON(){return this.isValid()?this.toISOString():null}function isValid$2(){return isValid(this)}function parsingFlags(){return extend({},getParsingFlags(this))}function invalidAt(){return getParsingFlags(this).overflow}function creationData(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}}addFormatToken(0,["gg",2],0,function(){return this.weekYear()%100});addFormatToken(0,["GG",2],0,function(){return this.isoWeekYear()%100});function addWeekYearFormatToken(token,getter){addFormatToken(0,[token,token.length],0,getter)}addWeekYearFormatToken("gggg","weekYear");addWeekYearFormatToken("ggggg","weekYear");addWeekYearFormatToken("GGGG","isoWeekYear");addWeekYearFormatToken("GGGGG","isoWeekYear");addUnitAlias("weekYear","gg");addUnitAlias("isoWeekYear","GG");addUnitPriority("weekYear",1);addUnitPriority("isoWeekYear",1);addRegexToken("G",matchSigned);addRegexToken("g",matchSigned);addRegexToken("GG",match1to2,match2);addRegexToken("gg",match1to2,match2);addRegexToken("GGGG",match1to4,match4);addRegexToken("gggg",match1to4,match4);addRegexToken("GGGGG",match1to6,match6);addRegexToken("ggggg",match1to6,match6);addWeekParseToken(["gggg","ggggg","GGGG","GGGGG"],function(input,week,config,token){week[token.substr(0,2)]=toInt(input)});addWeekParseToken(["gg","GG"],function(input,week,config,token){week[token]=hooks.parseTwoDigitYear(input)});function getSetWeekYear(input){return getSetWeekYearHelper.call(this,input,this.week(),this.weekday(),this.localeData()._week.dow,this.localeData()._week.doy)}function getSetISOWeekYear(input){return getSetWeekYearHelper.call(this,input,this.isoWeek(),this.isoWeekday(),1,4)}function getISOWeeksInYear(){return weeksInYear(this.year(),1,4)}function getWeeksInYear(){var weekInfo=this.localeData()._week;return weeksInYear(this.year(),weekInfo.dow,weekInfo.doy)}function getSetWeekYearHelper(input,week,weekday,dow,doy){var weeksTarget;if(input==null){return weekOfYear(this,dow,doy).year}else{weeksTarget=weeksInYear(input,dow,doy);if(week>weeksTarget){week=weeksTarget}return setWeekAll.call(this,input,week,weekday,dow,doy)}}function setWeekAll(weekYear,week,weekday,dow,doy){var dayOfYearData=dayOfYearFromWeeks(weekYear,week,weekday,dow,doy),date=createUTCDate(dayOfYearData.year,0,dayOfYearData.dayOfYear);this.year(date.getUTCFullYear());this.month(date.getUTCMonth());this.date(date.getUTCDate());return this}addFormatToken("Q",0,"Qo","quarter");addUnitAlias("quarter","Q");addUnitPriority("quarter",7);addRegexToken("Q",match1);addParseToken("Q",function(input,array){array[MONTH]=(toInt(input)-1)*3});function getSetQuarter(input){return input==null?Math.ceil((this.month()+1)/3):this.month((input-1)*3+this.month()%3)}addFormatToken("D",["DD",2],"Do","date");addUnitAlias("date","D");addUnitPriority("date",9);addRegexToken("D",match1to2);addRegexToken("DD",match1to2,match2);addRegexToken("Do",function(isStrict,locale){return isStrict?locale._dayOfMonthOrdinalParse||locale._ordinalParse:locale._dayOfMonthOrdinalParseLenient});addParseToken(["D","DD"],DATE);addParseToken("Do",function(input,array){array[DATE]=toInt(input.match(match1to2)[0],10)});var getSetDayOfMonth=makeGetSet("Date",true);addFormatToken("DDD",["DDDD",3],"DDDo","dayOfYear");addUnitAlias("dayOfYear","DDD");addUnitPriority("dayOfYear",4);addRegexToken("DDD",match1to3);addRegexToken("DDDD",match3);addParseToken(["DDD","DDDD"],function(input,array,config){config._dayOfYear=toInt(input)});function getSetDayOfYear(input){var dayOfYear=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return input==null?dayOfYear:this.add(input-dayOfYear,"d")}addFormatToken("m",["mm",2],0,"minute");addUnitAlias("minute","m");addUnitPriority("minute",14);addRegexToken("m",match1to2);addRegexToken("mm",match1to2,match2);addParseToken(["m","mm"],MINUTE);var getSetMinute=makeGetSet("Minutes",false);addFormatToken("s",["ss",2],0,"second");addUnitAlias("second","s");addUnitPriority("second",15);addRegexToken("s",match1to2);addRegexToken("ss",match1to2,match2);addParseToken(["s","ss"],SECOND);var getSetSecond=makeGetSet("Seconds",false);addFormatToken("S",0,0,function(){return~~(this.millisecond()/100)});addFormatToken(0,["SS",2],0,function(){return~~(this.millisecond()/10)});addFormatToken(0,["SSS",3],0,"millisecond");addFormatToken(0,["SSSS",4],0,function(){return this.millisecond()*10});addFormatToken(0,["SSSSS",5],0,function(){return this.millisecond()*100});addFormatToken(0,["SSSSSS",6],0,function(){return this.millisecond()*1e3});addFormatToken(0,["SSSSSSS",7],0,function(){return this.millisecond()*1e4});addFormatToken(0,["SSSSSSSS",8],0,function(){return this.millisecond()*1e5});addFormatToken(0,["SSSSSSSSS",9],0,function(){return this.millisecond()*1e6});addUnitAlias("millisecond","ms");addUnitPriority("millisecond",16);addRegexToken("S",match1to3,match1);addRegexToken("SS",match1to3,match2);addRegexToken("SSS",match1to3,match3);var token;for(token="SSSS";token.length<=9;token+="S"){addRegexToken(token,matchUnsigned)}function parseMs(input,array){array[MILLISECOND]=toInt(("0."+input)*1e3)}for(token="S";token.length<=9;token+="S"){addParseToken(token,parseMs)}var getSetMillisecond=makeGetSet("Milliseconds",false);addFormatToken("z",0,0,"zoneAbbr");addFormatToken("zz",0,0,"zoneName");function getZoneAbbr(){return this._isUTC?"UTC":""}function getZoneName(){return this._isUTC?"Coordinated Universal Time":""}var proto=Moment.prototype;proto.add=add;proto.calendar=calendar$1;proto.clone=clone;proto.diff=diff;proto.endOf=endOf;proto.format=format;proto.from=from;proto.fromNow=fromNow;proto.to=to;proto.toNow=toNow;proto.get=stringGet;proto.invalidAt=invalidAt;proto.isAfter=isAfter;proto.isBefore=isBefore;proto.isBetween=isBetween;proto.isSame=isSame;proto.isSameOrAfter=isSameOrAfter;proto.isSameOrBefore=isSameOrBefore;proto.isValid=isValid$2;proto.lang=lang;proto.locale=locale;proto.localeData=localeData;proto.max=prototypeMax;proto.min=prototypeMin;proto.parsingFlags=parsingFlags;proto.set=stringSet;proto.startOf=startOf;proto.subtract=subtract;proto.toArray=toArray;proto.toObject=toObject;proto.toDate=toDate;proto.toISOString=toISOString;proto.inspect=inspect;proto.toJSON=toJSON;proto.toString=toString;proto.unix=unix;proto.valueOf=valueOf;proto.creationData=creationData;proto.year=getSetYear;proto.isLeapYear=getIsLeapYear;proto.weekYear=getSetWeekYear;proto.isoWeekYear=getSetISOWeekYear;proto.quarter=proto.quarters=getSetQuarter;proto.month=getSetMonth;proto.daysInMonth=getDaysInMonth;proto.week=proto.weeks=getSetWeek;proto.isoWeek=proto.isoWeeks=getSetISOWeek;proto.weeksInYear=getWeeksInYear;proto.isoWeeksInYear=getISOWeeksInYear;proto.date=getSetDayOfMonth;proto.day=proto.days=getSetDayOfWeek;proto.weekday=getSetLocaleDayOfWeek;proto.isoWeekday=getSetISODayOfWeek;proto.dayOfYear=getSetDayOfYear;proto.hour=proto.hours=getSetHour;proto.minute=proto.minutes=getSetMinute;proto.second=proto.seconds=getSetSecond;proto.millisecond=proto.milliseconds=getSetMillisecond;proto.utcOffset=getSetOffset;proto.utc=setOffsetToUTC;proto.local=setOffsetToLocal;proto.parseZone=setOffsetToParsedOffset;proto.hasAlignedHourOffset=hasAlignedHourOffset;proto.isDST=isDaylightSavingTime;proto.isLocal=isLocal;proto.isUtcOffset=isUtcOffset;proto.isUtc=isUtc;proto.isUTC=isUtc;proto.zoneAbbr=getZoneAbbr;proto.zoneName=getZoneName;proto.dates=deprecate("dates accessor is deprecated. Use date instead.",getSetDayOfMonth);proto.months=deprecate("months accessor is deprecated. Use month instead",getSetMonth);proto.years=deprecate("years accessor is deprecated. Use year instead",getSetYear);proto.zone=deprecate("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/",getSetZone);proto.isDSTShifted=deprecate("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information",isDaylightSavingTimeShifted);function createUnix(input){return createLocal(input*1e3)}function createInZone(){return createLocal.apply(null,arguments).parseZone()}function preParsePostFormat(string){return string}var proto$1=Locale.prototype;proto$1.calendar=calendar;proto$1.longDateFormat=longDateFormat;proto$1.invalidDate=invalidDate;proto$1.ordinal=ordinal;proto$1.preparse=preParsePostFormat;proto$1.postformat=preParsePostFormat;proto$1.relativeTime=relativeTime;proto$1.pastFuture=pastFuture;proto$1.set=set;proto$1.months=localeMonths;proto$1.monthsShort=localeMonthsShort;proto$1.monthsParse=localeMonthsParse;proto$1.monthsRegex=monthsRegex;proto$1.monthsShortRegex=monthsShortRegex;proto$1.week=localeWeek;proto$1.firstDayOfYear=localeFirstDayOfYear;proto$1.firstDayOfWeek=localeFirstDayOfWeek;proto$1.weekdays=localeWeekdays;proto$1.weekdaysMin=localeWeekdaysMin;proto$1.weekdaysShort=localeWeekdaysShort;proto$1.weekdaysParse=localeWeekdaysParse;proto$1.weekdaysRegex=weekdaysRegex;proto$1.weekdaysShortRegex=weekdaysShortRegex;proto$1.weekdaysMinRegex=weekdaysMinRegex;proto$1.isPM=localeIsPM;proto$1.meridiem=localeMeridiem;function get$1(format,index,field,setter){var locale=getLocale();var utc=createUTC().set(setter,index);return locale[field](utc,format)}function listMonthsImpl(format,index,field){if(isNumber(format)){index=format;format=undefined}format=format||"";if(index!=null){return get$1(format,index,field,"month")}var i;var out=[];for(i=0;i<12;i++){out[i]=get$1(format,i,field,"month")}return out}function listWeekdaysImpl(localeSorted,format,index,field){if(typeof localeSorted==="boolean"){if(isNumber(format)){index=format;format=undefined}format=format||""}else{format=localeSorted;index=format;localeSorted=false;if(isNumber(format)){index=format;format=undefined}format=format||""}var locale=getLocale(),shift=localeSorted?locale._week.dow:0;if(index!=null){return get$1(format,(index+shift)%7,field,"day")}var i;var out=[];for(i=0;i<7;i++){out[i]=get$1(format,(i+shift)%7,field,"day")}return out}function listMonths(format,index){return listMonthsImpl(format,index,"months")}function listMonthsShort(format,index){return listMonthsImpl(format,index,"monthsShort")}function listWeekdays(localeSorted,format,index){return listWeekdaysImpl(localeSorted,format,index,"weekdays")}function listWeekdaysShort(localeSorted,format,index){return listWeekdaysImpl(localeSorted,format,index,"weekdaysShort")}function listWeekdaysMin(localeSorted,format,index){return listWeekdaysImpl(localeSorted,format,index,"weekdaysMin")}getSetGlobalLocale("en",{dayOfMonthOrdinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(number){var b=number%10,output=toInt(number%100/10)===1?"th":b===1?"st":b===2?"nd":b===3?"rd":"th";return number+output}});hooks.lang=deprecate("moment.lang is deprecated. Use moment.locale instead.",getSetGlobalLocale);hooks.langData=deprecate("moment.langData is deprecated. Use moment.localeData instead.",getLocale);var mathAbs=Math.abs;function abs(){var data=this._data;this._milliseconds=mathAbs(this._milliseconds);this._days=mathAbs(this._days);this._months=mathAbs(this._months);data.milliseconds=mathAbs(data.milliseconds);data.seconds=mathAbs(data.seconds);data.minutes=mathAbs(data.minutes);data.hours=mathAbs(data.hours);data.months=mathAbs(data.months);data.years=mathAbs(data.years);return this}function addSubtract$1(duration,input,value,direction){var other=createDuration(input,value);duration._milliseconds+=direction*other._milliseconds;duration._days+=direction*other._days;duration._months+=direction*other._months;return duration._bubble()}function add$1(input,value){return addSubtract$1(this,input,value,1)}function subtract$1(input,value){return addSubtract$1(this,input,value,-1)}function absCeil(number){if(number<0){return Math.floor(number)}else{return Math.ceil(number)}}function bubble(){var milliseconds=this._milliseconds;var days=this._days;var months=this._months;var data=this._data;var seconds,minutes,hours,years,monthsFromDays;if(!(milliseconds>=0&&days>=0&&months>=0||milliseconds<=0&&days<=0&&months<=0)){milliseconds+=absCeil(monthsToDays(months)+days)*864e5;days=0;months=0}data.milliseconds=milliseconds%1e3;seconds=absFloor(milliseconds/1e3);data.seconds=seconds%60;minutes=absFloor(seconds/60);data.minutes=minutes%60;hours=absFloor(minutes/60);data.hours=hours%24;days+=absFloor(hours/24);monthsFromDays=absFloor(daysToMonths(days));months+=monthsFromDays;days-=absCeil(monthsToDays(monthsFromDays));years=absFloor(months/12);months%=12;data.days=days;data.months=months;data.years=years;return this}function daysToMonths(days){return days*4800/146097}function monthsToDays(months){return months*146097/4800}function as(units){if(!this.isValid()){return NaN}var days;var months;var milliseconds=this._milliseconds;units=normalizeUnits(units);if(units==="month"||units==="year"){days=this._days+milliseconds/864e5;months=this._months+daysToMonths(days);return units==="month"?months:months/12}else{days=this._days+Math.round(monthsToDays(this._months));switch(units){case"week":return days/7+milliseconds/6048e5;case"day":return days+milliseconds/864e5;case"hour":return days*24+milliseconds/36e5;case"minute":return days*1440+milliseconds/6e4;case"second":return days*86400+milliseconds/1e3;case"millisecond":return Math.floor(days*864e5)+milliseconds;default:throw new Error("Unknown unit "+units)}}}function valueOf$1(){if(!this.isValid()){return NaN}return this._milliseconds+this._days*864e5+this._months%12*2592e6+toInt(this._months/12)*31536e6}function makeAs(alias){return function(){return this.as(alias)}}var asMilliseconds=makeAs("ms");var asSeconds=makeAs("s");var asMinutes=makeAs("m");var asHours=makeAs("h");var asDays=makeAs("d");var asWeeks=makeAs("w");var asMonths=makeAs("M");var asYears=makeAs("y");function get$2(units){units=normalizeUnits(units);return this.isValid()?this[units+"s"]():NaN}function makeGetter(name){return function(){return this.isValid()?this._data[name]:NaN}}var milliseconds=makeGetter("milliseconds");var seconds=makeGetter("seconds");var minutes=makeGetter("minutes");var hours=makeGetter("hours");var days=makeGetter("days");var months=makeGetter("months");var years=makeGetter("years");function weeks(){return absFloor(this.days()/7)}var round=Math.round;var thresholds={ss:44,s:45,m:45,h:22,d:26,M:11};function substituteTimeAgo(string,number,withoutSuffix,isFuture,locale){return locale.relativeTime(number||1,!!withoutSuffix,string,isFuture)}function relativeTime$1(posNegDuration,withoutSuffix,locale){var duration=createDuration(posNegDuration).abs();var seconds=round(duration.as("s"));var minutes=round(duration.as("m"));var hours=round(duration.as("h"));var days=round(duration.as("d"));var months=round(duration.as("M"));var years=round(duration.as("y"));var a=seconds<=thresholds.ss&&["s",seconds]||seconds<thresholds.s&&["ss",seconds]||minutes<=1&&["m"]||minutes<thresholds.m&&["mm",minutes]||hours<=1&&["h"]||hours<thresholds.h&&["hh",hours]||days<=1&&["d"]||days<thresholds.d&&["dd",days]||months<=1&&["M"]||months<thresholds.M&&["MM",months]||years<=1&&["y"]||["yy",years];a[2]=withoutSuffix;a[3]=+posNegDuration>0;a[4]=locale;return substituteTimeAgo.apply(null,a)}function getSetRelativeTimeRounding(roundingFunction){if(roundingFunction===undefined){return round}if(typeof roundingFunction==="function"){round=roundingFunction;return true}return false}function getSetRelativeTimeThreshold(threshold,limit){if(thresholds[threshold]===undefined){return false}if(limit===undefined){return thresholds[threshold]}thresholds[threshold]=limit;if(threshold==="s"){thresholds.ss=limit-1}return true}function humanize(withSuffix){if(!this.isValid()){return this.localeData().invalidDate()}var locale=this.localeData();var output=relativeTime$1(this,!withSuffix,locale);if(withSuffix){output=locale.pastFuture(+this,output)}return locale.postformat(output)}var abs$1=Math.abs;function toISOString$1(){if(!this.isValid()){return this.localeData().invalidDate()}var seconds=abs$1(this._milliseconds)/1e3;var days=abs$1(this._days);var months=abs$1(this._months);var minutes,hours,years;minutes=absFloor(seconds/60);hours=absFloor(minutes/60);seconds%=60;minutes%=60;years=absFloor(months/12);months%=12;var Y=years;var M=months;var D=days;var h=hours;var m=minutes;var s=seconds;var total=this.asSeconds();if(!total){return"P0D"}return(total<0?"-":"")+"P"+(Y?Y+"Y":"")+(M?M+"M":"")+(D?D+"D":"")+(h||m||s?"T":"")+(h?h+"H":"")+(m?m+"M":"")+(s?s+"S":"")}var proto$2=Duration.prototype;proto$2.isValid=isValid$1;proto$2.abs=abs;proto$2.add=add$1;proto$2.subtract=subtract$1;proto$2.as=as;proto$2.asMilliseconds=asMilliseconds;proto$2.asSeconds=asSeconds;proto$2.asMinutes=asMinutes;proto$2.asHours=asHours;proto$2.asDays=asDays;proto$2.asWeeks=asWeeks;proto$2.asMonths=asMonths;proto$2.asYears=asYears;proto$2.valueOf=valueOf$1;proto$2._bubble=bubble;proto$2.get=get$2;proto$2.milliseconds=milliseconds;proto$2.seconds=seconds;proto$2.minutes=minutes;proto$2.hours=hours;proto$2.days=days;proto$2.weeks=weeks;proto$2.months=months;proto$2.years=years;proto$2.humanize=humanize;proto$2.toISOString=toISOString$1;proto$2.toString=toISOString$1;proto$2.toJSON=toISOString$1;proto$2.locale=locale;proto$2.localeData=localeData;proto$2.toIsoString=deprecate("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",toISOString$1);proto$2.lang=lang;addFormatToken("X",0,0,"unix");addFormatToken("x",0,0,"valueOf");addRegexToken("x",matchSigned);addRegexToken("X",matchTimestamp);addParseToken("X",function(input,array,config){config._d=new Date(parseFloat(input,10)*1e3)});addParseToken("x",function(input,array,config){config._d=new Date(toInt(input))});hooks.version="2.18.1";setHookCallback(createLocal);hooks.fn=proto;hooks.min=min;hooks.max=max;hooks.now=now;hooks.utc=createUTC;hooks.unix=createUnix;hooks.months=listMonths;hooks.isDate=isDate;hooks.locale=getSetGlobalLocale;hooks.invalid=createInvalid;hooks.duration=createDuration;hooks.isMoment=isMoment;hooks.weekdays=listWeekdays;hooks.parseZone=createInZone;hooks.localeData=getLocale;hooks.isDuration=isDuration;hooks.monthsShort=listMonthsShort;hooks.weekdaysMin=listWeekdaysMin;hooks.defineLocale=defineLocale;hooks.updateLocale=updateLocale;hooks.locales=listLocales;hooks.weekdaysShort=listWeekdaysShort;hooks.normalizeUnits=normalizeUnits;hooks.relativeTimeRounding=getSetRelativeTimeRounding;hooks.relativeTimeThreshold=getSetRelativeTimeThreshold;hooks.calendarFormat=getCalendarFormat;hooks.prototype=proto;return hooks})},{}],17:[function(require,module,exports){exports.endianness=function(){return"LE"};exports.hostname=function(){if(typeof location!=="undefined"){return location.hostname}else return""};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(){if(typeof navigator!=="undefined"){return navigator.appVersion}return""};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"},{}],18:[function(require,module,exports){(function(process){"use strict";if(!process.version||process.version.indexOf("v0.")===0||process.version.indexOf("v1.")===0&&process.version.indexOf("v1.8.")!==0){module.exports=nextTick}else{module.exports=process.nextTick}function nextTick(fn,arg1,arg2,arg3){if(typeof fn!=="function"){throw new TypeError('"callback" argument must be a function')}var len=arguments.length;var args,i;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:args=new Array(len-1);i=0;while(i<args.length){args[i++]=arguments[i]}return process.nextTick(function afterTick(){fn.apply(null,args)})}}}).call(this,require("_process"))},{_process:19}],19:[function(require,module,exports){var process=module.exports={};var cachedSetTimeout;var cachedClearTimeout;function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}(function(){try{if(typeof setTimeout==="function"){cachedSetTimeout=setTimeout}else{cachedSetTimeout=defaultSetTimout}}catch(e){cachedSetTimeout=defaultSetTimout}try{if(typeof clearTimeout==="function"){cachedClearTimeout=clearTimeout}else{cachedClearTimeout=defaultClearTimeout}}catch(e){cachedClearTimeout=defaultClearTimeout}})();function runTimeout(fun){if(cachedSetTimeout===setTimeout){return setTimeout(fun,0)}if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout){cachedSetTimeout=setTimeout;return 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){cachedClearTimeout=clearTimeout;return clearTimeout(marker)}try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}var queue=[];var draining=false;var currentQueue;var queueIndex=-1;function cleanUpNextTick(){if(!draining||!currentQueue){return}draining=false;if(currentQueue.length){queue=currentQueue.concat(queue)}else{queueIndex=-1}if(queue.length){drainQueue()}}function drainQueue(){if(draining){return}var timeout=runTimeout(cleanUpNextTick);draining=true;var len=queue.length;while(len){currentQueue=queue;queue=[];while(++queueIndex<len){if(currentQueue){currentQueue[queueIndex].run()}}queueIndex=-1;len=queue.length}currentQueue=null;draining=false;runClearTimeout(timeout)}process.nextTick=function(fun){var args=new 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));if(queue.length===1&&!draining){runTimeout(drainQueue)}};function Item(fun,array){this.fun=fun;this.array=array}Item.prototype.run=function(){this.fun.apply(null,this.array)};process.title="browser";process.browser=true;process.env={};process.argv=[];process.version="";process.versions={};function noop(){}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 new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")};process.umask=function(){return 0}},{}],20:[function(require,module,exports){module.exports=require("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":21}],21:[function(require,module,exports){"use strict";var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj){keys.push(key)}return keys};module.exports=Duplex;var processNextTick=require("process-nextick-args");var util=require("core-util-is");util.inherits=require("inherits");var Readable=require("./_stream_readable");var Writable=require("./_stream_writable");util.inherits(Duplex,Readable);var keys=objectKeys(Writable.prototype);for(var v=0;v<keys.length;v++){var method=keys[v];if(!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);if(options&&options.readable===false)this.readable=false;if(options&&options.writable===false)this.writable=false;this.allowHalfOpen=true;if(options&&options.allowHalfOpen===false)this.allowHalfOpen=false;this.once("end",onend)}function onend(){if(this.allowHalfOpen||this._writableState.ended)return;processNextTick(onEndNT,this)}function onEndNT(self){self.end()}function forEach(xs,f){for(var i=0,l=xs.length;i<l;i++){f(xs[i],i)}}},{"./_stream_readable":23,"./_stream_writable":25,"core-util-is":10,inherits:13,"process-nextick-args":18}],22:[function(require,module,exports){"use strict";module.exports=PassThrough;var Transform=require("./_stream_transform");var util=require("core-util-is");util.inherits=require("inherits");util.inherits(PassThrough,Transform);function PassThrough(options){if(!(this instanceof PassThrough))return new PassThrough(options);Transform.call(this,options)}PassThrough.prototype._transform=function(chunk,encoding,cb){cb(null,chunk)}},{"./_stream_transform":24,"core-util-is":10,inherits:13}],23:[function(require,module,exports){(function(process){"use strict";module.exports=Readable;var processNextTick=require("process-nextick-args");var isArray=require("isarray");var Duplex;Readable.ReadableState=ReadableState;var EE=require("events").EventEmitter;var EElistenerCount=function(emitter,type){return emitter.listeners(type).length};var Stream=require("./internal/streams/stream");var Buffer=require("buffer").Buffer;var bufferShim=require("buffer-shims");var util=require("core-util-is");util.inherits=require("inherits");var debugUtil=require("util");var debug=void 0;if(debugUtil&&debugUtil.debuglog){debug=debugUtil.debuglog("stream")}else{debug=function(){}}var BufferList=require("./internal/streams/BufferList");var StringDecoder;util.inherits(Readable,Stream);var kProxyEvents=["error","close","destroy","pause","resume"];function prependListener(emitter,event,fn){if(typeof emitter.prependListener==="function"){return emitter.prependListener(event,fn)}else{if(!emitter._events||!emitter._events[event])emitter.on(event,fn);else if(isArray(emitter._events[event]))emitter._events[event].unshift(fn);else emitter._events[event]=[fn,emitter._events[event]]}}function ReadableState(options,stream){Duplex=Duplex||require("./_stream_duplex");options=options||{};this.objectMode=!!options.objectMode;if(stream instanceof Duplex)this.objectMode=this.objectMode||!!options.readableObjectMode;var hwm=options.highWaterMark;var defaultHwm=this.objectMode?16:16*1024;this.highWaterMark=hwm||hwm===0?hwm:defaultHwm;this.highWaterMark=~~this.highWaterMark;this.buffer=new BufferList;this.length=0;this.pipes=null;this.pipesCount=0;this.flowing=null;this.ended=false;this.endEmitted=false;this.reading=false;this.sync=true;this.needReadable=false;this.emittedReadable=false;this.readableListening=false;this.resumeScheduled=false;this.defaultEncoding=options.defaultEncoding||"utf8";this.ranOut=false;this.awaitDrain=0;this.readingMore=false;this.decoder=null;this.encoding=null;if(options.encoding){if(!StringDecoder)StringDecoder=require("string_decoder/").StringDecoder;this.decoder=new StringDecoder(options.encoding);this.encoding=options.encoding}}function Readable(options){Duplex=Duplex||require("./_stream_duplex");if(!(this instanceof Readable))return new Readable(options);this._readableState=new ReadableState(options,this);this.readable=true;if(options&&typeof options.read==="function")this._read=options.read;Stream.call(this)}Readable.prototype.push=function(chunk,encoding){var state=this._readableState;if(!state.objectMode&&typeof chunk==="string"){encoding=encoding||state.defaultEncoding;if(encoding!==state.encoding){chunk=bufferShim.from(chunk,encoding);encoding=""}}return readableAddChunk(this,state,chunk,encoding,false)};Readable.prototype.unshift=function(chunk){var state=this._readableState;return readableAddChunk(this,state,chunk,"",true)};Readable.prototype.isPaused=function(){return this._readableState.flowing===false};function readableAddChunk(stream,state,chunk,encoding,addToFront){var er=chunkInvalid(state,chunk);if(er){stream.emit("error",er)}else if(chunk===null){state.reading=false;onEofChunk(stream,state)}else if(state.objectMode||chunk&&chunk.length>0){if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var _e=new Error("stream.unshift() after end event");stream.emit("error",_e)}else{var skipAdd;if(state.decoder&&!addToFront&&!encoding){chunk=state.decoder.write(chunk);skipAdd=!state.objectMode&&chunk.length===0}if(!addToFront)state.reading=false;if(!skipAdd){if(state.flowing&&state.length===0&&!state.sync){stream.emit("data",chunk);stream.read(0)}else{state.length+=state.objectMode?1:chunk.length;if(addToFront)state.buffer.unshift(chunk);else state.buffer.push(chunk);if(state.needReadable)emitReadable(stream)}}maybeReadMore(stream,state)}}else if(!addToFront){state.reading=false}return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length<state.highWaterMark||state.length===0)}Readable.prototype.setEncoding=function(enc){if(!StringDecoder)StringDecoder=require("string_decoder/").StringDecoder;this._readableState.decoder=new StringDecoder(enc);this._readableState.encoding=enc;return this};var MAX_HWM=8388608;function computeNewHighWaterMark(n){if(n>=MAX_HWM){n=MAX_HWM}else{n--;n|=n>>>1;n|=n>>>2;n|=n>>>4;n|=n>>>8;n|=n>>>16;n++}return n}function howMuchToRead(n,state){if(n<=0||state.length===0&&state.ended)return 0;if(state.objectMode)return 1;if(n!==n){if(state.flowing&&state.length)return state.buffer.head.data.length;else return state.length}if(n>state.highWaterMark)state.highWaterMark=computeNewHighWaterMark(n);if(n<=state.length)return n;if(!state.ended){state.needReadable=true;return 0}return state.length}Readable.prototype.read=function(n){debug("read",n);n=parseInt(n,10);var state=this._readableState;var nOrig=n;if(n!==0)state.emittedReadable=false;if(n===0&&state.needReadable&&(state.length>=state.highWaterMark||state.ended)){debug("read: emitReadable",state.length,state.ended);if(state.length===0&&state.ended)endReadable(this);else emitReadable(this);return null}n=howMuchToRead(n,state);if(n===0&&state.ended){if(state.length===0)endReadable(this);return null}var doRead=state.needReadable;debug("need readable",doRead);if(state.length===0||state.length-n<state.highWaterMark){doRead=true;debug("length less than watermark",doRead)}if(state.ended||state.reading){doRead=false;debug("reading or ended",doRead)}else if(doRead){debug("do read");state.reading=true;state.sync=true;if(state.length===0)state.needReadable=true;this._read(state.highWaterMark);state.sync=false;if(!state.reading)n=howMuchToRead(nOrig,state)}var ret;if(n>0)ret=fromList(n,state);else ret=null;if(ret===null){state.needReadable=true;n=0}else{state.length-=n}if(state.length===0){if(!state.ended)state.needReadable=true;if(nOrig!==n&&state.ended)endReadable(this)}if(ret!==null)this.emit("data",ret);return ret};function chunkInvalid(state,chunk){var er=null;if(!Buffer.isBuffer(chunk)&&typeof chunk!=="string"&&chunk!==null&&chunk!==undefined&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}return er}function onEofChunk(stream,state){if(state.ended)return;if(state.decoder){var chunk=state.decoder.end();if(chunk&&chunk.length){state.buffer.push(chunk);state.length+=state.objectMode?1:chunk.length}}state.ended=true;emitReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=false;if(!state.emittedReadable){debug("emitReadable",state.flowing);state.emittedReadable=true;if(state.sync)processNextTick(emitReadable_,stream);else emitReadable_(stream)}}function emitReadable_(stream){debug("emit readable");stream.emit("readable");flow(stream)}function maybeReadMore(stream,state){if(!state.readingMore){state.readingMore=true;processNextTick(maybeReadMore_,stream,state)}}function maybeReadMore_(stream,state){var len=state.length;while(!state.reading&&!state.flowing&&!state.ended&&state.length<state.highWaterMark){debug("maybeReadMore read 0");stream.read(0);if(len===state.length)break;else len=state.length}state.readingMore=false}Readable.prototype._read=function(n){this.emit("error",new Error("_read() is not implemented"))};Readable.prototype.pipe=function(dest,pipeOpts){var src=this;var 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);break}state.pipesCount+=1;debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var doEnd=(!pipeOpts||pipeOpts.end!==false)&&dest!==process.stdout&&dest!==process.stderr;var endFn=doEnd?onend:cleanup;if(state.endEmitted)processNextTick(endFn);else src.once("end",endFn);dest.on("unpipe",onunpipe);function onunpipe(readable){debug("onunpipe");if(readable===src){cleanup()}}function onend(){debug("onend");dest.end()}var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);var cleanedUp=false;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",cleanup);src.removeListener("data",ondata);cleanedUp=true;if(state.awaitDrain&&(!dest._writableState||dest._writableState.needDrain))ondrain()}var increasedAwaitDrain=false;src.on("data",ondata);function ondata(chunk){debug("ondata");increasedAwaitDrain=false;var ret=dest.write(chunk);if(false===ret&&!increasedAwaitDrain){if((state.pipesCount===1&&state.pipes===dest||state.pipesCount>1&&indexOf(state.pipes,dest)!==-1)&&!cleanedUp){debug("false write response, pause",src._readableState.awaitDrain);src._readableState.awaitDrain++;increasedAwaitDrain=true}src.pause()}}function onerror(er){debug("onerror",er);unpipe();dest.removeListener("error",onerror);if(EElistenerCount(dest,"error")===0)dest.emit("error",er)}prependListener(dest,"error",onerror);function onclose(){dest.removeListener("finish",onfinish);unpipe()}dest.once("close",onclose);function onfinish(){debug("onfinish");dest.removeListener("close",onclose);unpipe()}dest.once("finish",onfinish);function unpipe(){debug("unpipe");src.unpipe(dest)}dest.emit("pipe",src);if(!state.flowing){debug("pipe resume");src.resume()}return dest};function pipeOnDrain(src){return function(){var state=src._readableState;debug("pipeOnDrain",state.awaitDrain);if(state.awaitDrain)state.awaitDrain--;if(state.awaitDrain===0&&EElistenerCount(src,"data")){state.flowing=true;flow(src)}}}Readable.prototype.unpipe=function(dest){var state=this._readableState;if(state.pipesCount===0)return this;if(state.pipesCount===1){if(dest&&dest!==state.pipes)return this;if(!dest)dest=state.pipes;state.pipes=null;state.pipesCount=0;state.flowing=false;if(dest)dest.emit("unpipe",this);return this}if(!dest){var dests=state.pipes;var len=state.pipesCount;state.pipes=null;state.pipesCount=0;state.flowing=false;for(var i=0;i<len;i++){dests[i].emit("unpipe",this)}return this}var index=indexOf(state.pipes,dest);if(index===-1)return this;state.pipes.splice(index,1);state.pipesCount-=1;if(state.pipesCount===1)state.pipes=state.pipes[0];dest.emit("unpipe",this);return this};Readable.prototype.on=function(ev,fn){var res=Stream.prototype.on.call(this,ev,fn);if(ev==="data"){if(this._readableState.flowing!==false)this.resume()}else if(ev==="readable"){var state=this._readableState;if(!state.endEmitted&&!state.readableListening){state.readableListening=state.needReadable=true;state.emittedReadable=false;if(!state.reading){processNextTick(nReadingNextTick,this)}else if(state.length){emitReadable(this,state)}}}return res};Readable.prototype.addListener=Readable.prototype.on;function nReadingNextTick(self){debug("readable nexttick read 0");self.read(0)}Readable.prototype.resume=function(){var state=this._readableState;if(!state.flowing){debug("resume");state.flowing=true;resume(this,state)}return this};function resume(stream,state){if(!state.resumeScheduled){state.resumeScheduled=true;processNextTick(resume_,stream,state)}}function resume_(stream,state){if(!state.reading){debug("resume read 0");stream.read(0)}state.resumeScheduled=false;state.awaitDrain=0;stream.emit("resume");flow(stream);if(state.flowing&&!state.reading)stream.read(0)}Readable.prototype.pause=function(){debug("call pause flowing=%j",this._readableState.flowing);if(false!==this._readableState.flowing){debug("pause");this._readableState.flowing=false;this.emit("pause")}return this};function flow(stream){var state=stream._readableState;debug("flow",state.flowing);while(state.flowing&&stream.read()!==null){}}Readable.prototype.wrap=function(stream){var state=this._readableState;var paused=false;var self=this;stream.on("end",function(){debug("wrapped end");if(state.decoder&&!state.ended){var chunk=state.decoder.end();if(chunk&&chunk.length)self.push(chunk)}self.push(null)});stream.on("data",function(chunk){debug("wrapped data");if(state.decoder)chunk=state.decoder.write(chunk);if(state.objectMode&&(chunk===null||chunk===undefined))return;else if(!state.objectMode&&(!chunk||!chunk.length))return;var ret=self.push(chunk);if(!ret){paused=true;stream.pause()}});for(var i in stream){if(this[i]===undefined&&typeof stream[i]==="function"){this[i]=function(method){return function(){return stream[method].apply(stream,arguments)}}(i)}}for(var n=0;n<kProxyEvents.length;n++){stream.on(kProxyEvents[n],self.emit.bind(self,kProxyEvents[n]))}self._read=function(n){debug("wrapped _read",n);if(paused){paused=false;stream.resume()}};return self};Readable._fromList=fromList;function fromList(n,state){if(state.length===0)return null;var ret;if(state.objectMode)ret=state.buffer.shift();else if(!n||n>=state.length){if(state.decoder)ret=state.buffer.join("");else if(state.buffer.length===1)ret=state.buffer.head.data;else ret=state.buffer.concat(state.length);state.buffer.clear()}else{ret=fromListPartial(n,state.buffer,state.decoder)}return ret}function fromListPartial(n,list,hasStrings){var ret;if(n<list.head.data.length){ret=list.head.data.slice(0,n);list.head.data=list.head.data.slice(n)}else if(n===list.head.data.length){ret=list.shift()}else{ret=hasStrings?copyFromBufferString(n,list):copyFromBuffer(n,list)}return ret}function copyFromBufferString(n,list){var p=list.head;var c=1;var ret=p.data;n-=ret.length;while(p=p.next){var str=p.data;var nb=n>str.length?str.length:n;if(nb===str.length)ret+=str;else ret+=str.slice(0,n);n-=nb;if(n===0){if(nb===str.length){++c;if(p.next)list.head=p.next;else list.head=list.tail=null}else{list.head=p;p.data=str.slice(nb)}break}++c}list.length-=c;return ret}function copyFromBuffer(n,list){var ret=bufferShim.allocUnsafe(n);var p=list.head;var c=1;p.data.copy(ret);n-=p.data.length;while(p=p.next){var buf=p.data;var nb=n>buf.length?buf.length:n;buf.copy(ret,ret.length-n,0,nb);n-=nb;if(n===0){if(nb===buf.length){++c;if(p.next)list.head=p.next;else list.head=list.tail=null}else{list.head=p;p.data=buf.slice(nb)}break}++c}list.length-=c;return ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error('"endReadable()" called on non-empty stream');if(!state.endEmitted){state.ended=true;processNextTick(endReadableNT,state,stream)}}function endReadableNT(state,stream){if(!state.endEmitted&&state.length===0){state.endEmitted=true;stream.readable=false;stream.emit("end")}}function forEach(xs,f){for(var i=0,l=xs.length;i<l;i++){f(xs[i],i)}}function indexOf(xs,x){for(var i=0,l=xs.length;i<l;i++){if(xs[i]===x)return i}return-1}}).call(this,require("_process"))},{"./_stream_duplex":21,"./internal/streams/BufferList":26,"./internal/streams/stream":27,_process:19,buffer:8,"buffer-shims":7,"core-util-is":10,events:11,inherits:13,isarray:15,"process-nextick-args":18,"string_decoder/":34,util:5}],24:[function(require,module,exports){"use strict";module.exports=Transform;var Duplex=require("./_stream_duplex");var util=require("core-util-is");util.inherits=require("inherits");util.inherits(Transform,Duplex);function TransformState(stream){this.afterTransform=function(er,data){return afterTransform(stream,er,data)};this.needTransform=false;this.transforming=false;this.writecb=null;this.writechunk=null;this.writeencoding=null}function afterTransform(stream,er,data){var ts=stream._transformState;ts.transforming=false;var cb=ts.writecb;if(!cb)return stream.emit("error",new Error("no writecb in Transform class"));ts.writechunk=null;ts.writecb=null;if(data!==null&&data!==undefined)stream.push(data);cb(er);var rs=stream._readableState;rs.reading=false;if(rs.needReadable||rs.length<rs.highWaterMark){stream._read(rs.highWaterMark)}}function Transform(options){if(!(this instanceof Transform))return new Transform(options);Duplex.call(this,options);this._transformState=new TransformState(this);var stream=this;this._readableState.needReadable=true;this._readableState.sync=false;if(options){if(typeof options.transform==="function")this._transform=options.transform;if(typeof options.flush==="function")this._flush=options.flush}this.once("prefinish",function(){if(typeof this._flush==="function")this._flush(function(er,data){done(stream,er,data)});else done(stream)})}Transform.prototype.push=function(chunk,encoding){this._transformState.needTransform=false;return Duplex.prototype.push.call(this,chunk,encoding)};Transform.prototype._transform=function(chunk,encoding,cb){throw new Error("_transform() is not implemented")};Transform.prototype._write=function(chunk,encoding,cb){var ts=this._transformState;ts.writecb=cb;ts.writechunk=chunk;ts.writeencoding=encoding;if(!ts.transforming){var rs=this._readableState;if(ts.needTransform||rs.needReadable||rs.length<rs.highWaterMark)this._read(rs.highWaterMark)}};Transform.prototype._read=function(n){var ts=this._transformState;if(ts.writechunk!==null&&ts.writecb&&!ts.transforming){ts.transforming=true;this._transform(ts.writechunk,ts.writeencoding,ts.afterTransform)}else{ts.needTransform=true}};function done(stream,er,data){if(er)return stream.emit("error",er);if(data!==null&&data!==undefined)stream.push(data);var ws=stream._writableState;var ts=stream._transformState;if(ws.length)throw new Error("Calling transform done when ws.length != 0");if(ts.transforming)throw new Error("Calling transform done when still transforming");return stream.push(null)}},{"./_stream_duplex":21,"core-util-is":10,inherits:13}],25:[function(require,module,exports){(function(process){"use strict";module.exports=Writable;var processNextTick=require("process-nextick-args");var asyncWrite=!process.browser&&["v0.10","v0.9."].indexOf(process.version.slice(0,5))>-1?setImmediate:processNextTick;var Duplex;Writable.WritableState=WritableState;var util=require("core-util-is");util.inherits=require("inherits");var internalUtil={deprecate:require("util-deprecate")};var Stream=require("./internal/streams/stream");var Buffer=require("buffer").Buffer;var bufferShim=require("buffer-shims");util.inherits(Writable,Stream);function nop(){}function WriteReq(chunk,encoding,cb){this.chunk=chunk;this.encoding=encoding;this.callback=cb;this.next=null}function WritableState(options,stream){Duplex=Duplex||require("./_stream_duplex");options=options||{};this.objectMode=!!options.objectMode;if(stream instanceof Duplex)this.objectMode=this.objectMode||!!options.writableObjectMode;var hwm=options.highWaterMark;var defaultHwm=this.objectMode?16:16*1024;this.highWaterMark=hwm||hwm===0?hwm:defaultHwm;this.highWaterMark=~~this.highWaterMark;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;var noDecode=options.decodeStrings===false;this.decodeStrings=!noDecode;this.defaultEncoding=options.defaultEncoding||"utf8";this.length=0;this.writing=false;this.corked=0;this.sync=true;this.bufferProcessing=false;this.onwrite=function(er){onwrite(stream,er)};this.writecb=null;this.writelen=0;this.bufferedRequest=null;this.lastBufferedRequest=null;this.pendingcb=0;this.prefinished=false;this.errorEmitted=false;this.bufferedRequestCount=0;this.corkedRequestsFree=new CorkedRequest(this)}WritableState.prototype.getBuffer=function getBuffer(){var current=this.bufferedRequest;var out=[];while(current){out.push(current);current=current.next}return out};(function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer "+"instead.")})}catch(_){}})();var realHasInstance;if(typeof Symbol==="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]==="function"){realHasInstance=Function.prototype[Symbol.hasInstance];Object.defineProperty(Writable,Symbol.hasInstance,{value:function(object){if(realHasInstance.call(this,object))return true;return object&&object._writableState instanceof WritableState}})}else{realHasInstance=function(object){return object instanceof this}}function Writable(options){Duplex=Duplex||require("./_stream_duplex");if(!realHasInstance.call(Writable,this)&&!(this instanceof Duplex)){return new Writable(options)}this._writableState=new WritableState(options,this);this.writable=true;if(options){if(typeof options.write==="function")this._write=options.write;if(typeof options.writev==="function")this._writev=options.writev}Stream.call(this)}Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))};function writeAfterEnd(stream,cb){var er=new Error("write after end");stream.emit("error",er);processNextTick(cb,er)}function validChunk(stream,state,chunk,cb){var valid=true;var er=false;if(chunk===null){er=new TypeError("May not write null values to stream")}else if(typeof chunk!=="string"&&chunk!==undefined&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}if(er){stream.emit("error",er);processNextTick(cb,er);valid=false}return valid}Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState;var ret=false;var isBuf=Buffer.isBuffer(chunk);if(typeof encoding==="function"){cb=encoding;encoding=null}if(isBuf)encoding="buffer";else if(!encoding)encoding=state.defaultEncoding;if(typeof cb!=="function")cb=nop;if(state.ended)writeAfterEnd(this,cb);else if(isBuf||validChunk(this,state,chunk,cb)){state.pendingcb++;ret=writeOrBuffer(this,state,isBuf,chunk,encoding,cb)}return ret};Writable.prototype.cork=function(){var state=this._writableState;state.corked++};Writable.prototype.uncork=function(){var state=this._writableState;if(state.corked){state.corked--;if(!state.writing&&!state.corked&&!state.finished&&!state.bufferProcessing&&state.bufferedRequest)clearBuffer(this,state)}};Writable.prototype.setDefaultEncoding=function setDefaultEncoding(encoding){if(typeof encoding==="string")encoding=encoding.toLowerCase();if(!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+encoding);this._writableState.defaultEncoding=encoding;return this};function decodeChunk(state,chunk,encoding){if(!state.objectMode&&state.decodeStrings!==false&&typeof chunk==="string"){chunk=bufferShim.from(chunk,encoding)}return chunk}function writeOrBuffer(stream,state,isBuf,chunk,encoding,cb){if(!isBuf){chunk=decodeChunk(state,chunk,encoding);if(Buffer.isBuffer(chunk))encoding="buffer"}var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length<state.highWaterMark;if(!ret)state.needDrain=true;if(state.writing||state.corked){var last=state.lastBufferedRequest;state.lastBufferedRequest=new WriteReq(chunk,encoding,cb);if(last){last.next=state.lastBufferedRequest}else{state.bufferedRequest=state.lastBufferedRequest}state.bufferedRequestCount+=1}else{doWrite(stream,state,false,len,chunk,encoding,cb)}return ret}function doWrite(stream,state,writev,len,chunk,encoding,cb){state.writelen=len;state.writecb=cb;state.writing=true;state.sync=true;if(writev)stream._writev(chunk,state.onwrite);else stream._write(chunk,encoding,state.onwrite);state.sync=false}function onwriteError(stream,state,sync,er,cb){--state.pendingcb;if(sync)processNextTick(cb,er);else cb(er);stream._writableState.errorEmitted=true;stream.emit("error",er)}function onwriteStateUpdate(state){state.writing=false;state.writecb=null;state.length-=state.writelen;state.writelen=0}function onwrite(stream,er){var state=stream._writableState;var sync=state.sync;var cb=state.writecb;onwriteStateUpdate(state);if(er)onwriteError(stream,state,sync,er,cb);else{var finished=needFinish(state);if(!finished&&!state.corked&&!state.bufferProcessing&&state.bufferedRequest){clearBuffer(stream,state)}if(sync){asyncWrite(afterWrite,stream,state,finished,cb)}else{afterWrite(stream,state,finished,cb)}}}function afterWrite(stream,state,finished,cb){if(!finished)onwriteDrain(stream,state);state.pendingcb--;cb();finishMaybe(stream,state)}function onwriteDrain(stream,state){if(state.length===0&&state.needDrain){state.needDrain=false;stream.emit("drain")}}function clearBuffer(stream,state){state.bufferProcessing=true;var entry=state.bufferedRequest;if(stream._writev&&entry&&entry.next){var l=state.bufferedRequestCount;var buffer=new Array(l);var holder=state.corkedRequestsFree;holder.entry=entry;var count=0;while(entry){buffer[count]=entry;entry=entry.next;count+=1}doWrite(stream,state,true,state.length,buffer,"",holder.finish);state.pendingcb++;state.lastBufferedRequest=null;if(holder.next){state.corkedRequestsFree=holder.next;holder.next=null}else{state.corkedRequestsFree=new CorkedRequest(state)}}else{while(entry){var chunk=entry.chunk;var encoding=entry.encoding;var cb=entry.callback;var len=state.objectMode?1:chunk.length;doWrite(stream,state,false,len,chunk,encoding,cb);entry=entry.next;if(state.writing){break}}if(entry===null)state.lastBufferedRequest=null}state.bufferedRequestCount=0;state.bufferedRequest=entry;state.bufferProcessing=false}Writable.prototype._write=function(chunk,encoding,cb){cb(new Error("_write() is not implemented"))};Writable.prototype._writev=null;Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;if(typeof chunk==="function"){cb=chunk;chunk=null;encoding=null}else if(typeof encoding==="function"){cb=encoding;encoding=null}if(chunk!==null&&chunk!==undefined)this.write(chunk,encoding);if(state.corked){state.corked=1;this.uncork()}if(!state.ending&&!state.finished)endWritable(this,state,cb)};function needFinish(state){return state.ending&&state.length===0&&state.bufferedRequest===null&&!state.finished&&!state.writing}function prefinish(stream,state){if(!state.prefinished){state.prefinished=true;stream.emit("prefinish")}}function finishMaybe(stream,state){var need=needFinish(state);if(need){if(state.pendingcb===0){prefinish(stream,state);state.finished=true;stream.emit("finish")}else{prefinish(stream,state)}}return need}function endWritable(stream,state,cb){state.ending=true;finishMaybe(stream,state);if(cb){if(state.finished)processNextTick(cb);else stream.once("finish",cb)}state.ended=true;stream.writable=false}function CorkedRequest(state){var _this=this;this.next=null;this.entry=null;this.finish=function(err){var entry=_this.entry;_this.entry=null;while(entry){var cb=entry.callback;state.pendingcb--;cb(err);entry=entry.next}if(state.corkedRequestsFree){state.corkedRequestsFree.next=_this}else{state.corkedRequestsFree=_this}}}}).call(this,require("_process"))},{"./_stream_duplex":21,"./internal/streams/stream":27,_process:19,buffer:8,"buffer-shims":7,"core-util-is":10,inherits:13,"process-nextick-args":18,"util-deprecate":35}],26:[function(require,module,exports){"use strict";var Buffer=require("buffer").Buffer;var bufferShim=require("buffer-shims");module.exports=BufferList;function BufferList(){this.head=null;this.tail=null;this.length=0}BufferList.prototype.push=function(v){var entry={data:v,next:null};if(this.length>0)this.tail.next=entry;else this.head=entry;this.tail=entry;++this.length};BufferList.prototype.unshift=function(v){var entry={data:v,next:this.head};if(this.length===0)this.tail=entry;this.head=entry;++this.length};BufferList.prototype.shift=function(){if(this.length===0)return;var ret=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;--this.length;return ret};BufferList.prototype.clear=function(){this.head=this.tail=null;this.length=0};BufferList.prototype.join=function(s){if(this.length===0)return"";var p=this.head;var ret=""+p.data;while(p=p.next){ret+=s+p.data}return ret};BufferList.prototype.concat=function(n){if(this.length===0)return bufferShim.alloc(0);if(this.length===1)return this.head.data;var ret=bufferShim.allocUnsafe(n>>>0);var p=this.head;var i=0;while(p){p.data.copy(ret,i);i+=p.data.length;p=p.next}return ret}},{buffer:8,"buffer-shims":7}],27:[function(require,module,exports){module.exports=require("events").EventEmitter},{events:11}],28:[function(require,module,exports){module.exports=require("./readable").PassThrough},{"./readable":29}],29:[function(require,module,exports){exports=module.exports=require("./lib/_stream_readable.js");exports.Stream=exports;exports.Readable=exports;exports.Writable=require("./lib/_stream_writable.js");exports.Duplex=require("./lib/_stream_duplex.js");exports.Transform=require("./lib/_stream_transform.js");exports.PassThrough=require("./lib/_stream_passthrough.js")},{"./lib/_stream_duplex.js":21,"./lib/_stream_passthrough.js":22,"./lib/_stream_readable.js":23,"./lib/_stream_transform.js":24,"./lib/_stream_writable.js":25}],30:[function(require,module,exports){module.exports=require("./readable").Transform},{"./readable":29}],31:[function(require,module,exports){module.exports=require("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":25}],32:[function(require,module,exports){var hasProp=Object.prototype.hasOwnProperty;function throwsMessage(err){return"[Throws: "+(err?err.message:"?")+"]"}function safeGetValueFromPropertyOnObject(obj,property){if(hasProp.call(obj,property)){try{return obj[property]}catch(err){return throwsMessage(err)}}return obj[property]}function ensureProperties(obj){var seen=[];function visit(obj){if(obj===null||typeof obj!=="object"){return obj}if(seen.indexOf(obj)!==-1){return"[Circular]"}seen.push(obj);if(typeof obj.toJSON==="function"){try{return visit(obj.toJSON())}catch(err){return throwsMessage(err)}}if(Array.isArray(obj)){return obj.map(visit)}return Object.keys(obj).reduce(function(result,prop){result[prop]=visit(safeGetValueFromPropertyOnObject(obj,prop));return result},{})}return visit(obj)}module.exports=function(data){return JSON.stringify(ensureProperties(data))};module.exports.ensureProperties=ensureProperties},{}],33:[function(require,module,exports){module.exports=Stream;var EE=require("events").EventEmitter;var inherits=require("inherits");inherits(Stream,EE);Stream.Readable=require("readable-stream/readable.js");Stream.Writable=require("readable-stream/writable.js");Stream.Duplex=require("readable-stream/duplex.js");Stream.Transform=require("readable-stream/transform.js");Stream.PassThrough=require("readable-stream/passthrough.js");Stream.Stream=Stream;function Stream(){EE.call(this)}Stream.prototype.pipe=function(dest,options){var source=this;function ondata(chunk){if(dest.writable){if(false===dest.write(chunk)&&source.pause){source.pause()}}}source.on("data",ondata);function ondrain(){if(source.readable&&source.resume){source.resume()}}dest.on("drain",ondrain);if(!dest._isStdio&&(!options||options.end!==false)){source.on("end",onend);source.on("close",onclose)}var didOnEnd=false;function onend(){if(didOnEnd)return;didOnEnd=true;dest.end()}function onclose(){if(didOnEnd)return;didOnEnd=true;if(typeof dest.destroy==="function")dest.destroy()}function onerror(er){cleanup();if(EE.listenerCount(this,"error")===0){throw er}}source.on("error",onerror);dest.on("error",onerror);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)}source.on("end",cleanup);source.on("close",cleanup);dest.on("close",cleanup);dest.emit("pipe",source);return dest}},{events:11,inherits:13,"readable-stream/duplex.js":20,"readable-stream/passthrough.js":28,"readable-stream/readable.js":29,"readable-stream/transform.js":30,"readable-stream/writable.js":31}],34:[function(require,module,exports){"use strict";var Buffer=require("buffer").Buffer;var bufferShim=require("buffer-shims");var isEncoding=Buffer.isEncoding||function(encoding){encoding=""+encoding;switch(encoding&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return true;default:return false}};function _normalizeEncoding(enc){if(!enc)return"utf8";var retried;while(true){switch(enc){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return enc;default:if(retried)return;enc=(""+enc).toLowerCase();retried=true}}}function normalizeEncoding(enc){var nenc=_normalizeEncoding(enc);if(typeof nenc!=="string"&&(Buffer.isEncoding===isEncoding||!isEncoding(enc)))throw new Error("Unknown encoding: "+enc);return nenc||enc}exports.StringDecoder=StringDecoder;function StringDecoder(encoding){this.encoding=normalizeEncoding(encoding);var nb;switch(this.encoding){case"utf16le":this.text=utf16Text;this.end=utf16End;nb=4;break;case"utf8":this.fillLast=utf8FillLast;nb=4;break;case"base64":this.text=base64Text;this.end=base64End;nb=3;break;default:this.write=simpleWrite;this.end=simpleEnd;return}this.lastNeed=0;this.lastTotal=0;this.lastChar=bufferShim.allocUnsafe(nb)}StringDecoder.prototype.write=function(buf){if(buf.length===0)return"";var r;var i;if(this.lastNeed){r=this.fillLast(buf);if(r===undefined)return"";i=this.lastNeed;this.lastNeed=0}else{i=0}if(i<buf.length)return r?r+this.text(buf,i):this.text(buf,i);return r||""};StringDecoder.prototype.end=utf8End;StringDecoder.prototype.text=utf8Text;StringDecoder.prototype.fillLast=function(buf){if(this.lastNeed<=buf.length){buf.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed);return this.lastChar.toString(this.encoding,0,this.lastTotal)}buf.copy(this.lastChar,this.lastTotal-this.lastNeed,0,buf.length);this.lastNeed-=buf.length};function utf8CheckByte(byte){if(byte<=127)return 0;else if(byte>>5===6)return 2;else if(byte>>4===14)return 3;else if(byte>>3===30)return 4;return-1}function utf8CheckIncomplete(self,buf,i){var j=buf.length-1;if(j<i)return 0;var nb=utf8CheckByte(buf[j]);if(nb>=0){if(nb>0)self.lastNeed=nb-1;return nb}if(--j<i)return 0;nb=utf8CheckByte(buf[j]);if(nb>=0){if(nb>0)self.lastNeed=nb-2;return nb}if(--j<i)return 0;nb=utf8CheckByte(buf[j]);if(nb>=0){if(nb>0){if(nb===2)nb=0;else self.lastNeed=nb-3}return nb}return 0}function utf8CheckExtraBytes(self,buf,p){if((buf[0]&192)!==128){self.lastNeed=0;return"�".repeat(p)}if(self.lastNeed>1&&buf.length>1){if((buf[1]&192)!==128){self.lastNeed=1;return"�".repeat(p+1)}if(self.lastNeed>2&&buf.length>2){if((buf[2]&192)!==128){self.lastNeed=2;return"�".repeat(p+2)}}}}function utf8FillLast(buf){var p=this.lastTotal-this.lastNeed;var r=utf8CheckExtraBytes(this,buf,p);if(r!==undefined)return r;if(this.lastNeed<=buf.length){buf.copy(this.lastChar,p,0,this.lastNeed);return this.lastChar.toString(this.encoding,0,this.lastTotal)}buf.copy(this.lastChar,p,0,buf.length);this.lastNeed-=buf.length}function utf8Text(buf,i){var total=utf8CheckIncomplete(this,buf,i);if(!this.lastNeed)return buf.toString("utf8",i);this.lastTotal=total;var end=buf.length-(total-this.lastNeed);buf.copy(this.lastChar,0,end);return buf.toString("utf8",i,end)}function utf8End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed)return r+"�".repeat(this.lastTotal-this.lastNeed);return r}function utf16Text(buf,i){if((buf.length-i)%2===0){var r=buf.toString("utf16le",i);if(r){var c=r.charCodeAt(r.length-1);if(c>=55296&&c<=56319){this.lastNeed=2;this.lastTotal=4;this.lastChar[0]=buf[buf.length-2];this.lastChar[1]=buf[buf.length-1];return r.slice(0,-1)}}return r}this.lastNeed=1;this.lastTotal=2;this.lastChar[0]=buf[buf.length-1];return buf.toString("utf16le",i,buf.length-1)}function utf16End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed){var end=this.lastTotal-this.lastNeed;return r+this.lastChar.toString("utf16le",0,end)}return r}function base64Text(buf,i){var n=(buf.length-i)%3;if(n===0)return buf.toString("base64",i);this.lastNeed=3-n;this.lastTotal=3;if(n===1){this.lastChar[0]=buf[buf.length-1]}else{this.lastChar[0]=buf[buf.length-2];this.lastChar[1]=buf[buf.length-1]}return buf.toString("base64",i,buf.length-n)}function base64End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed)return r+this.lastChar.toString("base64",0,3-this.lastNeed);return r}function simpleWrite(buf){return buf.toString(this.encoding)}function simpleEnd(buf){return buf&&buf.length?this.write(buf):""}},{buffer:8,"buffer-shims":7}],35:[function(require,module,exports){(function(global){module.exports=deprecate;function deprecate(fn,msg){if(config("noDeprecation")){return fn}var warned=false;function deprecated(){if(!warned){if(config("throwDeprecation")){throw new Error(msg)}else if(config("traceDeprecation")){console.trace(msg)}else{console.warn(msg)}warned=true}return fn.apply(this,arguments)}return deprecated}function config(name){try{if(!global.localStorage)return false}catch(_){return false}var val=global.localStorage[name];if(null==val)return false;return String(val).toLowerCase()==="true"}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],36:[function(require,module,exports){arguments[4][13][0].apply(exports,arguments)},{dup:13}],37:[function(require,module,exports){module.exports=function isBuffer(arg){return arg&&typeof arg==="object"&&typeof arg.copy==="function"&&typeof arg.fill==="function"&&typeof arg.readUInt8==="function"}},{}],38:[function(require,module,exports){(function(process,global){var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){var objects=[];for(var i=0;i<arguments.length;i++){objects.push(inspect(arguments[i]))}return objects.join(" ")}var i=1;var args=arguments;var len=args.length;var str=String(f).replace(formatRegExp,function(x){if(x==="%%")return"%";if(i>=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}});for(var x=args[i];i<len;x=args[++i]){if(isNull(x)||!isObject(x)){str+=" "+x}else{str+=" "+inspect(x)}}return str};exports.deprecate=function(fn,msg){if(isUndefined(global.process)){return function(){return exports.deprecate(fn,msg).apply(this,arguments)}}if(process.noDeprecation===true){return fn}var warned=false;function deprecated(){if(!warned){if(process.throwDeprecation){throw new Error(msg)}else if(process.traceDeprecation){console.trace(msg)}else{console.error(msg)}warned=true}return fn.apply(this,arguments)}return deprecated};var debugs={};var debugEnviron;exports.debuglog=function(set){if(isUndefined(debugEnviron))debugEnviron=process.env.NODE_DEBUG||"";set=set.toUpperCase();if(!debugs[set]){if(new RegExp("\\b"+set+"\\b","i").test(debugEnviron)){var pid=process.pid;debugs[set]=function(){var msg=exports.format.apply(exports,arguments);console.error("%s %d: %s",set,pid,msg)}}else{debugs[set]=function(){}}}return debugs[set]};function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};if(arguments.length>=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts)){ctx.showHidden=opts}else if(opts){exports._extend(ctx,opts)}if(isUndefined(ctx.showHidden))ctx.showHidden=false;if(isUndefined(ctx.depth))ctx.depth=2;if(isUndefined(ctx.colors))ctx.colors=false;if(isUndefined(ctx.customInspect))ctx.customInspect=true;if(ctx.colors)ctx.stylize=stylizeWithColor;return formatValue(ctx,obj,ctx.depth)}exports.inspect=inspect;inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};inspect.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style){return"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m"}else{return str}}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};array.forEach(function(val,idx){hash[val]=true});return hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret)){ret=formatValue(ctx,ret,recurseTimes)}return ret}var primitive=formatPrimitive(ctx,value);if(primitive){return primitive}var keys=Object.keys(value);var visibleKeys=arrayToHash(keys);if(ctx.showHidden){keys=Object.getOwnPropertyNames(value)}if(isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0)){return formatError(value)}if(keys.length===0){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}if(isDate(value)){return ctx.stylize(Date.prototype.toString.call(value),"date")}if(isError(value)){return formatError(value)}}var base="",array=false,braces=["{","}"];if(isArray(value)){array=true;braces=["[","]"]}if(isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)){base=" "+RegExp.prototype.toString.call(value)}if(isDate(value)){base=" "+Date.prototype.toUTCString.call(value)}if(isError(value)){base=" "+formatError(value)}if(keys.length===0&&(!array||value.length==0)){return braces[0]+base+braces[1]}if(recurseTimes<0){if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}else{return ctx.stylize("[Object]","special")}}ctx.seen.push(value);var output;if(array){output=formatArray(ctx,value,recurseTimes,visibleKeys,keys)}else{output=keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)})}ctx.seen.pop();return reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}if(isNumber(value))return ctx.stylize(""+value,"number");if(isBoolean(value))return ctx.stylize(""+value,"boolean");if(isNull(value))return ctx.stylize("null","null")}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){var output=[];for(var i=0,l=value.length;i<l;++i){if(hasOwnProperty(value,String(i))){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,String(i),true))}else{output.push("")}}keys.forEach(function(key){if(!key.match(/^\d+$/)){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,key,true))}});return output}function formatProperty(ctx,value,recurseTimes,visibleKeys,key,array){var name,str,desc;desc=Object.getOwnPropertyDescriptor(value,key)||{value:value[key]};if(desc.get){if(desc.set){str=ctx.stylize("[Getter/Setter]","special")}else{str=ctx.stylize("[Getter]","special")}}else{if(desc.set){str=ctx.stylize("[Setter]","special")}}if(!hasOwnProperty(visibleKeys,key)){name="["+key+"]"}if(!str){if(ctx.seen.indexOf(desc.value)<0){if(isNull(recurseTimes)){str=formatValue(ctx,desc.value,null)}else{str=formatValue(ctx,desc.value,recurseTimes-1)}if(str.indexOf("\n")>-1){if(array){str=str.split("\n").map(function(line){return"  "+line}).join("\n").substr(2)}else{str="\n"+str.split("\n").map(function(line){return"   "+line}).join("\n")}}}else{str=ctx.stylize("[Circular]","special")}}if(isUndefined(name)){if(array&&key.match(/^\d+$/)){return str}name=JSON.stringify(""+key);if(name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)){name=name.substr(1,name.length-2);name=ctx.stylize(name,"name")}else{name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'");name=ctx.stylize(name,"string")}}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0;var length=output.reduce(function(prev,cur){numLinesEst++;if(cur.indexOf("\n")>=0)numLinesEst++;return prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(length>60){return braces[0]+(base===""?"":base+"\n ")+" "+output.join(",\n  ")+" "+braces[1]}return braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return isObject(re)&&objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==="[object Error]"||e instanceof Error)}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=require("./support/isBuffer");function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function timestamp(){var d=new Date;var time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))};exports.inherits=require("inherits");exports._extend=function(origin,add){if(!add||!isObject(add))return origin;var keys=Object.keys(add);var i=keys.length;while(i--){origin[keys[i]]=add[keys[i]]}return origin};function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./support/isBuffer":37,_process:19,inherits:36}],39:[function(require,module,exports){"use strict";var EventEmitter=require("../utils/EventEmitter.js");var targetManager=require("../target/TargetManager.js");var log=require("../utils/Logger.js").child({component:"ws-base"});var cons=require("../utils/Constants.js");class Base extends EventEmitter{constructor(options){super(options);this.options=options||{};this.id=this.options.id;this.period=this.options.period;this.periodReadEnabled=true;this._timer=null;this._target=null;this._url=this.options.url;this.initCalled=false;this.reinit=false;this.state=cons.State.NONE;if(!this._url){this.isDefURL=true}if(!this.period){this.isDefPeriod=true}this.log=log}startPeriodicReading(period){this.period=period||this.period;if(this.periodReadEnabled===false){this.periodReadEnabled=true}if(this._timer){clearTimeout(this._timer)}this._readPeriodic()}stopPeriodicReading(){this.periodReadEnabled=false}_changeState(state){if(this.state!==state){var oldState=this.state;this.state=state;switch(state){case cons.State.ONLINE:if(oldState===cons.State.OFFLINE){this._readPeriodic()}this.emit("online",this);break;case cons.State.OFFLINE:if(this._timer){clearTimeout(this._timer)}this.emit("offline",this);break}this.emit("state",state,this)}}init(){if(this._timer){clearTimeout(this._timer)}this.initCalled=true;return Promise.resolve()}_getTarget(){if(!this._target){return new Promise((resolve,reject)=>{if(!this._url){this._url=targetManager.getDefaultURL()}targetManager.getTarget(this._url).then(target=>{this._target=target;this._onTargetOnlineHandle=this._onTargetOnline.bind(this);this._onTargetOfflineHandle=this._onTargetOffline.bind(this);this._target.on("online",this._onTargetOnlineHandle);this._target.on("offline",this._onTargetOfflineHandle);resolve(this._target)}).catch(reject)})}else{return Promise.resolve()}}_onTargetOnline(){this.init().then(()=>{this._changeState(cons.State.ONLINE)}).catch(err=>{this._changeState(cons.State.ERROR);if(err instanceof Error){this.emit("error",err)}else{this.emit("error",new Error(err))}})}_onTargetOffline(){if(this._timer){clearTimeout(this._timer)}this._changeState(cons.State.OFFLINE)}read(){return new Promise.resolve}dispose(){if(this._timer){clearTimeout(this._timer)}if(this._target){this.emit("offline");this._target.removeListener("online",this._onTargetOnline);this._target.removeListener("offline",this._onTargetOffline);this._changeState(cons.State.NONE);this.initCalled=false;this._target=null}else if(this._url){targetManager.disposeTarget(this._url).catch(err=>{log.debug(err)})}return Promise.resolve()}changePeriod(period){this.period=period;if(this._timer){clearTimeout(this._timer)}this._readPeriodic()}_readPeriodic(){if(!this._target||!this.periodReadEnabled||!this.period||this.period<=0){if(this._timer){clearTimeout(this._timer)}return}this.read().then(()=>{this.emit("periodic",null,this);if(this.period>0){this._timer=setTimeout(()=>{this._readPeriodic()},this.period)}}).catch(err=>{if(this._timer){clearTimeout(this._timer)}this.emit("periodic",err,this);if(this.period>0&&this.state===cons.State.ONLINE){this._timer=setTimeout(()=>{this._readPeriodic()},this.period)}})}_setURL(url){this._url=url}}module.exports=Base},{"../target/TargetManager.js":48,"../utils/Constants.js":61,"../utils/EventEmitter.js":63,"../utils/Logger.js":65}],40:[function(require,module,exports){"use strict";var Base=require("./Base.js");var targetManager=require("../target/TargetManager.js");var Item=require("./Item.js");var log=require("../utils/Logger.js").child({component:"ws-group"});var cons=require("../utils/Constants.js");class Group extends Base{constructor(options){super(options);this.log=log;this.items=[];this.activeItems=[];this.timestamp=null;if(this.options.items){for(let i of this.options.items){this.items.push(this,i,i)}}this.servHandle=null}size(){return this.items.length}_changeState(state){if(this.state!==state){if(state!==cons.State.ONLINE){for(let i of this.items){i._changeState(state)}}else{for(let i of this.activeItems){i._changeState(state)}}}super._changeState(state)}addItem(options){if(this.initCalled){return new Promise((resolve,reject)=>{var item=this._getNewItem(options);item.init().then(()=>{return item.browse()}).then(()=>{this.items.push(item);return this.init()}).then(()=>{resolve(item)}).catch(err=>{item._changeState(cons.State.ERROR);reject(err)})})}else{var item=this._getNewItem(options);this.items.push(item);return Promise.resolve(item)}}removeItem(id){for(let i=0;i<this.items.length;i++){if(this.items[i].id===id){this.items.splice(i,1);if(this.initCalled){return this.init()}else{return Promise.resolve()}}}return Promise.reject("Item: "+id+" not found")}addItems(options){if(this.initCalled){var promises=[];var newItems=[];for(let i of options){var item=this._getNewItem(i);newItems.push(item);var promise=(item=>{return new Promise((resolve,reject)=>{item.init().then(()=>{return item.browse()}).then(resolve).catch(err=>{item._changeState(cons.State.ERROR);reject(err)})})})(item);promises.push(promise)}return new Promise((resolve,reject)=>{Promise.all(promises).then(()=>{for(let i of newItems){this.items.push(i)}this.init().then(resolve).catch(reject)})})}else{for(let i of options){this.addItem(i)}}}removeItems(ids){for(let id of ids){for(let i=0;i<this.items.length;i++){if(this.items[i].id===id){this.items.splice(i,1);break}}}}get(itemId){for(let i of this.items){if(i.id===itemId||i.readCString===itemId){return i}}return null}$i(itemId){return this.get(itemId)}init(){if(!this.items||this.items.length===0){return Promise.reject("Group must have items specified")}return super.init().then(()=>{return new Promise((resolve,reject)=>{this._getTarget().then(()=>{var readCStrings=[];this.activeItems=[];for(let i of this.items){if(i.state!==cons.State.ERROR){readCStrings.push(i.readCString);this.activeItems.push(i)}}this._target.addGroup(readCStrings).catch(err=>{for(let i of this.items){i._changeState(cons.State.ERROR,err)}return Promise.reject()}).then(res=>{return new Promise((resolve,reject)=>{this.servHandle=res.groupid;for(let i=0;i<res.ids.length;i++){var item=this.activeItems[i];if(res.ids[i].errno<0){log.error({cstring:item.readCString,response:res.ids[i]},item.id+": Failed to add item to group "+this.id+" Error: "+res.ids[i].err);item._changeState(cons.State.ERROR)}}var initItemsPromises=[];for(let i of this.activeItems){if(i.state!==cons.State.ERROR){initItemsPromises.push((i=>{return i.init().catch(err=>{log.error(err);i._changeState(cons.State.ERROR);return i})})(i))}}Promise.all(initItemsPromises).then(()=>{for(let i of this.activeItems){if(i.state===cons.State.ERROR){reject();break}}resolve()})})}).catch(err=>{return new Promise((resolve,reject)=>{if(this.reinit){this.reinit=false;this._changeState(cons.State.ERROR);log.error("Failed to reinit group.");reject(err);return}if(this.servHandle!==undefined&&this.servHandle!==null){this._target.removeGroup(this.servHandle).then(()=>{this.reinit=true;return this.init()}).then(resolve).catch(reject)}else{var ok=false;for(let i of this.items){if(i.state!==cons.State.ERROR){ok=true;break}}if(ok){this.reinit=true;return this.init().then(resolve).catch(reject)}else{var cstring=this.activeItems[0]?this.activeItems[0].readCString:"";reject(new Error(this.id+": Adding group failed. Connection string "+cstring+" and many more was not found on target!"))}}})}).then(()=>{var promise=Promise.resolve();for(let i of this.activeItems){promise=promise.then(()=>{return new Promise((resolve,reject)=>{i.browse().then(()=>{return new Promise(res=>{setTimeout(res,500)})}).then(resolve).catch(err=>{log.debug(err);resolve()})})})}}).then(()=>{this._changeState(cons.State.ONLINE);return this.read()}).then(()=>{resolve(this.items);this._readPeriodic()}).catch(reject)}).catch(reject)})})}_onTargetOffline(){this.servHandle=null;super._onTargetOffline()}read(){if(this.servHandle!==undefined&&this.servHandle!==null){return new Promise((resolve,reject)=>{var done=null;var promise=new Promise(function(resolve){done=resolve});this._target.readGroup(this.servHandle).then(res=>{this.timestamp=res.t;for(let i=0;i<res.values.length;i++){this.activeItems[i].setValue(res.values[i],promise);this.activeItems[i].timestamp=res.t}this._changeState(cons.State.ONLINE);this.emit("read",this.items);resolve(this.items);done()}).catch(err=>{if(this.state===cons.State.ONLINE){this._changeState(cons.State.ERROR)}reject(err)})})}return Promise.reject("Group is not initialized. Call init() function first!")}dispose(){var oldTarget=this._target;return super.dispose().then(()=>{if(oldTarget){for(let i of this.items){i.dispose()}return oldTarget.removeGroup(this.servHandle).catch(err=>{log.error(err)}).then(()=>{targetManager.disposeTarget(oldTarget).catch(err=>{log.debug(err)})})}})}_setURL(url){super._setURL(url);for(let i of this.items){i._url=url}}_getNewItem(options){if(options instanceof Item){options._url=this._url;return options}options.url=this._url;return new Item(options)}}module.exports=Group},{"../target/TargetManager.js":48,"../utils/Constants.js":61,"../utils/Logger.js":65,"./Base.js":39,"./Item.js":41}],41:[function(require,module,exports){"use strict";var events=require("events");var cons=require("../utils/Constants.js");var targetManager=require("../target/TargetManager.js");class Item extends events.EventEmitter{constructor(options){options=options||{};super(options);this.readCString=options.readCString||options.cstring;this.id=options.id||options.alias||this.readCString;this._url=options.url;if(!this._url){this._url=targetManager.getDefaultURL()}this.kind=null;this.type=null;this.value=null;this.timestamp=null;this.maxUpdatePeriod=options.maxUpdatePeriod;this.state=cons.State.NONE}init(){if(!this.id||!this.readCString){throw new Error("Item readCString not specified.")}return new Promise((resolve,reject)=>{this._getTarget().then(()=>{this._changeState(cons.State.ONLINE);resolve(this)}).catch(reject)})}browse(){if(this.kind){return Promise.resolve(this)}else{return new Promise((resolve,reject)=>{var regexp=/(.+):(\w+)/;var match=regexp.exec(this.readCString);this._target.browseSymbol(match[1]).then(res=>{var symbol=null;for(let s of res.children){if(s.symbol===match[2]){symbol=s}}if(!symbol){this.kind=cons.getSymbolKind(15)}else{this.kind=cons.getSymbolKind(symbol.kind);this.type=cons.getSymbolType(symbol.type)}resolve(this)}).catch(err=>{this._changeState(cons.State.ERROR);reject(err)})})}}_setMaxPeriodTimer(){if(this.maxUpdatePeriod&&this.maxUpdatePeriod>0){if(this._maxPeriodTimer){clearTimeout(this._maxPeriodTimer)}this._maxPeriodTimer=setTimeout(()=>{this._emit("change",this)},this.maxUpdatePeriod)}}read(){return new Promise((resolve,reject)=>{this._target.readItems([this.readCString]).then(res=>{this.setValue(res.values[0]);resolve(this)}).catch(reject)})}write(){return Promise.reject("Item "+this.id+" is read-only!")}getValue(){return this.value}setValue(value,promise){if(this.value!==undefined&&this.value!==null){if(this.value!==value){if(typeof value==="number"){if(this.value-value>Number.EPSILON){if(this.value>value){this._emit("falling",promise)}else{this._emit("raising",promise)}}}else if(typeof value==="boolean"){if(this.value===true){this._emit("falling",promise)}else{this._emit("raising",promise)}}this.value=value;this._emit("change",promise)}}else{this.value=value;this._emit("change",promise)}this._setMaxPeriodTimer();this._emit("read",promise)}isOnline(){return this.state===cons.State.ONLINE}_changeState(state){if(this.state!==state){var oldState=this.state;this.state=state;switch(state){case cons.State.ONLINE:if(oldState===cons.State.OFFLINE){this._setMaxPeriodTimer()}this.emit("online",this);break;case cons.State.OFFLINE:if(this._maxPeriodTimer){clearTimeout(this._maxPeriodTimer)}this.emit("offline",this);break}this.emit("state",this)}}_getTarget(){if(!this._target){return new Promise((resolve,reject)=>{targetManager.getTarget(this._url).then(target=>{this._target=target;this._onTargetOnlineHandle=this._onTargetOnline.bind(this);this._onTargetOfflineHandle=this._onTargetOffline.bind(this);this._target.on("online",this._onTargetOnlineHandle);this._target.on("offline",this._onTargetOfflineHandle);resolve(this._target)}).catch(reject)})}else{return Promise.resolve()}}_onTargetOnline(){if(this.state!==cons.State.ERROR){this._changeState(cons.State.ONLINE);this.emit("online",this)}}_onTargetOffline(){if(this.state!==cons.State.ERROR){this._changeState(cons.State.OFFLINE);this.emit("offline",this)}}dispose(){if(this._maxPeriodTimer){clearTimeout(this._maxPeriodTimer)}if(this._target){this._target.removeListener("online",this._onTargetOnlineHandle);this._target.removeListener("offline",this._onTargetOfflineHandle);targetManager.disposeTarget(this._target)}else if(this._url){targetManager.disposeTarget(this._url)}this._changeState(cons.State.NONE);this._target=null}_emit(ev,promise){if(promise){promise.then(()=>{this.emit(ev,this)})}else{this.emit(ev,this)}}}module.exports=Item},{"../target/TargetManager.js":48,"../utils/Constants.js":61,events:11}],42:[function(require,module,exports){"use strict";var STATE=require("../utils/Constants.js").State;var events=require("events");class LocalItem extends events.EventEmitter{constructor(options){options=options||{};super(options);this.id=options.id||options.alias;this.state=STATE.ONLINE;this.type=null;this.value=isNaN(Number(options.cstring))?options.cstring:Number(options.cstring)}init(){this.emit("online",this);this.emit("state",this);this.emit("change",this);this.emit("read",this);return Promise.resolve()}browse(){return Promise.reject("Not supported for local item")}read(){return new Promise.resolve(this)}write(value){this.setValue(value);return Promise.resolve(this)}getValue(){return this.value}setValue(value,promise){if(this.value!==undefined&&this.value!==null){if(this.value!==value){if(typeof value==="number"){if(this.value-value>Number.EPSILON){if(this.value>value){this._emit("falling",promise)}else{this._emit("raising",promise)}}}else if(typeof value==="boolean"){if(this.value===true){this._emit("falling",promise)}else{this._emit("raising",promise)}}this.value=value;this._emit("change",promise)}}else{this.value=value;this._emit("change",promise)}this._emit("read",promise)}isOnline(){return true}_changeState(state){}dispose(){}_emit(ev,promise){if(promise){promise.then(()=>{this.emit(ev,this)})}else{this.emit(ev,this)}}}module.exports=LocalItem},{"../utils/Constants.js":61,events:11}],43:[function(require,module,exports){"use strict";var Item=require("./Item.js");var cons=require("../utils/Constants.js");class RWItem extends Item{constructor(options){options=options||{};options.readCString=options.readCString||options.cstring||options.writeCString;super(options);this.rKind=null;this.wKind=null;this.writeCString=options.writeCString||this.readCString;this.readCString=this.readCString||this.writeCString}init(){return super.init()}browse(){if(this.rKind&&this.wKind){return Promise.resolve(this)}else{return new Promise((resolve,reject)=>{var regexp=/(.+):(\w+)/;var matchReadCS=regexp.exec(this.readCString);var matchWriteCS=regexp.exec(this.writeCString);var browsePromise;if(matchReadCS[1]===matchWriteCS[1]){browsePromise=this._target.browseSymbol(matchReadCS[1]).then(res=>{var symbol=null;for(let s of res.children){if(s.symbol===matchReadCS[2]){symbol=s}}this.rKind=cons.getSymbolKind(symbol.kind);this.kind=this.rKind;this.type=cons.getSymbolType(symbol.type);symbol=null;for(let s of res.children){if(s.symbol===matchWriteCS[2]){symbol=s}}this.wKind=cons.getSymbolKind(symbol.kind);this.kind=this.wKind})}else{var p1=this._target.browseSymbol(matchReadCS[1]).then(res=>{var symbol=null;for(let s of res.children){if(s.symbol===matchReadCS[2]){symbol=s}}this.rKind=cons.getSymbolKind(symbol.kind);this.kind=this.rKind;this.type=cons.getSymbolType(symbol.type)});var p2=this._target.browseSymbol(matchWriteCS[1]).then(res=>{var symbol=null;for(let s of res.children){if(s.symbol===matchWriteCS[2]){symbol=s}}this.wKind=cons.getSymbolKind(symbol.kind)});browsePromise=Promise.all([p1,p2])}browsePromise.then(()=>{if(!this.kind.read){this.valid=false;reject("Item "+this.id+"("+this.readCString+") is not readable");return}if(!this.wKind.write){this.valid=false;reject("Item "+this.id+"("+this.writeCString+") is not writable");return}this.valid=true;this._changeState(cons.State.ONLINE);resolve(this)}).catch(err=>{this._changeState(cons.State.ERROR);reject(err)})})}}write(value){let oldValue=this.value;this.value=value;return new Promise((resolve,reject)=>{if(!this._target){reject("Writing value failed! "+this.id+" is not online!");return}this._target.writeItems([this.writeCString],[value]).then(()=>{this.value=oldValue;this.setValue(value);resolve(this)}).catch(err=>{this.setValue(oldValue);if(err&&err.errno===-106){reject(`Writing value failed! Alias ${this.id} does not exist or is not writable.`)}else if(err&&err.errno===-118){reject(`Writing value is not allowed. Permissions are to low.`)}else{reject(err)}})})}}module.exports=RWItem},{"../utils/Constants.js":61,"./Item.js":41}],44:[function(require,module,exports){"use strict";var Base=require("./Base.js");var targetManager=require("../target/TargetManager.js");var cons=require("../utils/Constants.js");var log=require("../utils/Logger.js").child({component:"ws-trend"});var utils=require("../utils/utils.js");class Trend extends Base{constructor(options){super(options);this.log=log;this.trndCfg=null;if(!this.options.cstring){throw new Error(this.id+" trend connection string (cstring) is not defined!")}this.cstring=this.options.cstring;this.readWholeBuffer=utils.check(this.options.readWholeBuffer,true);this.MAX_UPDATE_PERIOD=5}init(){return super.init().then(()=>{return new Promise((resolve,reject)=>{this._getTarget().then(()=>{this._target.getTrendConfig(this.cstring).catch(err=>{this.log.debug("Adding trend failed! Connection string "+this.cstring+" is not pointing to the TRND block!");return Promise.reject()}).then(cfg=>{this.trndCfg=cfg;this.emit("init")}).then(()=>{this._changeState(cons.State.ONLINE);return this.read()}).then(()=>{resolve(this.items);this._readPeriodic()}).catch(reject)}).catch(reject)})})}_onTargetOffline(){this.trndCfg=null;this.readWholeBuffer=utils.check(this.options.readWholeBuffer,true);super._onTargetOffline()}read(){if(this.trndCfg!==undefined&&this.trndCfg!==null){return new Promise((resolve,reject)=>{this._target.readTrend(this.trndCfg.trendid).then(res=>{this.emit("read",res);resolve(res)}).catch(reject)})}return Promise.reject("Trend is not initialized. Call init() function first!")}_readPeriodic(){if(!this._target||!this.periodReadEnabled||!this.period||this.period<=0){if(this._timer){clearTimeout(this._timer)}return}this.read().then(res=>{this.emit("periodic",null,this);if(this.readWholeBuffer&&!res.underflow&&res.unread>0){this._timer=setTimeout(()=>{this._readPeriodic()},this.MAX_UPDATE_PERIOD)}else if(this.period>0){this._timer=setTimeout(()=>{this._readPeriodic()},this.period)}else{}}).catch(err=>{if(this._timer){clearTimeout(this._timer)}this.emit("periodic",err,this);if(this.period>0&&this.state===cons.State.ONLINE){this._timer=setTimeout(()=>{this._readPeriodic()},this.period)}})}dispose(){this.trndCfg=null;this.readWholeBuffer=utils.check(this.options.readWholeBuffer,true);super.dispose()}}module.exports=Trend},{"../target/TargetManager.js":48,"../utils/Constants.js":61,"../utils/Logger.js":65,"../utils/utils.js":67,"./Base.js":39}],45:[function(require,module,exports){"use strict";var Group=require("./Group.js");var RWItem=require("./RWItem.js");class WGroup extends Group{constructor(options){options=options||{};super(options)}write(values){return new Promise((resolve,reject)=>{if(this.servHandle!==undefined&&this.servHandle!==null){if(!values){values=[];for(let item of this.activeItems){values.push(item.value)}}else{for(let i=0;i<values.length;i++){this.activeItems[i].value=values[i]}}this._target.writeGroup(this.servHandle,values).then(()=>{resolve(this.items)}).catch(reject)}else{reject(new Error("Group not initialized"))}})}_getNewItem(options){return new RWItem(options)}}module.exports=WGroup},{"./Group.js":40,"./RWItem.js":43}],46:[function(require,module,exports){"use strict";var targetManager=require("./target/TargetManager.js");var log=require("./utils/Logger.js").child({component:"hmi"});var EventEmitter=require("./utils/EventEmitter.js");var Base=require("./group-management/Base.js");var Group=require("./group-management/Group.js");var Item=require("./group-management/Item.js");var RWItem=require("./group-management/RWItem.js");var LocalItem=require("./group-management/LocalItem.js");var events=require("events");var HMIGraph=require("./ui/HMIGraph.js");var EventSync=require("./utils/EventSync");var utils=require("./utils/utils.js");var cons=require("./utils/Constants.js");class HMI extends EventEmitter{constructor(){super();this.GROUP_MAX_SIZE=100;this.DEFAULT_REFRESH_RATE=500;this.groups=[];this.baseObjects=[];this.userGroup=[];this._defaultRefreshRate=this.DEFAULT_REFRESH_RATE;this.initialized=false;this.defTarget=null;this._onTargetTimeHandle=this._onTargetTime.bind(this);this._onTargetHeartbeatHandle=this._onTargetHeartbeat.bind(this);this._onTargetOnlineHandle=this._onTargetOnline.bind(this);this._onTargetOfflineHandle=this._onTargetOffline.bind(this);this._showHeartBeatClock=false;this._useClientTime=false;this.Graph=HMIGraph;this.log=log;this.headerTitleElement=null;this._ownTarget=false;this.standalone=true;this.kioskMode=null;this.headerMode=null;this.disableAutoReload=false;this.on("init",()=>{this.getTarget().on("headerFlags",flags=>{if(!this.disableAutoReload){if(flags&cons.WSF_HMI_CHANGED||flags&cons.WSF_CONFIG_CHANGED){window.location.reload(true)}}})})}init(){}connect(){if(this.init.length===1){return new Promise((resolve,reject)=>{this.init(err=>{if(err){reject(err)}else{resolve()}})}).then(()=>{return this._initBaseObjects()})}else{this.init();return this._initBaseObjects()}}_initBaseObjects(){if(this.baseObjects.length===0){return targetManager.getTarget().then(target=>{this._setDefaultTarget(target);this._ownTarget=true;this.initialized=true;this.emit("init");return this.defTarget})}var promises=[];for(let obj of this.baseObjects){if(!obj.initCalled){promises.push(obj.init())}}for(let itm of this.userGroup){promises.push(itm.init())}var p=Promise.all(promises);this.initialized=true;return p.then(()=>{this._setDefaultTarget();this.emit("init");return this.defTarget}).catch(err=>{if(this.getTarget()){this._setDefaultTarget();this.emit("init")}return Promise.reject(err)})}disconnect(){for(let obj of this.baseObjects){obj.stopPeriodicReading();obj.dispose()}}getTarget(url){if(url){for(let obj of this.baseObjects){if(obj._target.url===url){return obj._target}}}else{if(this.defTarget){return this.defTarget}else{for(let obj of this.baseObjects){if(obj.isDefURL){return obj._target}}return null}}}setTargetUrl(url,force){if(!force){if(location&&location.hostname){url=""}}if(url&&!new RegExp("^(?:ws|wss|http|https):\\/\\/").test(url)){url="ws://"+url}if(targetManager.getDefaultURL()===url){return Promise.resolve()}this._disposeTarget();targetManager.setDefaultURL(url);var baseObjects=[];for(let obj of this.baseObjects){if(obj.isDefURL){baseObjects.push(obj)}}var promises=[];if(this.initialized){if(baseObjects.length===0){this._ownTarget=true;return targetManager.getTarget().then(target=>{this._setDefaultTarget(target)})}for(let obj of baseObjects){obj.dispose();obj._setURL(url);promises.push(obj.init())}return Promise.all(promises).then(()=>{this._setDefaultTarget();log.info("Target URL changed");return this.defTarget}).catch(err=>{log.error(err);return Promise.reject(err)})}else{for(let g of baseObjects){g._setURL(url)}return Promise.resolve()}}setRefreshRate(period){if(!utils.isNumber(period)){throw new Exception("Refresh rate must be number!")}this._defaultRefreshRate=period;for(let obj of this.baseObjects){if(obj.isDefPeriod){obj.changePeriod(this._defaultRefreshRate)}}this.emit("refreshRate");log.info("Refresh rate changed.")}addItem(opt){if(opt.type&&opt.type==="L"){let item=new LocalItem(opt);this.userGroup.push(item);return item}var isDefURL=false;var url=opt.url;if(!opt.url){isDefURL=true}var isDefPeriod=false;var period=opt.period;if(!opt.period){isDefPeriod=true;period=this._defaultRefreshRate}var group;for(let g of this.groups){if(g.isDefPeriod===isDefPeriod&&g.isDefURL===isDefURL&&g.period===period&&(!url||g._url===url)&&g.size()<this.GROUP_MAX_SIZE){if(!this.standalone&&g.initCalled){continue}group=g;break}}if(!group){let gOpt=Object.assign({},opt);gOpt.id=gOpt.id||"HMIGroup-"+this.groups.length;group=new Group(gOpt);group.period=period;this.groups.push(group);this.baseObjects.push(group)}var item;if(opt.writeCString||opt.write){opt.writeCString=opt.writeCString||opt.cstring;opt.cstring="";item=new RWItem(opt)}else{item=new Item(opt)}group.addItem(item).catch(err=>{this.log.debug("Adding %s failed! CString %s not found",opt.alias,opt.cstring)});return item}addItems(items){var res=[];for(var i=0;i<items.length;i++){res.push(this.addItem(items[i]))}return res}commit(){let promises=[];for(let baseObj of this.baseObjects){if(!baseObj.initCalled){promises.push(baseObj.init())}}return Promise.all(promises)}removeItem(alias){for(let obj of this.baseObjects){if(obj instanceof Group){let item=obj.get(alias);if(item){if(obj.items.length===1){this._removeBaseObject(obj)}return obj.removeItem(alias).then(()=>{if(obj.items.length===0){return obj.dispose()}})}}}return Promise.reject(alias+" not found")}get(alias){for(let obj of this.baseObjects){if(obj instanceof Group){let item=obj.get(alias);if(item){return item}}}for(let itm of this.userGroup){if(itm.id===alias){return itm}}return null}$i(alias){return this.get(alias)}_addBaseObject(obj){if(obj instanceof Base){this.baseObjects.push(obj)}else{throw new Error("Object is not instance of Base class. Cannot add!")}}_removeBaseObject(obj){var index=-1;if(obj instanceof Group){index=this.groups.indexOf(obj);if(index>-1){this.groups.splice(index,1)}}index=this.baseObjects.indexOf(obj);if(index>-1){return this.baseObjects.splice(index,1)}}addGroup(g){this._addBaseObject(g)}removeGroup(g){this._removeBaseObject(g)}addTrend(t){this._addBaseObject(t)}removeTrend(t){this._removeBaseObject(t)}writeValues(aliases,values){if(aliases.length!==values.length){log.error(new Error("Length of aliases and length of values must be the same."));return}var items=[];for(let alias of aliases){var itm=this.get(alias);if(itm){if(itm instanceof RWItem){items.push(itm)}else{log.error(new Error("Alias '"+alias+"' not writable."));return}}else{log.error(new Error("Alias '"+alias+"' not found."));return}}var tasks=[];for(let i=0;i<items.length;i++){var found=false;for(let j=0;j<tasks.length;j++){if(tasks[j].target===items[i]._target){tasks[j].items.push(items[i]);tasks[j].values.push(values[i]);found=true;break}}if(!found){tasks.push({target:items[i]._target,items:[items[i]],values:[values[i]]})}}var promises=[];for(let task of tasks){var names=[];for(let itm of task.items){names.push(itm.writeCString)}var promise=task.target.writeItems(names,task.values);promises.push(promise)}return Promise.all(promises)}setTitle(title){if(document&&document.title){document.title=title}this.setHeaderTitle(title)}setHeaderTitle(title){if(this.headerTitleElement){this.headerTitleElement.text(title)}}showHeartBeatClock(show){this._showHeartBeatClock=show!==undefined?show:true}useClientTime(use){this._useClientTime=use!==undefined?use:true}getItemsEventSynchonizer(aliases,events){if(typeof aliases==="string"){aliases=[aliases]}if(typeof events==="string"){events=[events]}var itemsSync=new EventSync(events);for(let alias of aliases){var item=this.get(alias);if(!item){throw new Error("Alias "+alias+" is not defined. Add item first!")}else{itemsSync.registerEventEmitter(item)}}return itemsSync}_setDefaultTarget(target){if(this.defTarget){this.emit("offline");this._disposeTarget()}if(target){this.defTarget=target}else{this.defTarget=this.getTarget()}this.emit("online");this.defTarget.on("time",this._onTargetTimeHandle);this.defTarget.on("heartbeat",this._onTargetHeartbeatHandle);this.defTarget.on("online",this._onTargetOnlineHandle);this.defTarget.on("offline",this._onTargetOfflineHandle)}_disposeTarget(){if(this._ownTarget){if(this.defTarget){this.defTarget.removeListener("time",this._onTargetTimeHandle);this.defTarget.removeListener("heartbeat",this._onTargetHeartbeatHandle);this.defTarget.removeListener("online",this._onTargetOnlineHandle);this.defTarget.removeListener("offline",this._onTargetOfflineHandle);targetManager.disposeTarget(this.defTarget)}else{targetManager.disposeTarget(targetManager.getDefaultURL())}this._ownTarget=false}this.defTarget=null}_onTargetTime(time){if(this.showClientTime){time=new Date}this.emit("time",time)}_onTargetOnline(){this.emit("online")}_onTargetOffline(){this.emit("offline")}_onTargetHeartbeat(){this.emit("heartbeat")}}module.exports=new HMI},{"./group-management/Base.js":39,"./group-management/Group.js":40,"./group-management/Item.js":41,"./group-management/LocalItem.js":42,"./group-management/RWItem.js":43,"./target/TargetManager.js":48,"./ui/HMIGraph.js":51,"./utils/Constants.js":61,"./utils/EventEmitter.js":63,"./utils/EventSync":64,"./utils/Logger.js":65,"./utils/utils.js":67,events:11}],47:[function(require,module,exports){"use strict";var utils=require("./utils/utils.js");var DivLoggerStream=require("./utils/DivLoggerStream.js");var HMI=require("./hmi.js");var Logger=require("./utils/Logger.js");var SVGManager=require("./ui/svg/SVGManager.js");var WebWatchEngine=require("./webwatch/Engine.js");var moment=require("moment");class HMILoader{constructor(){this.WebWatchEngineInitialized=false;this._hbTimer=null;this._hbElement=null}_startHB(){if(!this._hbElement){return}this._hbElement.addClass("heart-beat-on");if(this._hbTimer){clearTimeout(this._hbTimer)}this._hbTimer=setTimeout(()=>{this._hbElement.removeClass("heart-beat-on")},2e3)}refreshControls(){var target=HMI.getTarget();$("#info .info-version").text(target.version);$("#target-url").val(target.url);$("#target-refresh-rate").val(HMI._defaultRefreshRate);if(target.whoami){$("#info .whoami").text(target.whoami.login)}else{target.on("whoami",whoami=>{$("#info .whoami").text(whoami.login)})}$("#content").removeClass("error");this._startHB()}refreshSVGComponents(){var target=HMI.getTarget();if(target.whoami){let components=SVGManager.components;for(let c of components){if(c.setPermissions){c.setPermissions(target.whoami)}}}else{target.on("whoami",this.refreshSVGComponents)}}initializeBrowser(){function hideInfo(){$("#info").removeClass("open");$("#content").unbind("click",hideInfo)}$("#info-btn").click(function(evt){$("#info").toggleClass("open");if($("#info").is(":visible")){$("#log-error-counter").removeClass();$("#content").bind("click",hideInfo)}});this._hbElement=$("#header #heart-beat");if($(".current-time").length>0){var time_elem=$(".current-time");var hbClock=$("#heart-beat-clock");var hbClockVisible=false;var hbElement=this._hbElement;HMI.on("heartbeat",()=>{if(!hbClockVisible){this._startHB()}});HMI.on("time",date=>{if(HMI._useClientTime){time_elem.text(moment().format("HH:mm:ss"))}else{time_elem.text(moment(date).format("HH:mm:ss"))}if(HMI._showHeartBeatClock&&$(window).width()>800){if(!hbClock.is(":visible")){$("#header-title").removeClass("header-title-with-info-and-hearth-beat");$("#header-title").addClass("header-title-with-info-and-hearth-beat-clock");hbClock.show();hbElement.hide();hbClockVisible=true}}else{if(hbClock.is(":visible")){$("#header-title").addClass("header-title-with-info-and-hearth-beat");$("#header-title").removeClass("header-title-with-info-and-hearth-beat-clock");hbClock.hide();hbElement.show();hbClockVisible=false}}})}$("#content").prop("tab-index","-1");$("#target-refresh-rate").keyup(function(evt){"use strict";var keyCode=evt.keyCode||evt.which;var elem=$(this);var textField=elem.parent()[0].MDCTextField;if(keyCode===27){textField.valid=true;elem.blur();elem.val(HMI._defaultRefreshRate)}if(keyCode===13){textField.valid=true;if(utils.isUint(elem.val())){HMI.setRefreshRate(parseInt(elem.val()));elem.blur()}else{textField.valid=false}}});$("#target-url").keyup(function(evt){var keyCode=evt.keyCode||evt.which;var elem=$(this);var textField=elem.parent()[0].MDCTextField;if(keyCode===27){textField.valid=true;elem.blur();var target=HMI.getTarget();elem.val(target.url)}if(keyCode===13){textField.valid=true;HMI.setTargetUrl(elem.val(),true);elem.blur()}});HMI.headerTitleElement=$("#header-title");if($("#log").length>0){var divLoggerStream=new DivLoggerStream($("#log table"),$("#log-error-counter"));Logger.addStream({name:"DivLogger",stream:divLoggerStream,level:"info",type:"raw"})}HMI.kioskMode=function(){$("#header a").removeAttr("href");$("#controls input").prop("disabled",true)};HMI.headerMode=function(mode){if(!mode){mode=""}if(typeof mode==="string"){$("#logo").off().attr("href","/");$("#header").removeClass();switch(mode.toLowerCase()){case"thin":$("#header").addClass("header--"+mode.toLowerCase());break;case"pack-top-left":case"pack-top-right":case"pack-bottom-left":case"pack-bottom-right":$("#header").addClass("header--packed");$("#header").addClass("header--"+mode.toLowerCase());$("#logo").removeAttr("href");$("#logo").click(()=>{$("#header").toggleClass("header--packed")});break;default:break}}else{HMI.log.warn("[HMI Config] Header mode "+mode+" is not string!")}}}initializeInkscapeHMI(rootNode){var $rootNode=$(rootNode);var svgs=$rootNode.children('svg[rexsvg\\:module="REXSVG"]');if(svgs.length>0){for(var i=0;i<svgs.length;i++){SVGManager.init(svgs[i])}HMI.log.debug("SVG modules initialized.")}}initializeWebWatch(rootNode){var $rootNode=$(rootNode);var svgs=$rootNode.children("svg");if(svgs.length>0){WebWatchEngine.processSvg($(svgs[0]));HMI.log.debug("WebWatch initialized.");this.WebWatchEngineInitialized=true}}getRootURL(){var wsURL=HMI.getTarget().url||"";var rootURL=wsURL?"http"+wsURL.substr(2):"http://127.0.0.1:8008";var lastIndexOfRex=rootURL.lastIndexOf("/rex");if(lastIndexOfRex>=0){rootURL=rootURL.substr(0,lastIndexOfRex+1)}return rootURL}refreshBlockInfo(){if(this.WebWatchEngineInitialized&&WebWatchEngine&&WebWatchEngine._blocks.length>0&&Object.keys(WebWatchEngine._blockInfo).length===0){$.ajax({url:this.getRootURL()+"resources/block-info.json",success:data=>{WebWatchEngine.setBlockInfo(JSON.parse(data));HMI.log.debug("BlockInfo loaded")},dataType:"text"}).fail(err=>{HMI.log.warn("WebWatch block information resources loading failed!")})}}}let HMILoaderInstance=new HMILoader;module.exports=HMILoaderInstance;$(document).ready(function(){if(!REX.HMI.standalone){return}HMILoaderInstance.initializeBrowser();HMILoaderInstance.initializeWebWatch($("#rex-dialog-container")[0]);HMILoaderInstance.initializeInkscapeHMI($("#content")[0]);HMI.connect().then(target=>{}).catch(err=>{$("#content").addClass("error");if(err){HMI.log.error(err)}else{HMI.log.debug("HMI connect failed! Err is not defined!")}});HMI.on("online",function(){HMILoaderInstance.refreshControls();HMILoaderInstance.refreshBlockInfo();HMILoaderInstance.refreshSVGComponents()});HMI.on("offline",function(){$("#content").addClass("error")});$(window).on("beforeunload",function(){HMI.disconnect()})})},{"./hmi.js":46,"./ui/svg/SVGManager.js":59,"./utils/DivLoggerStream.js":62,"./utils/Logger.js":65,"./utils/utils.js":67,"./webwatch/Engine.js":84,moment:16}],48:[function(require,module,exports){(function(process){"use strict";var WSTarget=require("../target/WSTarget.js");var DEFAULT_TARGET_URL="ws://127.0.0.1:8008/rex";class TargetManager{constructor(){this._wsTargets=[];this._connecting=[];this._defaultUrl=""}setDefaultURL(url){this._defaultUrl=url}getDefaultURL(){if(!this._defaultUrl){if(process.browser&&location.host!=="localhost:3000"&&location.host!=="127.0.0.1:3000"&&(location.protocol==="https:"||location.protocol==="http:")){var url=location.host+"/rex";if(url.indexOf("s://")===-1){if(location.protocol==="https:"){url="wss://"+url}else{url="ws://"+url}}this._defaultUrl=url}else{this._defaultUrl=DEFAULT_TARGET_URL}}return this._defaultUrl}getTarget(url){if(!url){url=this.getDefaultURL()}if(new RegExp("^(?:ws|wss):\\/\\/").test(url)){for(let target of this._wsTargets){if(target.url===url){target.ref++;return Promise.resolve(target.target)}}for(let target of this._connecting){if(target.url===url){target.ref++;return target.promise}}var target=new WSTarget(url);var p=new Promise((resolve,reject)=>{target.init().then(()=>{var i;for(i=0;i<this._connecting.length;i++){if(this._connecting[i].url===url){var trgt=this._connecting.splice(i,1);this._wsTargets.push({target:target,url:url,ref:trgt[0].ref});break}}resolve(target)}).catch(target=>{reject(target)})});this._connecting.push({url:url,target:target,promise:p,ref:1});return p}else{return Promise.reject("REST not supported yet. Use WebSocket instead!")}}disposeTarget(target){var targets;if(typeof target==="string"){targets=this._connecting}else{targets=this._wsTargets}for(let i=0;i<targets.length;i++){if(typeof target==="string"){if(targets[i].url!==target){continue}}else if(targets[i].target!==target){continue}targets[i].ref--;if(targets[i].ref===0){return targets.splice(i,1)[0].target.dispose()}return Promise.resolve("Target is still referenced by some components")}}}module.exports=new TargetManager}).call(this,require("_process"))},{"../target/WSTarget.js":49,_process:19}],49:[function(require,module,exports){"use strict";var WsClient=require("../ws-client/Client.js");var log=require("../utils/Logger.js").child({component:"ws-target"});var utils=require("../utils/utils.js");var cons=require("../utils/Constants.js");class WSTarget extends WsClient{constructor(url){super();this.url=url;this._timeout=null;this._reconnectTimer=null;this.disposed=false;this._keepAliveTimer=null;this._keepAliveInterval=2e3;this.keepAlive=true;this.cmdTimeout=1e4;this._timeoutedRequests=0;this._maxTimeoutedRequests=5;this.reconnecting=false;this.version=null;this.whoami=null;this.time=null;this._syncTimeTimer=null;this._syncTimePeriod=3e5;this._calcTimeTimer=null;this._calcTimeTimerLastTime=null;this.syncTime=true;this._onInitResolve=null;this.on("online",()=>{this._clearTimers();this._resetKeepAlive();this._resetTimeSync();this._timeoutedRequests=0;this._calcTimeTimer=setInterval(()=>{let now=new Date;if(!this._calcTimeTimerLastTime){this._calcTimeTimerLastTime=now}let elapsed=now-this._calcTimeTimerLastTime;this.time.setTime(this.time.getTime()+elapsed);this.emit("time",this.time);this._calcTimeTimerLastTime=now},1e3)});this.on("offline",()=>{this._clearTimers();this.commands.clear()});this.on("closed",this._onSockClose);this.on("headerFlags",flags=>{if(flags&cons.WSF_CONFIG_CHANGED){log.info("REX configuration has been changed!");this.disconnect().then(this._reconnect.bind(this))}})}init(){return new Promise((resolve,reject)=>{this._onInitResolve=resolve;this.connect(this.url).then(()=>{this._init()}).catch(err=>{this._reconnect()})})}_init(){this.emit("online");var versionProm=this.getVersion();var timeProm=this.getTime();Promise.all([versionProm,timeProm]).then(ret=>{this.version=ret[0];this.time=utils.getDateFromREXSeconds(ret[1].utc/1e9);let resolve=whoami=>{if(whoami&&whoami.login){this.whoami=whoami;this.emit("whoami",whoami)}if(this._onInitResolve){this._onInitResolve(this);this._onInitResolve=null}};this.getWhoami().then(resolve).catch(resolve)}).catch(err=>{log.error(err)})}_makeAPICall(code,data){this._resetKeepAlive();var cmd=super._makeAPICall(code,data);cmd.promise.then(()=>{clearTimeout(cmd.cmdTimer)}).catch(()=>{clearTimeout(cmd.cmdTimer)});cmd.cmdTimer=setTimeout(()=>{cmd.reject("Request "+cmd.header.id+" timed out");this.commands.removeCmd(cmd.id);if(!this.reconnecting){this._timeoutedRequests++;log.debug("Remaining commands: "+this.commands.length+" message length: "+this.commands.getMsgLength());if(this._timeoutedRequests>=this._maxTimeoutedRequests){if(this._timeoutedRequests===this._maxTimeoutedRequests){this.commands.clear();this._clearTimers();this.idle().then(()=>{log.debug("Idle cmd after timeout successful");this._sock.close()}).catch(()=>{log.debug("Idle cmd after timeout failed");this._sock.close()})}else{}}}},this.cmdTimeout);return cmd.promise}_resetKeepAlive(){if(this._keepAliveTimer){clearTimeout(this._keepAliveTimer)}if(this.keepAlive){if(typeof this._onKeepAlive==="function"){this._keepAliveTimer=setTimeout(()=>{this._onKeepAlive()},this._keepAliveInterval)}}}_onKeepAlive(){this.idle().catch(err=>{if(this._keepAliveTimer){clearTimeout(this._keepAliveTimer)}log.debug("Keep alive (IDLE) request failed",err)})}_resetTimeSync(){if(this._syncTimeTimer){clearTimeout(this._syncTimeTimer)}if(this.syncTime){this._syncTimeTimer=setTimeout(()=>{this.getTime().then(time=>{this.time=utils.getDateFromREXSeconds(time.utc/1e9);this._calcTimeTimerLastTime=null;this._resetTimeSync()}).catch(err=>{if(this._syncTimeTimer){clearTimeout(this._syncTimeTimer)}log.debug(err)})},this._syncTimePeriod)}}_onSockClose(){this.emit("offline");this._reconnect()}_clearTimers(){if(this._keepAliveTimer){clearTimeout(this._keepAliveTimer);this._keepAliveTimer=null}if(this._syncTimeTimer){clearTimeout(this._syncTimeTimer);this._syncTimeTimer=null}if(this._calcTimeTimer){clearInterval(this._calcTimeTimer);this._calcTimeTimerLastTime=null}}dispose(){this.removeListener("closed",this._onSockClose);this.emit("offline");this._clearTimers();if(this._reconnectTimer){clearTimeout(this._reconnectTimer);this._reconnectTimer=null;this.reconnecting=false}this.disposed=true;log.debug("Target "+this.url+" is being disposed.");return this.disconnect()}disconnect(){this.emit("offline");this._clearTimers();return super.disconnect()}_reconnect(){if(!this.disposed&&!this.reconnecting){this._timeout=_getTimeoutGenerator();this._reconnectLoop();this.reconnecting=true}}_reconnectLoop(){var timeout=this._timeout.next().value;log.debug('Reconnecting to target "'+this.url+'" in '+timeout+" ms.");this._reconnectTimer=setTimeout(()=>{this.reconnect().then(()=>{if(this._reconnectTimer){clearTimeout(this._reconnectTimer)}this.reconnecting=false;this._init()}).catch(()=>{this._reconnectLoop()})},timeout)}}function*_getTimeoutGenerator(){yield 500;yield 1e3;yield 2e3;yield 5e3;yield 1e4;while(true){yield 6e4}}module.exports=WSTarget},{"../utils/Constants.js":61,"../utils/Logger.js":65,"../utils/utils.js":67,"../ws-client/Client.js":91}],50:[function(require,module,exports){"use strict";var EventEmitter=require("../utils/EventEmitter.js");var utils=require("../utils/utils.js");var State=require("../utils/Constants.js").State;var COLORS=require("../utils/Constants.js").COLORS;var log=require("../utils/Logger.js").child({component:"UI"});var HMI=require("../hmi.js");class Component extends EventEmitter{constructor(options){super();this.options=options=options||{};this.id=options.id||(options.element?options.element.id:"");this.state=State.NONE;this.element=options.element;this.version=options.version;this.COLORS=COLORS;this.readOnly=true;this._isDisabled=false;this._isVisible=false;this.log=log;this.writePerm=utils.check(options.writePerm,[]);if(this.constructor.name){this.log=require("../utils/Logger.js").child({component:`UI-${this.constructor.name}`,id:this.id})}}_disable(){this._isDisabled=true;this.emit("disable",true);return true}_enable(){this._isDisabled=false;this.emit("disable",false);return true}_show(){this._isVisible=true;this.emit("visible",true);return true}_hide(){this._isVisible=false;this.emit("visible",false);return true}disable(){return this._disable()}enable(){return this._enable()}show(){return this._show()}hide(){return this._hide()}isDisabled(){return this._isDisabled}isVisible(){return this._isVisible}state(newState){if(newState){let found=false;for(var prop in State){if(x.hasOwnProperty(prop)){if(State[prop]===newState){this.state=State[prop];found=true;this.emit("state",newState)}}}if(!found){throw Error("State "+newState+" is not defined!")}}return this.state}setPermissions(whoami){let login=whoami.login;if(this.writePerm&&this.writePerm.length>0){for(let p of this.writePerm){if(p.login.toLowerCase()===login.toLowerCase().trim()){return}}this.log.debug("Login "+login+" not found in write permission list.");this.setReadOnly()}}setReadOnly(){this.readOnly=true}}module.exports=Component},{"../hmi.js":46,"../utils/Constants.js":61,"../utils/EventEmitter.js":63,"../utils/Logger.js":65,"../utils/utils.js":67}],51:[function(require,module,exports){"use strict";var Graph=require("./graph/Graph.js");var utils=require("../utils/utils.js");var EventSync=require("../utils/EventSync.js");var Trend=require("../group-management/Trend.js");class HMIGraph extends Graph{constructor(){super({id:"rexhmi-graph",element:$('<div id="rexhmi-graph" class="mdc-card"></div>')[0]});this.trendSize=.39;this.initialized=false;this.eventSync=new EventSync(["read"]);this.eventSync.on("read",()=>{this.refresh()});this.eventSync.ignoreOfflineItems=true;$(window).resize(()=>{if(this._isVisible){this._resize()}});this.rootDiv=null}_resize(){var $content=$("#content");if(this._isVisible){var graph=$(this.element);var content_top=$content[0].getBoundingClientRect().y;var chart_bottom=parseInt(graph.css("bottom"),10);var height=$(window).height()-content_top-chart_bottom;if(graph.is(":visible")){$content.css("max-height",((1-this.trendSize)*height).toFixed(3)+"px");let bcr=$content[0].getBoundingClientRect();graph.css("top",(bcr.y+bcr.height).toFixed(3)+"px")}else{$content.css("max-height","none")}}else{$content.css("max-height","none")}}resume(){super.resume()}pause(){super.pause()}show(){super.show();this._resize()}hide(){super.hide();this._resize()}addSignal(opt){var HMI=require("../hmi.js");if(!this.initialized){if(this.rootDiv){this.rootDiv=$(this.rootDiv)[0]}else{this.rootDiv=$("#main-block")[0]}$("#content").css("overflow-y","auto");this.rootDiv.after(this.element);this.show();this.initialized=true}if(opt.alias||opt.desc){opt.alias=opt.alias||utils.createID(opt.desc);opt.label=opt.desc||opt.alias;if(opt.alias.indexOf(" ")!==-1){this.log.error(opt.label+": Alias "+opt.alias+" in trend signal must not contain spaces!");return}var item=HMI.get(opt.alias);if(item&&opt.cstring&&item.cstring!==opt.cstring){this.log.error(opt.label+": Alias "+opt.alias+" already defined! Must be unique!");return}if(!item&&!opt.cstring){if(!opt.cstring){this.log.error(opt.label+": Cannot create an item. There is no connection string for alias "+opt.alias);return}}if(!item){item=HMI.addItem({alias:opt.alias,cstring:opt.cstring})}var serieID=this.addSerie(opt);item.on("read",itm=>{this.data.addPoint(serieID,itm.timestamp,itm.value)});this.eventSync.registerEventEmitter(item);this.refresh()}else{if(!opt.cstring){this.log.error("addTrendSignal: Alias or ConnectionString is not define. Cannot add!");return}if(opt.cstring.indexOf(":")!==-1){opt.cstring=opt.cstring.substr(0,opt.cstring.indexOf(":"))}var isDefPeriod=false;var period=opt.period;if(!opt.period){isDefPeriod=true;period=HMI._defaultRefreshRate}var trend=new Trend(opt);trend.period=period;var trndID=null;trend.on("read",data=>{if(trndID===null){var cfg=trend.trndCfg;cfg.labels=opt.labels;trndID=this.addTrendConfig(cfg)}this.data.addTrend(trndID,data);if(!this._timer){this.refresh()}});HMI.addTrend(trend)}}addTrend(opt){if(!opt.cstring){this.log.error("addTrendSignal: ConnectionString is not define. Cannot add!");return}if(opt.alias){this.log.error("addTrendSignal: ALIAS is not allowed here! Only cstring should be specified.");return}this.addSignal(opt)}setSize(size){if(size<0||size>1){this.log.error("Trend size must be <0;1>");return}this.trendSize=size;$(window).trigger("resize")}setRefreshRate(period){if(utils.isNumber(period)){this.eventSync.removeAllListeners("read")}super.setRefreshRate(period)}hideLegend(){super.hideLegend()}}module.exports=new HMIGraph},{"../group-management/Trend.js":44,"../hmi.js":46,"../utils/EventSync.js":64,"../utils/utils.js":67,"./graph/Graph.js":52}],52:[function(require,module,exports){"use strict";var Component=require("../Component.js");var GraphData=require("../graph/GraphData.js");var utils=require("../../utils/utils.js");var Timer=require("../../utils/Timer.js");class Graph extends Component{constructor(options){super(options);this.$element=$(this.element);this.graph=null;this.dygraphOptions=null;this._timer=null;this._pause=false;this._autoZoom=false;this._autoZoomRange=-1;this._autoZoomChanged=false;this.data=new GraphData;this._injectTemplates();this._graphDiv=this.$element.find(".graph-graph");this._controlsDiv=this.$element.find(".graph-controls");this._labelsDiv=this.$element.find(".graph-labels");this._initControls();this.$element.css("overflow","hidden");$(window).resize(()=>{if(this.graph){this._graphDiv.css("width","").css("height","");this.graph.resize()}})}_initControls(){var self=this;var settingsBtn=this.$element.find(".graph-settings");settingsBtn.button({text:false,icons:{primary:"ui-icon-rex-cog"},label:"Show settings"}).css("z-index",11).click(function(){self._controlsDiv.toggle("slide",{direction:"down"})});this._controlsDiv.append($(`<button id="graphdiv-${this.id}-pause-btn"></button>`).button({text:false,icons:{primary:"ui-icon-rex-pause"},label:"Lock time axis"}).click(function(){var options;if(self._pause){self.resume();options={icons:{primary:"ui-icon-rex-pause"},label:"Lock time axis"}}else{self.pause();options={icons:{primary:"ui-icon-rex-play"},label:"Unlock time axis"}}$(this).button("option",options)}));this._controlsDiv.append($(`<button id="graphdiv-${this.id}-points-btn"></button>`).button({text:false,icons:{primary:"ui-icon-rex-chart-line"},label:"Show points markers"}).click(function(){self.graph.updateOptions({drawPoints:!self.graph.getOption("drawPoints")})}));this._controlsDiv.append($(`<button id="graphdiv-${this.id}-legend-btn"></button>`).button({text:false,icons:{primary:"ui-icon-rex-text-list-bullets"},label:"Show signal details"}).click(function(){self._labelsDiv.toggle();self._graphDiv.toggleClass("full-width");self.graph.resize()}));this._controlsDiv.append($(`<button id="graphdiv-${this.id}-range-btn"></button>`).button({text:false,icons:{primary:"ui-icon-circle-arrow-s"},label:"Hide range selector"}).click(function(){var options;if(self.graph.getOption("showRangeSelector")){options={icons:{primary:"ui-icon-circle-arrow-n"},label:"Show range selector"}}else{options={icons:{primary:"ui-icon-circle-arrow-s"},label:"Hide range selector"}}delete self.graph.rangeSelector_;self.graph.updateOptions({showRangeSelector:!self.graph.getOption("showRangeSelector")});self.graph.resize(10,10);self._graphDiv.css("width","").css("height","");self.graph.resize();$(this).button("option",options)}))}_initGraph(){var self=this;var annotations=new Dygraph.Plugins.SuperAnnotations({defaultAnnotationProperties:{text:""}});var firstData=[];for(let i=0;i<this.data.labels.length;i++){firstData.push(0)}if(this.data.pointBuffer.length!==0){firstData=this.data.pointBuffer[0]}this.graph=new Dygraph(this._graphDiv[0],[firstData],{drawPoints:false,showRoller:false,showRangeSelector:!self.isDisabled(),connectSeparatedPoints:true,labels:this.data.labels,axisLabelFontSize:12,rightGap:30,interactionModel:self.isDisabled()?Dygraph.nonInteractiveModel:Dygraph.defaultInteractionModel,title:this.options.title,axes:{x:{valueFormatter:function(val){var date=new Date(val);var mills=date.getMilliseconds().toString();switch(mills.length){case 1:mills="00"+mills;break;case 2:mills="0"+mills;break}return Globalize.format(date,"H:m:s")+"."+mills}}},zoomCallback:(minDate,maxDate,yRange)=>{this._autoZoomRange=maxDate-minDate},plugins:[annotations]});if(this.dygraphOptions){if(typeof this.dygraphOptions==="object"){try{this.graph.updateOptions(this.dygraphOptions)}catch(e){this.log.warn("Setting dygraph options failed! "+e)}}else{this.log.debug("Dygraph options are not an object.")}}this.graph.resize()}pause(){this._pause=true;if(this._timer){this._timer.stop()}}resume(){this._pause=false;this.refresh();if(this._timer){this._timer.start()}}show(){super.show();if(this._timer){this._timer.start()}}hide(){super.hide();if(this._timer){this._timer.stop()}}disable(){if(this.graph&&!this._isDisabled){this._isDisabled=true;this.graph.destroy();this._initGraph();this.refresh()}this._controlsDiv.hide();this.$element.find(".graph-settings").hide();return super.disable()}enable(){if(this.graph&&this._isDisabled){this._isDisabled=false;this.graph.destroy();this._initGraph();this.refresh()}this.$element.find(".graph-settings").show();return super.enable()}refresh(){if(!this._pause){if(!this.graph){this._initGraph()}if(this.data.pointBuffer.length>0){if(this.graph.isZoomed()){var range=this.graph.xAxisRange();var extremes=this.graph.xAxisExtremes();if(range[0]<=extremes[0]){this.graph.updateOptions({dateWindow:[extremes[0],extremes[0]+this._autoZoomRange]},true)}else if(range[1]===extremes[1]){var end=this.data.pointBuffer[this.data.pointBuffer.length-1][0].getTime();var start=end-this._autoZoomRange;this.graph.updateOptions({dateWindow:[start,end]},true)}else if(range[1]<this.data.pointBuffer[0][0].getTime()){this.graph.updateOptions({dateWindow:null,valueRange:null},true)}}if(this.data.needsUpdate){var series={};this.graph.updateOptions({labels:this.data.labels,file:this.data.pointBuffer,series:series})}else{this.graph.updateOptions({file:this.data.pointBuffer})}}if(this.data.needsUpdate){this.data.needsUpdate=false;var labels=this.data.labels;var self=this;this._labelsDiv.empty();for(let i=1;i<labels.length;i++){let tmp=`<div style = "font-size: 0.7em; font-weight: bold; color:${this.graph.colors_[i-1]};">`;tmp+=`<input id="${this.id}-signal-checkbox-${i}" type="checkbox" checked>`;tmp+=`<div style = "display: inline-block; position: relative; bottom: .5ex; padding-left: 1em; height: 1px; border-bottom: 2px solid ${this.graph.colors_[i-1]};"></div>`;tmp+=" "+labels[i]+"</div>";this._labelsDiv.append(tmp);$("#"+this.id+"-signal-checkbox-"+i).change(function(){self.graph.setVisibility(i-1,$(this).is(":checked"))})}}}}resize(){this.graph.resize()}addSerie(options){return this.data.addSerie(options)}addPoint(id,tstamp,y){this.data.addPoint(id,tstamp,y)}addTrendConfig(trndCfg){return this.data.addTrendConfig(trndCfg)}addTrend(ind,data){return this.data.addTrend(ind,data)}setMaxBufferSize(maxBuffSize){this.data.maxBuffSize=maxBuffSize}setTitle(title){this.graph.updateOptions({title:title})}hideLegend(){this._labelsDiv.toggle();this._graphDiv.toggleClass("full-width");if(this.graph){this.graph.resize()}}setRefreshRate(period){if(utils.isNumber(period)){if(!this._timer){this._timer=new Timer(()=>{this.refresh()});this._timer.start(period)}else{this._timer.stop();this._timer.start(period)}}}_injectTemplates(){if(this.$element.find(".graph-graph").length===0){var graph=`\x3c!-- Dygraph placeholder template --\x3e`;graph+=`<div id="graphdiv-${this.id}-graph" class="graph-graph"></div>`;graph+=`<div id="graphdiv-${this.id}-labels" class="graph-labels"></div>`;graph+=`<div id="graphdiv-${this.id}-controls" class="graph-controls"></div>`;graph+=`<button id="graphdiv-${this.id}-settings" class="graph-settings"></button>`;this.$element.append($(graph))}if($("#annotation-template").length===0){var tmp="\x3c!-- Dygraph Annotation Template --\x3e";tmp+='<div id="annotation-template" class="annotation-info" style="display:none">';tmp+="<div>{{text}}</div>";tmp+="<div>time: {{x}}</div>";tmp+="<div>{{series}}: {{y}}</div>";tmp+="</div>";tmp+="\x3c!-- Dygraph Editable Annotation Template --\x3e";tmp+='<div id="annotation-editable-template" class="annotation-info" style="display:none">';tmp+='<button class="annotation-update">OK</button>';tmp+='<button class="annotation-kill-button">Delete</button>';tmp+='<div><input dg-ann-field="text" type="text" size=30 value="{{text}}" placeholder="optional annotation" /></div>';tmp+="<div>{{x}}, {{series}}: {{y}}</div>";tmp+="</div>";this.$element.append(tmp)}}}module.exports=Graph},{"../../utils/Timer.js":66,"../../utils/utils.js":67,"../Component.js":50,"../graph/GraphData.js":53}],53:[function(require,module,exports){"use strict";var GraphSerie=require("./GraphSerie.js");var utils=require("../../utils/utils.js");class GraphData{constructor(){this.maxBuffSize=5e3;this.pointBuffer=[];this.labels=[];this.series=[];this.trends=[];this.timeAxisLabel="Time";this.needsUpdate=false}addSerie(options){options=options||{};options.id=options.id||"s"+this.series.length;options.index=this.series.length;this.series.push(new GraphSerie(options));this._update(options.index);this.needsUpdate=true;return this.series.length-1}addTrendConfig(trndCfg){trndCfg=trndCfg||{};trndCfg.index=this.trends.length;this.trends.push(trndCfg);this._update();this.needsUpdate=true;return this.trends.length-1}addPoint(id,tstamp,y){if(!this.series[id]){throw new Error(id+": series does not exist!")}var row=this.pointBuffer[this.pointBuffer.length-1];if(!(tstamp instanceof Date)){tstamp=utils.getDateFromREXNanoseconds(tstamp)}if(row&&tstamp.getTime()===row[0].getTime()){row[this.series[id].index+1]=y}else{row=Array(this.labels.length).fill(null);row[0]=tstamp;row[this.series[id].index+1]=y;this.pointBuffer.push(row)}if(this.pointBuffer.length>=this.maxBuffSize){this.pointBuffer.shift()}}_insertData(arr,startIndex,dataIndex,data){for(let i=0;i<data.length;i++){arr[startIndex+i]=data[i][dataIndex]}return arr}addTrend(ind,data){var cfg=this.trends[ind];var append=false;if(!cfg){throw new Error("Adding trend data failed. Trend configuration on index "+ind+" is not defined!")}if(!data.signals||cfg.signalcount!==data.signals.length){throw new Error("Trend data do not fit to trend configuration! Number of signals do not match")}var startIndex=this.series.length+1;for(let i=0;i<ind;i++){startIndex+=this.trends[i].signalcount}if(this.pointBuffer.length===0){append=true}else{if(this.pointBuffer[this.pointBuffer.length-1][0]<utils.getDateFromREXNanoseconds(data.times[0])){append=true}else{for(let i=0;i<data.times.length;i++){var t=utils.getDateFromREXNanoseconds(data.times[i]);var buffInd=this.pointBuffer.length-1;while(this.pointBuffer[buffInd][0]>t&&buffInd>0){buffInd--}if(this.pointBuffer[buffInd][0].getTime()===t.getTime()){this._insertData(this.pointBuffer[buffInd],startIndex,i,data.signals)}else{var tmp=Array(this.labels.length).fill(null);tmp[0]=t;this._insertData(tmp,startIndex,i,data.signals);this.pointBuffer.splice(buffInd+1,0,tmp)}}}}if(append){for(let i=0;i<data.times.length;i++){var tmp=Array(this.labels.length).fill(null);tmp[0]=utils.getDateFromREXNanoseconds(data.times[i]);this._insertData(tmp,startIndex,i,data.signals);this.pointBuffer.push(tmp)}}while(this.pointBuffer.length>=this.maxBuffSize){this.pointBuffer.shift()}}_update(newSerieIndex){this.labels.length=0;this.labels.push(this.timeAxisLabel);for(let serie of this.series){this.labels.push(serie.label)}for(let cfg of this.trends){for(let i=0;i<cfg.signalcount;i++){var label="";if(cfg.labels){label=cfg.labels[i]}else{if(this.trends.length>1){label+="t"+(this.trends.indexOf(cfg)+1)+"-"}label+="u"+i}this.labels.push(label)}}for(let point of this.pointBuffer){if(newSerieIndex!==undefined){point.splice(newSerieIndex+1,0,null)}while(point.length<this.labels.length){point.push(null)}}}reset(){this.pointBuffer.length=0}}module.exports=GraphData},{"../../utils/utils.js":67,"./GraphSerie.js":54}],54:[function(require,module,exports){class GraphDataLine{constructor(options){var opt=options||{};this.id=opt.id;this.index=opt.index!==undefined?opt.index:-1;this.label=opt.label||opt.name||opt.id;this.color=opt.color}}module.exports=GraphDataLine},{}],55:[function(require,module,exports){"use strict";var SVGComponent=require("./SVGComponent.js");var HMI=require("../../hmi.js");var utils=require("../../utils/utils.js");var Logger=require("../../utils/Logger.js");class HMIConfig extends SVGComponent{constructor(svgElem,options){super(svgElem,options);options=options||{};for(let o in options){if(options.hasOwnProperty(o)){if(options[o]){switch(o.toLowerCase()){case"target_url":HMI.setTargetUrl(options[o]);break;case"refresh_rate":if(utils.isNumber(options[o])){HMI.setRefreshRate(Number(options[o]))}else{this.log.warn("HMIConfig: Refresh rate is not number, default value is used")}break;case"log_level":Logger.level(options[o]);break;case"use_client_time":if(utils.parseBoolean(options[o])){HMI.useClientTime()}break;case"show_clock":if(utils.parseBoolean(options[o])){HMI.showHeartBeatClock()}break;case"kiosk_mode":if(utils.parseBoolean(options[o])&&HMI.kioskMode&&$.isFunction(HMI.kioskMode)){HMI.kioskMode()}break;case"header_mode":if(options[o]){HMI.headerMode(options[o])}break;case"debug":if(utils.parseBoolean(options[o])){Logger.level("debug")}break;case"ws_ip":this.log.warn("HMIConfig: Parameter WS IP is obsolete use target_url instead!");HMI.setTargetUrl(options[o]);break;default:}}}}this.element.setAttribute("visibility","hidden")}}module.exports=HMIConfig},{"../../hmi.js":46,"../../utils/Logger.js":65,"../../utils/utils.js":67,"./SVGComponent.js":57}],56:[function(require,module,exports){"use strict";var SVGComponent=require("./SVGComponent.js");class HTMLComponent extends SVGComponent{constructor(svgElem,options){super(svgElem,options);this.div=document.createElement("div");this.svg.parentNode.append(this.div);var $div=$(this.div);if($(this.element).parent().attr("rexsvg:module")==="GeneralComponent"){this.parGroup=this.element.parentElement;var oldOpacity=this.parGroup.getAttribute("opacity");let timer=setInterval(()=>{var newOpacity=this.parGroup.getAttribute("opacity");if(newOpacity!==oldOpacity){$div.css("opacity",newOpacity).css("pointer-events",$(this.parGroup).css("pointer-events"))}oldOpacity=newOpacity},200)}$div.css("position","absolute").addClass("ui-svg-div").attr("id",this.element.getAttributeNS(null,"id")+"-div");this.element.setAttributeNS(null,"visibility","hidden");$(this.element).children().css("visibility","hidden");let updPosTout=null;let resizeCalled=false;let delayedResize=()=>{if(!resizeCalled){this.updatePosition();if(updPosTout){clearTimeout(updPosTout)}updPosTout=setTimeout(()=>{this.updatePosition();resizeCalled=false},50);resizeCalled=true}};$(window).resize(delayedResize);window.addEventListener("orientationchange",()=>{if(!resizeCalled){this.updatePosition()}});$div.parent().scroll(()=>{this.updatePosition()});$div.parent().resize(()=>{delayedResize()});$div.parent().on("transitionstart",()=>{this.updatePosition()});$div.parent().on("transitionend",()=>{this.updatePosition()});if(!$div.parent().is($("#content"))){$("#content").on("transitionend",()=>{this.updatePosition()});$("#content").on("transitionstart",()=>{this.updatePosition()})}let updPosInterval=null;let updPosCounter=0;let updPosMaxCount=100;let observer=new MutationObserver(mutationsList=>{for(var mutation of mutationsList){if(mutation.attributeName==="class"){clearInterval(updPosInterval);updPosCounter=0;updPosInterval=setInterval(()=>{if(updPosCounter<updPosMaxCount){this.updatePosition();updPosCounter++}else{updPosCounter=0;clearInterval(updPosInterval)}},20);break}}});let nodes=[$div.parent()[0],$("#content")[0],$("#menu")[0],$("#header")[0]];for(let node of nodes){if(node){observer.observe(node,{attributes:true})}}this.updatePosition()}getAbsPosition(elem){let rect=elem.getBoundingClientRect();let win=elem.ownerDocument.defaultView;return{top:rect.top+win.pageYOffset,left:rect.left+win.pageXOffset,width:rect.width,height:rect.height}}updatePosition(){let posRect=this.getAbsPosition(this.element);let posRectDiv=this.getAbsPosition(this.div.parentNode);let scrollLeft=this.div.parentNode.scrollLeft;let scrollTop=this.div.parentNode.scrollTop;let style=window.getComputedStyle(this.div.parentNode);let borderTop=parseInt(style["border-top"]||style["border-top-width"]);let top=posRect.top-posRectDiv.top+scrollTop-borderTop;let left=posRect.left-posRectDiv.left+scrollLeft;this.div.style.top=top+"px";this.div.style.left=left+"px";this.div.style.width=posRect.width+"px";this.div.style.height=posRect.height+"px";if(posRect.width===0||posRect.height===0){this.div.style.display="none"}else{if(this._isVisible){this.div.style.display=""}}this.emit("updatePosition",{left:left,top:top,width:posRect.width,height:posRect.height})}hide(){if(super.hide()){$(this.div).hide();return true}}show(){if(super.show()){$(this.div).show();return true}}}module.exports=HTMLComponent},{"./SVGComponent.js":57}],57:[function(require,module,exports){"use strict";var Component=require("./../Component.js");var utils=require("../../utils/utils.js");var STATE=require("../../utils/Constants.js").State;var HMI=require("../../hmi.js");var RWItem=require("../../group-management/RWItem.js");var DISABLE_OPACITY=.5;class SVGComponent extends Component{constructor(svgElem,options){options=options||{};options.element=options.element||svgElem;super(options);Object.assign(this,utils);this.element=svgElem;this.svg=this.options.svg;this.defs=this.options.defs;this.module=this.type=this.options.module||"SVGComponent";if(this.constructor.name){this.log=require("../../utils/Logger.js").child({component:this.module||this.constructor.name,id:this.id})}var title_elem=$(this.element).children("title")[0];this.title=title_elem?title_elem.childNodes[0].nodeValue:null;var desc=$(this.element).children("desc")[0];if(desc){var desc_json;try{desc_json=JSON.parse(desc.childNodes[0].nodeValue)}catch(err){this.log.warn("Failed to parse options from DESC tag in "+this.element.id)}if(desc_json){this.$c=this.items=this._initConnections(desc_json["connections"]);this.options=Object.assign(this.options,desc_json.options);this.writePerm=utils.check(this.options.writePerm,[])}}else{this.log.warn("Element "+this.element.id+" has no description tag")}for(var key in this.items){if(this.items.hasOwnProperty(key)){let item=this.items[key];item.on("offline",itm=>{this.disable()});item.on("state",itm=>{switch(itm.state){case STATE.NONE:case STATE.OFFLINE:case STATE.ERROR:this.disable();break;case STATE.ONLINE:this.enable();break}})}}if(this.items.disable_by){this.items.disable_by.on("change",itm=>{if(itm.getValue()){this.disable()}else{this.enable()}})}if(this.items.hide_by){this.items.hide_by.on("change",itm=>{if(itm.getValue()){this.hide()}else{this.show()}})}this.disable()}hide(){this.element.setAttributeNS(null,"visibility","hidden");return super.hide()}show(){this.element.setAttributeNS(null,"visibility","visible");return super.show()}enable(){if(!this.isDisabled()){this.emit("disable",false);return true}for(var key in this.items){if(this.items.hasOwnProperty(key)){let item=this.items[key];if(item.state!==STATE.ONLINE){return false}}}if(super.enable()){this.element.setAttributeNS(null,"opacity",this.element.oldOpacity||"");this.element.oldOpacity=null;$(this.element).css("pointer-events","auto");return true}}disable(){if(this.isDisabled()){this.emit("disable",true);return true}if(super.disable()){this.element.oldOpacity=this.element.getAttributeNS(null,"opacity");this.element.setAttributeNS(null,"opacity",""+DISABLE_OPACITY);$(this.element).css("pointer-events","none")}}_replaceString(str){return this.title?str.replace("$T",this.title):str}_getChildOfElementByTag(element,childModule){var childNodes=Array.prototype.slice.call(element.childNodes);for(var i=0;i<childNodes.length;i++){var item=childNodes[i];var tag=null;if(item.getAttribute){tag=item.getAttribute("rexsvg:tag")||""}if(tag===childModule){return item}childNodes=childNodes.concat(Array.prototype.slice.call(item.childNodes))}}getChildByTag(tag){return this._getChildOfElementByTag(this.element,tag)}_initConnections(conn){if(!conn){return{}}var $c={};if(conn instanceof Array){for(var i=0;i<conn.length;i++){if(conn[i].type==="L"){if(!conn[i].alias){this.log.error("Alias for user item is not defined!")}else{let itmCfg={alias:conn[i].alias,type:conn[i].type,cstring:conn[i].cstring};HMI.addItem(itmCfg)}}else if(conn[i].alias&&this._replaceString(conn[i].cstring)&&conn[i].type){let itmCfg={alias:conn[i].alias,type:conn[i].type};if(conn[i].type==="W"){itmCfg.writeCString=this._replaceString(conn[i].cstring)}else{itmCfg.readCString=this._replaceString(conn[i].cstring)}HMI.addItem(itmCfg)}else{this.log.error("alias: "+conn[i].alias+" cstring: "+this._replaceString(conn[i].cstring)+" or type:"+conn[i].type+" is not defined")}}return $c}else{for(var prop in conn){if(conn.hasOwnProperty(prop)){if(conn[prop]instanceof Object){if(conn[prop].cstring){$c[prop]=conn[prop].type==="W"?HMI.addItem({alias:conn[prop].alias,writeCString:this._replaceString(conn[prop].cstring)}):HMI.addItem({alias:conn[prop].alias,readCString:this._replaceString(conn[prop].cstring)})}else{$c[prop]=HMI.$i(conn[prop].alias);if(!$c[prop]){this.log.error(this.element.id+": Alias "+conn[prop].alias+" is not found");$c[prop]=new RWItem}}}else{var itemStr=this._replaceString(conn[prop]);var item=HMI.$i(itemStr);if(item){$c[prop]=item}else{this.log.error(this.element.id+": Alias "+itemStr+" is not found");$c[prop]=new RWItem}}}}}return $c}}module.exports=SVGComponent},{"../../group-management/RWItem.js":43,"../../hmi.js":46,"../../utils/Constants.js":61,"../../utils/Logger.js":65,"../../utils/utils.js":67,"./../Component.js":50}],58:[function(require,module,exports){"use strict";var Graph=require("../graph/Graph.js");var HTMLComponent=require("./HTMLComponent.js");var utils=require("../../utils/utils.js");var EventSync=require("../../utils/EventSync.js");class SVGGraph extends HTMLComponent{constructor(svgElem,options){super(svgElem,options);var $div=$(this.div);if(this.options.chart.backgroundColor){$div.css("background-color",this.options.chart.backgroundColor)}if(utils.isNumber(this.options.chart.backgroundOpacity)){$div.css("background-color",this.options.chart.backgroundColor)}this._eventSync=new EventSync(["read"]);this._eventSync.on("read",()=>{this.graph.refresh()});this.graph=new Graph({id:this.id,element:this.div});this.graph.setMaxBufferSize(utils.checkNumber(options.chart.bufferSize,this.graph.data.maxBuffSize));if(options.chart.refreshRate){this.graph.setRefreshRate(utils.checkNumber(options.chart.refreshRate,500))}for(let i=1;i<=parseInt(options.chart.numberOfSignals);i++){if(options.chart.type.toLowerCase()!=="time"){this.log.warn("XY graph is not currently supported!")}else{var signal="signal"+i;var signalInd=this.graph.addSerie({id:signal,label:options.signals[i].name||signal,color:options.signals[i].color});if(options.signals[i].bufferCapacity>this.graph.data.maxBuffSize){this.graph.setMaxBufferSize(options.signals[i].bufferCapacity)}if(!this.items||!this.items[signal]){this.log.warn("Signal "+signal+" not found in connection strings!");continue}this.items[signal].on("read",()=>{this.graph.data.addPoint(signalInd,utils.getDateFromREXNanoseconds(this.items[signal].timestamp),this.items[signal].getValue())});this._eventSync.registerEventEmitter(this.items[signal])}}}}module.exports=SVGGraph},{"../../utils/EventSync.js":64,"../../utils/utils.js":67,"../graph/Graph.js":52,"./HTMLComponent.js":56}],59:[function(require,module,exports){"use strict";var utils=require("../../utils/utils.js");var HMIConfig=require("./HMIConfig.js");var log=require("../../utils/Logger.js").child({component:"SVGManager"});class SVGManager{constructor(){this.components=[];this.log=log}registerComponent(svgComponent){this.components.push(svgComponent)}unregisterComponent(svgComponent){this.components.splice(this.components.indexOf(svgComponent),1)}getComponentById(id){for(let component of this.components){if(component.id===id){return component}}}init(svg){var self=this;if(!svg)throw"SVG initialization failed. No SVG element found";var defs=null;var defs_elems=svg.getElementsByTagNameNS(utils.ns_svg,"defs");if(defs_elems.length>0){defs=defs_elems[0]}else{defs=document.createElementNS(utils.ns_svg,"defs");svg.appendChild(defs)}var $svg=$(svg);$svg.find('[rexsvg\\:module="HMIConfig"]').each(function(index,element){var module=this.getAttribute("rexsvg:module")||"";var component=new HMIConfig(element,{type:module,svg:svg,defs:defs});if(component.init)component.init();self.registerComponent(component)});$svg.find("[rexsvg\\:module]").not('[rexsvg\\:module="HMIConfig"]').each(function(index,element){var module=this.getAttribute("rexsvg:module")||"";var version=this.getAttribute("rexsvg:version")||"";if(version.indexOf("${version}")>=0){version=""}REX.UI.SVG.Modules[module]=REX.UI.SVG.Modules[module]?REX.UI.SVG.Modules[module]:REX.UI.SVG[module];if(REX.UI.SVG.Modules[module]){var component=new REX.UI.SVG.Modules[module](element,{module:module,type:module,svg:svg,defs:defs,version:version});if(component.init)component.init();self.registerComponent(component)}else{self.log.debug("Module %s not found!",module,element)}})}}module.exports=new SVGManager},{"../../utils/Logger.js":65,"../../utils/utils.js":67,"./HMIConfig.js":55}],60:[function(require,module,exports){"use strict";var Graph=require("../graph/Graph.js");var Trend=require("../../group-management/Trend.js");var HTMLComponent=require("./HTMLComponent.js");var utils=require("../../utils/utils.js");var HMI=require("../../hmi.js");class TRND extends HTMLComponent{constructor(svgElem,options){super(svgElem,options);this.graph=new Graph({id:this.id,element:this.div,title:this.options.title});this.graph.setMaxBufferSize(utils.checkNumber(this.options.bufferSize,this.graph.data.maxBuffSize));var refreshRate=utils.checkNumber(this.options.refreshRate,-1);if(utils.parseBoolean(this.options.hideLegend)){this.graph.hideLegend()}var cstring=this.$c.TRND.readCString;if(!cstring){this.log.warn(this.id+": Connection string is used twice or not at all. Pick exactly one alias for each TRND.");return}if(options.dygraphOptions){if(typeof options.dygraphOptions==="object"){this.graph.dygraphOptions=options.dygraphOptions}else{this.log.error(this.id+"dygraphOptions property is not an object. Write it as a value pair JSON object!")}}cstring=cstring.substr(0,cstring.indexOf(":"));HMI.removeItem(this.$c.TRND.id);var trend=new Trend({cstring:cstring});trend.period=HMI._defaultRefreshRate;var trndID=null;trend.on("read",data=>{if(trndID===null){var cfg=trend.trndCfg;if(this.options.signals){var optSignals=this.options.signals;var labels=[];if(optSignals.length>0&&cfg.signalcount!==optSignals.length){this.log.warn(this.id+": Length of signals array is not matching number of signals!")}for(let i=0;i<cfg.signalcount;i++){if(optSignals[i]){labels.push(optSignals[i]["label"])}else{labels.push("u"+(i+1))}}cfg.labels=labels}trndID=this.graph.data.addTrendConfig(cfg);if(refreshRate>=0){this.graph.setRefreshRate(refreshRate)}}this.graph.data.addTrend(trndID,data);if(!this.graph._timer){this.graph.refresh()}});HMI.addTrend(trend)}enable(){if(this.items.disable_by&&this.graph){this.graph.enable()}return super.enable()}disable(){if(this.items.disable_by&&this.graph){this.graph.disable()}return super.disable()}}module.exports=TRND},{"../../group-management/Trend.js":44,"../../hmi.js":46,"../../utils/utils.js":67,"../graph/Graph.js":52,"./HTMLComponent.js":56}],61:[function(require,module,exports){"use strict";var exports=module.exports;var cmdNames={};function define(name,value){Object.defineProperty(exports,name,{value:value,enumerable:true});if(name.toUpperCase().indexOf("CMD")>=0){cmdNames[value]=name}}define("CMD_INIT",1);define("CMD_EXIT",2);define("CMD_IDLE",3);define("CMD_VERSION",17);define("CMD_READ_GROUP",49);define("CMD_WRITE_GROUP",50);define("CMD_ADD_GROUP",51);define("CMD_REMOVE_GROUP",52);define("CMD_NAMES_TO_IDS",19);define("CMD_BROWSE_SYMBOL",21);define("CMD_WHO_AMI",514);define("CMD_READ_ITEMS",4097);define("CMD_WRITE_ITEMS",4098);define("CMD_SET_CRYPT_KEY",7);define("CMD_LOGIN",8);define("CMD_GET_TRND_CFG",85);define("CMD_TRND_READ",86);define("CMD_GET_TIME",258);define("CMD_SET_TIME",259);define("CMD_GET_ARC_CFG",81);define("CMD_GET_ARC_DGN",82);define("CMD_ARC_OPEN",92);define("CMD_ARC_CLOSE",93);define("CMD_ARC_READ",84);define("CMD_ARC_WRITE_STRING",87);define("CMD_ARC_WRITE_ACKN",90);define("CMD_ARC_STR_UPLOAD",91);define("WSF_CONFIG_CHANGED",1);define("WSF_HMI_CHANGED",2);define("WSF_SHUTDOWN",4);define("WSF_CONFIG_CHANGING",8);define("WSF_HMI_CHANGING",16);exports.getCmdName=function(cmd){if(cmdNames[cmd]){return cmdNames[cmd]}else{return"UNKNOWN"}};exports.KINDS={0:{kindName:"exec",browse:true,read:false,write:false,view:true},1:{kindName:"module",browse:false,read:false,write:false,view:false},2:{kindName:"iodrv",browse:true,read:false,write:false,view:true},3:{kindName:"archive",browse:true,read:false,write:false,view:true},4:{kindName:"level",browse:false,read:false,write:false,view:false},5:{kindName:"task",browse:true,read:false,write:false,view:true},6:{kindName:"qtask",browse:true,read:false,write:false,view:true},7:{kindName:"seq",browse:true,read:false,write:false,view:true},8:{kindName:"block",browse:true,read:false,write:false,view:true},9:{kindName:"in",browse:false,read:true,write:true,view:true,mode:"RW",type:"string"},10:{kindName:"out",browse:false,read:true,write:false,view:true,mode:"R",type:"string"},11:{kindName:"stat",browse:false,read:false,write:false,view:false},12:{kindName:"arr",browse:false,read:false,write:false,view:false},13:{kindName:"special",browse:false,read:false,write:false,view:false},15:{kindName:"type_unknown",browse:false,read:false,write:false,view:false},256:{kindName:"name",browse:true,read:false,write:false,view:false},257:{kindName:"device",browse:true,read:false,write:false,view:false}};exports.getSymbolKind=function(kind){return exports.KINDS[kind]};exports.TYPES={1:"boolean",2:"number",3:"number",4:"number",5:"number",6:"number",7:"float",8:"float",9:"number",10:"number",11:"number",12:"string"};exports.getSymbolType=function(kind){return exports.TYPES[kind]||""};exports.State={NONE:0,ONLINE:1,OFFLINE:2,ERROR:3};exports.COLORS={primary:"#00C8B4",complementary:"#0074C5",secondary:"#545e61",warning:"#f6a312",error:"#df2626",inactive:"#f2f4f4",background:"#eef1f0",icon:"#b6bab7",false:"#B8BDC5"};exports.REX_SVG_NS="http://www.rexcontrols.com/rexsvg/"},{}],62:[function(require,module,exports){"use strict";var bunyan=require("bunyan");var utils=require("./utils.js");var MAX_LOG_SIZE=100;class DivLoggerStream{constructor(jQelement,jQerrNum){this.element=jQelement;this.maxLogSize=MAX_LOG_SIZE;this._errNum=jQerrNum}write(rec){var level=bunyan.nameFromLevel[rec.level];var row=$("<tr></tr>");switch(level.toLowerCase()){case"error":row.addClass("error");row.append($("<td>cancel</td>"));if(this._errNum&&this._errNum.length>0){this._errNum.text(this.element.find(".error").length+1);this._errNum.addClass("error")}break;case"warn":row.addClass("warning");row.append($("<td>error</td>"));if(this._errNum&&this._errNum.length>0){this._errNum.text(this.element.find(".warning").length+1);this._errNum.addClass("warning")}break;default:row.append($("<td></td>"));break}row.append($("<td>"+rec.time.toLocaleTimeString()+"</td>"));row.append($("<td>"+(rec.id?`[${rec.id}] `:"")+rec.msg+"</td>"));this.element.append(row);if(this.element.children().length>this.maxLogSize){this.element.children().first().remove()}this.element.parent().scrollTop(this.element.parent()[0].scrollHeight)}}module.exports=DivLoggerStream},{"./utils.js":67,bunyan:9}],63:[function(require,module,exports){"use strict";var events=require("events");class EventEmitter extends events.EventEmitter{constructor(options){super(options);this.setMaxListeners(100)}off(){this.removeListener.apply(this,arguments)}}module.exports=EventEmitter},{events:11}],64:[function(require,module,exports){"use strict";var EventEmitter=require("./EventEmitter.js");var State=require("./Constants.js").State;var events=require("events");class EventSync extends EventEmitter{constructor(monitoredEvents){super();this.eventEmitterList=[];this._eventList={};this._eventNames=monitoredEvents||["read"];this._eventNames.forEach(evtName=>{this._eventList[evtName]=true});this.ignoreOfflineItems=true}registerEventEmitter(item){var self=this;if(!(item instanceof events.EventEmitter)){throw new Error("Cannot register item which is not instance of EventEmitter class")}var element={item:item};for(let evtName of this._eventNames){item.on(evtName,()=>{self._handleEvent(element,evtName)});element[evtName]=false}this.eventEmitterList.push(element)}_handleEvent(element,eventName){element[eventName]=true;this._refresh()}_refresh(){for(let evtName of this._eventNames){this._eventList[evtName]=true;for(let elem of this.eventEmitterList){if(this.ignoreOfflineItems&&elem.item.state!==State.ONLINE){continue}if(!elem[evtName]){this._eventList[evtName]=false;break}}if(this._eventList[evtName]){for(let elem of this.eventEmitterList){elem[evtName]=false}this.emit(evtName)}}}}module.exports=EventSync},{"./Constants.js":61,"./EventEmitter.js":63,events:11}],65:[function(require,module,exports){(function(process){"use strict";var bunyan=require("bunyan");var logger={};var childLoggers=[];if(process.browser){var MyRawStream=function(){};MyRawStream.prototype.write=function(rec){if(rec.err){console.log("[%s][%s]%s%s: %s\t at %s",rec.time.toLocaleTimeString(),bunyan.nameFromLevel[rec.level].toUpperCase(),rec.component?`[${rec.component}]`:"",rec.id?`[${rec.id}]`:"",rec.msg,rec.err.stack)}else{console.log("[%s][%s]%s%s: %s",rec.time.toLocaleTimeString(),bunyan.nameFromLevel[rec.level].toUpperCase(),rec.component?`[${rec.component}]`:"",rec.id?`[${rec.id}]`:"",rec.msg)}};logger=bunyan.createLogger({name:"RexHMI",streams:[{level:"info",stream:new MyRawStream,type:"raw"}]})}else{logger=bunyan.createLogger({name:"RexHMI",level:"debug"})}var old_child=logger.child;logger.child=function(){if(typeof arguments[0]==="object"&&arguments[0].component){let component=arguments[0].component;for(let child of childLoggers){if(child.component===component){return child}}}var childLogger=old_child.apply(logger,arguments);childLoggers.push(childLogger);return childLogger};var old_level=logger.level;logger.level=function(){for(let child of childLoggers){child.level.apply(child,arguments)}return old_level.apply(logger,arguments)};var old_addStream=logger.addStream;logger.addStream=function(){for(let child of childLoggers){child.addStream.apply(child,arguments)}return old_addStream.apply(logger,arguments)};logger.childLoggers=childLoggers;module.exports=logger}).call(this,require("_process"))},{_process:19,bunyan:9}],66:[function(require,module,exports){"use strict";class Timer{constructor(fcn){this.Initial=true;this._fcn=fcn;this._run=false;this._interval=null;this._tHandle=null;this._initialized=false}_loop(){if(!this._run){return}if(this.Initial||this._initialized){this._fcn()}this._initialized=true;this._tHandle=setTimeout(()=>{this._loop()},this._interval)}start(interval){if(!this._run){this._interval=interval;this._run=true;this._loop()}}stop(){this._initialized=false;this._run=false;clearTimeout(this._tHandle)}}module.exports=Timer},{}],67:[function(require,module,exports){"use strict";var log=require("../utils/Logger.js").child({component:"utils"});var utils={};var EPOCH_START=new Date(2e3,0,1).getTime()-new Date(2e3,0,1).getTimezoneOffset()*60*1e3;utils.ns_svg="http://www.w3.org/2000/svg";utils.ns_xlink="http://www.w3.org/1999/xlink";utils.round=function(number,decimals){if(decimals===undefined){decimals=6}let precision=Math.pow(10,decimals);return Math.round(number*precision)/precision};utils.round_prec=function(number,precision){return Math.round(number*precision)/precision};utils.isUint=function(number){return/^(\d+)$/.test(number)};utils.isInt=function(number,low,high){var result=/^(-?\d+)$/.test(number);if(result===true&&(low!==undefined||high!==undefined)){result=utils.inRange(parseInt(number),low,high)}return result};utils.inRange=function(number,low,high){var result=true;if(low!==undefined&&number<low){result=false}if(high!==undefined&&number>high){result=false}return result};utils.isReal=function(number,low,high){var result=/^((-?\d+|\d+)(.\d+)?\d*((\+|-)(E|e)\d+)?)$/.test(number);if(result===true&&(low!==undefined||high!==undefined)){result=utils.inRange(parseFloat(number),low,high)}return result};utils.isNumber=function(number){return number-parseFloat(number)>=0};utils.appendClass=function(element,className){var classes=element.getAttribute("class")?element.getAttribute("class").split(" "):[];for(var i=0;i<classes.length;i++){if(classes[i]===className){return}}element.setAttribute("class",classes.join(" ")+" "+className)};utils.removeClass=function(element,className){var classes=[];classes=element.getAttribute("class").split(" ");for(var i=0;i<classes.length;i++){if(classes[i]===className){classes.splice(i,1);element.setAttribute("class",classes.join(" "));return}}};utils.getDateFromREXSeconds=function(rexSeconds){var date=new Date(rexSeconds*1e3+EPOCH_START);return date};utils.getREXSecondsFromDate=function(date){return(date.getTime()-EPOCH_START)/1e3};utils.getREXNanosecondsFromDate=function(date){return(date.getTime()-EPOCH_START)*1e6};utils.getDateFromREXNanoseconds=function(ns){return new Date(ns/1e6+EPOCH_START)};utils.str2time=function(str){if(str.indexOf(":")===-1){return Number.NaN}var timearr=str.split(":");if(timearr.length===2){return Number(timearr[0])*3600+Number(timearr[1])*60}if(timearr.length===3){return Number(timearr[0])*3600+Number(timearr[1])*60+Number(timearr[2])}else{return Number.NaN}};utils.time2str=function(totSec,format){if(totSec<0){totSec=3600*24+totSec}var hours=parseInt(totSec/3600)%24;var minutes=parseInt(totSec/60)%60;var seconds=totSec%60;var result=(hours<10?"0"+hours:hours)+":"+(minutes<10?"0"+minutes:minutes);if(format&&format.toLowerCase()==="hh:mm:ss"){result+=":"+(seconds<10?"0"+seconds:seconds)}return result};utils.date2str=function(date){var curr_date=date.getDate();var curr_month=date.getMonth()+1;var curr_year=date.getFullYear();return(curr_date<10?"0"+curr_date:curr_date)+"."+(curr_month<10?"0"+curr_month:curr_month)+"."+curr_year};utils.webBuDi_validateNumericOption=function(name,options,defaultValue){if(options[name]&&REX.HELPERS.isNumber(options[name])){return options[name]}if(options[name]&&!REX.HELPERS.isNumber(options[name])){log.debug(options.alias+": "+name+" is not a number. Set to "+defaultValue);options[name]=defaultValue;return options[name]}if(options[name]===0){return options[name]}else{return defaultValue}};utils.parseBoolean=function(string){if(!string){return false}if(typeof string==="boolean"){return string}if(typeof string==="string"){switch(string.toLowerCase()){case"false":case"no":case"0":case"":return false;default:return true}}return false};utils.check=function(value,defaultVal){return typeof value==="undefined"?defaultVal:value};utils.checkNumber=function(value,defaultVal){if(typeof value==="undefined"){return defaultVal}if(utils.isNumber(value)){return parseFloat(value)}else{log.debug("Parameter "+value+" is not number, using defaultValue");return defaultVal}};utils.createID=function(name){var sdiak="áäčďéěíĺľňóôőöŕšťúůűüýřžÁÄČĎÉĚÍĹĽŇÓÔŐÖŔŠŤÚŮŰÜÝŘŽ ()[]{}";var bdiak="aacdeeillnoooorstuuuuyrzAACDEEILLNOOOORSTUUUUYRZ-------";var id="";for(var i=0;i<name.length;i++){var ind=sdiak.indexOf(name.charAt(i));if(ind!==-1){id+=bdiak.charAt(ind)}else{id+=name.charAt(i)}}return id};utils.color2RGBA=function(color){try{var div=document.createElement("div");div.style.color=color;var colors=window.getComputedStyle(document.body.appendChild(div)).color.match(/\d+/g).map(function(a){return parseInt(a,10)});document.body.removeChild(div);return{r:colors[0],g:colors[1],b:colors[2],a:colors[3]||1}}catch(e){return{r:0,g:0,b:0,a:1}}};utils.hexToRgb=function(hex){var bigint=parseInt(hex,16);var r=bigint>>16&255;var g=bigint>>8&255;var b=bigint&255;return{r:r,g:g,b:b}};utils.isBright=function(color){if(typeof color==="string"){color=utils.color2RGBA(color)}let a=1;if(typeof color==="object"){a=1-(.299*color.r+.587*color.g+.114*color.b)/255}return a<.5};utils.crlf2br=function(str){return str.replace(/(?:\r\n|\r|\n|\\n)/g,"<br />")};module.exports=utils},{"../utils/Logger.js":65}],68:[function(require,module,exports){"use strict";$.widget("wbd.column",$.wbd.component,{options:{},_create:function(){this._super();this.element.addClass("wbd-column")},_setOption:function(key,value){if(key==="title"||key==="desc"||key==="name"||key==="label"){var name=this.element.find(".wbd-column-title");if(name.length===0){this.element.prepend(['<div class="wbd-column-title"><h2>',value,"</h2></div>"].join(""))}else{name.find("h2").text(value)}}this._super(key,value)},addSection:function(section){section.addClass("wbd-section_"+(this.element.find(":wbd-section").length%4+1));this.element.append(section)}});$.widget("wbd.section",$.wbd.component,{options:{},_create:function(){this._super();this.element.addClass("wbd-section");this.element.attr("id",this.element.attr("id")||"wbd-c-"+this.options.column+"-s-"+$(":wbd-section").length);var row_data=this.options.rows;this.options.rows=[];for(var i=0;i<row_data.length;i++){this.addRow(row_data[i])}},_setOption:function(key,value){if(key==="title"||key==="desc"||key==="name"||key==="label"){var name=this.element.find(".wbd-section-title");if(name.length===0){this.element.prepend(['<div class="wbd-section-title"><h2>',value,"</h2></div>"].join(""))}else{name.find("h2").text(value)}}if(key==="background_color"){this.element.css("background-color",value)}if(key==="text_color"){this.element.find(".wbd-section-title").css("color",value)}this._super(key,value)},addRow:function(row_data){var row=$("<div></div>").row(row_data);row.attr("id",row.attr("id")||this.element.attr("id")+"-r-"+this.element.find(":wbd-row").length);this.element.append(row);this.options.rows.push(row);return row}})},{}],69:[function(require,module,exports){"use strict";var log=require("../utils/Logger.js").child({component:"webbudi"});var HMI=require("../hmi.js");$.widget("wbd.component",{options:{},_create:function(){this.element.addClass("wbd-component");var that=this;$.each(this.options,function(key,value){that._setOption(key,value)})},_setOption:function(key,value){var that=this;if(key==="hide_by"||key==="visibility"){this._super(key,this._bindItem(value,function(){that.element.hide()},function(){that.element.show()}))}if(key==="disable_by"||key==="state"){this._super(key,this._bindItem(value,function(){that.disable()},function(){that.enable()}))}this._super(key,value)},_bindItem:function(data,trueFcn,falseFcn){var item;if(typeof data==="string"){item=HMI.$i(data)}else{item=data.cstring?HMI.addItem(data.alias,data.cstring):HMI.$i(data.alias)}if(!item){log.error(this.options.desc+": Alias "+data+" not found!")}else{item.on("change",function(i){if(data.reverse_meaning){if(i.getValue()===0){trueFcn()}else{falseFcn()}}else{if(i.getValue()===0){falseFcn()}else{trueFcn()}}})}return item},disable:function(){this.element.disabler();this.element.disabler("disable");this.element.find(":wbd-row").row("disable");this.options.isDisabled=true},enable:function(){this.element.disabler();this.element.disabler("enable");this.element.find(":wbd-row").row("enable");this.options.isDisabled=false},isDisabled:function(){return this.options.isDisabled}})},{"../hmi.js":46,"../utils/Logger.js":65}],70:[function(require,module,exports){"use strict";var itemIdIndex=0;var utils=require("../utils/utils.js");var log=require("../utils/Logger.js").child({component:"webbudi"});var State=require("../utils/Constants.js").State;var HMI=require("../hmi.js");var AnalogLookupTable=require("./widget/AnalogLookupTable.js");var AnalogReadRow=require("./widget/AnalogReadRow.js");var AnalogWriteRow=require("./widget/AnalogWriteRow.js");var DigitalReadRow=require("./widget/DigitalReadRow.js");var DigitalWriteRow=require("./widget/DigitalWriteRow.js");var LinkButton=require("./widget/LinkButton.js");var ManualPulseRow=require("./widget/ManualPulseRow.js");var PushButton=require("./widget/PushButton.js");var EmptySpace=require("./widget/EmptySpace.js");$.widget("wbd.row",$.wbd.component,{options:{},_create:function(){if(this.options.options){$.extend(this.options,this.options.options);delete this.options.options}this._super();this.element.addClass("wbd-row");if(!this.options.type){log.debug("Row type is not defined, assume as empty space.")}if(this.options.name){this._setOption("desc",this.options.name);delete this.options.name}if(this.options.type&&this.options.type.toUpperCase()!=="ES"&&this.options.type.toUpperCase()!=="LINK"){if(!this.options.alias){if(!this.options.desc){log.error("Neither alias nor description is defined! Cannot create row");this.element.addClass("ui-state-error");return this}this._setOption("alias",utils.createID(this.options.desc))}if(!this.options.desc){this._setOption("desc",this.options.alias)}}this._createRow();this.disable()},_setOption:function(key,value){if(key==="desc"){this.element.find(".wbd-row-label").text(value)}this._super(key,value)},_initItem:function(type){if(this.options.alias.indexOf(" ")!==-1){log.error(this.options.desc+": Alias "+this.options.alias+" must not contain spaces!");return}this.options.item=HMI.$i(this.options.alias);if(this.options.item&&this.options.cstring&&this.options.item.cstring!==this.options.cstring){log.error(this.options.desc+": Alias "+this.options.alias+" already defined! Must be unique!");this.options.item=null;return}if(this.options.item&&type==="W"&&!this.options.item.write){log.error(this.options.desc+": Alias "+this.options.alias+" item is not writable!");this.options.item=null;return}this.options.id=this.options.item?this.options.alias+"-"+itemIdIndex++:this.options.alias;if(!this.options.item&&!this.options.cstring){if(!this.options.cstring){log.error(this.options.desc+": Cannot create an item. There is no connection string for alias "+this.options.alias);return}}if(!this.options.item){if(type==="W"){this.options.item=HMI.addItem({alias:this.options.alias,writeCString:this.options.cstring});this._initRefreshItem()}else{this.options.item=HMI.addItem({alias:this.options.alias,readCString:this.options.cstring})}}this.options.item.on("state",itm=>{if(itm.state===State.ONLINE){this.enable()}else{this.disable()}})},_initRefreshItem:function(){if(this.options.no_refresh){this.options.refresh_from=null;return}if(!this.options.refresh_from){if(!this.options.item){log.error(this.options.desc+": Cannot create an update item because either alias nor refresh_from is not defined.");return}this.options.refresh_from=this.options.item}else{var refItm=this.options.refresh_from;if(typeof refItm==="string"){this.options.refresh_from=HMI.$i(refItm);if(!this.options.refresh_from){log.error(this.options.desc+": Refresh item alias "+refItm+" is not defined!");return}}else{if(!refItm.alias){log.error(this.options.desc+": Refresh item alias is not defined");return}if(refItm.alias&&refItm.alias.indexOf(" ")!==-1){log.error(this.options.desc+": Refresh item alias "+refItm.alias+" must not contain spaces!");return}this.options.refresh_from=HMI.$i(refItm.alias);if(this.options.refresh_from&&refItm.cstring&&this.options.refresh_from.cstring!==refItm.cstring){log.error(this.options.desc+": Refresh item alias "+refItm.alias+" already defined! Must be unique!");return}if(!this.options.refresh_from&&!refItm.cstring){log.error(this.options.desc+": Cannot create an update item. There is no connection string for alias "+this.options.refresh_from.alias);return}if(!this.options.refresh_from){this.options.refresh_from=HMI.addItem({alias:refItm.alias,readCString:refItm.cstring})}}}this.options.refresh_from.on("state",itm=>{if(itm.state===State.ONLINE){this.enable()}else{this.disable()}})},_createRow:function(){this.element.append($('<span class="wbd-row-desc">'+this.options.desc+"</span>"));switch(this.options.type){case"AR":this._initItem("R");if(!this.options.item){this.element.addClass("ui-state-error");return}AnalogReadRow(this);break;case"DR":this._initItem("R");if(!this.options.item){this.element.addClass("ui-state-error");return}DigitalReadRow(this);break;case"AW":this._initItem("W");if(!this.options.item){this.element.addClass("ui-state-error");return}AnalogWriteRow(this);break;case"ALT":this._initItem("W");if(!this.options.item){this.element.addClass("ui-state-error");return}AnalogLookupTable(this);break;case"DW":this._initItem("W");if(!this.options.item){this.element.addClass("ui-state-error");return}DigitalWriteRow(this);break;case"MP":this.options.no_refresh=true;this._initItem("W");if(!this.options.item){this.element.addClass("ui-state-error");return}ManualPulseRow(this);break;case"PB":this.options.no_refresh=true;this._initItem("W");if(!this.options.item){this.element.addClass("ui-state-error");return}PushButton(this);break;case"ES":EmptySpace(this);break;case"LINK":LinkButton(this);break;default:this.element.empty();break}}})},{"../hmi.js":46,"../utils/Constants.js":61,"../utils/Logger.js":65,"../utils/utils.js":67,"./widget/AnalogLookupTable.js":72,"./widget/AnalogReadRow.js":73,"./widget/AnalogWriteRow.js":74,"./widget/DigitalReadRow.js":75,"./widget/DigitalWriteRow.js":76,"./widget/EmptySpace.js":77,"./widget/LinkButton.js":78,"./widget/ManualPulseRow.js":79,"./widget/PushButton.js":80}],71:[function(require,module,exports){"use strict";require("./Component.js");require("./Column.js");require("./Row.js");var HMI=require("../hmi.js");var log=require("../utils/Logger.js").child({component:"webbudi"});class WebBuDi{constructor(){this.ROUND_CONSTANT=1e4;this.DEFAULT_DECIMALS=4;this.customDivID="";this.rootDiv=null}addSection(data){if(arguments.length>1){throw new Error("Only 1 parameter with object is expected")}data.column=data.column||1;if(this.rootDiv){this.rootDiv=$(this.rootDiv)}else{if(this.customDivID){this.rootDiv=$("#"+this.customDivID)}else{this.rootDiv=$("<div></div>");this.rootDiv.addClass("wbd-main");this.rootDiv.appendTo($("#content"))}}var column_div_id=this.customDivID?"wbd-column-"+this.customDivID+"-"+data.column:"wbd-column-"+data.column;var column_div=this.rootDiv.children("#"+column_div_id);if(column_div.length<=0){column_div=$("<div></div>").attr("id",column_div_id);column_div.addClass("wbd-column_"+(this.rootDiv.find(":wbd-column").length%3+1));column_div.appendTo(this.rootDiv).column()}var section=$("<div></div>").section(data);column_div.column("addSection",section);section.data("wbd-section").disable();return this}add(data){return this.addSection(data)}addItems(items){return HMI.addItems(items)}defineAliases(items){log.warn("REX.WebBuDi.defineAliases is deprecated. Use REX.WebBuDi.addItems instead!");return HMI.addItems(items)}setTitle(title){log.warn("REX.WebBuDi.setTitle is deprecated. Use REX.HMI.setTitle instead!");return HMI.setTitle(title)}setWsIP(url){log.warn("REX.WebBuDi.setWsIP is deprecated. Use REX.HMI.setTargetUrl instead!");return HMI.setTargetUrl(url)}setRefreshRate(period){log.warn("REX.WebBuDi.setRefreshRate is deprecated. Use REX.HMI instead!");return HMI.setRefreshRate(period)}connect(){log.warn("REX.WebBuDi.connect is deprecated. REX.HMI autoconnects to the target.")}addTrendSignal(opt){log.warn("REX.WebBuDi.addTrendSignal is deprecated. Use REX.HMI.Graph.addSignal instead!");return HMI.Graph.addSignal(opt)}setTrendSize(size){log.warn("REX.WebBuDi.setTrendSize is deprecated. Use REX.HMI.Graph.setSize instead!");return HMI.Graph.setSize(size)}}module.exports=new WebBuDi},{"../hmi.js":46,"../utils/Logger.js":65,"./Column.js":68,"./Component.js":69,"./Row.js":70}],72:[function(require,module,exports){"use strict";var log=require("../../utils/Logger.js").child({component:"webbudi"});var utils=require("../../utils/utils.js");function AnalogLookupTable(row){$(['<span id="ALT_{id}" class="ui-spinner ui-widget ui-widget-content ui-corner-all">','<select id="select_{id}" class="ui-select-custom"></select></span></span>'].join("").replace(/{id}/gi,row.options.id)).appendTo(row.element);row.options.showKey=utils.check(row.options.show_key,false);var select=row.element.find("select");for(var key in row.options.values){if(row.options.values.hasOwnProperty(key)){var option=$("<option></option>").attr("value",Number(key)).appendTo(select);if(row.options.showKey){option.html(key+": "+row.options.values[key])}else{option.html(row.options.values[key])}}}select.change(function(){log.debug(row.options.id+": "+select.find("option:selected").text());row.options.item.write(Number(select.val())).catch(err=>{log.error(new Error(row.options.id+" writing failed! Probably R/O item!"));log.debug(err.err||err)})});function refresh(itm){let key=itm.value;if(select.find('option[value="'+key+'"]').length>0){select.val(key)}else{var option=$("<option></option>").attr("value",key).appendTo(select);if(row.options.showKey&&row.options.values[key]){option.html(key+": "+row.options.values[key])}else{if(row.options.values[key]){option.html(row.options.values[key])}else{option.html(key)}}select.val(key)}}row.options.item.on("change",function(itm){refresh(itm)});if(row.options.refresh_from&&row.options.refresh_from!==row.options.item){row.options.refresh_from.on("change",function(itm){refresh(itm)})}}module.exports=AnalogLookupTable},{"../../utils/Logger.js":65,"../../utils/utils.js":67}],73:[function(require,module,exports){"use strict";var utils=require("../../utils/utils.js");function AnalogReadRow(row){var DEFAULT_DECIMALS=4;var format=row.options.format||"";var scale=utils.webBuDi_validateNumericOption("scale",row.options,1);var offset=utils.webBuDi_validateNumericOption("offset",row.options,0);var decimals=utils.webBuDi_validateNumericOption("decimals",row.options,DEFAULT_DECIMALS);var convert=row.options.convert||null;$(('<span id="AR-{id}" '+'class="ui-state-default ui-widget ui-widget-content ui-corner-all analog-read">'+'<span id="ai-read-{id}"></span>'+"</span>").replace(/{id}/gi,row.options.id)).appendTo(row.element);var ai_read=row.element.find("#ai-read-"+row.options.id);row.options.item.on("change",function(itm){switch(format.toLowerCase()){case"date":ai_read.text(utils.date2str(utils.getDateFromREXSeconds(itm.value)));break;case"time":ai_read.text(utils.getDateFromREXSeconds(itm.value).toLocaleTimeString());break;case"datetime":ai_read.text(utils.date2str(utils.getDateFromREXSeconds(itm.value))+" "+utils.getDateFromREXSeconds(itm.value).toLocaleTimeString());break;case"text":ai_read.text(itm.value);break;default:if(convert&&$.isFunction(convert)){ai_read.text(""+convert(itm.value))}else{var resultValue=itm.value*scale+offset;resultValue=utils.round(resultValue,decimals);ai_read.text(""+resultValue)}break}})}module.exports=AnalogReadRow},{"../../utils/utils.js":67}],74:[function(require,module,exports){"use strict";var utils=require("../../utils/utils.js");var log=require("../../utils/Logger.js").child({component:"webbudi"});function AnalogWriteRow(row){var DEFAULT_DECIMALS=4;var format=(row.options.format||"").toLowerCase();var min=utils.webBuDi_validateNumericOption("min",row.options,-Number.MAX_VALUE);var max=utils.webBuDi_validateNumericOption("max",row.options,Number.MAX_VALUE);var scale=utils.webBuDi_validateNumericOption("scale",row.options,1);var offset=utils.webBuDi_validateNumericOption("offset",row.options,0);var decimals=utils.webBuDi_validateNumericOption("decimals",row.options,DEFAULT_DECIMALS);var setOnBlur=row.options.set_on_blur||false;var convert=row.options.convert||null;var convertW=row.options.convert_W||null;$(['<span id="AW-{id}">','<input id="AW-input-{id}" name="value" value="NaN" /></span>'].join("").replace(/{id}/gi,row.options.id)).appendTo(row.element);var input=row.element.find("#AW-input-"+row.options.id);var old_disable=row.disable;row.disable=function(){row.element.find("#AW-"+row.options.id).addClass("ui-state-disabled");old_disable.apply(this,arguments)};var old_enable=row.enable;row.enable=function(){row.element.find("#AW-"+row.options.id).removeClass("ui-state-disabled");old_enable.apply(this,arguments)};var dateSelected=false;switch(format){case"date":row.element.find("#AW-"+row.options.id).addClass("ui-spinner ui-widget ui-widget-content ui-corner-all");input.addClass("ui-spinner-input");input.datepicker({dateFormat:row.options.dateFormat||"dd.mm.yy",onSelect:function(){if(!row.options.isDisabled){row.options.item.write(utils.getREXSecondsFromDate(input.datepicker("getDate"))).catch(err=>{log.error(new Error(row.options.id+" writing failed! Probably R/O item!"));log.debug(err.err||err)})}}});break;case"time":row.element.find("#AW-"+row.options.id).addClass("ui-spinner ui-widget ui-widget-content ui-corner-all");input.addClass("ui-spinner-input");input.timepicker({parse:"loose",alwaysSetTime:false,timeFormat:row.options.timeFormat||"HH:mm",onOpen:function(){row.options.item.disableRefresh=true},onSelect:function(){dateSelected=true},onClose:function(date){if(date&&dateSelected&&!row.options.isDisabled){log.debug(row.options.id+": "+date);row.options.item.write(utils.getREXSecondsFromDate(input.datetimepicker("getDate"))).catch(err=>{log.error(new Error(row.options.id+" writing failed! Probably R/O item!"));log.debug(err.err||err)});updateRefreshFromItemAfterWrite()}dateSelected=false;row.options.item.disableRefresh=false}});break;case"datetime":row.element.find("#AW-"+row.options.id).addClass("ui-spinner ui-widget ui-widget-content ui-corner-all");input.addClass("ui-spinner-input");input.datetimepicker({parse:"loose",alwaysSetTime:false,dateFormat:row.options.dateFormat||"dd.mm.yy",timeFormat:row.options.timeFormat||"HH:mm",onOpen:function(){row.options.item.disableRefresh=true},onSelect:function(){dateSelected=true},onClose:function(date){if(date&&dateSelected&&!row.options.isDisabled){log.debug(row.options.id+": "+date);row.options.item.write(utils.getREXSecondsFromDate(input.datetimepicker("getDate"))).catch(err=>{log.error(new Error(row.options.id+" writing failed! Probably R/O item!"));log.debug(err.err||err)});updateRefreshFromItemAfterWrite()}dateSelected=false;row.options.item.disableRefresh=false}});break;default:row.element.find("#AW-"+row.options.id).addClass("ui-spinner ui-widget ui-widget-content ui-corner-all");input.addClass("ui-spinner-input");input.focus(function(){row.options.item.disableRefresh=true}).blur(function(){if(setOnBlur){var e=$.Event("keypress");e.which=13;e.keyCode=13;input.trigger(e)}row.options.item.disableRefresh=false;if(row.options.refresh_from){row.options.refresh_from.emit("change")}});input.keypress(function(evt){var keyCode=evt.keyCode||evt.which;if(keyCode===13){if(format==="text"){var text=input.prop("value");log.debug(row.options.id+": "+text);row.options.item.write(text).catch(err=>{log.error(new Error(row.options.id+" writing failed! Probably R/O item!"));log.debug(err.err||err)});updateRefreshFromItemAfterWrite()}else{var numberStr=input.prop("value").replace(",",".");if(utils.isNumber(numberStr)){var number=Number(numberStr);if(number>=min&&number<=max){input.removeClass("ui-state-error");if(!row.options.isDisabled){if(convertW&&$.isFunction(convertW)){number=convertW(number)}else{number=(number-offset)/scale}log.debug(row.options.id+": "+number);row.options.item.write(number).catch(err=>{log.error(new Error(row.options.id+" writing failed! Probably R/O item!"));log.debug(err.err||err)});updateRefreshFromItemAfterWrite()}}else{input.addClass("ui-state-error");return}}else{input.addClass("ui-state-error")}}}});input.keyup(function(evt){var keyCode=evt.keyCode||evt.which;if(keyCode===27){var setOnBlurTmp=setOnBlur;setOnBlur=false;input.blur();setOnBlur=setOnBlurTmp}});break}function updateRefreshFromItemAfterWrite(){if(row.options.refresh_from){row.options.refresh_from.setValue(row.options.item.getValue())}}function refresh(itm){switch(format){case"date":input.datepicker("setDate",utils.getDateFromREXSeconds(itm.value));break;case"time":input.datetimepicker("setDate",utils.getDateFromREXSeconds(itm.value));break;case"datetime":input.datetimepicker("setDate",utils.getDateFromREXSeconds(itm.value));break;case"text":input.prop("value",""+itm.value);break;default:if(convert&&$.isFunction(convert)){input.prop("value",""+convert(itm.value))}else{var resultValue=itm.value*scale+offset;resultValue=utils.round(resultValue,decimals);input.prop("value",""+resultValue)}break}}row.options.item.on("change",function(){refresh(row.options.item)});if(row.options.refresh_from&&row.options.refresh_from!==row.options.item){row.options.refresh_from.on("change",function(){refresh(row.options.refresh_from)})}}module.exports=AnalogWriteRow},{"../../utils/Logger.js":65,"../../utils/utils.js":67}],75:[function(require,module,exports){"use strict";function DigitalReadRow(row){var options=row.options;options.label_false=options.label_false||options.false_label||(options.reverse_meaning?"OFF(1)":"OFF(0)");options.label_true=options.label_true||options.true_label||(options.reverse_meaning?"ON(0)":"ON(1)");options.reverse_meaning=options.reverse_meaning||false;options.color_false=options.color_false||options.false_color||null;options.color_true=options.color_true||options.true_color||null;var di_read=$(['<span id="DR_{id}" class="mp-button ui-widget ui-state-default ui-corner-all digital-read">',"NaN","</span>"].join("").replace(/{id}/gi,row.options.id));di_read.appendTo(row.element);row.options.item.on("change",function(itm){di_read.css("background","");if(!row.options.isDisabled){if(itm.value==options.reverse_meaning){di_read.text(options.label_false).removeClass("ui-state-active").addClass("ui-state-default");if(options.color_false){di_read.css("background",options.color_false)}}else{di_read.text(options.label_true).removeClass("ui-state-default").addClass("ui-state-active");if(options.color_true){di_read.css("background",options.color_true)}}}});var old_disable=row.disable;row.disable=function(){old_disable.apply(this,arguments);di_read.addClass("ui-state-disabled");di_read.css("background","");di_read.text("---")};var old_enable=row.enable;row.enable=function(){old_enable.apply(this,arguments);if(row.options.item.isOnline()){di_read.removeClass("ui-state-disabled")}}}module.exports=DigitalReadRow},{}],76:[function(require,module,exports){"use strict";var log=require("../../utils/Logger.js").child({component:"webbudi"});function DigitalWriteRow(row){var options=row.options;options.reverse_meaning=options.reverse_meaning||false;options.label_false=options.label_false||options.false_label||(options.reverse_meaning?"OFF(1)":"OFF(0)");options.label_true=options.label_true||options.true_label||(options.reverse_meaning?"ON(0)":"ON(1)");options.color_false=options.color_false||null;options.color_true=options.color_true||null;options.flip=options.flip||false;if(options.flip){$(['<span id="DO_{id}">','<input type="radio" id="radio_{id}_1" name="radio_{id}" />','<label for="radio_{id}_1">',options.label_true,"</label>",'<input type="radio" id="radio_{id}_0" name="radio_{id}" />','<label for="radio_{id}_0">',options.label_false,"</label></span>"].join("").replace(/{id}/gi,row.options.id)).appendTo(row.element)}else{$(['<span id="DO_{id}">','<input type="radio" id="radio_{id}_0" name="radio_{id}" />','<label for="radio_{id}_0">',options.label_false,"</label>",'<input type="radio" id="radio_{id}_1" name="radio_{id}" />','<label for="radio_{id}_1">',options.label_true,"</label></span>"].join("").replace(/{id}/gi,row.options.id)).appendTo(row.element)}var DO_buttonset=row.element.find("#DO_"+row.options.id).controlgroup();DO_buttonset.find("input").checkboxradio({icon:false});DO_buttonset.find("label").mousedown(function(evt){if(evt.button===0&&!row.isDisabled()){$("#"+$(evt.target).parent().attr("for")).trigger("click")}});DO_buttonset.find("input[type=radio]").change(function(){row.options.item.disableRefresh=true;if(this.id==="radio_"+row.options.id+"_0"){if(options.reverse_meaning){log.debug(row.options.id+": 1");row.options.item.write(1).catch(err=>{log.error(new Error(row.options.id+" writing failed! Probably R/O item!"));log.debug(err.err||err)})}else{log.debug(row.options.id+": 0");row.options.item.write(0).catch(err=>{log.error(new Error(row.options.id+" writing failed! Probably R/O item!"));log.debug(err.err||err)})}}else{if(options.reverse_meaning){log.debug(row.options.id+": 0");row.options.item.write(0).catch(err=>{log.error(new Error(row.options.id+" writing failed! Probably R/O item!"));log.debug(err.err||err)})}else{log.debug(row.options.id+": 1");row.options.item.write(1).catch(err=>{log.error(new Error(row.options.id+" writing failed! Probably R/O item!"));log.debug(err.err||err)})}}row.options.item.disableRefresh=false;if(row.options.refresh_from){row.options.refresh_from.setValue(row.options.item.getValue())}});var old_disable=row.disable;row.disable=function(){old_disable.apply(this,arguments);DO_buttonset.controlgroup("disable")};var old_enable=row.enable;row.enable=function(){old_enable.apply(this,arguments);if(row.options.item.isOnline()){DO_buttonset.controlgroup("enable")}};var radio_0=row.element.find("#radio_"+row.options.id+"_0"),radio_1=row.element.find("#radio_"+row.options.id+"_1");var radio_label_0=row.element.find("label[for='radio_"+row.options.id+"_0']"),radio_label_1=row.element.find("label[for='radio_"+row.options.id+"_1']");function refresh(itm){if(itm.value==options.reverse_meaning){radio_0.prop("checked",true);radio_1.prop("checked",false);if(options.color_true){radio_label_1.css("background","")}if(options.color_false){radio_label_0.css("background",options.color_false)}}else{radio_0.prop("checked",false);radio_1.prop("checked",true);if(options.color_true){radio_label_1.css("background",options.color_true)}if(options.color_false){radio_label_0.css("background","")}}DO_buttonset.controlgroup("refresh")}row.options.item.on("change",function(){refresh(row.options.item)});if(row.options.refresh_from&&row.options.refresh_from!==row.options.item){row.options.refresh_from.on("change",function(){refresh(row.options.refresh_from)})}}module.exports=DigitalWriteRow},{"../../utils/Logger.js":65}],77:[function(require,module,exports){"use strict";function EmptySpace(row){row.element.empty()}module.exports=EmptySpace},{}],78:[function(require,module,exports){"use strict";function LinkButton(row){var options=row.options;options.target_url=options.target_url||options.url||"";options.desc=options.desc||options.alias||"LINK";options.id=options.alias||(Math.random().toString(16)+"000000000").substr(2,8);options.label=options.label||options.desc;$(['<span id="LINK_{id}">','<a id="LINK_BTN_{id}" class="mp-button-link" ','href="{url}">{label}</a></span>'].join("").replace(/{id}/gi,options.id).replace(/{label}/gi,options.label).replace(/{url}/gi,options.target_url)).appendTo(row.element);var linkBtn=row.element.find("#LINK_BTN_"+row.options.id).button();linkBtn.click(function(){window.location.href=options.target_url});var old_disable=row.disable;row.disable=function(){linkBtn.button("enable");return};row.enable=function(){linkBtn.button("enable")}}module.exports=LinkButton},{}],79:[function(require,module,exports){"use strict";var log=require("../../utils/Logger.js").child({component:"webbudi"});function ManualPulseRow(row){var options=row.options;options.label=options.label||options.desc;$(['<span id="MP_{id}">','<button id="MP_BTN_{id}" class="mp-button">{label}</button></span>'].join("").replace(/{id}/gi,row.options.id).replace(/{label}/gi,row.options.label)).appendTo(row.element);let pressed;var MP_button=row.element.find("#MP_BTN_"+row.options.id).button();MP_button.bind("touchend touchcancel touchleave mouseup mouseout",function(evt){evt.preventDefault();pressed=false;row.options.item.write(false).catch(err=>{log.error(new Error(row.options.id+" writing failed! Probably R/O item!"));log.debug(err.err||err)})}).on("touchstart mousedown",function(evt){evt.preventDefault();pressed=true;let loopWrite=()=>{row.options.item.write(true).then(()=>{setTimeout(()=>{if(pressed){loopWrite()}},20)}).catch(err=>{log.error(new Error(row.options.id+" writing failed! Probably R/O item!"));log.debug(err.err||err)})};loopWrite();log.debug(row.options.id+" pulse")})}module.exports=ManualPulseRow},{"../../utils/Logger.js":65}],80:[function(require,module,exports){"use strict";var log=require("../../utils/Logger.js").child({component:"webbudi"});function PushButton(row){var options=row.options;options.reverse_meaning=options.reverse_meaning||false;options.label_false=options.label_false||options.false_label||(options.reverse_meaning?"OFF(1)":"OFF(0)");options.label_true=options.label_true||options.true_label||(options.reverse_meaning?"ON(0)":"ON(1)");options.color_false=options.color_false||options.false_color||null;options.color_true=options.color_true||options.true_color||null;options.value_release=options.value_release||options.release_value||null;options.value_press=options.value_press||null;$(['<span id="PB_{id}">','<button id="PB_BTN_{id}" class="mp-button">XXX</button></span>'].join("").replace(/{id}/gi,row.options.id)).appendTo(row.element);var DB_button=row.element.find("#PB_BTN_"+row.options.id).button();var pressed=false;DB_button.bind("touchend touchcancel touchleave mouseup mouseout",function(evt){evt.stopPropagation();evt.preventDefault();if(evt.handled!==true){if(!(evt.button&&evt.button>0)&&pressed){log.debug(row.options.id+" "+evt.type);if(!options.reverse_meaning){row.options.item.write(row.options.value_release||0).catch(err=>{log.error(new Error(row.options.id+" writing failed! Probably R/O item!"));log.debug(err.err||err)})}else{row.options.item.write(row.options.value_release||1).catch(err=>{log.error(new Error(row.options.id+" writing failed! Probably R/O item!"));log.debug(err.err||err)})}if(!options.reverse_meaning){DB_button.button("option","label",options.label_false);DB_button.css("background",options.color_false)}else{DB_button.button("option","label",options.label_true);DB_button.css("background",options.color_true)}pressed=false}evt.handled=true}else{return false}}).bind("touchstart mousedown",function(evt){evt.stopPropagation();evt.preventDefault();if(evt.handled!==true){if(!(evt.button&&evt.button>0)){log.debug(row.options.id+" "+evt.type);if(!options.reverse_meaning){row.options.item.write(row.options.value_press||1).catch(err=>{log.error(new Error(row.options.id+" writing failed! Probably R/O item!"));log.debug(err.err||err)})}else{row.options.item.write(row.options.value_press||0).catch(err=>{log.error(new Error(row.options.id+" writing failed! Probably R/O item!"));log.debug(err.err||err)})}if(!options.reverse_meaning){DB_button.button("option","label",options.label_true);DB_button.css("background",options.color_true)}else{DB_button.button("option","label",options.label_false);DB_button.css("background",options.color_false)}pressed=true}evt.handled=true}else{return false}});if(!options.reverse_meaning){DB_button.button("option","label",options.label_false);DB_button.css("background",options.color_false)}else{DB_button.button("option","label",options.label_true);DB_button.css("background",options.color_true)}}module.exports=PushButton},{"../../utils/Logger.js":65}],81:[function(require,module,exports){"use strict";var log=require("../utils/Logger.js").child({component:"webwatch"});var IntParameter=require("./IntParameter.js");var BoolParameter=require("./BoolParameter.js");var DoubleParameter=require("./DoubleParameter.js");var StringParameter=require("./StringParameter.js");var EnumParameter=require("./EnumParameter.js");var WGroup=require("../group-management/WGroup.js");class BlockDialog{constructor(template,block){this.template=template;this.block=block;this.initDialog();this.block.dialog=this.dialog}createMarkup(){var title=this.block.id.split(".");title=title[title.length-1];this.dialog=$('<div id="'+this.template.name+"-"+this.block.id+'"></div>').dialog({autoOpen:false,title:title,width:300,maxHeight:$("#rex-dialog-container").height(),create:function(){$(window).resize(()=>{$(this).dialog("option","maxHeight",$("#rex-dialog-container").height())})},buttons:{OK:function(){if(writeDialogValues()){$(this).dialog("close")}},Apply:function(){writeDialogValues()},Close:function(){$(this).dialog("close")}},open:()=>{$errorLabel.hide();$(":button:contains('OK')").focus()}});$("body").append(this.dialog.parent());var $content=this.dialog;$content.append('<div class="rex-dialog-desc">'+this.template.description+"</div>");this.block.parameters=[];if(this.template.parameters!==undefined){for(let index in this.template.parameters){var param=this.template.parameters[index];var paramField=this.createParameter($content,this.block,param,this.block.id.replace(/\./g,"__")+"-"+index);this.block.parameters.push(paramField);$content.append("<br/>")}}if(this.template.helpUrl!==undefined){$content.append('<a href="'+this.template.helpUrl+'" target="_blanc"><img style="position: absolute;top:8px;right:6px;" width="16" src="images/rex-block/info.png" /></a>')}var $errorLabel=$("<div id='"+this.block.id+"-error' style='width:100%;color:white;text-align:center;background-color: #FF5925;font: 10pt Segoe UI;'>Unexpected type!</div>");$content.append($errorLabel);this.block.group.on("read",()=>{for(let p of this.block.parameters){p.readHandler()}});var writeDialogValues=()=>{var result=true;for(let param of this.block.parameters){var writeResult=param.writeHandler();param.errorHandler(!writeResult);if(!writeResult){result=false}}if(result===true){if(this.block.group.items.length>0){this.block.group.write().catch(err=>{if(err.msg&&err.msg.header.errno==-1){log.debug(err)}else{log.error(err)}})}$errorLabel.slideUp("fast")}else{$errorLabel.slideDown("fast")}return result}}createParameter(container,block,param,id){var type=param.type;if(param.type==="long"&&param["enum"]!==undefined){type="enum"}switch(type){case"word":case"byte":case"long":return new IntParameter(container,block,param,id);case"double":return new DoubleParameter(container,block,param,id);case"string":return new StringParameter(container,block,param,id);case"enum":return new EnumParameter(container,block,param,id);case"bool":return new BoolParameter(container,block,param,id);default:return}}initDialog(){this.block.group=new WGroup({id:this.block.type+"-"+this.block.id+"-group"});this.block.group.periodReadEnabled=false;this.createMarkup()}}module.exports=BlockDialog},{"../group-management/WGroup.js":45,"../utils/Logger.js":65,"./BoolParameter.js":82,"./DoubleParameter.js":83,"./EnumParameter.js":85,"./IntParameter.js":86,"./StringParameter.js":88}],82:[function(require,module,exports){"use strict";var Parameter=require("./Parameter.js");class BoolParameter extends Parameter{constructor(container,block,param,id){super(container,block,param,id)}createMarkup(container){super.createMarkup(container);var $a=$("<div  title='"+this.tooltip+"' id="+this.id+">"+"<input  value='1' type='radio' id="+this.id+"-on"+" name="+this.id+"radio"+" /><label for="+this.id+"-on"+">ON</label>"+"<input  value='0' type='radio' id="+this.id+"-off"+" name="+this.id+"radio"+" /><label for="+this.id+"-off"+">OFF</label>"+"</div>");$a.controlgroup();$a.find("input").checkboxradio({icon:false});$a.find("label").css("min-width","30px");container.append($a)}readHandler(){if(this.data.value===1){$("#"+this.id+"-on").prop("checked",true).checkboxradio("refresh")}else{$("#"+this.id+"-off").prop("checked",true).checkboxradio("refresh")}this.errorHandler(false)}writeHandler(){this.data.value=$("#"+this.id+"-on").prop("checked");return true}}module.exports=BoolParameter},{"./Parameter.js":87}],83:[function(require,module,exports){"use strict";var utils=require("../utils/utils.js");var IntParameter=require("./IntParameter.js");class DoubleParameter extends IntParameter{constructor(container,block,param,id){super(container,block,param,id)}writeHandler(){var value=$("#"+this.id).val();if(utils.isReal(value,this.param.min,this.param.max)){this.data.value=parseFloat(value);return true}else{return false}}}module.exports=DoubleParameter},{"../utils/utils.js":67,"./IntParameter.js":86}],84:[function(require,module,exports){"use strict";var hmi=require("../hmi.js");var log=require("../utils/Logger.js").child({component:"webwatch"});var Timer=require("../utils/Timer.js");var utils=require("../utils/utils.js");var SubSystem=require("./SubSystem.js");var BlockDialog=require("./BlockDialog.js");var TRNDDialog=require("./TRNDDialog.js");var Group=require("../group-management/Group.js");var EventEmitter=require("../utils/EventEmitter.js");var DECIMALS=3;var HINT_PERIOD=1e4;var State={NONE:0,READY:1,CONNECTED:2,DISCONNECTED:3,FAILED:4};var init=true;class Engine extends EventEmitter{constructor(){super();this._blocks=[];this._displays=[];this._taskName=null;this._svg=null;this._showHint=true;this._blockInfo={};hmi.once("init",()=>{this.State=State.CONNECTED;if(this._blockInfo){this.emit("online")}})}processSvg(svg){if(svg===undefined||!svg.is("svg")){log.error("Given element is not jQuery and SVG element");return}this._svg=svg;this._displays=[];this._recursivProcessing(this._svg[0]);this._taskname=$(this._svg[0]).attr("id");this._initDisplays();if(this.State===State.CONNECTED){log.info("Connection established. Press right mouse button on block to start reading values.");if(this._showHint){this.showHint()}if(this._blockInfo){this.emit("online")}}}disableHint(){this._showHint=false}showHint(){var hint=$("#rex-watch-hint");if(hint.length===0){hint=$(['<div id="rex-watch-hint">',"<strong>Left</strong> click or <strong>Touch</strong> on block to open dialog <br />","<strong>Right</strong> click or <strong>Long press</strong> to start reading the block.","</div>"].join("")).appendTo("body")}hint.show().fadeOut(HINT_PERIOD);hint.on("click",evt=>{hint.hide()})}setBlockInfo(blockInfo){this._blockInfo=blockInfo;if(this.State===State.CONNECTED){this.emit("online")}}enableMonitoring(blockIDs){if(!Array.isArray(blockIDs)){blockIDs=[blockIDs]}for(let bID of blockIDs){let found=false;for(let block of this._blocks){if(bID===block.id){if(block.toggleMonitorFcn){this.on("online",()=>{if(block.monitor){block.toggleMonitorFcn()}})}found=true;break}}if(!found){log.error("Block ID {0} not found!",bID)}}this.disableHint()}_recursivProcessing(element){for(let elName in element.childNodes){var el=element.childNodes[elName];if(el.getAttribute!==undefined){var block_type=el.getAttribute("rex-block-type");if(block_type){var block={element:el,id:el.getAttribute("id"),escapedId:el.getAttribute("id").replace(/\./g,"-"),type:block_type,orientation:el.getAttribute("rex-orientation"),monitor:false,toggleDialogFcn:null,toggleMonitorFcn:null};this._blocks.push(block);if(block.type==="Display"){this._displays.push(block)}if("ontouchstart"in document.documentElement){((element,block)=>{var clickHandler=this._getClickHandler(block);var toggleHandler=this._getToggleMonitoringHandler(block);var cancelUp=false;var timer=new Timer(()=>{toggleHandler();timer.stop();cancelUp=true});timer.Initial=false;element.addEventListener("touchstart",e=>{e.preventDefault();timer.start(1e3)},false);element.addEventListener("touchend",e=>{e.preventDefault();timer.stop();if(!cancelUp){clickHandler(e)}cancelUp=false},false)})(el,block)}if(block.type!=="Display"){el.addEventListener("click",this._getClickHandler(block),false);el.addEventListener("contextmenu",this._getToggleMonitoringHandler(block),false)}el.addEventListener("mouseover",(block=>{return()=>{utils.appendClass(block.element,"rex-block-hover")}})(block),false);el.addEventListener("mouseout",(block=>{return()=>{utils.removeClass(block.element,"rex-block-hover")}})(block),false)}}if(el.childNodes){this._recursivProcessing(el)}}}_getClickHandler(block){var toggleDialogFcn=evt=>{if(this.State!==State.CONNECTED){return}if(!block.dialog){this._createDialog(block,evt).then(()=>{if(block.group){hmi.addGroup(block.group)}if(block.trend){hmi.addTrend(block.trend)}block.dialog.dialog("open")}).catch(err=>{log.error(err)})}else if(block.type==="TRND"||block.type==="TRNDV"){block._dialog.startPeriodicReading(hmi._defaultRefreshRate);block.dialog.dialog("open")}else{if(block.group&&block.group.items.length>0){block.group.read().then(()=>{block.dialog.dialog("open")}).catch(()=>{log.warn(block.id+": Failed to load dialog data. Using old one!");block.dialog.dialog("open")})}else{block.dialog.dialog("open")}}if(evt){evt.preventDefault();evt.stopPropagation()}};block.toggleDialogFcn=toggleDialogFcn;return toggleDialogFcn}_getToggleMonitoringHandler(block){var toggleMonitorFcn=evt=>{if(this.State!==State.CONNECTED){return}if(!block.monitor){if(!block.monitoringGroup){var escapedId=block.id.replace(/\./g,"\\.");var inputs=$("#"+escapedId+" .rex-block-in");var outputs=$("#"+escapedId+" .rex-block-out");if(block.type==="CNB"||block.type==="CNI"||block.type==="CNR"||block.type==="CNE"||block.type==="CNS"||block.type==="CNA"){outputs.push($("#"+escapedId+" text")[1])}if(inputs&&inputs.length>0||outputs&&outputs.length>0){var monitorG=new Group({id:"mon-"+block.id,period:hmi._defaultRefreshRate});monitorG.isDefPeriod=true;monitorG.isDefURL=true;block.monitoringGroup=monitorG;monitorG.Label=[];block.monitorLabelGroup=document.createElementNS(utils.ns_svg,"g");block.element.appendChild(block.monitorLabelGroup);monitorG.on("periodic",(err,group)=>{if(err){log.error(err);group.stopPeriodicReading()}else{for(var i=0;i<group.Label.length;i++){var input=group.Label[i];if(group.items[i].type=="number"||group.items[i].type=="float"){input.textContent=utils.round(group.items[i].value,DECIMALS)}else{input.textContent=""+group.items[i].value}}}});var inCStrings=[];var outCStrings=[];if(this._blockInfo[block.type]!==undefined){var template=this._blockInfo[block.type];if(template.inPorts!==undefined){inCStrings=template.inPorts}if(template.outPorts!==undefined){outCStrings=template.outPorts}}else{for(let i=0;i<inputs.length;i++){inCStrings.push(inputs[i].textContent)}for(let i=0;i<outputs.length;i++){outCStrings.push(outputs[i].textContent)}}for(let i=0;i<inCStrings.length;i++){monitorG.addItem({id:block.id+"-mon-in-"+i,readCString:block.id+":"+inCStrings[i]});this._createLabel(block,inputs[i],"in")}for(let i=0;i<outCStrings.length;i++){monitorG.addItem({id:block.id+"-mon-out-"+i,readCString:block.id+":"+outCStrings[i]});this._createLabel(block,outputs[i],"out")}block.monitoringGroup.init().then(()=>{hmi.addGroup(block.monitoringGroup)}).catch(()=>{log.error(new Error("Failed to initialize group of items for block: "+block.id))});block.monitoringGroup.on("online",group=>{if(block.monitor){utils.appendClass(block.element,"rex-block-monitor");block.monitorLabelGroup.setAttribute("display","inline");block.monitoringGroup.startPeriodicReading()}})}}else{utils.appendClass(block.element,"rex-block-monitor");block.monitorLabelGroup.setAttribute("display","inline");block.monitoringGroup.startPeriodicReading()}block.monitor=true}else{if(block.monitoringGroup){utils.removeClass(block.element,"rex-block-monitor");block.monitorLabelGroup.setAttribute("display","none");block.monitoringGroup.stopPeriodicReading()}block.monitor=false}if(evt){evt.preventDefault();evt.stopPropagation()}};block.toggleMonitorFcn=toggleMonitorFcn;return toggleMonitorFcn}_initDisplays(){if(this._displays.length>0){if(!this._displaysG){this._displaysG=new Group({period:hmi._defaultRefreshRate});this._displaysG.Label=[]}for(let d of this._displays){d.monitorLabelGroup=document.createElementNS(utils.ns_svg,"g");d.element.appendChild(d.monitorLabelGroup);d.monitoringGroup=this._displaysG;d.monitorLabelGroup.setAttribute("display","inline");this._displaysG.addItem({readCString:d.id+":DispValue"});var label=$(d.element).find("tspan")[0];d.monitoringGroup.Label.push(label)}this._displaysG.on("periodic",(err,group)=>{if(!err){for(var i=0;i<group.Label.length;i++){var input=group.Label[i];input.textContent=group.items[i].value}}});this._displaysG.init().then(()=>{this._displaysG.isDefPeriod=true;this._displaysG.isDefURL=true;if(hmi.baseObjects.indexOf(this._displaysG)==-1){hmi.addGroup(this._displaysG)}}).catch(err=>{log.error(err)})}}_createLabel(block,pin,type){var monLabel=document.createElementNS(utils.ns_svg,"text");var x=parseFloat(pin.getAttribute("x"));var y=parseFloat(pin.getAttribute("y"));var family=pin.getAttribute("font-family");var size=pin.getAttribute("font-size");var fill=pin.getAttribute("fill");if(block.type==="CNB"||block.type==="CNI"||block.type==="CNR"||block.type==="CNE"){x+=3}else if(block.type==="CNS"||block.type==="CNA"){x+=7}if(type==="in"){if(block.orientation===0||block.orientation==="0"){x=x-12;y=y-size/2;monLabel.setAttribute("text-anchor","end")}else if(block.orientation===2||block.orientation==="2"){x=x+12;y=y-size/2;monLabel.setAttribute("text-anchor","start")}else if(block.orientation===1||block.orientation==="1"){y=y+10;monLabel.setAttribute("text-anchor","middle")}else if(block.orientation===3||block.orientation==="3"){y=y-10;monLabel.setAttribute("text-anchor","middle")}}else if(type==="out"){if(block.orientation===0||block.orientation==="0"){x=x+10;y=y-size/2;monLabel.setAttribute("text-anchor","start")}else if(block.orientation===2||block.orientation==="2"){x=x-10;y=y-size/2;monLabel.setAttribute("text-anchor","end")}else if(block.orientation===1||block.orientation==="1"){y=y+10;monLabel.setAttribute("text-anchor","middle")}else if(block.orientation===3||block.orientation==="3"){y=y-10;monLabel.setAttribute("text-anchor","middle")}}monLabel.setAttribute("x",x);monLabel.setAttribute("y",y);monLabel.setAttribute("font-family",family);monLabel.setAttribute("font-size",size);monLabel.setAttribute("fill",fill);block.monitorLabelGroup.appendChild(monLabel);block.monitoringGroup.Label.push(monLabel)}_createDialog(block){if(block.type==="SubSystem"){var $subSvg=$(document.getElementById("sub-"+block.id));new SubSystem($subSvg,block,this);return Promise.resolve()}else if(block.type==="TRND"||block.type==="TRNDV"){return new Promise((resolve,reject)=>{block._dialog=new TRNDDialog(this._blockInfo[block.type],block);block._dialog.init().then(()=>{block.dialog=block._dialog.dialog;block._dialog.startPeriodicReading(hmi._defaultRefreshRate);resolve()}).catch(err=>{reject(new Error("Failed to init trend "+block.id+". "+err))})})}else if(this._blockInfo[block.type]!==undefined){new BlockDialog(this._blockInfo[block.type],block);if(block.group.items.length===0){return Promise.resolve()}if(block.dialog!==null&&block.dialog!==undefined){return block.group.init()}else{block.group=null;return Promise.reject("Failed to create dialog")}}else{if(Object.keys(this._blockInfo).length>0){alert("Dialog is not supported for this block!");return Promise.reject("Dialog is not supported for this block!")}else{alert("Information about block is not ready yet, try it later!");return Promise.reject("Information about block is not ready yet, try it later!")}}}}module.exports=new Engine},{"../group-management/Group.js":40,"../hmi.js":46,"../utils/EventEmitter.js":63,"../utils/Logger.js":65,"../utils/Timer.js":66,"../utils/utils.js":67,"./BlockDialog.js":81,"./SubSystem.js":89,"./TRNDDialog.js":90}],85:[function(require,module,exports){"use strict";var utils=require("../utils/utils.js");var Parameter=require("./Parameter.js");class EnumParameter extends Parameter{constructor(container,block,param,id){super(container,block,param,id)}createMarkup(container){super.createMarkup(container);container.append("<div class='rex-dialog-input' id='in-"+this.id+"'><select title='"+this.tooltip+"' id="+this.id+"/><img style='display:none;' src='images/rex-block/error.png'/></div>");var $select=$("#"+this.id);for(let index in this.param["enum"]){var text=this.param["enum"][index];var value=null;var tmp=text.split(":");if(tmp.length>1){value=parseInt(tmp[0])}$("<option />",{value:value,text:text}).appendTo($select)}}writeHandler(){var value=$("#"+this.id).val();if(utils.isInt(value,this.param.min,this.param.max)){this.data.value=parseInt(value);return true}return false}}module.exports=EnumParameter},{"../utils/utils.js":67,"./Parameter.js":87}],86:[function(require,module,exports){"use strict";var utils=require("../utils/utils.js");var Parameter=require("./Parameter.js");class IntParameter extends Parameter{constructor(container,block,param,id){super(container,block,param,id)}createMarkup(container){super.createMarkup(container);container.append("<div class='rex-dialog-input' id='in-"+this.id+"'><input title='"+this.tooltip+"' type='text' maxlength='10' id="+this.id+" class='text ui-widget-content ui-corner-all' /><img style='display:none;' src='images/rex-block/error.png'/></div>")}writeHandler(){var value=$("#"+this.id).val();if(utils.isInt(value,this.param.min,this.param.max)){this.data.value=parseInt(value);return true}else{return false}}}module.exports=IntParameter},{"../utils/utils.js":67,"./Parameter.js":87}],87:[function(require,module,exports){"use strict";var log=require("../utils/Logger.js").child({component:"webwatch"});class Parameter{constructor(container,block,param,id){this.param=param;this.id=id;this.block=block;this.container=container;block.group.addItem({id:id,cstring:block.id.replace(/__/g,".")+":"+param.name}).then(item=>{this.data=item}).catch(err=>{log.error(err)});this.tooltip=param.description===undefined?"":param.description;this.createMarkup(container)}createMarkup(container){container.append("<label for="+this.id+">"+this.param.label+"</label></br>")}readHandler(){$("#"+this.id).val(this.data.value);this.errorHandler(false)}writeHandler(){this.data.value=$("#"+this.id).val();return true}errorHandler(error){if(!error){$("#in-"+this.id).removeClass("rex-dialog-input-failed")}else{$("#in-"+this.id).addClass("rex-dialog-input-failed")}}}module.exports=Parameter},{"../utils/Logger.js":65}],88:[function(require,module,exports){"use strict";var Parameter=require("./Parameter.js");class StringParameter extends Parameter{constructor(container,block,param,id){super(container,block,param,id)}createMarkup(container){super.createMarkup(container);container.append("<div class='rex-dialog-input' id='in-"+this.id+"'><input title='"+this.tooltip+"' type='text' id="+this.id+" class='text ui-widget-content ui-corner-all' /><img style='display:none;' src='images/rex-block/error.png'/></div>")}}module.exports=StringParameter},{"./Parameter.js":87}],89:[function(require,module,exports){"use strict";class SubSystem{constructor(svg,block){this._svg=svg;this._block=block;this.createMarkup();this._block.dialog=this.dialog}createMarkup(){this.dialog=$('<div id="subsystem-'+this._block.id+'"></div>').dialog({autoOpen:false,title:this._block.id,width:$("#rex-dialog-container").height()-20,maxWidth:$("#rex-dialog-container").width()-20,maxHeight:$("#rex-dialog-container").height()-150});$("body").append(this.dialog.parent());this._svg.detach();this.dialog.append(this._svg);this._svg.css("display","inline")}}module.exports=SubSystem},{}],90:[function(require,module,exports){"use strict";var Graph=require("../ui/graph/Graph.js");var Trend=require("../group-management/Trend.js");var HMI=require("../hmi.js");class TRNDDialog{constructor(template,block){this.template=template;this.block=block;this.graph=null;this.trend=null}createMarkup(){var title=this.trend.trndCfg.title;var self=this;this.dialog=$(`<div id="${this.template.name}-${this.block.escapedId}" style="width=650px;height:300px"></div>`).dialog({autoOpen:false,title:title,create:()=>{},open:()=>{$(":button:contains('OK')").focus();$(this.dialog).find(".graph-graph").removeAttr("style");this.graph.resize()},width:690,height:500,minWidth:300,minHeight:300});this.dialog.on("dialogclose",()=>{this.stopPeriodicReading()});$("body").append(this.dialog.parent());var desc=$('<div class="rex-dialog-desc" style="margin-bottom:5px;">'+this.template.description+"</div>");var graphDiv=$('<div id="graph-'+this.block.escapedId+'" style="width:100%; height:calc(100% - 20px);"></div>');$(this.dialog).append(desc).append(graphDiv);this.graph=new Graph({id:this.block.escapedId,element:graphDiv[0]});$(this.dialog).find(".graph-graph").addClass("webwatch");$(this.dialog).find(".graph-labels").addClass("webwatch")}startPeriodicReading(period){if(this.trend){this.trend.startPeriodicReading(period)}}stopPeriodicReading(){if(this.trend){this.trend.stopPeriodicReading()}}init(){if(!this.trend){this.trend=new Trend({cstring:this.block.id});this.trend.once("init",()=>{this.createMarkup()});var trndID=null;this.trend.on("read",data=>{if(trndID===null){var cfg=this.trend.trndCfg;trndID=this.graph.data.addTrendConfig(cfg);if(cfg.samplecount){if(this.graph.data.maxBuffSize<cfg.samplecount){this.graph.data.maxBuffSize=cfg.samplecount}}}this.graph.data.addTrend(trndID,data);this.graph.refresh()});return this.trend.init()}return Promise.reject("Already initialized")}}module.exports=TRNDDialog},{"../group-management/Trend.js":44,"../hmi.js":46,"../ui/graph/Graph.js":52}],91:[function(require,module,exports){(function(global){"use strict";var events=require("events");var WebSock=global.WebSocket||global.MozWebSocket||require("ws");var cons=require("../utils/Constants.js");var Command=require("./Command.js");var CommandList=require("./CommandList.js");var log=require("../utils/Logger.js").child({component:"ws-client"});class Client extends events.EventEmitter{constructor(options){options=options||{};super(options);this._sock=null;this._url="unset";this._recvdata="";this.subProtocol="visualization-1.1";this.callbacks={};this.commands=new CommandList(this);this.setMaxListeners(0)}off(){this.removeListener.apply(this,arguments)}_onClose(){log.info("Connection closed.");this.emit("closed",this)}_onError(err){log.error({err:err},"WebSocket connection error")}_onMessage(msg){this.emit("heartbeat");log.trace("<<< msg from "+this._url+": "+msg.data);if(typeof msg==="string"){let tmp=msg;msg={data:tmp}}if(this.subProtocol==="visualization-v1"){log.error("Unsupported subprotocol."+this.subProtocol)}else{this._parseMessage(msg)}}_parseMessage(msg){var inframe;try{inframe=JSON.parse(msg.data);if(!inframe.cmd||!inframe.header||inframe.header.id===undefined||!inframe.header.err||inframe.header.errno===undefined){throw new Error("Wrong format of incoming message.")}}catch(e){this.emit("err",new Error("Failed to parse message from server: "+e));log.debug({msg:msg},"Failed to parse message from server:"+e);return}if(inframe.header.errno>=0||inframe.header.err==="Success"){this.commands.resolveCmd(inframe.header.id,inframe)}else{this.commands.rejectCmd(inframe.header.id,inframe)}if(inframe.header.flags){this.emit("headerFlags",inframe.header.flags)}}connect(url){if(this.isConnected()){return Promise.reject("Already connected")}this._url=url;return new Promise((resolve,reject)=>{log.debug("Connecting to: "+url);this._sock=new WebSock(url,this.subProtocol);this._sock.onopen=(()=>{this._sock.onopen=(()=>{});this._sock.onerror=(evt=>{this._onError(evt)});this._sock.onclose=(evt=>{this._onClose(evt)});this._sock.onmessage=(msg=>{this._onMessage(msg)});log.info("Connected to: "+url);this.emit("connected");resolve()});this._sock.onerror=(err=>{log.error("Connecting to: %s failed.",this._url);reject(err)})})}reconnect(){if(this.isConnected()){return Promise.resolve("Already connected")}if(this._keepAliveTimer){clearTimeout(this._keepAliveTimer)}return new Promise((resolve,reject)=>{this.callbacks={};this.commands=new CommandList(this);log.info("Reconnecting to: "+this._url);this._sock=new WebSock(this._url,this.subProtocol);this._sock.onopen=(()=>{this._sock.onopen=(()=>{});this._sock.onerror=(evt=>{this._onError(evt)});this._sock.onclose=(evt=>{this._onClose(evt)});this._sock.onmessage=(msg=>{this._onMessage(msg)});log.info("Connected successfully to: "+this._url);this.emit("connected");resolve()});this._sock.onerror=(err=>{log.error("Connecting to: %s failed.",this._url);reject(err)})})}disconnect(){if(!this.isConnected()){if(this._sock){this._sock.onerror=(()=>{});this._sock.onclose=(()=>{});this._sock.close();this._sock=null}return Promise.resolve("Target "+this.url+" is not connected")}if(this._keepAliveTimer){clearTimeout(this._keepAliveTimer)}return new Promise((resolve,reject)=>{log.info("Disconnecting from: "+this._url);this._sock.onclose=(()=>{this.emit("disconnected");resolve()});this._sock.onerror=(err=>{log.debug("Failed to disconnect from target "+this.url+" .");reject(err)});this._sock.close()})}_makeAPICall(code,data){if(!this.isConnected()){return{promise:Promise.reject(new Error("Connection to  "+this._url+" lost."))}}var cmd=new Command(this._sock,code,data);this.commands.push(cmd);cmd.promise.catch(err=>{log.debug(err.err||err);this.commands.removeCmd(cmd.id)});return cmd}readItems(names){return this._makeAPICall(cons.CMD_READ_ITEMS,{names:names})}writeItems(names,values){return this._makeAPICall(cons.CMD_WRITE_ITEMS,{names:names,values:values})}addGroup(names){return this._makeAPICall(cons.CMD_ADD_GROUP,{names:names})}removeGroup(groupid){return this._makeAPICall(cons.CMD_REMOVE_GROUP,{groupid:groupid})}readGroup(groupid){return this._makeAPICall(cons.CMD_READ_GROUP,{groupid:groupid})}writeGroup(groupid,values){return this._makeAPICall(cons.CMD_WRITE_GROUP,{groupid:groupid,values:values})}idle(){return this._makeAPICall(cons.CMD_IDLE)}getVersion(){return this._makeAPICall(cons.CMD_VERSION)}getWhoami(){return this._makeAPICall(cons.CMD_WHO_AMI)}getTrendConfig(trend){return this._makeAPICall(cons.CMD_GET_TRND_CFG,{trend:trend})}readTrend(trendid){return this._makeAPICall(cons.CMD_TRND_READ,{trendid:trendid})}browseSymbol(symbol){return this._makeAPICall(cons.CMD_BROWSE_SYMBOL,{symbol:symbol})}names2ids(names){return this._makeAPICall(cons.CMD_NAMES_TO_IDS,{names:names})}getTime(){return this._makeAPICall(cons.CMD_GET_TIME,{})}isConnected(){if(!this._sock){return false}return this._sock.readyState===this._sock.OPEN}setSubProtocol(protocol){this.subProtocol=protocol}}module.exports=Client}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../utils/Constants.js":61,"../utils/Logger.js":65,"./Command.js":92,"./CommandList.js":93,events:11,ws:6}],92:[function(require,module,exports){"use strict";var log=require("../utils/Logger.js").child({component:"ws-client"});const MAX_ID=1e4;class Command{constructor(wsock,cmdCode,data,header){this.cmdCode=cmdCode;this.wsock=wsock;this.data=data||{};this.header=header||{};this.cmdTimer=null;this.msg="";this.promise=new Promise((resolve,reject)=>{this.resolve=resolve;this.reject=reject;if(!this.header.id){this.id=this.header.id=Command.getId()}var frame={cmd:this.cmdCode,header:this.header,data:this.data};this.msg=JSON.stringify(frame);log.trace(">>> msg to "+this.wsock.url+" : "+this.msg);this.wsock.send(this.msg)})}static getId(){if(!Command.requestNo||Command.requestNo>=MAX_ID){Command.requestNo=0}return Command.requestNo++}}module.exports=Command},{"../utils/Logger.js":65}],93:[function(require,module,exports){"use strict";var Command=require("./Command.js");var log=require("../utils/Logger.js").child({component:"ws-client"});var dgnConst=require("../utils/Constants.js");var events=require("events");class CommandList extends Array{constructor(evEmitter){super();this.evEmitter=evEmitter instanceof events.EventEmitter?evEmitter:{emit:()=>{}}}resolveCmd(id,msg){var cmd=this.getCmd(id);let result=msg.data;switch(msg.cmd){case dgnConst.CMD_INIT:{this.evEmitter.emit("init");cmd.resolve();break}case dgnConst.CMD_EXIT:{this.evEmitter.emit("exit");cmd.resolve();break}case dgnConst.CMD_IDLE:{this.evEmitter.emit("idle");cmd.resolve();break}case dgnConst.CMD_VERSION:{this.evEmitter.rexVersionDetails=msg.data;this.evEmitter.rexVersion=msg.data.version.hi+"."+msg.data.version.lo+"."+msg.data.version.rel+"-"+msg.data.version.rev;this.evEmitter.emit("version",this.evEmitter.rexVersion);cmd.resolve(this.evEmitter.rexVersion);break}case dgnConst.CMD_READ_ITEMS:{result.names=cmd.data.names;this.evEmitter.emit("read",result);cmd.resolve(result);break}case dgnConst.CMD_WRITE_ITEMS:{result.names=cmd.data.names;this.evEmitter.emit("write",result);cmd.resolve(result);break}case dgnConst.CMD_ADD_GROUP:{result.names=cmd.data.names;if(result.ids.length<cmd.data.names.length){this.rejectCmd(id,msg);return}this.evEmitter.emit("add",result);cmd.resolve(result);break}case dgnConst.CMD_READ_GROUP:{this.evEmitter.emit("read",result);cmd.resolve(result);break}case dgnConst.CMD_WRITE_GROUP:{this.evEmitter.emit("write",result);cmd.resolve(result);break}case dgnConst.CMD_WHO_AMI:{this.evEmitter.emit("whoami",result);cmd.resolve(result);break}default:{if(cmd){cmd.resolve(result)}else{if(msg.header.id){log.debug("CMD id: "+msg.header.id+" does not exit!")}}}}this.removeCmd(id)}rejectCmd(id,msg){var cmd=this.getCmd(id);if(msg.cmd){switch(msg.cmd){default:{var err=new Error(dgnConst.getCmdName(msg.cmd)+" command failed."+" "+msg.header.err);cmd.reject({id:msg.header.id,err:err,errno:msg.header.errno,msg:msg});this.evEmitter.emit("err",err)}}}else{cmd.reject({err:new Error(msg),msg:msg})}this.removeCmd(id)}push(cmd){if(cmd instanceof Command){super.push(cmd)}else{log.debug("CommandList accepts only instances of Command")}}getCmd(id){for(let i=0;i<this.length;i++){if(id===this[i].header.id){return this[i]}}}removeCmd(id){var index=-1;for(let i=0;i<this.length;i++){if(id===this[i].header.id){index=i}}if(index>=0){this.splice(index,1)}}getMsgLength(){var msgLength=0;for(let i=0;i<this.length;i++){if(this[i].msg){msgLength+=this[i].msg.length}}return msgLength}clear(){for(var i=0,l=this.length;i<l;i++){clearTimeout(this[i].cmdTimer)}this.length=0}}module.exports=CommandList},{"../utils/Constants.js":61,"../utils/Logger.js":65,"./Command.js":92,events:11}]},{},[2])(2)});
  //# sourceMappingURL=/rexhmi.min.js-2.50.7-9228.map