@wiotp/sdk 0.7.6-pre.monitoring-dashboard-updates → 0.7.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/BaseClient.js +23 -9
- package/dist/BaseConfig.js +1 -3
- package/dist/api/ApiClient.js +8 -8
- package/dist/api/ApiErrors.js +24 -22
- package/dist/api/DscClient.js +2 -4
- package/dist/api/LecClient.js +1 -3
- package/dist/api/MgmtClient.js +1 -3
- package/dist/api/RegistryClient.js +1 -3
- package/dist/api/RulesClient.js +1 -3
- package/dist/api/StateClient.js +1 -3
- package/dist/application/ApplicationClient.js +15 -11
- package/dist/application/ApplicationConfig.js +14 -10
- package/dist/bundled/wiotp-bundle.js +34834 -30156
- package/dist/bundled/wiotp-bundle.min.js +6 -6
- package/dist/device/DeviceClient.js +15 -11
- package/dist/device/DeviceConfig.js +18 -10
- package/dist/gateway/GatewayClient.js +15 -11
- package/dist/gateway/GatewayConfig.js +13 -9
- package/dist/index.js +56 -0
- package/package.json +9 -5
- package/src/BaseClient.js +9 -0
- package/src/api/ApiClient.js +4 -2
- package/src/application/ApplicationConfig.js +1 -1
- package/src/device/DeviceConfig.js +7 -1
- package/src/index.js +8 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,(function(r){var n=e[i][1][r];return o(n||r)}),p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){(function(Buffer){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _events=_interopRequireDefault(require("events"));var _mqtt=_interopRequireDefault(require("mqtt"));var _loglevel=_interopRequireDefault(require("loglevel"));var _tinycache=_interopRequireDefault(require("tinycache"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}function _possibleConstructorReturn(self,call){if(call&&(_typeof(call)==="object"||typeof call==="function")){return call}return _assertThisInitialized(self)}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return self}function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o)};return _getPrototypeOf(o)}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function")}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:true,configurable:true}});if(superClass)_setPrototypeOf(subClass,superClass)}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o};return _setPrototypeOf(o,p)}var uuidv4=require("uuid/v4");var BaseClient=function(_events$EventEmitter){_inherits(BaseClient,_events$EventEmitter);function BaseClient(config){var _this;_classCallCheck(this,BaseClient);_this=_possibleConstructorReturn(this,_getPrototypeOf(BaseClient).call(this));_this.log=_loglevel["default"];_this.log.setDefaultLevel(config.options.logLevel);_this.config=config;_this.reconnectLog=0;_this.mqtt=null;_this.lostConnectionLog=new _tinycache["default"];return _this}_createClass(BaseClient,[{key:"isConnected",value:function isConnected(){if(this.mqtt==null){return false}return this.mqtt.connected}},{key:"connect",value:function connect(){var _this2=this;if(this.mqtt!=null){this.log.info("[BaseClient:connect] Reconnecting to "+this.config.getMqttHost()+" as "+this.config.getClientId());this.mqtt.reconnect();return}this.log.info("[BaseClient:connect] Connecting to "+this.config.getMqttHost()+" as "+this.config.getClientId());this.mqtt=_mqtt["default"].connect(this.config.getMqttHost(),this.config.getMqttConfig());this.mqtt.on("connect",(function(){_this2.log.info("[BaseClient:onConnect] MQTT client is connected.");_this2.emit("connect");var connectionLostCount=_this2.lostConnectionLog.size;var reconnectPeriod=1e3;if(connectionLostCount>=9){reconnectPeriod=2e4;_this2.log.warn("[BaseClient:onOffline] This client is likely suffering from clientId stealing (where two connections try to use the same client Id).");_this2.emit("error","Exceeded 9 connection losses in a 5 minute period. Check for clientId conflict with another connection.")}else if(connectionLostCount>=6){reconnectPeriod=5e3}else if(connectionLostCount>=3){reconnectPeriod=2e3}if(reconnectPeriod!=_this2.mqtt.options.reconnectPeriod){_this2.log.info("[BaseClient:onOffline] Client has lost connection "+connectionLostCount+" times during the last 5 minutes, reconnect delay adjusted to "+reconnectPeriod+" ms");_this2.mqtt.options.reconnectPeriod=reconnectPeriod}}));this.mqtt.on("reconnect",(function(){_this2.log.info("[BaseClient:onReconnect] MQTT client is reconnecting.");_this2.emit("reconnect")}));this.mqtt.on("close",(function(){_this2.log.info("[BaseClient:onClose] MQTT client connection was closed.");_this2.emit("close")}));this.mqtt.on("offline",(function(){var newId=uuidv4();_this2.log.info("[BaseClient:onOffline] MQTT client connection is offline. ["+newId+"]");_this2.emit("offline");_this2.lostConnectionLog.put(newId,"1",3e5);var connectionLostCount=_this2.lostConnectionLog.size;_this2.log.info("[BaseClient:onOffline] Connection losses in the last 5 minutes: "+connectionLostCount)}));this.mqtt.on("error",(function(error){_this2.log.error("[BaseClient:onError] "+error);var errorMsg=""+error;if(errorMsg.indexOf("Not authorized")>-1){_this2.log.error("[BaseClient:onError] One or more configuration parameters are wrong. Modify the configuration before trying to reconnect.");_this2.mqtt.end(false,(function(){_this2.log.info("[BaseClient:onError] Closed the MQTT connection due to client misconfiguration")}))}_this2.emit("error",error)}))}},{key:"disconnect",value:function disconnect(){var _this3=this;if(this.mqtt==null){this.log.info("[BaseClient:disconnect] Client was never connected");return}this.mqtt.end(false,(function(){_this3.log.info("[BaseClient:disconnect] Closed the MQTT connection due to disconnect() call")}))}},{key:"_subscribe",value:function _subscribe(topic,QoS,callback){if(this.mqtt==null){this.emit("error","[BaseClient:_subscribe] MQTT Client is not initialized - call connect() first");return}if(!this.mqtt.connected){this.emit("error","[BaseClient:_subscribe] MQTT Client is not connected - call connect() first");return}QoS=QoS||0;callback=callback||function(err,granted){if(err==null){for(var index in granted){var grant=granted[index];this.log.debug("[BaseClient:_subscribe] Subscribed to "+grant.topic+" at QoS "+grant.qos)}}else{this.log.error("[BaseClient:_subscribe] "+err);this.emit("error",err)}}.bind(this);this.log.debug("[BaseClient:_subscribe] Subscribing to topic "+topic+" with QoS "+QoS);this.mqtt.subscribe(topic,{qos:parseInt(QoS)},callback)}},{key:"_unsubscribe",value:function _unsubscribe(topic,callback){if(this.mqtt==null){this.emit("error","[BaseClient:_unsubscribe] MQTT Client is not initialized - call connect() first");return}if(!this.mqtt.connected){this.emit("error","[BaseClient:_unsubscribe] MQTT Client is not connected - call connect() first");return}callback=callback||function(err){if(err==null){this.log.debug("[BaseClient:_unsubscribe] Unsubscribed from: "+topic)}else{this.log.error("[BaseClient:_unsubscribe] "+err);this.emit("error",err)}}.bind(this);this.log.debug("[BaseClient:_unsubscribe] Unsubscribe: "+topic);this.mqtt.unsubscribe(topic,callback)}},{key:"_publish",value:function _publish(topic,msg,QoS,callback){QoS=QoS||0;if((_typeof(msg)==="object"||typeof msg==="boolean"||typeof msg==="number")&&!Buffer.isBuffer(msg)){msg=JSON.stringify(msg)}this.log.debug("[BaseClient:_publish] Publish: "+topic+", "+msg+", QoS : "+QoS);this.mqtt.publish(topic,msg,{qos:parseInt(QoS)},callback)}}]);return BaseClient}(_events["default"].EventEmitter);exports["default"]=BaseClient}).call(this,{isBuffer:require("../node_modules/is-buffer/index.js")})},{"../node_modules/is-buffer/index.js":149,events:73,loglevel:152,mqtt:162,tinycache:192,"uuid/v4":212}],2:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}var BaseConfig=function(){function BaseConfig(identity,auth,options){_classCallCheck(this,BaseConfig);this.identity=identity;this.auth=auth;this.options=options;if(this.options!=null&&"mqtt"in this.options){if("port"in this.options.mqtt&&this.options.mqtt.port!=null){if(isNaN(this.options.mqtt.port)){throw new Error("Optional setting options.mqtt.port must be a number if provided")}}if("cleanStart"in this.options.mqtt&&typeof this.options.mqtt.cleanStart!="boolean"){throw new Error("Optional setting options.mqtt.cleanStart must be a boolean if provided")}}if(this.options==null){this.options={}}if(!("domain"in this.options)||this.options.domain==null){this.options.domain="internetofthings.ibmcloud.com"}if(!("logLevel"in this.options)||this.options.logLevel==null){this.options.logLevel="info"}if(!("mqtt"in this.options)){this.options.mqtt={}}if(!("port"in this.options.mqtt)||this.options.mqtt.port==null){this.options.mqtt.port=8883}if(!("transport"in this.options.mqtt)||this.options.mqtt.transport==null){this.options.mqtt.transport="tcp"}if(!("cleanStart"in this.options.mqtt)){this.options.mqtt.cleanStart=true}if(!("sessionExpiry"in this.options.mqtt)){this.options.mqtt.sessionExpiry=3600}if(!("keepAlive"in this.options.mqtt)){this.options.mqtt.keepAlive=60}if(!("caFile"in this.options.mqtt)){this.options.mqtt.caFile=null}}_createClass(BaseConfig,[{key:"getOrgId",value:function getOrgId(){throw new Error("Sub class must implement getOrgId()")}},{key:"isQuickstart",value:function isQuickstart(){return this.getOrgId()=="quickstart"}},{key:"getClientId",value:function getClientId(){throw new Error("Sub class must implement getClientId()")}},{key:"getMqttUsername",value:function getMqttUsername(){throw new Error("Sub class must implement getMqttUsername()")}},{key:"getMqttPassword",value:function getMqttPassword(){throw new Error("Sub class must implement getMqttPassowrd()")}},{key:"getMqttConfig",value:function getMqttConfig(){var mqttConfig={clientId:this.getClientId(),keepalive:this.options.mqtt.keepAlive,connectTimeout:90*1e3,reconnectPeriod:1e3,queueQoSZero:true,resubscribe:true,clean:this.options.mqtt.cleanStart,username:this.getMqttUsername(),password:this.getMqttPassword(),rejectUnauthorized:true};return mqttConfig}},{key:"getMqttHost",value:function getMqttHost(){var server=this.getOrgId()+".messaging."+this.options.domain+":"+this.options.mqtt.port;if(this.options.mqtt.port==80||this.options.mqtt.port==1883){if(this.options.mqtt.transport=="tcp"){return"tcp://"+server}if(this.options.mqtt.transport=="websockets"){return"ws://"+server}}if(this.options.mqtt.port==433||this.options.mqtt.port==8883){if(this.options.mqtt.transport=="tcp"){return"ssl://"+server}if(this.options.mqtt.transport=="websockets"){return"wss://"+server}}return"ssl://"+server}}],[{key:"parseEnvVars",value:function parseEnvVars(){throw new Error("Sub class must implement parseEnvVars()")}},{key:"parseConfigFile",value:function parseConfigFile(){throw new Error("Sub class must implement parseConfigFile()")}}]);return BaseConfig}();exports["default"]=BaseConfig},{}],3:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _axios=_interopRequireDefault(require("axios"));var _bluebird=_interopRequireDefault(require("bluebird"));var _btoa=_interopRequireDefault(require("btoa"));var _formData=_interopRequireDefault(require("form-data"));var _loglevel=_interopRequireDefault(require("loglevel"));var _util=require("../util");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}function ownKeys(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);if(enumerableOnly)symbols=symbols.filter((function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable}));keys.push.apply(keys,symbols)}return keys}function _objectSpread(target){for(var i=1;i<arguments.length;i++){var source=arguments[i]!=null?arguments[i]:{};if(i%2){ownKeys(Object(source),true).forEach((function(key){_defineProperty(target,key,source[key])}))}else if(Object.getOwnPropertyDescriptors){Object.defineProperties(target,Object.getOwnPropertyDescriptors(source))}else{ownKeys(Object(source)).forEach((function(key){Object.defineProperty(target,key,Object.getOwnPropertyDescriptor(source,key))}))}}return target}function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true})}else{obj[key]=value}return obj}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}var ApiClient=function(){function ApiClient(config){_classCallCheck(this,ApiClient);this.log=_loglevel["default"];this.log.setDefaultLevel(config.options.logLevel);this.config=config;this.useLtpa=this.config.auth&&this.config.auth.useLtpa;this.log.debug("[ApiClient:constructor] ApiClient initialized for "+this.config.getApiBaseUri())}_createClass(ApiClient,[{key:"parseSortSpec",value:function parseSortSpec(sortSpec){return sortSpec?sortSpec.map((function(s){var e=Object.entries(s)[0];return"".concat(e[1]?"-":"").concat(e[0])})).join(","):undefined}},{key:"callApi",value:function callApi(method,expectedHttpCode,expectJsonContent,paths,body,params){var _this=this;return new _bluebird["default"]((function(resolve,reject){var uri=_this.config.getApiBaseUri();if(Array.isArray(paths)){for(var i=0,l=paths.length;i<l;i++){uri+="/"+paths[i]}}var xhrConfig={url:uri,method:method,headers:{"Content-Type":"application/json"},validateStatus:function validateStatus(status){if(Array.isArray(expectedHttpCode)){return expectedHttpCode.includes(status)}else{return status===expectedHttpCode}}};if(_this.useLtpa){xhrConfig.withCredentials=true}else{xhrConfig.headers["Authorization"]="Basic "+(0,_btoa["default"])(_this.config.auth.key+":"+_this.config.auth.token)}if(body){xhrConfig.data=body}if(params){xhrConfig.params=params}if(_this.config.getAdditionalHeaders()){xhrConfig.headers=_objectSpread({},xhrConfig.headers,{},_this.config.getAdditionalHeaders())}function transformResponse(response){if(expectJsonContent&&!(_typeof(response.data)==="object")){try{resolve(JSON.parse(response.data))}catch(e){reject(e)}}else{resolve(response.data)}}_this.log.debug("[ApiClient:transformResponse] "+xhrConfig);(0,_axios["default"])(xhrConfig).then(transformResponse,reject)}))}},{key:"getOrganizationDetails",value:function getOrganizationDetails(){this.log.debug("[ApiClient] getOrganizationDetails()");return this.callApi("GET",200,true,null,null)}},{key:"getServiceStatus",value:function getServiceStatus(){this.log.debug("[ApiClient] getServiceStatus()");return this.callApi("GET",200,true,["service-status"],null)}},{key:"getActiveDevices",value:function getActiveDevices(start,end,detail){this.log.debug("[ApiClient] getActiveDevices("+start+", "+end+")");detail=detail|false;var params={start:start,end:end,detail:detail};return this.callApi("GET",200,true,["usage","active-devices"],null,params)}},{key:"getHistoricalDataUsage",value:function getHistoricalDataUsage(start,end,detail){this.log.debug("[ApiClient] getHistoricalDataUsage("+start+", "+end+")");detail=detail|false;var params={start:start,end:end,detail:detail};return this.callApi("GET",200,true,["usage","historical-data"],null,params)}},{key:"getDataUsage",value:function getDataUsage(start,end,detail){this.log.debug("[ApiClient] getDataUsage("+start+", "+end+")");detail=detail|false;var params={start:start,end:end,detail:detail};return this.callApi("GET",200,true,["usage","data-traffic"],null,params)}},{key:"getConnectionStates",value:function getConnectionStates(){this.log.debug("[ApiClient] getConnectionStates() - client connectivity");return this.callApi("GET",200,true,["clientconnectionstates"],null)}},{key:"getConnectionState",value:function getConnectionState(id){this.log.debug("[ApiClient] getConnectionState() - client connectivity");return this.callApi("GET",200,true,["clientconnectionstates/"+id],null)}},{key:"getConnectedClientsConnectionStates",value:function getConnectedClientsConnectionStates(){this.log.debug("[ApiClient] getConnectedClientsConnectionStates() - client connectivity");return this.callApi("GET",200,true,["clientconnectionstates?connectionStatus=connected"],null)}},{key:"getRecentConnectionStates",value:function getRecentConnectionStates(date){this.log.debug("[ApiClient] getRecentConnectionStates() - client connectivity");return this.callApi("GET",200,true,["clientconnectionstates?connectedAfter="+date],null)}},{key:"getCustomConnectionState",value:function getCustomConnectionState(query){this.log.debug("[ApiClient] getCustomConnectionStates() - client connectivity");return this.callApi("GET",200,true,["clientconnectionstates"+query],null)}},{key:"getAllDevices",value:function getAllDevices(params){this.log.debug("[ApiClient] getAllDevices() - BULK");return this.callApi("GET",200,true,["bulk","devices"],null,params)}},{key:"getGroupIdsForDevice",value:function getGroupIdsForDevice(deviceId){this.log.debug("[ApiClient] getGroupIdsForDevice("+deviceId+")");return this.callApi("GET",200,true,["authorization","devices",deviceId],null)}},{key:"updateDeviceRoles",value:function updateDeviceRoles(deviceId,roles){this.log.debug("[ApiClient] updateDeviceRoles("+deviceId+","+roles+")");return this.callApi("PUT",200,false,["authorization","devices",deviceId,"roles"],roles)}},{key:"getAllDevicesInGroup",value:function getAllDevicesInGroup(groupId){this.log.debug("[ApiClient] getAllDevicesInGropu("+groupId+")");return this.callApi("GET",200,true,["bulk","devices",groupId],null)}},{key:"addDevicesToGroup",value:function addDevicesToGroup(groupId,deviceList){this.log.debug("[ApiClient] addDevicesToGroup("+groupId+","+deviceList+")");return this.callApi("PUT",200,false,["bulk","devices",groupId,"add"],deviceList)}},{key:"removeDevicesFromGroup",value:function removeDevicesFromGroup(groupId,deviceList){this.log.debug("[ApiClient] removeDevicesFromGroup("+groupId+","+deviceList+")");return this.callApi("PUT",200,false,["bulk","devices",groupId,"remove"],deviceList)}},{key:"getAllGroups",value:function getAllGroups(){this.log.debug("[ApiClient] getAllGroups()");return this.callApi("GET",200,true,["groups"],null)}},{key:"getAllDeviceIdsInGroup",value:function getAllDeviceIdsInGroup(groupId){this.log.debug("[ApiClient] getAllDeviceIdsInGroup("+groupId+")");return this.callApi("GET",200,true,["bulk","devices",groupId,"ids"],null)}},{key:"getGroup",value:function getGroup(groupId){this.log.debug("[ApiClient] getGroup("+groupId+")");return this.callApi("GET",200,true,["groups",groupId],null)}},{key:"createGroup",value:function createGroup(groupInfo){this.log.debug("[ApiClient] createGroup()");return this.callApi("POST",201,true,["groups"],groupInfo)}},{key:"deleteGroup",value:function deleteGroup(groupId){this.log.debug("[ApiClient] deleteGroup("+groupId+")");return this.callApi("DELETE",200,false,["groups",groupId],null)}},{key:"getAllDeviceAccessControlProperties",value:function getAllDeviceAccessControlProperties(){this.log.debug("[ApiClient] getAllDeviceAccessControlProperties()");return this.callApi("GET",200,true,["authorization","devices"],null)}},{key:"getDeviceAccessControlProperties",value:function getDeviceAccessControlProperties(deviceId){this.log.debug("[ApiClient] getDeviceAccessControlProperties("+deviceId+")");return this.callApi("GET",200,true,["authorization","devices",deviceId,"roles"],null)}},{key:"updateDeviceAccessControlProperties",value:function updateDeviceAccessControlProperties(deviceId,deviceProps){this.log.debug("[ApiClient] updateDeviceAccessControlProperties("+deviceId+")");return this.callApi("PUT",200,true,["authorization","devices",deviceId],deviceProps)}},{key:"updateDeviceAccessControlPropertiesWithRoles",value:function updateDeviceAccessControlPropertiesWithRoles(deviceId,devicePropsWithRoles){this.log.debug("[ApiClient] updateDeviceAccessControlPropertiesWithRoles("+deviceId+","+devicePropsWithRoles+")");return this.callApi("PUT",200,true,["authorization","devices",deviceId,"withroles"],devicePropsWithRoles)}},{key:"updateGatewayRoles",value:function updateGatewayRoles(gatewayId,roles){this.log.debug("[ApiClient] updateGatewayRoles("+gatewayId+","+roles+")");return this.callApi("PUT",200,false,["authorization","devices",gatewayId,"roles"],roles)}},{key:"getGroups",value:function getGroups(groupId){this.log.debug("[ApiClient] getGroups("+groupId+")");return this.callApi("GET",200,true,["groups",groupId],null)}},{key:"callFormDataApi",value:function callFormDataApi(method,expectedHttpCode,expectJsonContent,paths,body,params){var _this2=this;return new _bluebird["default"]((function(resolve,reject){var uri=_this2.config.getApiBaseUri();if(Array.isArray(paths)){for(var i=0,l=paths.length;i<l;i++){uri+="/"+paths[i]}}var xhrConfig={url:uri,method:method,headers:{"Content-Type":"multipart/form-data"}};if(_this2.useLtpa){xhrConfig.withCredentials=true}else{xhrConfig.headers["Authorization"]="Basic "+(0,_btoa["default"])(_this2.apiKey+":"+_this2.apiToken)}if(body){xhrConfig.data=body;if((0,_util.isBrowser)()){xhrConfig.transformRequest=[function(data){var formData=new _formData["default"];if(xhrConfig.method=="POST"){if(data.schemaFile){var blob=new Blob([data.schemaFile],{type:"application/json"});formData.append("schemaFile",blob)}if(data.name){formData.append("name",data.name)}if(data.schemaType){formData.append("schemaType","json-schema")}if(data.description){formData.append("description",data.description)}}else if(xhrConfig.method=="PUT"){if(data.schemaFile){var blob=new Blob([data.schemaFile],{type:"application/json",name:data.name});formData.append("schemaFile",blob)}}return formData}]}}if(params){xhrConfig.params=params}if(_this2.config.getAdditionalHeaders()){xhrConfig.headers=_objectSpread({},xhrConfig.headers,{},_this2.config.getAdditionalHeaders())}function transformResponse(response){if(response.status===expectedHttpCode){if(expectJsonContent&&!(_typeof(response.data)==="object")){try{resolve(JSON.parse(response.data))}catch(e){reject(e)}}else{resolve(response.data)}}else{reject(new Error(method+" "+uri+": Expected HTTP "+expectedHttpCode+" from server but got HTTP "+response.status+". Error Body: "+JSON.stringify(response.data)))}}_this2.log.debug("[ApiClient:transformResponse] "+xhrConfig);if((0,_util.isBrowser)()){(0,_axios["default"])(xhrConfig).then(transformResponse,reject)}else{var formData=null;var config={url:uri,method:method,headers:{"Content-Type":"multipart/form-data"},auth:{user:_this2.apiKey,pass:_this2.apiToken},formData:{},rejectUnauthorized:false};if(xhrConfig.method=="POST"){formData={schemaFile:{value:body.schemaFile,options:{contentType:"application/json",filename:body.name}},schemaType:"json-schema",name:body.name};config.formData=formData}else if(xhrConfig.method=="PUT"){formData={schemaFile:{value:body.schemaFile,options:{contentType:"application/json",filename:body.name}}};config.formData=formData}request(config,(function optionalCallback(err,response,body){if(response.statusCode===expectedHttpCode){if(expectJsonContent&&!(_typeof(response.data)==="object")){try{resolve(JSON.parse(body))}catch(e){reject(e)}}else{resolve(body)}}else{reject(new Error(method+" "+uri+": Expected HTTP "+expectedHttpCode+" from server but got HTTP "+response.statusCode+". Error Body: "+err))}}))}}))}},{key:"invalidOperation",value:function invalidOperation(message){return new _bluebird["default"]((function(resolve,reject){resolve(message)}))}}]);return ApiClient}();exports["default"]=ApiClient},{"../util":18,axios:41,bluebird:70,btoa:74,"form-data":146,loglevel:152}],4:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=exports.handleError=exports.ServiceNotFound=exports.DestinationAlreadyExists=exports.InvalidServiceCredentials=exports.WiotpError=void 0;function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(call&&(_typeof(call)==="object"||typeof call==="function")){return call}return _assertThisInitialized(self)}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function")}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:true,configurable:true}});if(superClass)_setPrototypeOf(subClass,superClass)}function _wrapNativeSuper(Class){var _cache=typeof Map==="function"?new Map:undefined;_wrapNativeSuper=function _wrapNativeSuper(Class){if(Class===null||!_isNativeFunction(Class))return Class;if(typeof Class!=="function"){throw new TypeError("Super expression must either be null or a function")}if(typeof _cache!=="undefined"){if(_cache.has(Class))return _cache.get(Class);_cache.set(Class,Wrapper)}function Wrapper(){return _construct(Class,arguments,_getPrototypeOf(this).constructor)}Wrapper.prototype=Object.create(Class.prototype,{constructor:{value:Wrapper,enumerable:false,writable:true,configurable:true}});return _setPrototypeOf(Wrapper,Class)};return _wrapNativeSuper(Class)}function isNativeReflectConstruct(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{Date.prototype.toString.call(Reflect.construct(Date,[],(function(){})));return true}catch(e){return false}}function _construct(Parent,args,Class){if(isNativeReflectConstruct()){_construct=Reflect.construct}else{_construct=function _construct(Parent,args,Class){var a=[null];a.push.apply(a,args);var Constructor=Function.bind.apply(Parent,a);var instance=new Constructor;if(Class)_setPrototypeOf(instance,Class.prototype);return instance}}return _construct.apply(null,arguments)}function _isNativeFunction(fn){return Function.toString.call(fn).indexOf("[native code]")!==-1}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o};return _setPrototypeOf(o,p)}function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o)};return _getPrototypeOf(o)}var WiotpError=function(_Error){_inherits(WiotpError,_Error);function WiotpError(message,cause){var _this;_classCallCheck(this,WiotpError);_this=_possibleConstructorReturn(this,_getPrototypeOf(WiotpError).call(this,message));_this.cause=cause;_this.name=_this.constructor.name;return _this}return WiotpError}(_wrapNativeSuper(Error));exports.WiotpError=WiotpError;var InvalidServiceCredentials=function(_WiotpError){_inherits(InvalidServiceCredentials,_WiotpError);function InvalidServiceCredentials(){_classCallCheck(this,InvalidServiceCredentials);return _possibleConstructorReturn(this,_getPrototypeOf(InvalidServiceCredentials).apply(this,arguments))}return InvalidServiceCredentials}(WiotpError);exports.InvalidServiceCredentials=InvalidServiceCredentials;var DestinationAlreadyExists=function(_WiotpError2){_inherits(DestinationAlreadyExists,_WiotpError2);function DestinationAlreadyExists(){_classCallCheck(this,DestinationAlreadyExists);return _possibleConstructorReturn(this,_getPrototypeOf(DestinationAlreadyExists).apply(this,arguments))}return DestinationAlreadyExists}(WiotpError);exports.DestinationAlreadyExists=DestinationAlreadyExists;var ServiceNotFound=function(_WiotpError3){_inherits(ServiceNotFound,_WiotpError3);function ServiceNotFound(){_classCallCheck(this,ServiceNotFound);return _possibleConstructorReturn(this,_getPrototypeOf(ServiceNotFound).apply(this,arguments))}return ServiceNotFound}(WiotpError);exports.ServiceNotFound=ServiceNotFound;var handleError=function handleError(err,errorMappings){if(err&&err.response&&err.response.data&&err.response.data.exception&&err.response.data.exception.id){if(errorMappings&&errorMappings[err.response.data.exception.id]){throw new errorMappings[err.response.data.exception.id](err.response.data.message,err)}else{throw new WiotpError(err.response.data.message,err)}}else{throw err}};exports.handleError=handleError;var _default={WiotpError:WiotpError,InvalidServiceCredentials:InvalidServiceCredentials,DestinationAlreadyExists:DestinationAlreadyExists,ServiceNotFound:ServiceNotFound};exports["default"]=_default},{}],5:[function(require,module,exports){"use strict";function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _loglevel=_interopRequireDefault(require("loglevel"));var errors=_interopRequireWildcard(require("./ApiErrors"));function _getRequireWildcardCache(){if(typeof WeakMap!=="function")return null;var cache=new WeakMap;_getRequireWildcardCache=function _getRequireWildcardCache(){return cache};return cache}function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}if(obj===null||_typeof(obj)!=="object"&&typeof obj!=="function"){return{default:obj}}var cache=_getRequireWildcardCache();if(cache&&cache.has(obj)){return cache.get(obj)}var newObj={};var hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;if(desc&&(desc.get||desc.set)){Object.defineProperty(newObj,key,desc)}else{newObj[key]=obj[key]}}}newObj["default"]=obj;if(cache){cache.set(obj,newObj)}return newObj}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}var DscClient=function(){function DscClient(apiClient){_classCallCheck(this,DscClient);this.log=_loglevel["default"];this.apiClient=apiClient}_createClass(DscClient,[{key:"createService",value:function createService(service){return this.apiClient.callApi("POST",201,true,["s2s","services"],service)["catch"]((function(err){return errors.handleError(err,{CUDSS0026E:errors.InvalidServiceCredentials})}))}},{key:"createCloudantService",value:function createCloudantService(_ref){var name=_ref.name,description=_ref.description,username=_ref.username,password=_ref.password,_ref$host=_ref.host,host=_ref$host===void 0?"".concat(username,".cloudant.com"):_ref$host,_ref$port=_ref.port,port=_ref$port===void 0?443:_ref$port,_ref$url=_ref.url,url=_ref$url===void 0?"https://".concat(username,":").concat(password,"@").concat(host):_ref$url,apikey=_ref.apikey,iam_apikey_name=_ref.iam_apikey_name,iam_apikey_description=_ref.iam_apikey_description,iam_role_crn=_ref.iam_role_crn,iam_serviceid_crn=_ref.iam_serviceid_crn;return this.createService({name:name,description:description,type:"cloudant",credentials:{username:username,password:password,host:host,port:port,url:url,apikey:apikey,iam_apikey_name:iam_apikey_name,iam_apikey_description:iam_apikey_description,iam_role_crn:iam_role_crn,iam_serviceid_crn:iam_serviceid_crn}})}},{key:"createEventstreamsService",value:function createEventstreamsService(_ref2){var name=_ref2.name,description=_ref2.description,api_key=_ref2.api_key,kafka_admin_url=_ref2.kafka_admin_url,kafka_brokers_sasl=_ref2.kafka_brokers_sasl,user=_ref2.user,password=_ref2.password,apikey=_ref2.apikey,iam_apikey_name=_ref2.iam_apikey_name,iam_apikey_description=_ref2.iam_apikey_description,iam_role_crn=_ref2.iam_role_crn,iam_serviceid_crn=_ref2.iam_serviceid_crn;return this.createService({name:name,description:description,type:"eventstreams",credentials:{api_key:api_key,kafka_admin_url:kafka_admin_url,kafka_brokers_sasl:kafka_brokers_sasl,user:user,password:password,apikey:apikey,iam_apikey_name:iam_apikey_name,iam_apikey_description:iam_apikey_description,iam_role_crn:iam_role_crn,iam_serviceid_crn:iam_serviceid_crn}})}},{key:"getService",value:function getService(serviceId){return this.apiClient.callApi("GET",200,true,["s2s","services",serviceId])["catch"]((function(err){return errors.handleError(err,{CUDSS0019E:errors.ServiceNotFound})}))}},{key:"getServices",value:function getServices(serviceType){return this.apiClient.callApi("GET",200,true,["s2s","services"],null,{bindingMode:"manual",serviceType:serviceType})["catch"]((function(err){return errors.handleError(err,{})}))}},{key:"deleteService",value:function deleteService(serviceId){return this.apiClient.callApi("DELETE",204,false,["s2s","services",serviceId])["catch"]((function(err){return errors.handleError(err,{})}))}},{key:"createConnector",value:function createConnector(_ref3){var name=_ref3.name,type=_ref3.type,_ref3$description=_ref3.description,description=_ref3$description===void 0?undefined:_ref3$description,serviceId=_ref3.serviceId,_ref3$timezone=_ref3.timezone,timezone=_ref3$timezone===void 0?"UTC":_ref3$timezone,_ref3$enabled=_ref3.enabled,enabled=_ref3$enabled===void 0?true:_ref3$enabled;return this.apiClient.callApi("POST",201,true,["historianconnectors"],{name:name,description:description,type:type,serviceId:serviceId,timezone:timezone,enabled:enabled})["catch"]((function(err){return errors.handleError(err,{})}))}},{key:"updateConnector",value:function updateConnector(_ref4){var id=_ref4.id,name=_ref4.name,description=_ref4.description,serviceId=_ref4.serviceId,type=_ref4.type,enabled=_ref4.enabled,timezone=_ref4.timezone;return this.apiClient.callApi("PUT",200,true,["historianconnectors",id],{id:id,name:name,description:description,serviceId:serviceId,type:type,enabled:enabled,timezone:timezone})["catch"]((function(err){return errors.handleError(err,{})}))}},{key:"getConnectors",value:function getConnectors(_ref5){var name=_ref5.name,serviceType=_ref5.serviceType,enabled=_ref5.enabled,serviceId=_ref5.serviceId;return this.apiClient.callApi("GET",200,true,["historianconnectors"],null,{name:name?name:undefined,type:serviceType?serviceType:undefined,enabled:enabled===undefined?undefined:enabled,serviceId:serviceId?serviceId:undefined})["catch"]((function(err){return errors.handleError(err,{})}))}},{key:"deleteConnector",value:function deleteConnector(connectorId){return this.apiClient.callApi("DELETE",204,false,["historianconnectors",connectorId])["catch"]((function(err){return errors.handleError(err,{})}))}},{key:"createDestination",value:function createDestination(connectorId,destination){return this.apiClient.callApi("POST",201,true,["historianconnectors",connectorId,"destinations"],destination)["catch"]((function(err){return errors.handleError(err,{CUDDSC0103E:errors.DestinationAlreadyExists})}))}},{key:"createCloudantDestination",value:function createCloudantDestination(connectorId,_ref6){var name=_ref6.name,bucketInterval=_ref6.bucketInterval;return this.createDestination(connectorId,{name:name,type:"cloudant",configuration:{bucketInterval:bucketInterval}})}},{key:"createEventstreamsDestination",value:function createEventstreamsDestination(connectorId,_ref7){var name=_ref7.name,_ref7$partitions=_ref7.partitions,partitions=_ref7$partitions===void 0?1:_ref7$partitions;return this.createDestination(connectorId,{name:name,type:"eventstreams",configuration:{partitions:partitions}})}},{key:"getDestinations",value:function getDestinations(connectorId){var params=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{name:undefined};var name=params.name;return this.apiClient.callApi("GET",200,true,["historianconnectors",connectorId,"destinations"],null,{name:name?name:undefined})["catch"]((function(err){return errors.handleError(err,{})}))}},{key:"deleteDestination",value:function deleteDestination(connectorId,destinationName){return this.apiClient.callApi("DELETE",[200,204],false,["historianconnectors",connectorId,"destinations",destinationName])["catch"]((function(err){return errors.handleError(err,{})}))}},{key:"createForwardingRule",value:function createForwardingRule(connectorId,forwardingrule){return this.apiClient.callApi("POST",201,true,["historianconnectors",connectorId,"forwardingrules"],forwardingrule)["catch"]((function(err){return errors.handleError(err,{})}))}},{key:"createEventForwardingRule",value:function createEventForwardingRule(connectorId,_ref8){var name=_ref8.name,destinationName=_ref8.destinationName,_ref8$deviceType=_ref8.deviceType,deviceType=_ref8$deviceType===void 0?"*":_ref8$deviceType,_ref8$eventId=_ref8.eventId,eventId=_ref8$eventId===void 0?"*":_ref8$eventId;return this.createForwardingRule(connectorId,{name:name,destinationName:destinationName,type:"event",selector:{deviceType:deviceType,eventId:eventId}})}},{key:"getForwardingRules",value:function getForwardingRules(connectorId){return this.apiClient.callApi("GET",200,true,["historianconnectors",connectorId,"forwardingrules"])["catch"]((function(err){return errors.handleError(err,{})}))}},{key:"deleteForwardingRule",value:function deleteForwardingRule(connectorId,forwardingRuleId){return this.apiClient.callApi("DELETE",204,false,["historianconnectors",connectorId,"forwardingrules",forwardingRuleId])["catch"]((function(err){return errors.handleError(err,{})}))}}]);return DscClient}();exports["default"]=DscClient},{"./ApiErrors":4,loglevel:152}],6:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _loglevel=_interopRequireDefault(require("loglevel"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}var LecClient=function(){function LecClient(apiClient){_classCallCheck(this,LecClient);this.log=_loglevel["default"];this.apiClient=apiClient;this.callApi=this.apiClient.callApi.bind(this.apiClient)}_createClass(LecClient,[{key:"getLastEvents",value:function getLastEvents(type,id){this.log.debug("[ApiClient] getLastEvents() - event cache");return this.callApi("GET",200,true,["device","types",type,"devices",id,"events"],null)}},{key:"getLastEventsByEventType",value:function getLastEventsByEventType(type,id,eventType){this.log.debug("[ApiClient] getLastEventsByEventType() - event cache");return this.callApi("GET",200,true,["device","types",type,"devices",id,"events",eventType],null)}}]);return LecClient}();exports["default"]=LecClient},{loglevel:152}],7:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _loglevel=_interopRequireDefault(require("loglevel"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}var MgmtClient=function(){function MgmtClient(apiClient){_classCallCheck(this,MgmtClient);this.log=_loglevel["default"];this.apiClient=apiClient;this.callApi=this.apiClient.callApi.bind(this.apiClient)}_createClass(MgmtClient,[{key:"getAllDeviceManagementRequests",value:function getAllDeviceManagementRequests(){this.log.debug("[ApiClient] getAllDeviceManagementRequests()");return this.callApi("GET",200,true,["mgmt","requests"],null)}},{key:"initiateDeviceManagementRequest",value:function initiateDeviceManagementRequest(action,parameters,devices){this.log.debug("[ApiClient] initiateDeviceManagementRequest("+action+", "+parameters+", "+devices+")");var body={action:action,parameters:parameters,devices:devices};return this.callApi("POST",202,true,["mgmt","requests"],JSON.stringify(body))}},{key:"getDeviceManagementRequest",value:function getDeviceManagementRequest(requestId){this.log.debug("[ApiClient] getDeviceManagementRequest("+requestId+")");return this.callApi("GET",200,true,["mgmt","requests",requestId],null)}},{key:"deleteDeviceManagementRequest",value:function deleteDeviceManagementRequest(requestId){this.log.debug("[ApiClient] deleteDeviceManagementRequest("+requestId+")");return this.callApi("DELETE",204,false,["mgmt","requests",requestId],null)}},{key:"getDeviceManagementRequestStatus",value:function getDeviceManagementRequestStatus(requestId){this.log.debug("[ApiClient] getDeviceManagementRequestStatus("+requestId+")");return this.callApi("GET",200,true,["mgmt","requests",requestId,"deviceStatus"],null)}},{key:"getDeviceManagementRequestStatusByDevice",value:function getDeviceManagementRequestStatusByDevice(requestId,typeId,deviceId){this.log.debug("[ApiClient] getDeviceManagementRequestStatusByDevice("+requestId+", "+typeId+", "+deviceId+")");return this.callApi("GET",200,true,["mgmt","requests",requestId,"deviceStatus",typeId,deviceId],null)}}]);return MgmtClient}();exports["default"]=MgmtClient},{loglevel:152}],8:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}var RegistryClient=function(){function RegistryClient(apiClient){_classCallCheck(this,RegistryClient);this.apiClient=apiClient}_createClass(RegistryClient,[{key:"listAllDevicesOfType",value:function listAllDevicesOfType(type){this.apiClient.log.debug("[ApiClient] listAllDevicesOfType("+type+")");return this.apiClient.callApi("GET",200,true,["device","types",type,"devices"],null)}},{key:"deleteDeviceType",value:function deleteDeviceType(type){this.apiClient.log.debug("[ApiClient] deleteDeviceType("+type+")");return this.apiClient.callApi("DELETE",204,false,["device","types",type],null)}},{key:"getDeviceType",value:function getDeviceType(type){this.apiClient.log.debug("[ApiClient] getDeviceType("+type+")");return this.apiClient.callApi("GET",200,true,["device","types",type],null)}},{key:"getAllDeviceTypes",value:function getAllDeviceTypes(){this.apiClient.log.debug("[ApiClient] getAllDeviceTypes()");return this.apiClient.callApi("GET",200,true,["device","types"],null)}},{key:"updateDeviceType",value:function updateDeviceType(type,description,deviceInfo,metadata){this.apiClient.log.debug("[ApiClient] updateDeviceType("+type+", "+description+", "+deviceInfo+", "+metadata+")");var body={deviceInfo:deviceInfo,description:description,metadata:metadata};return this.apiClient.callApi("PUT",200,true,["device","types",type],JSON.stringify(body))}},{key:"registerDeviceType",value:function registerDeviceType(typeId,description,deviceInfo,metadata,classId){this.apiClient.log.debug("[ApiClient] registerDeviceType("+typeId+", "+description+", "+deviceInfo+", "+metadata+", "+classId+")");classId=classId||"Device";var body={id:typeId,classId:classId,deviceInfo:deviceInfo,description:description,metadata:metadata};return this.apiClient.callApi("POST",201,true,["device","types"],JSON.stringify(body))}},{key:"registerDevice",value:function registerDevice(type,deviceId,authToken,deviceInfo,location,metadata){this.apiClient.log.debug("[ApiClient] registerDevice("+type+", "+deviceId+", "+deviceInfo+", "+location+", "+metadata+")");var body={deviceId:deviceId,authToken:authToken,deviceInfo:deviceInfo,location:location,metadata:metadata};return this.apiClient.callApi("POST",201,true,["device","types",type,"devices"],JSON.stringify(body))}},{key:"unregisterDevice",value:function unregisterDevice(type,deviceId){this.apiClient.log.debug("[ApiClient] unregisterDevice("+type+", "+deviceId+")");return this.apiClient.callApi("DELETE",204,false,["device","types",type,"devices",deviceId],null)}},{key:"updateDevice",value:function updateDevice(type,deviceId,deviceInfo,status,metadata,extensions){this.apiClient.log.debug("[ApiClient] updateDevice("+type+", "+deviceId+", "+deviceInfo+", "+status+", "+metadata+")");var body={deviceInfo:deviceInfo,status:status,metadata:metadata,extensions:extensions};return this.apiClient.callApi("PUT",200,true,["device","types",type,"devices",deviceId],JSON.stringify(body))}},{key:"getDevice",value:function getDevice(type,deviceId){this.apiClient.log.debug("[ApiClient] getDevice("+type+", "+deviceId+")");return this.apiClient.callApi("GET",200,true,["device","types",type,"devices",deviceId],null)}},{key:"registerMultipleDevices",value:function registerMultipleDevices(arryOfDevicesToBeAdded){this.apiClient.log.debug("[ApiClient] arryOfDevicesToBeAdded() - BULK");return this.apiClient.callApi("POST",201,true,["bulk","devices","add"],JSON.stringify(arryOfDevicesToBeAdded))}},{key:"deleteMultipleDevices",value:function deleteMultipleDevices(arryOfDevicesToBeDeleted){this.apiClient.log.debug("[ApiClient] deleteMultipleDevices() - BULK");return this.apiClient.callApi("POST",201,true,["bulk","devices","remove"],JSON.stringify(arryOfDevicesToBeDeleted))}},{key:"getDeviceLocation",value:function getDeviceLocation(type,deviceId){this.apiClient.log.debug("[ApiClient] getDeviceLocation("+type+", "+deviceId+")");return this.apiClient.callApi("GET",200,true,["device","types",type,"devices",deviceId,"location"],null)}},{key:"updateDeviceLocation",value:function updateDeviceLocation(type,deviceId,location){this.apiClient.log.debug("[ApiClient] updateDeviceLocation("+type+", "+deviceId+", "+location+")");return this.apiClient.callApi("PUT",200,true,["device","types",type,"devices",deviceId,"location"],JSON.stringify(location))}},{key:"getDeviceManagementInformation",value:function getDeviceManagementInformation(type,deviceId){this.apiClient.log.debug("[ApiClient] getDeviceManagementInformation("+type+", "+deviceId+")");return this.apiClient.callApi("GET",200,true,["device","types",type,"devices",deviceId,"mgmt"],null)}},{key:"getAllDiagnosticLogs",value:function getAllDiagnosticLogs(type,deviceId){this.apiClient.log.debug("[ApiClient] getAllDiagnosticLogs("+type+", "+deviceId+")");return this.apiClient.callApi("GET",200,true,["device","types",type,"devices",deviceId,"diag","logs"],null)}},{key:"clearAllDiagnosticLogs",value:function clearAllDiagnosticLogs(type,deviceId){this.apiClient.log.debug("[ApiClient] clearAllDiagnosticLogs("+type+", "+deviceId+")");return this.apiClient.callApi("DELETE",204,false,["device","types",type,"devices",deviceId,"diag","logs"],null)}},{key:"addDeviceDiagLogs",value:function addDeviceDiagLogs(type,deviceId,log){this.apiClient.log.debug("[ApiClient] addDeviceDiagLogs("+type+", "+deviceId+", "+log+")");return this.apiClient.callApi("POST",201,false,["device","types",type,"devices",deviceId,"diag","logs"],JSON.stringify(log))}},{key:"getDiagnosticLog",value:function getDiagnosticLog(type,deviceId,logId){this.apiClient.log.debug("[ApiClient] getAllDiagnosticLogs("+type+", "+deviceId+", "+logId+")");return this.apiClient.callApi("GET",200,true,["device","types",type,"devices",deviceId,"diag","logs",logId],null)}},{key:"deleteDiagnosticLog",value:function deleteDiagnosticLog(type,deviceId,logId){this.apiClient.log.debug("[ApiClient] deleteDiagnosticLog("+type+", "+deviceId+", "+logId+")");return this.apiClient.callApi("DELETE",204,false,["device","types",type,"devices",deviceId,"diag","logs",logId],null)}},{key:"getDeviceErrorCodes",value:function getDeviceErrorCodes(type,deviceId){this.apiClient.log.debug("[ApiClient] getDeviceErrorCodes("+type+", "+deviceId+")");return this.apiClient.callApi("GET",200,true,["device","types",type,"devices",deviceId,"diag","errorCodes"],null)}},{key:"clearDeviceErrorCodes",value:function clearDeviceErrorCodes(type,deviceId){this.apiClient.log.debug("[ApiClient] clearDeviceErrorCodes("+type+", "+deviceId+")");return this.apiClient.callApi("DELETE",204,false,["device","types",type,"devices",deviceId,"diag","errorCodes"],null)}},{key:"addErrorCode",value:function addErrorCode(type,deviceId,log){this.apiClient.log.debug("[ApiClient] addErrorCode("+type+", "+deviceId+", "+log+")");return this.apiClient.callApi("POST",201,false,["device","types",type,"devices",deviceId,"diag","errorCodes"],JSON.stringify(log))}},{key:"getDeviceConnectionLogs",value:function getDeviceConnectionLogs(typeId,deviceId){this.apiClient.log.debug("[ApiClient] getDeviceConnectionLogs("+typeId+", "+deviceId+")");var params={typeId:typeId,deviceId:deviceId};return this.apiClient.callApi("GET",200,true,["logs","connection"],null,params)}}]);return RegistryClient}();exports["default"]=RegistryClient},{}],9:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _loglevel=_interopRequireDefault(require("loglevel"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}var RulesClient=function(){function RulesClient(apiClient){_classCallCheck(this,RulesClient);this.log=_loglevel["default"];this.apiClient=apiClient;this.callApi=this.apiClient.callApi.bind(this.apiClient)}_createClass(RulesClient,[{key:"getRulesForLogicalInterface",value:function getRulesForLogicalInterface(logicalInterfaceId){if(this.draftMode){return this.getRulesForLogicalInterface(logicalInterfaceId)}else{return this.getActiveRulesForLogicalInterface(logicalInterfaceId)}}},{key:"getDraftRulesForLogicalInterface",value:function getDraftRulesForLogicalInterface(logicalInterfaceId){return this.callApi("GET",200,true,["draft","logicalinterfaces",logicalInterfaceId,"rules"])}},{key:"getActiveRulesForLogicalInterface",value:function getActiveRulesForLogicalInterface(logicalInterfaceId){return this.callApi("GET",200,true,["logicalinterfaces",logicalInterfaceId,"rules"])}},{key:"createRule",value:function createRule(logicalInterfaceId,name,condition){var description=arguments.length>3&&arguments[3]!==undefined?arguments[3]:undefined;var notificationStrategy=arguments.length>4&&arguments[4]!==undefined?arguments[4]:RulesClient.RuleNotificationStrategy.EVERY_TIME();var body={name:name,condition:condition,notificationStrategy:notificationStrategy};if(description)body["description"]=description;var base=this.draftMode?["draft","logicalinterfaces",logicalInterfaceId,"rules"]:["logicalinterfaces",logicalInterfaceId,"rules"];return this.callApi("POST",201,true,base,JSON.stringify(body))}},{key:"updateRule",value:function updateRule(rule){var base=this.draftMode?["draft","logicalinterfaces",rule.logicalInterfaceId,"rules",rule.id]:["logicalinterfaces",rule.logicalInterfaceId,"rules",rule.id];return this.callApi("PUT",200,true,base,JSON.stringify(rule))}},{key:"deleteRule",value:function deleteRule(logicalInterfaceId,ruleId){var base=this.draftMode?["draft","logicalinterfaces",logicalInterfaceId,"rules",ruleId]:["logicalinterfaces",logicalInterfaceId,"rules",ruleId];return this.callApi("DELETE",204,false,base)}}]);return RulesClient}();exports["default"]=RulesClient;RulesClient.RuleNotificationStrategy={EVERY_TIME:function EVERY_TIME(){return{when:"every-time"}},BECOMES_TRUE:function BECOMES_TRUE(){return{when:"becomes-true"}},X_IN_Y:function X_IN_Y(count){return{when:"x-in-y",count:count}},PERSISTS:function PERSISTS(count,timePeriod){return{when:"persists",count:count,timePeriod:timePeriod}}}},{loglevel:152}],10:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _loglevel=_interopRequireDefault(require("loglevel"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}var StateClient=function(){function StateClient(apiClient){_classCallCheck(this,StateClient);this.log=_loglevel["default"];this.apiClient=apiClient;this.draftMode=true;this.callApi=this.apiClient.callApi.bind(this.apiClient);this.parseSortSpec=this.apiClient.parseSortSpec.bind(this.apiClient);this.callFormDataApi=this.apiClient.callFormDataApi.bind(this.apiClient);this.invalidOperation=this.apiClient.invalidOperation.bind(this.apiClient)}_createClass(StateClient,[{key:"workWithActive",value:function workWithActive(){this.draftMode=false}},{key:"workWithDraft",value:function workWithDraft(){this.draftMode=true}},{key:"createSchema",value:function createSchema(schemaContents,name,description){var body={schemaFile:schemaContents,schemaType:"json-schema",name:name};if(description){body.description=description}var base=this.draftMode?["draft","schemas"]:["schemas"];return this.callFormDataApi("POST",201,true,base,body,null)}},{key:"getSchema",value:function getSchema(schemaId){var base=this.draftMode?["draft","schemas",schemaId]:["schemas",schemaId];return this.callApi("GET",200,true,base)}},{key:"getActiveSchema",value:function getActiveSchema(schemaId){return this.callApi("GET",200,true,["schemas",schemaId])}},{key:"getSchemas",value:function getSchemas(){var base=this.draftMode?["draft","schemas"]:["schemas"];return this.callApi("GET",200,true,base)}},{key:"getActiveSchemas",value:function getActiveSchemas(){return this.callApi("GET",200,true,["schemas"])}},{key:"updateSchema",value:function updateSchema(schemaId,name,description){var body={id:schemaId,name:name,description:description};var base=this.draftMode?["draft","schemas",schemaId]:["schemas",schemaId];return this.callApi("PUT",200,true,base,body)}},{key:"updateSchemaContent",value:function updateSchemaContent(schemaId,schemaContents,filename){var body={schemaFile:schemaContents,name:filename};var base=this.draftMode?["draft","schemas",schemaId,"content"]:["schemas",schemaId,"content"];return this.callFormDataApi("PUT",204,false,base,body,null)}},{key:"getSchemaContent",value:function getSchemaContent(schemaId){var base=this.draftMode?["draft","schemas",schemaId,"content"]:["schemas",schemaId,"content"];return this.callApi("GET",200,true,base)}},{key:"getActiveSchemaContent",value:function getActiveSchemaContent(schemaId){return this.callApi("GET",200,true,["schemas",schemaId,"content"])}},{key:"deleteSchema",value:function deleteSchema(schemaId){var base=this.draftMode?["draft","schemas",schemaId]:["schemas",schemaId];return this.callApi("DELETE",204,false,base,null)}},{key:"createEventType",value:function createEventType(name,description,schemaId){var body={name:name,description:description,schemaId:schemaId};var base=this.draftMode?["draft","event","types"]:["event","types"];return this.callApi("POST",201,true,base,JSON.stringify(body))}},{key:"getEventType",value:function getEventType(eventTypeId){var base=this.draftMode?["draft","event","types",eventTypeId]:["event","types",eventTypeId];return this.callApi("GET",200,true,base)}},{key:"getActiveEventType",value:function getActiveEventType(eventTypeId){return this.callApi("GET",200,true,["event","types",eventTypeId])}},{key:"deleteEventType",value:function deleteEventType(eventTypeId){var base=this.draftMode?["draft","event","types",eventTypeId]:["event","types",eventTypeId];return this.callApi("DELETE",204,false,base)}},{key:"updateEventType",value:function updateEventType(eventTypeId,name,description,schemaId){var body={id:eventTypeId,name:name,description:description,schemaId:schemaId};var base=this.draftMode?["draft","event","types",eventTypeId]:["event","types",eventTypeId];return this.callApi("PUT",200,true,base,body)}},{key:"getEventTypes",value:function getEventTypes(){var base=this.draftMode?["draft","event","types"]:["event","types"];return this.callApi("GET",200,true,base)}},{key:"getActiveEventTypes",value:function getActiveEventTypes(){return this.callApi("GET",200,true,["event","types"])}},{key:"createPhysicalInterface",value:function createPhysicalInterface(name,description){var body={name:name,description:description};var base=this.draftMode?["draft","physicalinterfaces"]:["physicalinterfaces"];return this.callApi("POST",201,true,base,body)}},{key:"getPhysicalInterface",value:function getPhysicalInterface(physicalInterfaceId){var base=this.draftMode?["draft","physicalinterfaces",physicalInterfaceId]:["physicalinterfaces",physicalInterfaceId];return this.callApi("GET",200,true,base)}},{key:"getActivePhysicalInterface",value:function getActivePhysicalInterface(physicalInterfaceId){return this.callApi("GET",200,true,["physicalinterfaces",physicalInterfaceId])}},{key:"deletePhysicalInterface",value:function deletePhysicalInterface(physicalInterfaceId){var base=this.draftMode?["draft","physicalinterfaces",physicalInterfaceId]:["physicalinterfaces",physicalInterfaceId];return this.callApi("DELETE",204,false,base)}},{key:"updatePhysicalInterface",value:function updatePhysicalInterface(physicalInterfaceId,name,description){var body={id:physicalInterfaceId,name:name,description:description};var base=this.draftMode?["draft","physicalinterfaces",physicalInterfaceId]:["physicalinterfaces",physicalInterfaceId];return this.callApi("PUT",200,true,base,body)}},{key:"getPhysicalInterfaces",value:function getPhysicalInterfaces(){var base=this.draftMode?["draft","physicalinterfaces"]:["physicalinterfaces"];return this.callApi("GET",200,true,base)}},{key:"getActivePhysicalInterfaces",value:function getActivePhysicalInterfaces(){return this.callApi("GET",200,true,["physicalinterfaces"])}},{key:"createPhysicalInterfaceEventMapping",value:function createPhysicalInterfaceEventMapping(physicalInterfaceId,eventId,eventTypeId){var body={eventId:eventId,eventTypeId:eventTypeId};var base=this.draftMode?["draft","physicalinterfaces",physicalInterfaceId,"events"]:["physicalinterfaces",physicalInterfaceId,"events"];return this.callApi("POST",201,true,base,body)}},{key:"getPhysicalInterfaceEventMappings",value:function getPhysicalInterfaceEventMappings(physicalInterfaceId){var base=this.draftMode?["draft","physicalinterfaces",physicalInterfaceId,"events"]:["physicalinterfaces",physicalInterfaceId,"events"];return this.callApi("GET",200,true,base)}},{key:"getActivePhysicalInterfaceEventMappings",value:function getActivePhysicalInterfaceEventMappings(physicalInterfaceId){return this.callApi("GET",200,true,["physicalinterfaces",physicalInterfaceId,"events"])}},{key:"deletePhysicalInterfaceEventMapping",value:function deletePhysicalInterfaceEventMapping(physicalInterfaceId,eventId){var base=this.draftMode?["draft","physicalinterfaces",physicalInterfaceId,"events",eventId]:["physicalinterfaces",physicalInterfaceId,"events",eventId];return this.callApi("DELETE",204,false,base)}},{key:"createLogicalInterface",value:function createLogicalInterface(name,description,schemaId,alias){var body={name:name,description:description,schemaId:schemaId};if(alias!==undefined){body.alias=alias}var base=this.draftMode?["draft","logicalinterfaces"]:["applicationinterfaces"];return this.callApi("POST",201,true,base,body)}},{key:"getLogicalInterface",value:function getLogicalInterface(logicalInterfaceId){var base=this.draftMode?["draft","logicalinterfaces",logicalInterfaceId]:["applicationinterfaces",logicalInterfaceId];return this.callApi("GET",200,true,base)}},{key:"getActiveLogicalInterface",value:function getActiveLogicalInterface(logicalInterfaceId){return this.callApi("GET",200,true,["logicalinterfaces",logicalInterfaceId])}},{key:"deleteLogicalInterface",value:function deleteLogicalInterface(logicalInterfaceId){var base=this.draftMode?["draft","logicalinterfaces",logicalInterfaceId]:["applicationinterfaces",logicalInterfaceId];return this.callApi("DELETE",204,false,base)}},{key:"updateLogicalInterface",value:function updateLogicalInterface(logicalInterfaceId,name,description,schemaId,alias){var body={id:logicalInterfaceId,name:name,description:description,schemaId:schemaId};if(alias!==undefined){body.alias=alias}var base=this.draftMode?["draft","logicalinterfaces",logicalInterfaceId]:["applicationinterfaces",logicalInterfaceId];return this.callApi("PUT",200,true,base,body)}},{key:"getLogicalInterfaces",value:function getLogicalInterfaces(bookmark,limit,sort,name){var base=this.draftMode?["draft","logicalinterfaces"]:["logicalinterfaces"];var _sort=this.parseSortSpec(sort);return this.callApi("GET",200,true,base,undefined,{_bookmark:bookmark,_limit:limit,_sort:_sort,name:name?name:undefined})}},{key:"getActiveLogicalInterfaces",value:function getActiveLogicalInterfaces(){return this.callApi("GET",200,true,["logicalinterfaces"])}},{key:"patchOperationLogicalInterface",value:function patchOperationLogicalInterface(logicalInterfaceId,operationId){var body={operation:operationId};if(this.draftMode){switch(operationId){case"validate-configuration":return this.callApi("PATCH",200,true,["draft","logicalinterfaces",logicalInterfaceId],body);case"activate-configuration":return this.callApi("PATCH",202,true,["draft","logicalinterfaces",logicalInterfaceId],body);case"deactivate-configuration":return this.callApi("PATCH",202,true,["draft","logicalinterfaces",logicalInterfaceId],body);case"list-differences":return this.callApi("PATCH",200,true,["draft","logicalinterfaces",logicalInterfaceId],body);default:return this.callApi("PATCH",200,true,["draft","logicalinterfaces",logicalInterfaceId],body)}}else{return this.invalidOperation("PATCH operation not allowed on active logical interface")}}},{key:"patchOperationActiveLogicalInterface",value:function patchOperationActiveLogicalInterface(logicalInterfaceId,operationId){var body={operation:operationId};if(this.draftMode){return this.callApi("PATCH",202,true,["logicalinterfaces",logicalInterfaceId],body)}else{return this.invalidOperation("PATCH operation 'deactivate-configuration' not allowed on logical interface")}}},{key:"patchOperationDeviceType",value:function patchOperationDeviceType(deviceTypeId,operationId){var body={operation:operationId};if(this.draftMode){switch(operationId){case"validate-configuration":return this.callApi("PATCH",200,true,["draft","device","types",deviceTypeId],body);case"activate-configuration":return this.callApi("PATCH",202,true,["draft","device","types",deviceTypeId],body);case"deactivate-configuration":return this.callApi("PATCH",202,true,["draft","device","types",deviceTypeId],body);case"list-differences":return this.callApi("PATCH",200,true,["draft","device","types",deviceTypeId],body);default:return this.callApi("PATCH",200,true,["draft","device","types",deviceTypeId],body)}}else{return this.invalidOperation("this method cannot be called when draftMode=false")}}},{key:"createDeviceType",value:function createDeviceType(typeId,description,deviceInfo,metadata,classId,physicalInterfaceId){this.log.debug("[ApiClient] registerDeviceType("+typeId+", "+description+", "+deviceInfo+", "+metadata+", "+classId+", "+physicalInterfaceId+")");classId=classId||"Device";var body={id:typeId,classId:classId,deviceInfo:deviceInfo,description:description,metadata:metadata,physicalInterfaceId:physicalInterfaceId};return this.callApi("POST",201,true,["device","types"],JSON.stringify(body))}},{key:"getDeviceTypesByLogicalInterfaceId",value:function getDeviceTypesByLogicalInterfaceId(logicalInterfaceId){var bookmark=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var limit=arguments.length>2&&arguments[2]!==undefined?arguments[2]:10;if(this.draftMode){return this.callApi("GET",200,true,["draft","device","types"],null,{logicalInterfaceId:logicalInterfaceId,_bookmark:bookmark,_limit:limit})}else{return this.callApi("GET",200,true,["device","types"],null,{_bookmark:bookmark,_limit:limit})}}},{key:"createDeviceTypePhysicalInterfaceAssociation",value:function createDeviceTypePhysicalInterfaceAssociation(typeId,physicalInterfaceId){var body={id:physicalInterfaceId};if(this.draftMode){return this.callApi("POST",201,true,["draft","device","types",typeId,"physicalinterface"],JSON.stringify(body))}else{return this.callApi("PUT",200,true,["device","types",typeId],JSON.stringify({physicalInterfaceId:physicalInterfaceId}))}}},{key:"getDeviceTypePhysicalInterfaces",value:function getDeviceTypePhysicalInterfaces(typeId){if(this.draftMode){return this.callApi("GET",200,true,["draft","device","types",typeId,"physicalinterface"])}else{return this.invalidOperation("GET Device type's physical interface is not allowed")}}},{key:"getActiveDeviceTypePhysicalInterfaces",value:function getActiveDeviceTypePhysicalInterfaces(typeId){return this.callApi("GET",200,true,["device","types",typeId,"physicalinterface"])}},{key:"deleteDeviceTypePhysicalInterfaceAssociation",value:function deleteDeviceTypePhysicalInterfaceAssociation(typeId){if(this.draftMode){return this.callApi("DELETE",204,false,["draft","device","types",typeId,"physicalinterface"])}else{return this.invalidOperation("DELETE Device type's physical interface is not allowed")}}},{key:"createDeviceTypeLogicalInterfaceAssociation",value:function createDeviceTypeLogicalInterfaceAssociation(typeId,logicalInterfaceId){var body={id:logicalInterfaceId};var base=this.draftMode?["draft","device","types",typeId,"logicalinterfaces"]:["device","types",typeId,"applicationinterfaces"];return this.callApi("POST",201,true,base,body)}},{key:"getDeviceTypeLogicalInterfaces",value:function getDeviceTypeLogicalInterfaces(typeId){var base=this.draftMode?["draft","device","types",typeId,"logicalinterfaces"]:["device","types",typeId,"applicationinterfaces"];return this.callApi("GET",200,true,base)}},{key:"getActiveDeviceTypeLogicalInterfaces",value:function getActiveDeviceTypeLogicalInterfaces(typeId){return this.callApi("GET",200,true,["device","types",typeId,"logicalinterfaces"])}},{key:"createDeviceTypeLogicalInterfacePropertyMappings",value:function createDeviceTypeLogicalInterfacePropertyMappings(typeId,logicalInterfaceId,mappings,notificationStrategy){var body=null,base=null;if(this.draftMode){body={logicalInterfaceId:logicalInterfaceId,propertyMappings:mappings,notificationStrategy:"never"};if(notificationStrategy){body.notificationStrategy=notificationStrategy}base=["draft","device","types",typeId,"mappings"]}else{body={applicationInterfaceId:logicalInterfaceId,propertyMappings:mappings};base=["device","types",typeId,"mappings"]}return this.callApi("POST",201,true,base,body)}},{key:"getDeviceTypePropertyMappings",value:function getDeviceTypePropertyMappings(typeId){var base=this.draftMode?["draft","device","types",typeId,"mappings"]:["device","types",typeId,"mappings"];return this.callApi("GET",200,true,base)}},{key:"getActiveDeviceTypePropertyMappings",value:function getActiveDeviceTypePropertyMappings(typeId){return this.callApi("GET",200,true,["device","types",typeId,"mappings"])}},{key:"getDeviceTypeLogicalInterfacePropertyMappings",value:function getDeviceTypeLogicalInterfacePropertyMappings(typeId,logicalInterfaceId){var base=this.draftMode?["draft","device","types",typeId,"mappings",logicalInterfaceId]:["device","types",typeId,"mappings",logicalInterfaceId];return this.callApi("GET",200,true,base)}},{key:"getActiveDeviceTypeLogicalInterfacePropertyMappings",value:function getActiveDeviceTypeLogicalInterfacePropertyMappings(typeId,logicalInterfaceId){return this.callApi("GET",200,true,["device","types",typeId,"mappings",logicalInterfaceId])}},{key:"updateDeviceTypeLogicalInterfacePropertyMappings",value:function updateDeviceTypeLogicalInterfacePropertyMappings(typeId,logicalInterfaceId,mappings,notificationStrategy){var body=null,base=null;if(this.draftMode){body={logicalInterfaceId:logicalInterfaceId,propertyMappings:mappings,notificationStrategy:"never"};if(notificationStrategy){body.notificationStrategy=notificationStrategy}base=["draft","device","types",typeId,"mappings",logicalInterfaceId]}else{body={applicationInterfaceId:logicalInterfaceId,propertyMappings:mappings};base=["device","types",typeId,"mappings",logicalInterfaceId]}return this.callApi("PUT",200,false,base,body)}},{key:"deleteDeviceTypeLogicalInterfacePropertyMappings",value:function deleteDeviceTypeLogicalInterfacePropertyMappings(typeId,logicalInterfaceId){var base=this.draftMode?["draft","device","types",typeId,"mappings",logicalInterfaceId]:["device","types",typeId,"mappings",logicalInterfaceId];return this.callApi("DELETE",204,false,base)}},{key:"deleteDeviceTypeLogicalInterfaceAssociation",value:function deleteDeviceTypeLogicalInterfaceAssociation(typeId,logicalInterfaceId){var base=this.draftMode?["draft","device","types",typeId,"logicalinterfaces",logicalInterfaceId]:["device","types",typeId,"applicationinterfaces",logicalInterfaceId];return this.callApi("DELETE",204,false,base)}},{key:"patchOperationDeviceType",value:function patchOperationDeviceType(typeId,operationId){if(!operationId){return invalidOperation("PATCH operation is not allowed. Operation id is expected")}var body={operation:operationId};var base=this.draftMode?["draft","device","types",typeId]:["device","types",typeId];if(this.draftMode){switch(operationId){case"validate-configuration":return this.callApi("PATCH",200,true,base,body);break;case"activate-configuration":return this.callApi("PATCH",202,true,base,body);break;case"deactivate-configuration":return this.callApi("PATCH",202,true,base,body);break;case"list-differences":return this.callApi("PATCH",200,true,base,body);break;default:return this.invalidOperation("PATCH operation is not allowed. Invalid operation id")}}else{switch(operationId){case"validate-configuration":return this.callApi("PATCH",200,true,base,body);break;case"deploy-configuration":return this.callApi("PATCH",202,true,base,body);break;case"remove-deployed-configuration":return this.callApi("PATCH",202,true,base,body);break;case"list-differences":return this.invalidOperation("PATCH operation 'list-differences' is not allowed");break;default:return this.invalidOperation("PATCH operation is not allowed. Invalid operation id")}}}},{key:"patchOperationActiveDeviceType",value:function patchOperationActiveDeviceType(typeId,operationId){var body={operation:operationId};if(this.draftMode){return this.callApi("PATCH",202,true,["device","types",typeId],body)}else{return this.invalidOperation("PATCH operation 'deactivate-configuration' is not allowed")}}},{key:"getDeviceTypeDeployedConfiguration",value:function getDeviceTypeDeployedConfiguration(typeId){if(this.draftMode){return this.invalidOperation("GET deployed configuration is not allowed")}else{return this.callApi("GET",200,true,["device","types",typeId,"deployedconfiguration"])}}},{key:"getDeviceState",value:function getDeviceState(typeId,deviceId,logicalInterfaceId){return this.callApi("GET",200,true,["device","types",typeId,"devices",deviceId,"state",logicalInterfaceId])}},{key:"createSchemaAndEventType",value:function createSchemaAndEventType(schemaContents,schemaFileName,eventTypeName,eventDescription){var _this=this;var body={schemaFile:schemaContents,schemaType:"json-schema",name:schemaFileName};var createSchema=new Promise((function(resolve,reject){var base=_this.draftMode?["draft","schemas"]:["schemas"];_this.callFormDataApi("POST",201,true,base,body,null).then((function(result){resolve(result)}),(function(error){reject(error)}))}));return createSchema.then((function(value){var schemaId=value["id"];return _this.createEventType(eventTypeName,eventDescription,schemaId)}))}},{key:"createSchemaAndLogicalInterface",value:function createSchemaAndLogicalInterface(schemaContents,schemaFileName,appInterfaceName,appInterfaceDescription,appInterfaceAlias){var _this2=this;var body={schemaFile:schemaContents,schemaType:"json-schema",name:schemaFileName};var createSchema=new Promise((function(resolve,reject){var base=_this2.draftMode?["draft","schemas"]:["schemas"];_this2.callFormDataApi("POST",201,true,base,body,null).then((function(result){resolve(result)}),(function(error){reject(error)}))}));return createSchema.then((function(value){var schemaId=value.id;return _this2.createLogicalInterface(appInterfaceName,appInterfaceDescription,schemaId,appInterfaceAlias)}))}},{key:"createPhysicalInterfaceWithEventMapping",value:function createPhysicalInterfaceWithEventMapping(physicalInterfaceName,description,eventId,eventTypeId){var _this3=this;var createPhysicalInterface=new Promise((function(resolve,reject){_this3.createPhysicalInterface(physicalInterfaceName,description).then((function(result){resolve(result)}),(function(error){reject(error)}))}));return createPhysicalInterface.then((function(value){var physicalInterface=value;var PhysicalInterfaceEventMapping=new Promise((function(resolve,reject){_this3.createPhysicalInterfaceEventMapping(physicalInterface.id,eventId,eventTypeId).then((function(result){resolve([physicalInterface,result])}),(function(error){reject(error)}))}));return PhysicalInterfaceEventMapping.then((function(result){return result}))}))}},{key:"createDeviceTypeLogicalInterfaceEventMapping",value:function createDeviceTypeLogicalInterfaceEventMapping(deviceTypeName,description,logicalInterfaceId,eventMapping,notificationStrategy){var _this4=this;var createDeviceType=new Promise((function(resolve,reject){_this4.createDeviceType(deviceTypeName,description).then((function(result){resolve(result)}),(function(error){reject(error)}))}));return createDeviceType.then((function(result){var deviceObject=result;var deviceTypeLogicalInterface=null;var deviceTypeLogicalInterface=new Promise((function(resolve,reject){_this4.createDeviceTypeLogicalInterfaceAssociation(deviceObject.id,logicalInterfaceId).then((function(result){resolve(result)}),(function(error){reject(error)}))}));return deviceTypeLogicalInterface.then((function(result){deviceTypeLogicalInterface=result;var deviceTypeLogicalInterfacePropertyMappings=new Promise((function(resolve,reject){var notificationstrategy="never";if(notificationStrategy){notificationstrategy=notificationStrategy}_this4.createDeviceTypeLogicalInterfacePropertyMappings(deviceObject.id,logicalInterfaceId,eventMapping,notificationstrategy).then((function(result){var arr=[deviceObject,deviceTypeLogicalInterface,result];resolve(arr)}),(function(error){reject(error)}))}));return deviceTypeLogicalInterfacePropertyMappings.then((function(result){return result}))}))}))}}]);return StateClient}();exports["default"]=StateClient},{loglevel:152}],11:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _util=require("../util");var _BaseClient2=_interopRequireDefault(require("../BaseClient"));var _ApiClient=_interopRequireDefault(require("../api/ApiClient"));var _RegistryClient=_interopRequireDefault(require("../api/RegistryClient"));var _MgmtClient=_interopRequireDefault(require("../api/MgmtClient"));var _LecClient=_interopRequireDefault(require("../api/LecClient"));var _DscClient=_interopRequireDefault(require("../api/DscClient"));var _RulesClient=_interopRequireDefault(require("../api/RulesClient"));var _StateClient=_interopRequireDefault(require("../api/StateClient"));var _ApplicationConfig=_interopRequireDefault(require("./ApplicationConfig"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}function _possibleConstructorReturn(self,call){if(call&&(_typeof(call)==="object"||typeof call==="function")){return call}return _assertThisInitialized(self)}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return self}function _get(target,property,receiver){if(typeof Reflect!=="undefined"&&Reflect.get){_get=Reflect.get}else{_get=function _get(target,property,receiver){var base=_superPropBase(target,property);if(!base)return;var desc=Object.getOwnPropertyDescriptor(base,property);if(desc.get){return desc.get.call(receiver)}return desc.value}}return _get(target,property,receiver||target)}function _superPropBase(object,property){while(!Object.prototype.hasOwnProperty.call(object,property)){object=_getPrototypeOf(object);if(object===null)break}return object}function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o)};return _getPrototypeOf(o)}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function")}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:true,configurable:true}});if(superClass)_setPrototypeOf(subClass,superClass)}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o};return _setPrototypeOf(o,p)}var DEVICE_EVT_RE=/^iot-2\/type\/(.+)\/id\/(.+)\/evt\/(.+)\/fmt\/(.+)$/;var DEVICE_CMD_RE=/^iot-2\/type\/(.+)\/id\/(.+)\/cmd\/(.+)\/fmt\/(.+)$/;var DEVICE_STATE_RE=/^iot-2\/type\/(.+)\/id\/(.+)\/intf\/(.+)\/evt\/state$/;var DEVICE_STATE_ERROR_RE=/^iot-2\/type\/(.+)\/id\/(.+)\/err\/data$/;var RULE_TRIGGER_RE=/^iot-2\/intf\/(.+)\/rule\/(.+)\/evt\/trigger$/;var RULE_ERROR_RE=/^iot-2\/intf\/(.+)\/rule\/(.+)\/err\/data$/;var DEVICE_MON_RE=/^iot-2\/type\/(.+)\/id\/(.+)\/mon$/;var APP_MON_RE=/^iot-2\/app\/(.+)\/mon$/;var ApplicationClient=function(_BaseClient){_inherits(ApplicationClient,_BaseClient);function ApplicationClient(config){var _this;_classCallCheck(this,ApplicationClient);if(!config instanceof _ApplicationConfig["default"]){throw new Error("Config must be an instance of ApplicationConfig")}_this=_possibleConstructorReturn(this,_getPrototypeOf(ApplicationClient).call(this,config));_this.useLtpa=config.auth&&config.auth.useLtpa;if(config.auth&&config.auth.useLtpa||config.getOrgId()!="quickstart"){_this._apiClient=new _ApiClient["default"](_this.config);_this.dsc=new _DscClient["default"](_this._apiClient);_this.lec=new _LecClient["default"](_this._apiClient);_this.mgmt=new _MgmtClient["default"](_this._apiClient);_this.registry=new _RegistryClient["default"](_this._apiClient);_this.rules=new _RulesClient["default"](_this._apiClient);_this.state=new _StateClient["default"](_this._apiClient)}_this.log.debug("[ApplicationClient:constructor] ApplicationClient initialized for organization : "+config.getOrgId());return _this}_createClass(ApplicationClient,[{key:"connect",value:function connect(){var _this2=this;_get(_getPrototypeOf(ApplicationClient.prototype),"connect",this).call(this);this.mqtt.on("message",(function(topic,payload){_this2.log.trace("[ApplicationClient:onMessage] mqtt: ",topic,payload.toString());var match=DEVICE_EVT_RE.exec(topic);if(match){_this2.emit("deviceEvent",match[1],match[2],match[3],match[4],payload,topic);return}var match=DEVICE_CMD_RE.exec(topic);if(match){_this2.emit("deviceCommand",match[1],match[2],match[3],match[4],payload,topic);return}var match=DEVICE_STATE_RE.exec(topic);if(match){_this2.emit("deviceState",match[1],match[2],match[3],payload,topic);return}var match=DEVICE_STATE_ERROR_RE.exec(topic);if(match){_this2.emit("deviceStateError",match[1],match[2],payload,topic);return}var match=RULE_TRIGGER_RE.exec(topic);if(match){_this2.emit("ruleTrigger",match[1],match[2],payload,topic);return}var match=RULE_ERROR_RE.exec(topic);if(match){_this2.emit("ruleError",match[1],match[2],payload,topic);return}var match=DEVICE_MON_RE.exec(topic);if(match){_this2.emit("deviceStatus",match[1],match[2],payload,topic);return}var match=APP_MON_RE.exec(topic);if(match){_this2.emit("appStatus",match[1],payload,topic);return}_this2.log.warn("[ApplicationClient:onMessage] Message received on unexpected topic"+", "+topic+", "+payload)}))}},{key:"publishEvent",value:function publishEvent(typeId,deviceId,eventId,format,data,qos,callback){qos=qos||0;if(!(0,_util.isDefined)(typeId)||!(0,_util.isDefined)(deviceId)||!(0,_util.isDefined)(eventId)||!(0,_util.isDefined)(format)){this.log.error("[ApplicationClient:publishDeviceEvent] Required params for publishDeviceEvent not present");this.emit("error","[ApplicationClient:publishDeviceEvent] Required params for publishDeviceEvent not present");return}var topic="iot-2/type/"+typeId+"/id/"+deviceId+"/evt/"+eventId+"/fmt/"+format;this._publish(topic,data,qos,callback);return this}},{key:"subscribeToEvents",value:function subscribeToEvents(typeId,deviceId,eventId,format,qos,callback){typeId=typeId||"+";deviceId=deviceId||"+";eventId=eventId||"+";format=format||"+";qos=qos||0;var topic="iot-2/type/"+typeId+"/id/"+deviceId+"/evt/"+eventId+"/fmt/"+format;this._subscribe(topic,qos,callback);return this}},{key:"unsubscribeFromEvents",value:function unsubscribeFromEvents(typeId,deviceId,eventId,format,callback){typeId=typeId||"+";deviceId=deviceId||"+";eventId=eventId||"+";format=format||"+";var topic="iot-2/type/"+typeId+"/id/"+deviceId+"/evt/"+eventId+"/fmt/"+format;this._unsubscribe(topic,callback);return this}},{key:"publishCommand",value:function publishCommand(typeId,deviceId,commandId,format,data,qos,callback){qos=qos||0;if(!(0,_util.isDefined)(typeId)||!(0,_util.isDefined)(deviceId)||!(0,_util.isDefined)(commandId)||!(0,_util.isDefined)(format)){this.log.error("[ApplicationClient:publishDeviceCommand] Required params for publishDeviceCommand not present");this.emit("error","[ApplicationClient:publishDeviceCommand] Required params for publishDeviceCommand not present");return}var topic="iot-2/type/"+typeId+"/id/"+deviceId+"/cmd/"+commandId+"/fmt/"+format;this._publish(topic,data,qos,callback);return this}},{key:"subscribeToCommands",value:function subscribeToCommands(typeId,deviceId,commandId,format,qos,callback){typeId=typeId||"+";deviceId=deviceId||"+";commandId=commandId||"+";format=format||"+";qos=qos||0;var topic="iot-2/type/"+typeId+"/id/"+deviceId+"/cmd/"+commandId+"/fmt/"+format;this.log.debug("[ApplicationClient:subscribeToDeviceCommands] Calling subscribe with QoS "+qos);this._subscribe(topic,qos,callback);return this}},{key:"unsubscribeFromCommands",value:function unsubscribeFromCommands(typeId,deviceId,commandId,format,callback){typeId=typeId||"+";deviceId=deviceId||"+";commandId=commandId||"+";format=format||"+";var topic="iot-2/type/"+typeId+"/id/"+deviceId+"/cmd/"+commandId+"/fmt/"+format;this._unsubscribe(topic,callback);return this}},{key:"subscribeToDeviceState",value:function subscribeToDeviceState(type,id,interfaceId,qos){type=type||"+";id=id||"+";interfaceId=interfaceId||"+";qos=qos||0;var topic="iot-2/type/"+type+"/id/"+id+"/intf/"+interfaceId+"/evt/state";this.log.debug("[ApplicationClient:subscribeToDeviceState] Calling subscribe with QoS "+qos);this._subscribe(topic,qos);return this}},{key:"unsubscribeToDeviceState",value:function unsubscribeToDeviceState(type,id,interfaceId){type=type||"+";id=id||"+";interfaceId=interfaceId||"+";var topic="iot-2/type/"+type+"/id/"+id+"/intf/"+interfaceId+"/evt/state";this._unsubscribe(topic);return this}},{key:"subscribeToDeviceErrors",value:function subscribeToDeviceErrors(type,id,qos){type=type||"+";id=id||"+";qos=qos||0;var topic="iot-2/type/"+type+"/id/"+id+"/err/data";this.log.debug("[ApplicationClient:subscribeToDeviceErrors] Calling subscribe with QoS "+qos);this._subscribe(topic,qos);return this}},{key:"unsubscribeToDeviceErrors",value:function unsubscribeToDeviceErrors(type,id){type=type||"+";id=id||"+";var topic="iot-2/type/"+type+"/id/"+id+"/err/data";this._unsubscribe(topic);return this}},{key:"subscribeToRuleTriggers",value:function subscribeToRuleTriggers(interfaceId,ruleId,qos){interfaceId=interfaceId||"+";ruleId=ruleId||"+";qos=qos||0;var topic="iot-2/intf/"+interfaceId+"/rule/"+ruleId+"/evt/trigger";this.log.debug("[ApplicationClient:subscribeToRuleTriggers] Calling subscribe with QoS "+qos);this._subscribe(topic,qos);return this}},{key:"unsubscribeToRuleTriggers",value:function unsubscribeToRuleTriggers(interfaceId,ruleId){interfaceId=interfaceId||"+";ruleId=ruleId||"+";var topic="iot-2/intf/"+interfaceId+"/rule/"+ruleId+"/evt/trigger";this._unsubscribe(topic);return this}},{key:"subscribeToRuleErrors",value:function subscribeToRuleErrors(interfaceId,ruleId,qos){interfaceId=interfaceId||"+";ruleId=ruleId||"+";qos=qos||0;var topic="iot-2/intf/"+interfaceId+"/rule/"+ruleId+"/err/data";this.log.debug("[ApplicationClient:subscribeToRuleErrors] Calling subscribe with QoS "+qos);this._subscribe(topic,qos);return this}},{key:"unsubscribeToRuleErrors",value:function unsubscribeToRuleErrors(interfaceId,ruleId){interfaceId=interfaceId||"+";ruleId=ruleId||"+";var topic="iot-2/intf/"+interfaceId+"/rule/"+ruleId+"/err/data";this._unsubscribe(topic);return this}},{key:"subscribeToDeviceStatus",value:function subscribeToDeviceStatus(type,id,qos){type=type||"+";id=id||"+";qos=qos||0;var topic="iot-2/type/"+type+"/id/"+id+"/mon";this.log.debug("[ApplicationClient:subscribeToDeviceStatus] Calling subscribe with QoS "+qos);this._subscribe(topic,qos);return this}},{key:"unsubscribeToDeviceStatus",value:function unsubscribeToDeviceStatus(type,id){type=type||"+";id=id||"+";var topic="iot-2/type/"+type+"/id/"+id+"/mon";this._unsubscribe(topic);return this}},{key:"subscribeToAppStatus",value:function subscribeToAppStatus(id,qos){id=id||"+";qos=qos||0;var topic="iot-2/app/"+id+"/mon";this.log.debug("[ApplicationClient:subscribeToAppStatus] Calling subscribe with QoS "+qos);this._subscribe(topic,qos);return this}},{key:"unsubscribeToAppStatus",value:function unsubscribeToAppStatus(id){id=id||"+";var topic="iot-2/app/"+id+"/mon";this._unsubscribe(topic);return this}}]);return ApplicationClient}(_BaseClient2["default"]);exports["default"]=ApplicationClient},{"../BaseClient":1,"../api/ApiClient":3,"../api/DscClient":5,"../api/LecClient":6,"../api/MgmtClient":7,"../api/RegistryClient":8,"../api/RulesClient":9,"../api/StateClient":10,"../util":18,"./ApplicationConfig":12}],12:[function(require,module,exports){(function(process){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _BaseConfig2=_interopRequireDefault(require("../BaseConfig"));var _loglevel=_interopRequireDefault(require("loglevel"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}function _possibleConstructorReturn(self,call){if(call&&(_typeof(call)==="object"||typeof call==="function")){return call}return _assertThisInitialized(self)}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return self}function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o)};return _getPrototypeOf(o)}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function")}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:true,configurable:true}});if(superClass)_setPrototypeOf(subClass,superClass)}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o};return _setPrototypeOf(o,p)}var YAML=require("yaml");var fs=require("fs");var uuidv4=require("uuid/v4");var ApplicationConfig=function(_BaseConfig){_inherits(ApplicationConfig,_BaseConfig);function ApplicationConfig(identity,auth,options){var _this;_classCallCheck(this,ApplicationConfig);_this=_possibleConstructorReturn(this,_getPrototypeOf(ApplicationConfig).call(this,identity,auth,options));if(_this.auth!=null&&!_this.auth.useLtpa){if(!("key"in _this.auth)||_this.auth.key==null){throw new Error("Missing auth.key from configuration")}if(!("token"in _this.auth)||_this.auth.token==null){throw new Error("Missing auth.token from configuration")}}if(_this.identity==null){_this.identity={}}if(!("appId"in _this.identity)){_this.identity.appId=uuidv4()}if(!("sharedSubscription"in _this.options.mqtt)){_this.options.mqtt.sharedSubscription=false}return _this}_createClass(ApplicationConfig,[{key:"getOrgId",value:function getOrgId(){if(this.auth==null){return"quickstart"}else if(this.auth.key){return this.auth.key.split("-")[1]}else{return null}}},{key:"getApiRoot",value:function getApiRoot(){return this.options.apiRoot||"api/v0002"}},{key:"getApiBaseUri",value:function getApiBaseUri(){return this.auth&&this.auth.useLtpa?"/".concat(this.getApiRoot()):"https://".concat(this.getOrgId(),".").concat(this.options.domain,"/").concat(this.getApiRoot())}},{key:"getClientId",value:function getClientId(){var clientIdPrefix="a";if(this.sharedSubscription==true){clientIdPrefix="A"}return clientIdPrefix+":"+this.getOrgId()+":"+this.identity.appId}},{key:"getMqttUsername",value:function getMqttUsername(){return this.auth.key}},{key:"getMqttPassword",value:function getMqttPassword(){return this.auth.token}},{key:"getAdditionalHeaders",value:function getAdditionalHeaders(){return this.options&&this.options.http?this.options.http.additionalHeaders:[]}},{key:"setAdditionalHeader",value:function setAdditionalHeader(key,value){if(!this.options.http)this.options.http={};if(!this.options.http.additionalHeaders)this.options.http.additionalHeaders={};this.options.http.additionalHeaders[key]=value}}],[{key:"parseEnvVars",value:function parseEnvVars(){var authKey=process.env.WIOTP_AUTH_KEY||null;var authToken=process.env.WIOTP_AUTH_TOKEN||null;if(authKey==null&&authToken==null){authKey=process.env.WIOTP_API_KEY||null;authToken=process.env.WIOTP_API_TOKEN||null}var appId=process.env.WIOTP_IDENTITY_APPID||uuidv4();var domain=process.env.WIOTP_OPTIONS_DOMAIN||null;var apiRoot=process.env.WIOTP_OPTIONS_API_ROOT||null;var logLevel=process.env.WIOTP_OPTIONS_LOGLEVEL||"info";var port=process.env.WIOTP_OPTIONS_MQTT_PORT||null;var transport=process.env.WIOTP_OPTIONS_MQTT_TRANSPORT||null;var caFile=process.env.WIOTP_OPTIONS_MQTT_CAFILE||null;var cleanStart=process.env.WIOTP_OPTIONS_MQTT_CLEANSTART||"true";var sessionExpiry=process.env.WIOTP_OPTIONS_MQTT_SESSIONEXPIRY||3600;var keepAlive=process.env.WIOTP_OPTIONS_MQTT_KEEPALIVE||60;var sharedSubs=process.env.WIOTP_OPTIONS_MQTT_SHAREDSUBSCRIPTION||"false";var verifyCert=process.env.WIOTP_OPTIONS_HTTP_VERIFY||"true";if(port!=null){port=parseInt(port)}sessionExpiry=parseInt(sessionExpiry);keepAlive=parseInt(keepAlive);var identity={appId:appId};var options={domain:domain,apiRoot:apiRoot,logLevel:logLevel,mqtt:{port:port,transport:transport,cleanStart:["True","true","1"].includes(cleanStart),sessionExpiry:sessionExpiry,keepAlive:keepAlive,sharedSubscription:["True","true","1"].includes(sharedSubs),caFile:caFile},http:{verify:["True","true","1"].includes(verifyCert)}};var auth=null;if(authToken!=null){auth={key:authKey,token:authToken}}return new ApplicationConfig(identity,auth,options)}},{key:"parseConfigFile",value:function parseConfigFile(configFilePath){var configFile=fs.readFileSync(configFilePath,"utf8");var data=YAML.parse(configFile);if(!fs.existsSync(configFilePath)){throw new Error("File not found")}else{try{var _configFile=fs.readFileSync(configFilePath,"utf8");var data=YAML.parse(_configFile)}catch(err){throw new Error("Error reading device configuration file: "+err.code)}}if("options"in data&"logLevel"in data["options"]){var validLevels=["error","warning","info","debug"];if(!validLevels.includes(data["options"]["logLevel"])){throw new Error("Optional setting options.logLevel (Currently: "+data["options"]["logLevel"]+") must be one of error, warning, info, debug")}}else{data["options"]["logLevel"]=_loglevel["default"].GetLogger(data["options"]["logLevel"].toUpperCase())}return new ApplicationConfig(data["identity"],data["auth"],data["options"])}}]);return ApplicationConfig}(_BaseConfig2["default"]);exports["default"]=ApplicationConfig}).call(this,require("_process"))},{"../BaseConfig":2,_process:171,fs:72,loglevel:152,"uuid/v4":212,yaml:271}],13:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _util=require("../util");var _BaseClient2=_interopRequireDefault(require("../BaseClient"));var _DeviceConfig=_interopRequireDefault(require("./DeviceConfig"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}function _possibleConstructorReturn(self,call){if(call&&(_typeof(call)==="object"||typeof call==="function")){return call}return _assertThisInitialized(self)}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return self}function _get(target,property,receiver){if(typeof Reflect!=="undefined"&&Reflect.get){_get=Reflect.get}else{_get=function _get(target,property,receiver){var base=_superPropBase(target,property);if(!base)return;var desc=Object.getOwnPropertyDescriptor(base,property);if(desc.get){return desc.get.call(receiver)}return desc.value}}return _get(target,property,receiver||target)}function _superPropBase(object,property){while(!Object.prototype.hasOwnProperty.call(object,property)){object=_getPrototypeOf(object);if(object===null)break}return object}function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o)};return _getPrototypeOf(o)}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function")}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:true,configurable:true}});if(superClass)_setPrototypeOf(subClass,superClass)}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o};return _setPrototypeOf(o,p)}var WILDCARD_TOPIC="iot-2/cmd/+/fmt/+";var CMD_RE=/^iot-2\/cmd\/(.+)\/fmt\/(.+)$/;var util=require("util");var DeviceClient=function(_BaseClient){_inherits(DeviceClient,_BaseClient);function DeviceClient(config){var _this;_classCallCheck(this,DeviceClient);if(!config instanceof _DeviceConfig["default"]){throw new Error("Config must be an instance of DeviceConfig")}_this=_possibleConstructorReturn(this,_getPrototypeOf(DeviceClient).call(this,config));_this.log.debug("[DeviceClient:constructor] DeviceClient initialized for "+config.getClientId());return _this}_createClass(DeviceClient,[{key:"_commandSubscriptionCallback",value:function _commandSubscriptionCallback(err,granted){if(err==null){for(var index in granted){var grant=granted[index];this.log.debug("[DeviceClient:connect] Subscribed to device commands on "+grant.topic+" at QoS "+grant.qos)}}else{this.log.error("[DeviceClient:connect] Unable to establish subscription for device commands: "+err);this.emit("error",new Error("Unable to establish subscription for device commands: "+err))}}},{key:"connect",value:function connect(){var _this2=this;_get(_getPrototypeOf(DeviceClient.prototype),"connect",this).call(this);this.mqtt.on("connect",(function(){if(!_this2.config.isQuickstart()){_this2.mqtt.subscribe(WILDCARD_TOPIC,{qos:1},_this2._commandSubscriptionCallback.bind(_this2))}}));this.mqtt.on("message",(function(topic,payload){_this2.log.debug("[DeviceClient:onMessage] Message received on topic : "+topic+" with payload : "+payload);var match=CMD_RE.exec(topic);if(match){_this2.emit("command",match[1],match[2],payload,topic)}}))}},{key:"publishEvent",value:function publishEvent(eventId,format,data,qos,callback){qos=qos||0;if(!(0,_util.isDefined)(eventId)||!(0,_util.isDefined)(format)){this.log.error("[DeviceClient:publishEvent] Required params for publishEvent not present");this.emit("error","[DeviceClient:publishEvent] Required params for publishEvent not present");return}var topic=util.format("iot-2/evt/%s/fmt/%s",eventId,format);this._publish(topic,data,qos,callback);return this}}]);return DeviceClient}(_BaseClient2["default"]);exports["default"]=DeviceClient},{"../BaseClient":1,"../util":18,"./DeviceConfig":14,util:209}],14:[function(require,module,exports){(function(process){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _BaseConfig2=_interopRequireDefault(require("../BaseConfig"));var _loglevel=_interopRequireDefault(require("loglevel"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}function _possibleConstructorReturn(self,call){if(call&&(_typeof(call)==="object"||typeof call==="function")){return call}return _assertThisInitialized(self)}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return self}function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o)};return _getPrototypeOf(o)}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function")}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:true,configurable:true}});if(superClass)_setPrototypeOf(subClass,superClass)}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o};return _setPrototypeOf(o,p)}var YAML=require("yaml");var fs=require("fs");var DeviceConfig=function(_BaseConfig){_inherits(DeviceConfig,_BaseConfig);function DeviceConfig(identity,auth,options){var _this;_classCallCheck(this,DeviceConfig);_this=_possibleConstructorReturn(this,_getPrototypeOf(DeviceConfig).call(this,identity,auth,options));if(_this.identity==null){throw new Error("Missing identity from configuration")}if(!("orgId"in _this.identity)||_this.identity.orgId==null){throw new Error("Missing identity.orgId from configuration")}if(!("typeId"in _this.identity)||_this.identity.typeId==null){throw new Error("Missing identity.typeId from configuration")}if(!("deviceId"in _this.identity)||_this.identity.deviceId==null){throw new Error("Missing identity.deviceId from configuration")}if(_this.identity.orgId=="quickstart"){if(_this.auth!=null){throw new Error("Quickstart service does not support device authentication")}}else{if(_this.auth==null){throw new Error("Missing auth from configuration")}if(!("token"in _this.auth)||_this.auth.token==null){throw new Error("Missing auth.token from configuration")}}return _this}_createClass(DeviceConfig,[{key:"getOrgId",value:function getOrgId(){return this.identity.orgId}},{key:"getClientId",value:function getClientId(){return"d:"+this.identity.orgId+":"+this.identity.typeId+":"+this.identity.deviceId}},{key:"getMqttUsername",value:function getMqttUsername(){return"use-token-auth"}},{key:"getMqttPassword",value:function getMqttPassword(){return this.auth.token}}],[{key:"parseEnvVars",value:function parseEnvVars(){var orgId=process.env.WIOTP_IDENTITY_ORGID||null;var typeId=process.env.WIOTP_IDENTITY_TYPEID||null;var deviceId=process.env.WIOTP_IDENTITY_DEVICEID||null;var authToken=process.env.WIOTP_AUTH_TOKEN||null;if(authToken==null){authToken=process.env.WIOTP_API_TOKEN||null}var domain=process.env.WIOTP_OPTIONS_DOMAIN||null;var logLevel=process.env.WIOTP_OPTIONS_LOGLEVEL||"info";var port=process.env.WIOTP_OPTIONS_MQTT_PORT||null;var transport=process.env.WIOTP_OPTIONS_MQTT_TRANSPORT||null;var caFile=process.env.WIOTP_OPTIONS_MQTT_CAFILE||null;var cleanStart=process.env.WIOTP_OPTIONS_MQTT_CLEANSTART||"true";var sessionExpiry=process.env.WIOTP_OPTIONS_MQTT_SESSIONEXPIRY||3600;var keepAlive=process.env.WIOTP_OPTIONS_MQTT_KEEPALIVE||60;var sharedSubs=process.env.WIOTP_OPTIONS_MQTT_SHAREDSUBSCRIPTION||"false";if(port!=null){port=parseInt(port)}sessionExpiry=parseInt(sessionExpiry);keepAlive=parseInt(keepAlive);var identity={orgId:orgId,typeId:typeId,deviceId:deviceId};var options={domain:domain,logLevel:logLevel,mqtt:{port:port,transport:transport,cleanStart:["True","true","1"].includes(cleanStart),sessionExpiry:sessionExpiry,keepAlive:keepAlive,sharedSubscription:["True","true","1"].includes(sharedSubs),caFile:caFile}};var auth=null;if(authToken!=null){auth={token:authToken}}return new DeviceConfig(identity,auth,options)}},{key:"parseConfigFile",value:function parseConfigFile(configFilePath){var configFile=fs.readFileSync(configFilePath,"utf8");var data=YAML.parse(configFile);if(!fs.existsSync(configFilePath)){throw new Error("File not found")}else{try{var _configFile=fs.readFileSync(configFilePath,"utf8");var data=YAML.parse(_configFile)}catch(err){throw new Error("Error reading device configuration file: "+err.code)}}if("options"in data&"logLevel"in data["options"]){var validLevels=["error","warning","info","debug"];if(!validLevels.includes(data["options"]["logLevel"])){throw new Error("Optional setting options.logLevel (Currently: "+data["options"]["logLevel"]+") must be one of error, warning, info, debug")}}else{data["options"]["logLevel"]=_loglevel["default"].GetLogger(data["options"]["logLevel"].toUpperCase())}return new DeviceConfig(data["identity"],data["auth"],data["options"])}}]);return DeviceConfig}(_BaseConfig2["default"]);exports["default"]=DeviceConfig}).call(this,require("_process"))},{"../BaseConfig":2,_process:171,fs:72,loglevel:152,yaml:271}],15:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _BaseClient2=_interopRequireDefault(require("../BaseClient"));var _GatewayConfig=_interopRequireDefault(require("./GatewayConfig"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}function _possibleConstructorReturn(self,call){if(call&&(_typeof(call)==="object"||typeof call==="function")){return call}return _assertThisInitialized(self)}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return self}function _get(target,property,receiver){if(typeof Reflect!=="undefined"&&Reflect.get){_get=Reflect.get}else{_get=function _get(target,property,receiver){var base=_superPropBase(target,property);if(!base)return;var desc=Object.getOwnPropertyDescriptor(base,property);if(desc.get){return desc.get.call(receiver)}return desc.value}}return _get(target,property,receiver||target)}function _superPropBase(object,property){while(!Object.prototype.hasOwnProperty.call(object,property)){object=_getPrototypeOf(object);if(object===null)break}return object}function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o)};return _getPrototypeOf(o)}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function")}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:true,configurable:true}});if(superClass)_setPrototypeOf(subClass,superClass)}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o};return _setPrototypeOf(o,p)}var CMD_RE=/^iot-2\/type\/(.+)\/id\/(.+)\/cmd\/(.+)\/fmt\/(.+)$/;var util=require("util");var GatewayClient=function(_BaseClient){_inherits(GatewayClient,_BaseClient);function GatewayClient(config){var _this;_classCallCheck(this,GatewayClient);if(!config instanceof _GatewayConfig["default"]){throw new Error("Config must be an instance of GatewayConfig")}if(config.isQuickstart()){throw new Error("[GatewayClient:constructor] Quickstart not supported in Gateways")}_this=_possibleConstructorReturn(this,_getPrototypeOf(GatewayClient).call(this,config));_this.log.debug("[GatewayClient:constructor] GatewayClient initialized for "+config.getClientId());return _this}_createClass(GatewayClient,[{key:"connect",value:function connect(){var _this2=this;_get(_getPrototypeOf(GatewayClient.prototype),"connect",this).call(this);this.mqtt.on("connect",(function(){}));this.mqtt.on("message",(function(topic,payload){_this2.log.debug("[GatewayClient:onMessage] Message received on topic : "+topic+" with payload : "+payload);var match=CMD_RE.exec(topic);if(match){_this2.emit("command",match[1],match[2],match[3],match[4],payload,topic)}}))}},{key:"publishEvent",value:function publishEvent(eventId,format,payload,qos,callback){return this._publishEvent(this.config.identity.typeId,this.config.identity.deviceId,eventId,format,payload,qos,callback)}},{key:"publishDeviceEvent",value:function publishDeviceEvent(typeid,deviceId,eventid,format,payload,qos,callback){return this._publishEvent(typeId,deviceId,eventid,format,payload,qos,callback)}},{key:"_publishEvent",value:function _publishEvent(typeId,deviceId,eventId,format,data,qos,callback){var topic=util.format("iot-2/type/%s/id/%s/evt/%s/fmt/%s",typeId,deviceId,eventId,format);qos=qos||0;this._publish(topic,data,qos,callback);return this}},{key:"subscribeToDeviceCommands",value:function subscribeToDeviceCommands(typeId,deviceId,commandId,format,qos,callback){typeId=typeId||"+";deviceId=deviceId||"+";commandId=commandid||"+";format=format||"+";qos=qos||0;var topic="iot-2/type/"+typeId+"/id/"+deviceId+"/cmd/"+commandId+"/fmt/"+format;this._subscribe(topic,qos,callback);return this}},{key:"unsubscribeFromDeviceCommands",value:function unsubscribeFromDeviceCommands(typeId,deviceId,commandId,format,callback){typeId=typeId||"+";deviceId=deviceId||"+";commandId=commandId||"+";format=format||"+";var topic="iot-2/type/"+typeId+"/id/"+deviceId+"/cmd/"+commandId+"/fmt/"+format;this._unsubscribe(topic,callback);return this}},{key:"subscribeToCommands",value:function subscribeToCommands(commandId,format,qos,callback){commandId=commandId||"+";format=format||"+";qos=qos||0;var topic="iot-2/type/"+this.config.identity.typeId+"/id/"+this.config.identity.deviceId+"/cmd/"+commandId+"/fmt/"+format;this._subscribe(topic,qos,callback);return this}},{key:"unsubscribeFromCommands",value:function unsubscribeFromCommands(commandId,format,callback){commandId=commandId||"+";format=format||"+";var topic="iot-2/type/"+this.config.identity.typeId+"/id/"+this.config.identity.deviceId+"/cmd/"+commandId+"/fmt/"+format;this._unsubscribe(topic,callback);return this}}]);return GatewayClient}(_BaseClient2["default"]);exports["default"]=GatewayClient},{"../BaseClient":1,"./GatewayConfig":16,util:209}],16:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _DeviceConfig2=_interopRequireDefault(require("../device/DeviceConfig"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}function _possibleConstructorReturn(self,call){if(call&&(_typeof(call)==="object"||typeof call==="function")){return call}return _assertThisInitialized(self)}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return self}function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o)};return _getPrototypeOf(o)}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function")}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:true,configurable:true}});if(superClass)_setPrototypeOf(subClass,superClass)}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o};return _setPrototypeOf(o,p)}var GatewayConfig=function(_DeviceConfig){_inherits(GatewayConfig,_DeviceConfig);function GatewayConfig(identity,auth,options){_classCallCheck(this,GatewayConfig);return _possibleConstructorReturn(this,_getPrototypeOf(GatewayConfig).call(this,identity,auth,options))}_createClass(GatewayConfig,[{key:"getClientId",value:function getClientId(){return"g:"+this.identity.orgId+":"+this.identity.typeId+":"+this.identity.deviceId}}]);return GatewayConfig}(_DeviceConfig2["default"]);exports["default"]=GatewayConfig},{"../device/DeviceConfig":14}],17:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"ApplicationClient",{enumerable:true,get:function get(){return _ApplicationClient["default"]}});Object.defineProperty(exports,"DeviceClient",{enumerable:true,get:function get(){return _DeviceClient["default"]}});Object.defineProperty(exports,"GatewayClient",{enumerable:true,get:function get(){return _GatewayClient["default"]}});Object.defineProperty(exports,"ApplicationConfig",{enumerable:true,get:function get(){return _ApplicationConfig["default"]}});Object.defineProperty(exports,"DeviceConfig",{enumerable:true,get:function get(){return _DeviceConfig["default"]}});Object.defineProperty(exports,"ApiErrors",{enumerable:true,get:function get(){return _ApiErrors["default"]}});var _ApplicationClient=_interopRequireDefault(require("./application/ApplicationClient"));var _DeviceClient=_interopRequireDefault(require("./device/DeviceClient"));var _GatewayClient=_interopRequireDefault(require("./gateway/GatewayClient"));var _ApplicationConfig=_interopRequireDefault(require("./application/ApplicationConfig"));var _DeviceConfig=_interopRequireDefault(require("./device/DeviceConfig"));var _ApiErrors=_interopRequireDefault(require("./api/ApiErrors"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}},{"./api/ApiErrors":4,"./application/ApplicationClient":11,"./application/ApplicationConfig":12,"./device/DeviceClient":13,"./device/DeviceConfig":14,"./gateway/GatewayClient":15}],18:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isString=isString;exports.isNumber=isNumber;exports.isBoolean=isBoolean;exports.isDefined=isDefined;exports.generateUUID=generateUUID;exports.isNode=exports.isBrowser=void 0;function isString(value){return typeof value==="string"}function isNumber(value){return typeof value==="number"}function isBoolean(value){return typeof value==="boolean"}function isDefined(value){return value!==undefined&&value!==null}var isBrowser=new Function("try {return this===window;}catch(e){ return false;}");exports.isBrowser=isBrowser;var isNode=new Function("try {return this===global;}catch(e){return false;}");exports.isNode=isNode;function generateUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(c){var r=Math.random()*16|0,v=c=="x"?r:r&3|8;return v.toString(16)}))}},{}],19:[function(require,module,exports){function _arrayWithHoles(arr){if(Array.isArray(arr))return arr}module.exports=_arrayWithHoles},{}],20:[function(require,module,exports){function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return self}module.exports=_assertThisInitialized},{}],21:[function(require,module,exports){function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}module.exports=_classCallCheck},{}],22:[function(require,module,exports){var setPrototypeOf=require("./setPrototypeOf");function isNativeReflectConstruct(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{Date.prototype.toString.call(Reflect.construct(Date,[],(function(){})));return true}catch(e){return false}}function _construct(Parent,args,Class){if(isNativeReflectConstruct()){module.exports=_construct=Reflect.construct}else{module.exports=_construct=function _construct(Parent,args,Class){var a=[null];a.push.apply(a,args);var Constructor=Function.bind.apply(Parent,a);var instance=new Constructor;if(Class)setPrototypeOf(instance,Class.prototype);return instance}}return _construct.apply(null,arguments)}module.exports=_construct},{"./setPrototypeOf":35}],23:[function(require,module,exports){function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}module.exports=_createClass},{}],24:[function(require,module,exports){function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true})}else{obj[key]=value}return obj}module.exports=_defineProperty},{}],25:[function(require,module,exports){var superPropBase=require("./superPropBase");function _get(target,property,receiver){if(typeof Reflect!=="undefined"&&Reflect.get){module.exports=_get=Reflect.get}else{module.exports=_get=function _get(target,property,receiver){var base=superPropBase(target,property);if(!base)return;var desc=Object.getOwnPropertyDescriptor(base,property);if(desc.get){return desc.get.call(receiver)}return desc.value}}return _get(target,property,receiver||target)}module.exports=_get},{"./superPropBase":37}],26:[function(require,module,exports){function _getPrototypeOf(o){module.exports=_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o)};return _getPrototypeOf(o)}module.exports=_getPrototypeOf},{}],27:[function(require,module,exports){var setPrototypeOf=require("./setPrototypeOf");function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function")}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:true,configurable:true}});if(superClass)setPrototypeOf(subClass,superClass)}module.exports=_inherits},{"./setPrototypeOf":35}],28:[function(require,module,exports){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}module.exports=_interopRequireDefault},{}],29:[function(require,module,exports){var _typeof=require("../helpers/typeof");function _getRequireWildcardCache(){if(typeof WeakMap!=="function")return null;var cache=new WeakMap;_getRequireWildcardCache=function _getRequireWildcardCache(){return cache};return cache}function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}if(obj===null||_typeof(obj)!=="object"&&typeof obj!=="function"){return{default:obj}}var cache=_getRequireWildcardCache();if(cache&&cache.has(obj)){return cache.get(obj)}var newObj={};var hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;if(desc&&(desc.get||desc.set)){Object.defineProperty(newObj,key,desc)}else{newObj[key]=obj[key]}}}newObj["default"]=obj;if(cache){cache.set(obj,newObj)}return newObj}module.exports=_interopRequireWildcard},{"../helpers/typeof":39}],30:[function(require,module,exports){function _isNativeFunction(fn){return Function.toString.call(fn).indexOf("[native code]")!==-1}module.exports=_isNativeFunction},{}],31:[function(require,module,exports){function _iterableToArray(iter){if(Symbol.iterator in Object(iter)||Object.prototype.toString.call(iter)==="[object Arguments]")return Array.from(iter)}module.exports=_iterableToArray},{}],32:[function(require,module,exports){function _iterableToArrayLimit(arr,i){if(!(Symbol.iterator in Object(arr)||Object.prototype.toString.call(arr)==="[object Arguments]")){return}var _arr=[];var _n=true;var _d=false;var _e=undefined;try{for(var _i=arr[Symbol.iterator](),_s;!(_n=(_s=_i.next()).done);_n=true){_arr.push(_s.value);if(i&&_arr.length===i)break}}catch(err){_d=true;_e=err}finally{try{if(!_n&&_i["return"]!=null)_i["return"]()}finally{if(_d)throw _e}}return _arr}module.exports=_iterableToArrayLimit},{}],33:[function(require,module,exports){function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}module.exports=_nonIterableRest},{}],34:[function(require,module,exports){var _typeof=require("../helpers/typeof");var assertThisInitialized=require("./assertThisInitialized");function _possibleConstructorReturn(self,call){if(call&&(_typeof(call)==="object"||typeof call==="function")){return call}return assertThisInitialized(self)}module.exports=_possibleConstructorReturn},{"../helpers/typeof":39,"./assertThisInitialized":20}],35:[function(require,module,exports){function _setPrototypeOf(o,p){module.exports=_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o};return _setPrototypeOf(o,p)}module.exports=_setPrototypeOf},{}],36:[function(require,module,exports){var arrayWithHoles=require("./arrayWithHoles");var iterableToArrayLimit=require("./iterableToArrayLimit");var nonIterableRest=require("./nonIterableRest");function _slicedToArray(arr,i){return arrayWithHoles(arr)||iterableToArrayLimit(arr,i)||nonIterableRest()}module.exports=_slicedToArray},{"./arrayWithHoles":19,"./iterableToArrayLimit":32,"./nonIterableRest":33}],37:[function(require,module,exports){var getPrototypeOf=require("./getPrototypeOf");function _superPropBase(object,property){while(!Object.prototype.hasOwnProperty.call(object,property)){object=getPrototypeOf(object);if(object===null)break}return object}module.exports=_superPropBase},{"./getPrototypeOf":26}],38:[function(require,module,exports){var arrayWithHoles=require("./arrayWithHoles");var iterableToArray=require("./iterableToArray");var nonIterableRest=require("./nonIterableRest");function _toArray(arr){return arrayWithHoles(arr)||iterableToArray(arr)||nonIterableRest()}module.exports=_toArray},{"./arrayWithHoles":19,"./iterableToArray":31,"./nonIterableRest":33}],39:[function(require,module,exports){function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){module.exports=_typeof=function _typeof(obj){return typeof obj}}else{module.exports=_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}module.exports=_typeof},{}],40:[function(require,module,exports){var getPrototypeOf=require("./getPrototypeOf");var setPrototypeOf=require("./setPrototypeOf");var isNativeFunction=require("./isNativeFunction");var construct=require("./construct");function _wrapNativeSuper(Class){var _cache=typeof Map==="function"?new Map:undefined;module.exports=_wrapNativeSuper=function _wrapNativeSuper(Class){if(Class===null||!isNativeFunction(Class))return Class;if(typeof Class!=="function"){throw new TypeError("Super expression must either be null or a function")}if(typeof _cache!=="undefined"){if(_cache.has(Class))return _cache.get(Class);_cache.set(Class,Wrapper)}function Wrapper(){return construct(Class,arguments,getPrototypeOf(this).constructor)}Wrapper.prototype=Object.create(Class.prototype,{constructor:{value:Wrapper,enumerable:false,writable:true,configurable:true}});return setPrototypeOf(Wrapper,Class)};return _wrapNativeSuper(Class)}module.exports=_wrapNativeSuper},{"./construct":22,"./getPrototypeOf":26,"./isNativeFunction":30,"./setPrototypeOf":35}],41:[function(require,module,exports){module.exports=require("./lib/axios")},{"./lib/axios":43}],42:[function(require,module,exports){"use strict";var utils=require("./../utils");var settle=require("./../core/settle");var buildURL=require("./../helpers/buildURL");var buildFullPath=require("../core/buildFullPath");var parseHeaders=require("./../helpers/parseHeaders");var isURLSameOrigin=require("./../helpers/isURLSameOrigin");var createError=require("../core/createError");module.exports=function xhrAdapter(config){return new Promise((function dispatchXhrRequest(resolve,reject){var requestData=config.data;var requestHeaders=config.headers;if(utils.isFormData(requestData)){delete requestHeaders["Content-Type"]}var request=new XMLHttpRequest;if(config.auth){var username=config.auth.username||"";var password=config.auth.password||"";requestHeaders.Authorization="Basic "+btoa(username+":"+password)}var fullPath=buildFullPath(config.baseURL,config.url);request.open(config.method.toUpperCase(),buildURL(fullPath,config.params,config.paramsSerializer),true);request.timeout=config.timeout;request.onreadystatechange=function handleLoad(){if(!request||request.readyState!==4){return}if(request.status===0&&!(request.responseURL&&request.responseURL.indexOf("file:")===0)){return}var responseHeaders="getAllResponseHeaders"in request?parseHeaders(request.getAllResponseHeaders()):null;var responseData=!config.responseType||config.responseType==="text"?request.responseText:request.response;var response={data:responseData,status:request.status,statusText:request.statusText,headers:responseHeaders,config:config,request:request};settle(resolve,reject,response);request=null};request.onabort=function handleAbort(){if(!request){return}reject(createError("Request aborted",config,"ECONNABORTED",request));request=null};request.onerror=function handleError(){reject(createError("Network Error",config,null,request));request=null};request.ontimeout=function handleTimeout(){var timeoutErrorMessage="timeout of "+config.timeout+"ms exceeded";if(config.timeoutErrorMessage){timeoutErrorMessage=config.timeoutErrorMessage}reject(createError(timeoutErrorMessage,config,"ECONNABORTED",request));request=null};if(utils.isStandardBrowserEnv()){var cookies=require("./../helpers/cookies");var xsrfValue=(config.withCredentials||isURLSameOrigin(fullPath))&&config.xsrfCookieName?cookies.read(config.xsrfCookieName):undefined;if(xsrfValue){requestHeaders[config.xsrfHeaderName]=xsrfValue}}if("setRequestHeader"in request){utils.forEach(requestHeaders,(function setRequestHeader(val,key){if(typeof requestData==="undefined"&&key.toLowerCase()==="content-type"){delete requestHeaders[key]}else{request.setRequestHeader(key,val)}}))}if(!utils.isUndefined(config.withCredentials)){request.withCredentials=!!config.withCredentials}if(config.responseType){try{request.responseType=config.responseType}catch(e){if(config.responseType!=="json"){throw e}}}if(typeof config.onDownloadProgress==="function"){request.addEventListener("progress",config.onDownloadProgress)}if(typeof config.onUploadProgress==="function"&&request.upload){request.upload.addEventListener("progress",config.onUploadProgress)}if(config.cancelToken){config.cancelToken.promise.then((function onCanceled(cancel){if(!request){return}request.abort();reject(cancel);request=null}))}if(requestData===undefined){requestData=null}request.send(requestData)}))}},{"../core/buildFullPath":49,"../core/createError":50,"./../core/settle":54,"./../helpers/buildURL":58,"./../helpers/cookies":60,"./../helpers/isURLSameOrigin":62,"./../helpers/parseHeaders":65,"./../utils":67}],43:[function(require,module,exports){"use strict";var utils=require("./utils");var bind=require("./helpers/bind");var Axios=require("./core/Axios");var mergeConfig=require("./core/mergeConfig");var defaults=require("./defaults");function createInstance(defaultConfig){var context=new Axios(defaultConfig);var instance=bind(Axios.prototype.request,context);utils.extend(instance,Axios.prototype,context);utils.extend(instance,context);return instance}var axios=createInstance(defaults);axios.Axios=Axios;axios.create=function create(instanceConfig){return createInstance(mergeConfig(axios.defaults,instanceConfig))};axios.Cancel=require("./cancel/Cancel");axios.CancelToken=require("./cancel/CancelToken");axios.isCancel=require("./cancel/isCancel");axios.all=function all(promises){return Promise.all(promises)};axios.spread=require("./helpers/spread");module.exports=axios;module.exports.default=axios},{"./cancel/Cancel":44,"./cancel/CancelToken":45,"./cancel/isCancel":46,"./core/Axios":47,"./core/mergeConfig":53,"./defaults":56,"./helpers/bind":57,"./helpers/spread":66,"./utils":67}],44:[function(require,module,exports){"use strict";function Cancel(message){this.message=message}Cancel.prototype.toString=function toString(){return"Cancel"+(this.message?": "+this.message:"")};Cancel.prototype.__CANCEL__=true;module.exports=Cancel},{}],45:[function(require,module,exports){"use strict";var Cancel=require("./Cancel");function CancelToken(executor){if(typeof executor!=="function"){throw new TypeError("executor must be a function.")}var resolvePromise;this.promise=new Promise((function promiseExecutor(resolve){resolvePromise=resolve}));var token=this;executor((function cancel(message){if(token.reason){return}token.reason=new Cancel(message);resolvePromise(token.reason)}))}CancelToken.prototype.throwIfRequested=function throwIfRequested(){if(this.reason){throw this.reason}};CancelToken.source=function source(){var cancel;var token=new CancelToken((function executor(c){cancel=c}));return{token:token,cancel:cancel}};module.exports=CancelToken},{"./Cancel":44}],46:[function(require,module,exports){"use strict";module.exports=function isCancel(value){return!!(value&&value.__CANCEL__)}},{}],47:[function(require,module,exports){"use strict";var utils=require("./../utils");var buildURL=require("../helpers/buildURL");var InterceptorManager=require("./InterceptorManager");var dispatchRequest=require("./dispatchRequest");var mergeConfig=require("./mergeConfig");function Axios(instanceConfig){this.defaults=instanceConfig;this.interceptors={request:new InterceptorManager,response:new InterceptorManager}}Axios.prototype.request=function request(config){if(typeof config==="string"){config=arguments[1]||{};config.url=arguments[0]}else{config=config||{}}config=mergeConfig(this.defaults,config);if(config.method){config.method=config.method.toLowerCase()}else if(this.defaults.method){config.method=this.defaults.method.toLowerCase()}else{config.method="get"}var chain=[dispatchRequest,undefined];var promise=Promise.resolve(config);this.interceptors.request.forEach((function unshiftRequestInterceptors(interceptor){chain.unshift(interceptor.fulfilled,interceptor.rejected)}));this.interceptors.response.forEach((function pushResponseInterceptors(interceptor){chain.push(interceptor.fulfilled,interceptor.rejected)}));while(chain.length){promise=promise.then(chain.shift(),chain.shift())}return promise};Axios.prototype.getUri=function getUri(config){config=mergeConfig(this.defaults,config);return buildURL(config.url,config.params,config.paramsSerializer).replace(/^\?/,"")};utils.forEach(["delete","get","head","options"],(function forEachMethodNoData(method){Axios.prototype[method]=function(url,config){return this.request(utils.merge(config||{},{method:method,url:url}))}}));utils.forEach(["post","put","patch"],(function forEachMethodWithData(method){Axios.prototype[method]=function(url,data,config){return this.request(utils.merge(config||{},{method:method,url:url,data:data}))}}));module.exports=Axios},{"../helpers/buildURL":58,"./../utils":67,"./InterceptorManager":48,"./dispatchRequest":51,"./mergeConfig":53}],48:[function(require,module,exports){"use strict";var utils=require("./../utils");function InterceptorManager(){this.handlers=[]}InterceptorManager.prototype.use=function use(fulfilled,rejected){this.handlers.push({fulfilled:fulfilled,rejected:rejected});return this.handlers.length-1};InterceptorManager.prototype.eject=function eject(id){if(this.handlers[id]){this.handlers[id]=null}};InterceptorManager.prototype.forEach=function forEach(fn){utils.forEach(this.handlers,(function forEachHandler(h){if(h!==null){fn(h)}}))};module.exports=InterceptorManager},{"./../utils":67}],49:[function(require,module,exports){"use strict";var isAbsoluteURL=require("../helpers/isAbsoluteURL");var combineURLs=require("../helpers/combineURLs");module.exports=function buildFullPath(baseURL,requestedURL){if(baseURL&&!isAbsoluteURL(requestedURL)){return combineURLs(baseURL,requestedURL)}return requestedURL}},{"../helpers/combineURLs":59,"../helpers/isAbsoluteURL":61}],50:[function(require,module,exports){"use strict";var enhanceError=require("./enhanceError");module.exports=function createError(message,config,code,request,response){var error=new Error(message);return enhanceError(error,config,code,request,response)}},{"./enhanceError":52}],51:[function(require,module,exports){"use strict";var utils=require("./../utils");var transformData=require("./transformData");var isCancel=require("../cancel/isCancel");var defaults=require("../defaults");function throwIfCancellationRequested(config){if(config.cancelToken){config.cancelToken.throwIfRequested()}}module.exports=function dispatchRequest(config){throwIfCancellationRequested(config);config.headers=config.headers||{};config.data=transformData(config.data,config.headers,config.transformRequest);config.headers=utils.merge(config.headers.common||{},config.headers[config.method]||{},config.headers);utils.forEach(["delete","get","head","post","put","patch","common"],(function cleanHeaderConfig(method){delete config.headers[method]}));var adapter=config.adapter||defaults.adapter;return adapter(config).then((function onAdapterResolution(response){throwIfCancellationRequested(config);response.data=transformData(response.data,response.headers,config.transformResponse);return response}),(function onAdapterRejection(reason){if(!isCancel(reason)){throwIfCancellationRequested(config);if(reason&&reason.response){reason.response.data=transformData(reason.response.data,reason.response.headers,config.transformResponse)}}return Promise.reject(reason)}))}},{"../cancel/isCancel":46,"../defaults":56,"./../utils":67,"./transformData":55}],52:[function(require,module,exports){"use strict";module.exports=function enhanceError(error,config,code,request,response){error.config=config;if(code){error.code=code}error.request=request;error.response=response;error.isAxiosError=true;error.toJSON=function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code}};return error}},{}],53:[function(require,module,exports){"use strict";var utils=require("../utils");module.exports=function mergeConfig(config1,config2){config2=config2||{};var config={};var valueFromConfig2Keys=["url","method","params","data"];var mergeDeepPropertiesKeys=["headers","auth","proxy"];var defaultToConfig2Keys=["baseURL","url","transformRequest","transformResponse","paramsSerializer","timeout","withCredentials","adapter","responseType","xsrfCookieName","xsrfHeaderName","onUploadProgress","onDownloadProgress","maxContentLength","validateStatus","maxRedirects","httpAgent","httpsAgent","cancelToken","socketPath"];utils.forEach(valueFromConfig2Keys,(function valueFromConfig2(prop){if(typeof config2[prop]!=="undefined"){config[prop]=config2[prop]}}));utils.forEach(mergeDeepPropertiesKeys,(function mergeDeepProperties(prop){if(utils.isObject(config2[prop])){config[prop]=utils.deepMerge(config1[prop],config2[prop])}else if(typeof config2[prop]!=="undefined"){config[prop]=config2[prop]}else if(utils.isObject(config1[prop])){config[prop]=utils.deepMerge(config1[prop])}else if(typeof config1[prop]!=="undefined"){config[prop]=config1[prop]}}));utils.forEach(defaultToConfig2Keys,(function defaultToConfig2(prop){if(typeof config2[prop]!=="undefined"){config[prop]=config2[prop]}else if(typeof config1[prop]!=="undefined"){config[prop]=config1[prop]}}));var axiosKeys=valueFromConfig2Keys.concat(mergeDeepPropertiesKeys).concat(defaultToConfig2Keys);var otherKeys=Object.keys(config2).filter((function filterAxiosKeys(key){return axiosKeys.indexOf(key)===-1}));utils.forEach(otherKeys,(function otherKeysDefaultToConfig2(prop){if(typeof config2[prop]!=="undefined"){config[prop]=config2[prop]}else if(typeof config1[prop]!=="undefined"){config[prop]=config1[prop]}}));return config}},{"../utils":67}],54:[function(require,module,exports){"use strict";var createError=require("./createError");module.exports=function settle(resolve,reject,response){var validateStatus=response.config.validateStatus;if(!validateStatus||validateStatus(response.status)){resolve(response)}else{reject(createError("Request failed with status code "+response.status,response.config,null,response.request,response))}}},{"./createError":50}],55:[function(require,module,exports){"use strict";var utils=require("./../utils");module.exports=function transformData(data,headers,fns){utils.forEach(fns,(function transform(fn){data=fn(data,headers)}));return data}},{"./../utils":67}],56:[function(require,module,exports){(function(process){"use strict";var utils=require("./utils");var normalizeHeaderName=require("./helpers/normalizeHeaderName");var DEFAULT_CONTENT_TYPE={"Content-Type":"application/x-www-form-urlencoded"};function setContentTypeIfUnset(headers,value){if(!utils.isUndefined(headers)&&utils.isUndefined(headers["Content-Type"])){headers["Content-Type"]=value}}function getDefaultAdapter(){var adapter;if(typeof XMLHttpRequest!=="undefined"){adapter=require("./adapters/xhr")}else if(typeof process!=="undefined"&&Object.prototype.toString.call(process)==="[object process]"){adapter=require("./adapters/http")}return adapter}var defaults={adapter:getDefaultAdapter(),transformRequest:[function transformRequest(data,headers){normalizeHeaderName(headers,"Accept");normalizeHeaderName(headers,"Content-Type");if(utils.isFormData(data)||utils.isArrayBuffer(data)||utils.isBuffer(data)||utils.isStream(data)||utils.isFile(data)||utils.isBlob(data)){return data}if(utils.isArrayBufferView(data)){return data.buffer}if(utils.isURLSearchParams(data)){setContentTypeIfUnset(headers,"application/x-www-form-urlencoded;charset=utf-8");return data.toString()}if(utils.isObject(data)){setContentTypeIfUnset(headers,"application/json;charset=utf-8");return JSON.stringify(data)}return data}],transformResponse:[function transformResponse(data){if(typeof data==="string"){try{data=JSON.parse(data)}catch(e){}}return data}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,validateStatus:function validateStatus(status){return status>=200&&status<300}};defaults.headers={common:{Accept:"application/json, text/plain, */*"}};utils.forEach(["delete","get","head"],(function forEachMethodNoData(method){defaults.headers[method]={}}));utils.forEach(["post","put","patch"],(function forEachMethodWithData(method){defaults.headers[method]=utils.merge(DEFAULT_CONTENT_TYPE)}));module.exports=defaults}).call(this,require("_process"))},{"./adapters/http":42,"./adapters/xhr":42,"./helpers/normalizeHeaderName":64,"./utils":67,_process:171}],57:[function(require,module,exports){"use strict";module.exports=function bind(fn,thisArg){return function wrap(){var args=new Array(arguments.length);for(var i=0;i<args.length;i++){args[i]=arguments[i]}return fn.apply(thisArg,args)}}},{}],58:[function(require,module,exports){"use strict";var utils=require("./../utils");function encode(val){return encodeURIComponent(val).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}module.exports=function buildURL(url,params,paramsSerializer){if(!params){return url}var serializedParams;if(paramsSerializer){serializedParams=paramsSerializer(params)}else if(utils.isURLSearchParams(params)){serializedParams=params.toString()}else{var parts=[];utils.forEach(params,(function serialize(val,key){if(val===null||typeof val==="undefined"){return}if(utils.isArray(val)){key=key+"[]"}else{val=[val]}utils.forEach(val,(function parseValue(v){if(utils.isDate(v)){v=v.toISOString()}else if(utils.isObject(v)){v=JSON.stringify(v)}parts.push(encode(key)+"="+encode(v))}))}));serializedParams=parts.join("&")}if(serializedParams){var hashmarkIndex=url.indexOf("#");if(hashmarkIndex!==-1){url=url.slice(0,hashmarkIndex)}url+=(url.indexOf("?")===-1?"?":"&")+serializedParams}return url}},{"./../utils":67}],59:[function(require,module,exports){"use strict";module.exports=function combineURLs(baseURL,relativeURL){return relativeURL?baseURL.replace(/\/+$/,"")+"/"+relativeURL.replace(/^\/+/,""):baseURL}},{}],60:[function(require,module,exports){"use strict";var utils=require("./../utils");module.exports=utils.isStandardBrowserEnv()?function standardBrowserEnv(){return{write:function write(name,value,expires,path,domain,secure){var cookie=[];cookie.push(name+"="+encodeURIComponent(value));if(utils.isNumber(expires)){cookie.push("expires="+new Date(expires).toGMTString())}if(utils.isString(path)){cookie.push("path="+path)}if(utils.isString(domain)){cookie.push("domain="+domain)}if(secure===true){cookie.push("secure")}document.cookie=cookie.join("; ")},read:function read(name){var match=document.cookie.match(new RegExp("(^|;\\s*)("+name+")=([^;]*)"));return match?decodeURIComponent(match[3]):null},remove:function remove(name){this.write(name,"",Date.now()-864e5)}}}():function nonStandardBrowserEnv(){return{write:function write(){},read:function read(){return null},remove:function remove(){}}}()},{"./../utils":67}],61:[function(require,module,exports){"use strict";module.exports=function isAbsoluteURL(url){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url)}},{}],62:[function(require,module,exports){"use strict";var utils=require("./../utils");var isValidXss=require("./isValidXss");module.exports=utils.isStandardBrowserEnv()?function standardBrowserEnv(){var msie=/(msie|trident)/i.test(navigator.userAgent);var urlParsingNode=document.createElement("a");var originURL;function resolveURL(url){var href=url;if(isValidXss(url)){throw new Error("URL contains XSS injection attempt")}if(msie){urlParsingNode.setAttribute("href",href);href=urlParsingNode.href}urlParsingNode.setAttribute("href",href);return{href:urlParsingNode.href,protocol:urlParsingNode.protocol?urlParsingNode.protocol.replace(/:$/,""):"",host:urlParsingNode.host,search:urlParsingNode.search?urlParsingNode.search.replace(/^\?/,""):"",hash:urlParsingNode.hash?urlParsingNode.hash.replace(/^#/,""):"",hostname:urlParsingNode.hostname,port:urlParsingNode.port,pathname:urlParsingNode.pathname.charAt(0)==="/"?urlParsingNode.pathname:"/"+urlParsingNode.pathname}}originURL=resolveURL(window.location.href);return function isURLSameOrigin(requestURL){var parsed=utils.isString(requestURL)?resolveURL(requestURL):requestURL;return parsed.protocol===originURL.protocol&&parsed.host===originURL.host}}():function nonStandardBrowserEnv(){return function isURLSameOrigin(){return true}}()},{"./../utils":67,"./isValidXss":63}],63:[function(require,module,exports){"use strict";module.exports=function isValidXss(requestURL){var xssRegex=/(\b)(on\w+)=|javascript|(<\s*)(\/*)script/gi;return xssRegex.test(requestURL)}},{}],64:[function(require,module,exports){"use strict";var utils=require("../utils");module.exports=function normalizeHeaderName(headers,normalizedName){utils.forEach(headers,(function processHeader(value,name){if(name!==normalizedName&&name.toUpperCase()===normalizedName.toUpperCase()){headers[normalizedName]=value;delete headers[name]}}))}},{"../utils":67}],65:[function(require,module,exports){"use strict";var utils=require("./../utils");var ignoreDuplicateOf=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"];module.exports=function parseHeaders(headers){var parsed={};var key;var val;var i;if(!headers){return parsed}utils.forEach(headers.split("\n"),(function parser(line){i=line.indexOf(":");key=utils.trim(line.substr(0,i)).toLowerCase();val=utils.trim(line.substr(i+1));if(key){if(parsed[key]&&ignoreDuplicateOf.indexOf(key)>=0){return}if(key==="set-cookie"){parsed[key]=(parsed[key]?parsed[key]:[]).concat([val])}else{parsed[key]=parsed[key]?parsed[key]+", "+val:val}}}));return parsed}},{"./../utils":67}],66:[function(require,module,exports){"use strict";module.exports=function spread(callback){return function wrap(arr){return callback.apply(null,arr)}}},{}],67:[function(require,module,exports){"use strict";var bind=require("./helpers/bind");var toString=Object.prototype.toString;function isArray(val){return toString.call(val)==="[object Array]"}function isUndefined(val){return typeof val==="undefined"}function isBuffer(val){return val!==null&&!isUndefined(val)&&val.constructor!==null&&!isUndefined(val.constructor)&&typeof val.constructor.isBuffer==="function"&&val.constructor.isBuffer(val)}function isArrayBuffer(val){return toString.call(val)==="[object ArrayBuffer]"}function isFormData(val){return typeof FormData!=="undefined"&&val instanceof FormData}function isArrayBufferView(val){var result;if(typeof ArrayBuffer!=="undefined"&&ArrayBuffer.isView){result=ArrayBuffer.isView(val)}else{result=val&&val.buffer&&val.buffer instanceof ArrayBuffer}return result}function isString(val){return typeof val==="string"}function isNumber(val){return typeof val==="number"}function isObject(val){return val!==null&&typeof val==="object"}function isDate(val){return toString.call(val)==="[object Date]"}function isFile(val){return toString.call(val)==="[object File]"}function isBlob(val){return toString.call(val)==="[object Blob]"}function isFunction(val){return toString.call(val)==="[object Function]"}function isStream(val){return isObject(val)&&isFunction(val.pipe)}function isURLSearchParams(val){return typeof URLSearchParams!=="undefined"&&val instanceof URLSearchParams}function trim(str){return str.replace(/^\s*/,"").replace(/\s*$/,"")}function isStandardBrowserEnv(){if(typeof navigator!=="undefined"&&(navigator.product==="ReactNative"||navigator.product==="NativeScript"||navigator.product==="NS")){return false}return typeof window!=="undefined"&&typeof document!=="undefined"}function forEach(obj,fn){if(obj===null||typeof obj==="undefined"){return}if(typeof obj!=="object"){obj=[obj]}if(isArray(obj)){for(var i=0,l=obj.length;i<l;i++){fn.call(null,obj[i],i,obj)}}else{for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key)){fn.call(null,obj[key],key,obj)}}}}function merge(){var result={};function assignValue(val,key){if(typeof result[key]==="object"&&typeof val==="object"){result[key]=merge(result[key],val)}else{result[key]=val}}for(var i=0,l=arguments.length;i<l;i++){forEach(arguments[i],assignValue)}return result}function deepMerge(){var result={};function assignValue(val,key){if(typeof result[key]==="object"&&typeof val==="object"){result[key]=deepMerge(result[key],val)}else if(typeof val==="object"){result[key]=deepMerge({},val)}else{result[key]=val}}for(var i=0,l=arguments.length;i<l;i++){forEach(arguments[i],assignValue)}return result}function extend(a,b,thisArg){forEach(b,(function assignValue(val,key){if(thisArg&&typeof val==="function"){a[key]=bind(val,thisArg)}else{a[key]=val}}));return a}module.exports={isArray:isArray,isArrayBuffer:isArrayBuffer,isBuffer:isBuffer,isFormData:isFormData,isArrayBufferView:isArrayBufferView,isString:isString,isNumber:isNumber,isObject:isObject,isUndefined:isUndefined,isDate:isDate,isFile:isFile,isBlob:isBlob,isFunction:isFunction,isStream:isStream,isURLSearchParams:isURLSearchParams,isStandardBrowserEnv:isStandardBrowserEnv,forEach:forEach,merge:merge,deepMerge:deepMerge,extend:extend,trim:trim}},{"./helpers/bind":57}],68:[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 getLens(b64){var len=b64.length;if(len%4>0){throw new Error("Invalid string. Length must be a multiple of 4")}var validLen=b64.indexOf("=");if(validLen===-1)validLen=len;var placeHoldersLen=validLen===len?0:4-validLen%4;return[validLen,placeHoldersLen]}function byteLength(b64){var lens=getLens(b64);var validLen=lens[0];var placeHoldersLen=lens[1];return(validLen+placeHoldersLen)*3/4-placeHoldersLen}function _byteLength(b64,validLen,placeHoldersLen){return(validLen+placeHoldersLen)*3/4-placeHoldersLen}function toByteArray(b64){var tmp;var lens=getLens(b64);var validLen=lens[0];var placeHoldersLen=lens[1];var arr=new Arr(_byteLength(b64,validLen,placeHoldersLen));var curByte=0;var len=placeHoldersLen>0?validLen-4:validLen;var i;for(i=0;i<len;i+=4){tmp=revLookup[b64.charCodeAt(i)]<<18|revLookup[b64.charCodeAt(i+1)]<<12|revLookup[b64.charCodeAt(i+2)]<<6|revLookup[b64.charCodeAt(i+3)];arr[curByte++]=tmp>>16&255;arr[curByte++]=tmp>>8&255;arr[curByte++]=tmp&255}if(placeHoldersLen===2){tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4;arr[curByte++]=tmp&255}if(placeHoldersLen===1){tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2;arr[curByte++]=tmp>>8&255;arr[curByte++]=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&16711680)+(uint8[i+1]<<8&65280)+(uint8[i+2]&255);output.push(tripletToBase64(tmp))}return output.join("")}function fromByteArray(uint8){var tmp;var len=uint8.length;var extraBytes=len%3;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];parts.push(lookup[tmp>>2]+lookup[tmp<<4&63]+"==")}else if(extraBytes===2){tmp=(uint8[len-2]<<8)+uint8[len-1];parts.push(lookup[tmp>>10]+lookup[tmp>>4&63]+lookup[tmp<<2&63]+"=")}return parts.join("")}},{}],69:[function(require,module,exports){var DuplexStream=require("readable-stream/duplex"),util=require("util"),Buffer=require("safe-buffer").Buffer;function BufferList(callback){if(!(this instanceof BufferList))return new BufferList(callback);this._bufs=[];this.length=0;if(typeof callback=="function"){this._callback=callback;var piper=function piper(err){if(this._callback){this._callback(err);this._callback=null}}.bind(this);this.on("pipe",(function onPipe(src){src.on("error",piper)}));this.on("unpipe",(function onUnpipe(src){src.removeListener("error",piper)}))}else{this.append(callback)}DuplexStream.call(this)}util.inherits(BufferList,DuplexStream);BufferList.prototype._offset=function _offset(offset){var tot=0,i=0,_t;if(offset===0)return[0,0];for(;i<this._bufs.length;i++){_t=tot+this._bufs[i].length;if(offset<_t||i==this._bufs.length-1)return[i,offset-tot];tot=_t}};BufferList.prototype.append=function append(buf){var i=0;if(Buffer.isBuffer(buf)){this._appendBuffer(buf)}else if(Array.isArray(buf)){for(;i<buf.length;i++)this.append(buf[i])}else if(buf instanceof BufferList){for(;i<buf._bufs.length;i++)this.append(buf._bufs[i])}else if(buf!=null){if(typeof buf=="number")buf=buf.toString();this._appendBuffer(Buffer.from(buf))}return this};BufferList.prototype._appendBuffer=function appendBuffer(buf){this._bufs.push(buf);this.length+=buf.length};BufferList.prototype._write=function _write(buf,encoding,callback){this._appendBuffer(buf);if(typeof callback=="function")callback()};BufferList.prototype._read=function _read(size){if(!this.length)return this.push(null);size=Math.min(size,this.length);this.push(this.slice(0,size));this.consume(size)};BufferList.prototype.end=function end(chunk){DuplexStream.prototype.end.call(this,chunk);if(this._callback){this._callback(null,this.slice());this._callback=null}};BufferList.prototype.get=function get(index){return this.slice(index,index+1)[0]};BufferList.prototype.slice=function slice(start,end){if(typeof start=="number"&&start<0)start+=this.length;if(typeof end=="number"&&end<0)end+=this.length;return this.copy(null,0,start,end)};BufferList.prototype.copy=function copy(dst,dstStart,srcStart,srcEnd){if(typeof srcStart!="number"||srcStart<0)srcStart=0;if(typeof srcEnd!="number"||srcEnd>this.length)srcEnd=this.length;if(srcStart>=this.length)return dst||Buffer.alloc(0);if(srcEnd<=0)return dst||Buffer.alloc(0);var copy=!!dst,off=this._offset(srcStart),len=srcEnd-srcStart,bytes=len,bufoff=copy&&dstStart||0,start=off[1],l,i;if(srcStart===0&&srcEnd==this.length){if(!copy){return this._bufs.length===1?this._bufs[0]:Buffer.concat(this._bufs,this.length)}for(i=0;i<this._bufs.length;i++){this._bufs[i].copy(dst,bufoff);bufoff+=this._bufs[i].length}return dst}if(bytes<=this._bufs[off[0]].length-start){return copy?this._bufs[off[0]].copy(dst,dstStart,start,start+bytes):this._bufs[off[0]].slice(start,start+bytes)}if(!copy)dst=Buffer.allocUnsafe(len);for(i=off[0];i<this._bufs.length;i++){l=this._bufs[i].length-start;if(bytes>l){this._bufs[i].copy(dst,bufoff,start)}else{this._bufs[i].copy(dst,bufoff,start,start+bytes);break}bufoff+=l;bytes-=l;if(start)start=0}return dst};BufferList.prototype.shallowSlice=function shallowSlice(start,end){start=start||0;end=end||this.length;if(start<0)start+=this.length;if(end<0)end+=this.length;var startOffset=this._offset(start),endOffset=this._offset(end),buffers=this._bufs.slice(startOffset[0],endOffset[0]+1);if(endOffset[1]==0)buffers.pop();else buffers[buffers.length-1]=buffers[buffers.length-1].slice(0,endOffset[1]);if(startOffset[1]!=0)buffers[0]=buffers[0].slice(startOffset[1]);return new BufferList(buffers)};BufferList.prototype.toString=function toString(encoding,start,end){return this.slice(start,end).toString(encoding)};BufferList.prototype.consume=function consume(bytes){while(this._bufs.length){if(bytes>=this._bufs[0].length){bytes-=this._bufs[0].length;this.length-=this._bufs[0].length;this._bufs.shift()}else{this._bufs[0]=this._bufs[0].slice(bytes);this.length-=bytes;break}}return this};BufferList.prototype.duplicate=function duplicate(){var i=0,copy=new BufferList;for(;i<this._bufs.length;i++)copy.append(this._bufs[i]);return copy};BufferList.prototype.destroy=function destroy(){this._bufs.length=0;this.length=0;this.push(null)};(function(){var methods={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1};for(var m in methods){(function(m){BufferList.prototype[m]=function(offset){return this.slice(offset,offset+methods[m])[m](0)}})(m)}})();module.exports=BufferList},{"readable-stream/duplex":176,"safe-buffer":189,util:209}],70:[function(require,module,exports){(function(process,global,setImmediate){
|
|
1
|
+
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,(function(r){var n=e[i][1][r];return o(n||r)}),p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){"use strict";module.exports=require("./lib/axios")},{"./lib/axios":3}],2:[function(require,module,exports){"use strict";var utils=require("./../utils");var settle=require("./../core/settle");var buildURL=require("./../helpers/buildURL");var buildFullPath=require("../core/buildFullPath");var parseHeaders=require("./../helpers/parseHeaders");var isURLSameOrigin=require("./../helpers/isURLSameOrigin");var createError=require("../core/createError");module.exports=function xhrAdapter(config){return new Promise((function dispatchXhrRequest(resolve,reject){var requestData=config.data;var requestHeaders=config.headers;if(utils.isFormData(requestData)){delete requestHeaders["Content-Type"]}var request=new XMLHttpRequest;if(config.auth){var username=config.auth.username||"";var password=config.auth.password||"";requestHeaders.Authorization="Basic "+btoa(username+":"+password)}var fullPath=buildFullPath(config.baseURL,config.url);request.open(config.method.toUpperCase(),buildURL(fullPath,config.params,config.paramsSerializer),true);request.timeout=config.timeout;request.onreadystatechange=function handleLoad(){if(!request||request.readyState!==4){return}if(request.status===0&&!(request.responseURL&&request.responseURL.indexOf("file:")===0)){return}var responseHeaders="getAllResponseHeaders"in request?parseHeaders(request.getAllResponseHeaders()):null;var responseData=!config.responseType||config.responseType==="text"?request.responseText:request.response;var response={data:responseData,status:request.status,statusText:request.statusText,headers:responseHeaders,config:config,request:request};settle(resolve,reject,response);request=null};request.onabort=function handleAbort(){if(!request){return}reject(createError("Request aborted",config,"ECONNABORTED",request));request=null};request.onerror=function handleError(){reject(createError("Network Error",config,null,request));request=null};request.ontimeout=function handleTimeout(){var timeoutErrorMessage="timeout of "+config.timeout+"ms exceeded";if(config.timeoutErrorMessage){timeoutErrorMessage=config.timeoutErrorMessage}reject(createError(timeoutErrorMessage,config,"ECONNABORTED",request));request=null};if(utils.isStandardBrowserEnv()){var cookies=require("./../helpers/cookies");var xsrfValue=(config.withCredentials||isURLSameOrigin(fullPath))&&config.xsrfCookieName?cookies.read(config.xsrfCookieName):undefined;if(xsrfValue){requestHeaders[config.xsrfHeaderName]=xsrfValue}}if("setRequestHeader"in request){utils.forEach(requestHeaders,(function setRequestHeader(val,key){if(typeof requestData==="undefined"&&key.toLowerCase()==="content-type"){delete requestHeaders[key]}else{request.setRequestHeader(key,val)}}))}if(!utils.isUndefined(config.withCredentials)){request.withCredentials=!!config.withCredentials}if(config.responseType){try{request.responseType=config.responseType}catch(e){if(config.responseType!=="json"){throw e}}}if(typeof config.onDownloadProgress==="function"){request.addEventListener("progress",config.onDownloadProgress)}if(typeof config.onUploadProgress==="function"&&request.upload){request.upload.addEventListener("progress",config.onUploadProgress)}if(config.cancelToken){config.cancelToken.promise.then((function onCanceled(cancel){if(!request){return}request.abort();reject(cancel);request=null}))}if(requestData===undefined){requestData=null}request.send(requestData)}))}},{"../core/buildFullPath":9,"../core/createError":10,"./../core/settle":14,"./../helpers/buildURL":18,"./../helpers/cookies":20,"./../helpers/isURLSameOrigin":22,"./../helpers/parseHeaders":24,"./../utils":26}],3:[function(require,module,exports){"use strict";var utils=require("./utils");var bind=require("./helpers/bind");var Axios=require("./core/Axios");var mergeConfig=require("./core/mergeConfig");var defaults=require("./defaults");function createInstance(defaultConfig){var context=new Axios(defaultConfig);var instance=bind(Axios.prototype.request,context);utils.extend(instance,Axios.prototype,context);utils.extend(instance,context);return instance}var axios=createInstance(defaults);axios.Axios=Axios;axios.create=function create(instanceConfig){return createInstance(mergeConfig(axios.defaults,instanceConfig))};axios.Cancel=require("./cancel/Cancel");axios.CancelToken=require("./cancel/CancelToken");axios.isCancel=require("./cancel/isCancel");axios.all=function all(promises){return Promise.all(promises)};axios.spread=require("./helpers/spread");module.exports=axios;module.exports["default"]=axios},{"./cancel/Cancel":4,"./cancel/CancelToken":5,"./cancel/isCancel":6,"./core/Axios":7,"./core/mergeConfig":13,"./defaults":16,"./helpers/bind":17,"./helpers/spread":25,"./utils":26}],4:[function(require,module,exports){"use strict";function Cancel(message){this.message=message}Cancel.prototype.toString=function toString(){return"Cancel"+(this.message?": "+this.message:"")};Cancel.prototype.__CANCEL__=true;module.exports=Cancel},{}],5:[function(require,module,exports){"use strict";var Cancel=require("./Cancel");function CancelToken(executor){if(typeof executor!=="function"){throw new TypeError("executor must be a function.")}var resolvePromise;this.promise=new Promise((function promiseExecutor(resolve){resolvePromise=resolve}));var token=this;executor((function cancel(message){if(token.reason){return}token.reason=new Cancel(message);resolvePromise(token.reason)}))}CancelToken.prototype.throwIfRequested=function throwIfRequested(){if(this.reason){throw this.reason}};CancelToken.source=function source(){var cancel;var token=new CancelToken((function executor(c){cancel=c}));return{token:token,cancel:cancel}};module.exports=CancelToken},{"./Cancel":4}],6:[function(require,module,exports){"use strict";module.exports=function isCancel(value){return!!(value&&value.__CANCEL__)}},{}],7:[function(require,module,exports){"use strict";var utils=require("./../utils");var buildURL=require("../helpers/buildURL");var InterceptorManager=require("./InterceptorManager");var dispatchRequest=require("./dispatchRequest");var mergeConfig=require("./mergeConfig");function Axios(instanceConfig){this.defaults=instanceConfig;this.interceptors={request:new InterceptorManager,response:new InterceptorManager}}Axios.prototype.request=function request(config){if(typeof config==="string"){config=arguments[1]||{};config.url=arguments[0]}else{config=config||{}}config=mergeConfig(this.defaults,config);if(config.method){config.method=config.method.toLowerCase()}else if(this.defaults.method){config.method=this.defaults.method.toLowerCase()}else{config.method="get"}var chain=[dispatchRequest,undefined];var promise=Promise.resolve(config);this.interceptors.request.forEach((function unshiftRequestInterceptors(interceptor){chain.unshift(interceptor.fulfilled,interceptor.rejected)}));this.interceptors.response.forEach((function pushResponseInterceptors(interceptor){chain.push(interceptor.fulfilled,interceptor.rejected)}));while(chain.length){promise=promise.then(chain.shift(),chain.shift())}return promise};Axios.prototype.getUri=function getUri(config){config=mergeConfig(this.defaults,config);return buildURL(config.url,config.params,config.paramsSerializer).replace(/^\?/,"")};utils.forEach(["delete","get","head","options"],(function forEachMethodNoData(method){Axios.prototype[method]=function(url,config){return this.request(utils.merge(config||{},{method:method,url:url}))}}));utils.forEach(["post","put","patch"],(function forEachMethodWithData(method){Axios.prototype[method]=function(url,data,config){return this.request(utils.merge(config||{},{method:method,url:url,data:data}))}}));module.exports=Axios},{"../helpers/buildURL":18,"./../utils":26,"./InterceptorManager":8,"./dispatchRequest":11,"./mergeConfig":13}],8:[function(require,module,exports){"use strict";var utils=require("./../utils");function InterceptorManager(){this.handlers=[]}InterceptorManager.prototype.use=function use(fulfilled,rejected){this.handlers.push({fulfilled:fulfilled,rejected:rejected});return this.handlers.length-1};InterceptorManager.prototype.eject=function eject(id){if(this.handlers[id]){this.handlers[id]=null}};InterceptorManager.prototype.forEach=function forEach(fn){utils.forEach(this.handlers,(function forEachHandler(h){if(h!==null){fn(h)}}))};module.exports=InterceptorManager},{"./../utils":26}],9:[function(require,module,exports){"use strict";var isAbsoluteURL=require("../helpers/isAbsoluteURL");var combineURLs=require("../helpers/combineURLs");module.exports=function buildFullPath(baseURL,requestedURL){if(baseURL&&!isAbsoluteURL(requestedURL)){return combineURLs(baseURL,requestedURL)}return requestedURL}},{"../helpers/combineURLs":19,"../helpers/isAbsoluteURL":21}],10:[function(require,module,exports){"use strict";var enhanceError=require("./enhanceError");module.exports=function createError(message,config,code,request,response){var error=new Error(message);return enhanceError(error,config,code,request,response)}},{"./enhanceError":12}],11:[function(require,module,exports){"use strict";var utils=require("./../utils");var transformData=require("./transformData");var isCancel=require("../cancel/isCancel");var defaults=require("../defaults");function throwIfCancellationRequested(config){if(config.cancelToken){config.cancelToken.throwIfRequested()}}module.exports=function dispatchRequest(config){throwIfCancellationRequested(config);config.headers=config.headers||{};config.data=transformData(config.data,config.headers,config.transformRequest);config.headers=utils.merge(config.headers.common||{},config.headers[config.method]||{},config.headers);utils.forEach(["delete","get","head","post","put","patch","common"],(function cleanHeaderConfig(method){delete config.headers[method]}));var adapter=config.adapter||defaults.adapter;return adapter(config).then((function onAdapterResolution(response){throwIfCancellationRequested(config);response.data=transformData(response.data,response.headers,config.transformResponse);return response}),(function onAdapterRejection(reason){if(!isCancel(reason)){throwIfCancellationRequested(config);if(reason&&reason.response){reason.response.data=transformData(reason.response.data,reason.response.headers,config.transformResponse)}}return Promise.reject(reason)}))}},{"../cancel/isCancel":6,"../defaults":16,"./../utils":26,"./transformData":15}],12:[function(require,module,exports){"use strict";module.exports=function enhanceError(error,config,code,request,response){error.config=config;if(code){error.code=code}error.request=request;error.response=response;error.isAxiosError=true;error.toJSON=function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code}};return error}},{}],13:[function(require,module,exports){"use strict";var utils=require("../utils");module.exports=function mergeConfig(config1,config2){config2=config2||{};var config={};var valueFromConfig2Keys=["url","method","params","data"];var mergeDeepPropertiesKeys=["headers","auth","proxy"];var defaultToConfig2Keys=["baseURL","url","transformRequest","transformResponse","paramsSerializer","timeout","withCredentials","adapter","responseType","xsrfCookieName","xsrfHeaderName","onUploadProgress","onDownloadProgress","maxContentLength","validateStatus","maxRedirects","httpAgent","httpsAgent","cancelToken","socketPath"];utils.forEach(valueFromConfig2Keys,(function valueFromConfig2(prop){if(typeof config2[prop]!=="undefined"){config[prop]=config2[prop]}}));utils.forEach(mergeDeepPropertiesKeys,(function mergeDeepProperties(prop){if(utils.isObject(config2[prop])){config[prop]=utils.deepMerge(config1[prop],config2[prop])}else if(typeof config2[prop]!=="undefined"){config[prop]=config2[prop]}else if(utils.isObject(config1[prop])){config[prop]=utils.deepMerge(config1[prop])}else if(typeof config1[prop]!=="undefined"){config[prop]=config1[prop]}}));utils.forEach(defaultToConfig2Keys,(function defaultToConfig2(prop){if(typeof config2[prop]!=="undefined"){config[prop]=config2[prop]}else if(typeof config1[prop]!=="undefined"){config[prop]=config1[prop]}}));var axiosKeys=valueFromConfig2Keys.concat(mergeDeepPropertiesKeys).concat(defaultToConfig2Keys);var otherKeys=Object.keys(config2).filter((function filterAxiosKeys(key){return axiosKeys.indexOf(key)===-1}));utils.forEach(otherKeys,(function otherKeysDefaultToConfig2(prop){if(typeof config2[prop]!=="undefined"){config[prop]=config2[prop]}else if(typeof config1[prop]!=="undefined"){config[prop]=config1[prop]}}));return config}},{"../utils":26}],14:[function(require,module,exports){"use strict";var createError=require("./createError");module.exports=function settle(resolve,reject,response){var validateStatus=response.config.validateStatus;if(!validateStatus||validateStatus(response.status)){resolve(response)}else{reject(createError("Request failed with status code "+response.status,response.config,null,response.request,response))}}},{"./createError":10}],15:[function(require,module,exports){"use strict";var utils=require("./../utils");module.exports=function transformData(data,headers,fns){utils.forEach(fns,(function transform(fn){data=fn(data,headers)}));return data}},{"./../utils":26}],16:[function(require,module,exports){(function(process){"use strict";var utils=require("./utils");var normalizeHeaderName=require("./helpers/normalizeHeaderName");var DEFAULT_CONTENT_TYPE={"Content-Type":"application/x-www-form-urlencoded"};function setContentTypeIfUnset(headers,value){if(!utils.isUndefined(headers)&&utils.isUndefined(headers["Content-Type"])){headers["Content-Type"]=value}}function getDefaultAdapter(){var adapter;if(typeof XMLHttpRequest!=="undefined"){adapter=require("./adapters/xhr")}else if(typeof process!=="undefined"&&Object.prototype.toString.call(process)==="[object process]"){adapter=require("./adapters/http")}return adapter}var defaults={adapter:getDefaultAdapter(),transformRequest:[function transformRequest(data,headers){normalizeHeaderName(headers,"Accept");normalizeHeaderName(headers,"Content-Type");if(utils.isFormData(data)||utils.isArrayBuffer(data)||utils.isBuffer(data)||utils.isStream(data)||utils.isFile(data)||utils.isBlob(data)){return data}if(utils.isArrayBufferView(data)){return data.buffer}if(utils.isURLSearchParams(data)){setContentTypeIfUnset(headers,"application/x-www-form-urlencoded;charset=utf-8");return data.toString()}if(utils.isObject(data)){setContentTypeIfUnset(headers,"application/json;charset=utf-8");return JSON.stringify(data)}return data}],transformResponse:[function transformResponse(data){if(typeof data==="string"){try{data=JSON.parse(data)}catch(e){}}return data}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,validateStatus:function validateStatus(status){return status>=200&&status<300}};defaults.headers={common:{Accept:"application/json, text/plain, */*"}};utils.forEach(["delete","get","head"],(function forEachMethodNoData(method){defaults.headers[method]={}}));utils.forEach(["post","put","patch"],(function forEachMethodWithData(method){defaults.headers[method]=utils.merge(DEFAULT_CONTENT_TYPE)}));module.exports=defaults}).call(this,require("_process"))},{"./adapters/http":2,"./adapters/xhr":2,"./helpers/normalizeHeaderName":23,"./utils":26,_process:157}],17:[function(require,module,exports){"use strict";module.exports=function bind(fn,thisArg){return function wrap(){var args=new Array(arguments.length);for(var i=0;i<args.length;i++){args[i]=arguments[i]}return fn.apply(thisArg,args)}}},{}],18:[function(require,module,exports){"use strict";var utils=require("./../utils");function encode(val){return encodeURIComponent(val).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}module.exports=function buildURL(url,params,paramsSerializer){if(!params){return url}var serializedParams;if(paramsSerializer){serializedParams=paramsSerializer(params)}else if(utils.isURLSearchParams(params)){serializedParams=params.toString()}else{var parts=[];utils.forEach(params,(function serialize(val,key){if(val===null||typeof val==="undefined"){return}if(utils.isArray(val)){key=key+"[]"}else{val=[val]}utils.forEach(val,(function parseValue(v){if(utils.isDate(v)){v=v.toISOString()}else if(utils.isObject(v)){v=JSON.stringify(v)}parts.push(encode(key)+"="+encode(v))}))}));serializedParams=parts.join("&")}if(serializedParams){var hashmarkIndex=url.indexOf("#");if(hashmarkIndex!==-1){url=url.slice(0,hashmarkIndex)}url+=(url.indexOf("?")===-1?"?":"&")+serializedParams}return url}},{"./../utils":26}],19:[function(require,module,exports){"use strict";module.exports=function combineURLs(baseURL,relativeURL){return relativeURL?baseURL.replace(/\/+$/,"")+"/"+relativeURL.replace(/^\/+/,""):baseURL}},{}],20:[function(require,module,exports){"use strict";var utils=require("./../utils");module.exports=utils.isStandardBrowserEnv()?function standardBrowserEnv(){return{write:function write(name,value,expires,path,domain,secure){var cookie=[];cookie.push(name+"="+encodeURIComponent(value));if(utils.isNumber(expires)){cookie.push("expires="+new Date(expires).toGMTString())}if(utils.isString(path)){cookie.push("path="+path)}if(utils.isString(domain)){cookie.push("domain="+domain)}if(secure===true){cookie.push("secure")}document.cookie=cookie.join("; ")},read:function read(name){var match=document.cookie.match(new RegExp("(^|;\\s*)("+name+")=([^;]*)"));return match?decodeURIComponent(match[3]):null},remove:function remove(name){this.write(name,"",Date.now()-864e5)}}}():function nonStandardBrowserEnv(){return{write:function write(){},read:function read(){return null},remove:function remove(){}}}()},{"./../utils":26}],21:[function(require,module,exports){"use strict";module.exports=function isAbsoluteURL(url){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url)}},{}],22:[function(require,module,exports){"use strict";var utils=require("./../utils");module.exports=utils.isStandardBrowserEnv()?function standardBrowserEnv(){var msie=/(msie|trident)/i.test(navigator.userAgent);var urlParsingNode=document.createElement("a");var originURL;function resolveURL(url){var href=url;if(msie){urlParsingNode.setAttribute("href",href);href=urlParsingNode.href}urlParsingNode.setAttribute("href",href);return{href:urlParsingNode.href,protocol:urlParsingNode.protocol?urlParsingNode.protocol.replace(/:$/,""):"",host:urlParsingNode.host,search:urlParsingNode.search?urlParsingNode.search.replace(/^\?/,""):"",hash:urlParsingNode.hash?urlParsingNode.hash.replace(/^#/,""):"",hostname:urlParsingNode.hostname,port:urlParsingNode.port,pathname:urlParsingNode.pathname.charAt(0)==="/"?urlParsingNode.pathname:"/"+urlParsingNode.pathname}}originURL=resolveURL(window.location.href);return function isURLSameOrigin(requestURL){var parsed=utils.isString(requestURL)?resolveURL(requestURL):requestURL;return parsed.protocol===originURL.protocol&&parsed.host===originURL.host}}():function nonStandardBrowserEnv(){return function isURLSameOrigin(){return true}}()},{"./../utils":26}],23:[function(require,module,exports){"use strict";var utils=require("../utils");module.exports=function normalizeHeaderName(headers,normalizedName){utils.forEach(headers,(function processHeader(value,name){if(name!==normalizedName&&name.toUpperCase()===normalizedName.toUpperCase()){headers[normalizedName]=value;delete headers[name]}}))}},{"../utils":26}],24:[function(require,module,exports){"use strict";var utils=require("./../utils");var ignoreDuplicateOf=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"];module.exports=function parseHeaders(headers){var parsed={};var key;var val;var i;if(!headers){return parsed}utils.forEach(headers.split("\n"),(function parser(line){i=line.indexOf(":");key=utils.trim(line.substr(0,i)).toLowerCase();val=utils.trim(line.substr(i+1));if(key){if(parsed[key]&&ignoreDuplicateOf.indexOf(key)>=0){return}if(key==="set-cookie"){parsed[key]=(parsed[key]?parsed[key]:[]).concat([val])}else{parsed[key]=parsed[key]?parsed[key]+", "+val:val}}}));return parsed}},{"./../utils":26}],25:[function(require,module,exports){"use strict";module.exports=function spread(callback){return function wrap(arr){return callback.apply(null,arr)}}},{}],26:[function(require,module,exports){"use strict";function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}var bind=require("./helpers/bind");var toString=Object.prototype.toString;function isArray(val){return toString.call(val)==="[object Array]"}function isUndefined(val){return typeof val==="undefined"}function isBuffer(val){return val!==null&&!isUndefined(val)&&val.constructor!==null&&!isUndefined(val.constructor)&&typeof val.constructor.isBuffer==="function"&&val.constructor.isBuffer(val)}function isArrayBuffer(val){return toString.call(val)==="[object ArrayBuffer]"}function isFormData(val){return typeof FormData!=="undefined"&&val instanceof FormData}function isArrayBufferView(val){var result;if(typeof ArrayBuffer!=="undefined"&&ArrayBuffer.isView){result=ArrayBuffer.isView(val)}else{result=val&&val.buffer&&val.buffer instanceof ArrayBuffer}return result}function isString(val){return typeof val==="string"}function isNumber(val){return typeof val==="number"}function isObject(val){return val!==null&&_typeof(val)==="object"}function isDate(val){return toString.call(val)==="[object Date]"}function isFile(val){return toString.call(val)==="[object File]"}function isBlob(val){return toString.call(val)==="[object Blob]"}function isFunction(val){return toString.call(val)==="[object Function]"}function isStream(val){return isObject(val)&&isFunction(val.pipe)}function isURLSearchParams(val){return typeof URLSearchParams!=="undefined"&&val instanceof URLSearchParams}function trim(str){return str.replace(/^\s*/,"").replace(/\s*$/,"")}function isStandardBrowserEnv(){if(typeof navigator!=="undefined"&&(navigator.product==="ReactNative"||navigator.product==="NativeScript"||navigator.product==="NS")){return false}return typeof window!=="undefined"&&typeof document!=="undefined"}function forEach(obj,fn){if(obj===null||typeof obj==="undefined"){return}if(_typeof(obj)!=="object"){obj=[obj]}if(isArray(obj)){for(var i=0,l=obj.length;i<l;i++){fn.call(null,obj[i],i,obj)}}else{for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key)){fn.call(null,obj[key],key,obj)}}}}function merge(){var result={};function assignValue(val,key){if(_typeof(result[key])==="object"&&_typeof(val)==="object"){result[key]=merge(result[key],val)}else{result[key]=val}}for(var i=0,l=arguments.length;i<l;i++){forEach(arguments[i],assignValue)}return result}function deepMerge(){var result={};function assignValue(val,key){if(_typeof(result[key])==="object"&&_typeof(val)==="object"){result[key]=deepMerge(result[key],val)}else if(_typeof(val)==="object"){result[key]=deepMerge({},val)}else{result[key]=val}}for(var i=0,l=arguments.length;i<l;i++){forEach(arguments[i],assignValue)}return result}function extend(a,b,thisArg){forEach(b,(function assignValue(val,key){if(thisArg&&typeof val==="function"){a[key]=bind(val,thisArg)}else{a[key]=val}}));return a}module.exports={isArray:isArray,isArrayBuffer:isArrayBuffer,isBuffer:isBuffer,isFormData:isFormData,isArrayBufferView:isArrayBufferView,isString:isString,isNumber:isNumber,isObject:isObject,isUndefined:isUndefined,isDate:isDate,isFile:isFile,isBlob:isBlob,isFunction:isFunction,isStream:isStream,isURLSearchParams:isURLSearchParams,isStandardBrowserEnv:isStandardBrowserEnv,forEach:forEach,merge:merge,deepMerge:deepMerge,extend:extend,trim:trim}},{"./helpers/bind":17}],27:[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 getLens(b64){var len=b64.length;if(len%4>0){throw new Error("Invalid string. Length must be a multiple of 4")}var validLen=b64.indexOf("=");if(validLen===-1)validLen=len;var placeHoldersLen=validLen===len?0:4-validLen%4;return[validLen,placeHoldersLen]}function byteLength(b64){var lens=getLens(b64);var validLen=lens[0];var placeHoldersLen=lens[1];return(validLen+placeHoldersLen)*3/4-placeHoldersLen}function _byteLength(b64,validLen,placeHoldersLen){return(validLen+placeHoldersLen)*3/4-placeHoldersLen}function toByteArray(b64){var tmp;var lens=getLens(b64);var validLen=lens[0];var placeHoldersLen=lens[1];var arr=new Arr(_byteLength(b64,validLen,placeHoldersLen));var curByte=0;var len=placeHoldersLen>0?validLen-4:validLen;var i;for(i=0;i<len;i+=4){tmp=revLookup[b64.charCodeAt(i)]<<18|revLookup[b64.charCodeAt(i+1)]<<12|revLookup[b64.charCodeAt(i+2)]<<6|revLookup[b64.charCodeAt(i+3)];arr[curByte++]=tmp>>16&255;arr[curByte++]=tmp>>8&255;arr[curByte++]=tmp&255}if(placeHoldersLen===2){tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4;arr[curByte++]=tmp&255}if(placeHoldersLen===1){tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2;arr[curByte++]=tmp>>8&255;arr[curByte++]=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&16711680)+(uint8[i+1]<<8&65280)+(uint8[i+2]&255);output.push(tripletToBase64(tmp))}return output.join("")}function fromByteArray(uint8){var tmp;var len=uint8.length;var extraBytes=len%3;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];parts.push(lookup[tmp>>2]+lookup[tmp<<4&63]+"==")}else if(extraBytes===2){tmp=(uint8[len-2]<<8)+uint8[len-1];parts.push(lookup[tmp>>10]+lookup[tmp>>4&63]+lookup[tmp<<2&63]+"=")}return parts.join("")}},{}],28:[function(require,module,exports){"use strict";var _require=require("buffer"),Buffer=_require.Buffer;var symbol=Symbol["for"]("BufferList");function BufferList(buf){if(!(this instanceof BufferList)){return new BufferList(buf)}BufferList._init.call(this,buf)}BufferList._init=function _init(buf){Object.defineProperty(this,symbol,{value:true});this._bufs=[];this.length=0;if(buf){this.append(buf)}};BufferList.prototype._new=function _new(buf){return new BufferList(buf)};BufferList.prototype._offset=function _offset(offset){if(offset===0){return[0,0]}var tot=0;for(var i=0;i<this._bufs.length;i++){var _t=tot+this._bufs[i].length;if(offset<_t||i===this._bufs.length-1){return[i,offset-tot]}tot=_t}};BufferList.prototype._reverseOffset=function(blOffset){var bufferId=blOffset[0];var offset=blOffset[1];for(var i=0;i<bufferId;i++){offset+=this._bufs[i].length}return offset};BufferList.prototype.get=function get(index){if(index>this.length||index<0){return undefined}var offset=this._offset(index);return this._bufs[offset[0]][offset[1]]};BufferList.prototype.slice=function slice(start,end){if(typeof start==="number"&&start<0){start+=this.length}if(typeof end==="number"&&end<0){end+=this.length}return this.copy(null,0,start,end)};BufferList.prototype.copy=function copy(dst,dstStart,srcStart,srcEnd){if(typeof srcStart!=="number"||srcStart<0){srcStart=0}if(typeof srcEnd!=="number"||srcEnd>this.length){srcEnd=this.length}if(srcStart>=this.length){return dst||Buffer.alloc(0)}if(srcEnd<=0){return dst||Buffer.alloc(0)}var copy=!!dst;var off=this._offset(srcStart);var len=srcEnd-srcStart;var bytes=len;var bufoff=copy&&dstStart||0;var start=off[1];if(srcStart===0&&srcEnd===this.length){if(!copy){return this._bufs.length===1?this._bufs[0]:Buffer.concat(this._bufs,this.length)}for(var i=0;i<this._bufs.length;i++){this._bufs[i].copy(dst,bufoff);bufoff+=this._bufs[i].length}return dst}if(bytes<=this._bufs[off[0]].length-start){return copy?this._bufs[off[0]].copy(dst,dstStart,start,start+bytes):this._bufs[off[0]].slice(start,start+bytes)}if(!copy){dst=Buffer.allocUnsafe(len)}for(var _i=off[0];_i<this._bufs.length;_i++){var l=this._bufs[_i].length-start;if(bytes>l){this._bufs[_i].copy(dst,bufoff,start);bufoff+=l}else{this._bufs[_i].copy(dst,bufoff,start,start+bytes);bufoff+=l;break}bytes-=l;if(start){start=0}}if(dst.length>bufoff)return dst.slice(0,bufoff);return dst};BufferList.prototype.shallowSlice=function shallowSlice(start,end){start=start||0;end=typeof end!=="number"?this.length:end;if(start<0){start+=this.length}if(end<0){end+=this.length}if(start===end){return this._new()}var startOffset=this._offset(start);var endOffset=this._offset(end);var buffers=this._bufs.slice(startOffset[0],endOffset[0]+1);if(endOffset[1]===0){buffers.pop()}else{buffers[buffers.length-1]=buffers[buffers.length-1].slice(0,endOffset[1])}if(startOffset[1]!==0){buffers[0]=buffers[0].slice(startOffset[1])}return this._new(buffers)};BufferList.prototype.toString=function toString(encoding,start,end){return this.slice(start,end).toString(encoding)};BufferList.prototype.consume=function consume(bytes){bytes=Math.trunc(bytes);if(Number.isNaN(bytes)||bytes<=0)return this;while(this._bufs.length){if(bytes>=this._bufs[0].length){bytes-=this._bufs[0].length;this.length-=this._bufs[0].length;this._bufs.shift()}else{this._bufs[0]=this._bufs[0].slice(bytes);this.length-=bytes;break}}return this};BufferList.prototype.duplicate=function duplicate(){var copy=this._new();for(var i=0;i<this._bufs.length;i++){copy.append(this._bufs[i])}return copy};BufferList.prototype.append=function append(buf){if(buf==null){return this}if(buf.buffer){this._appendBuffer(Buffer.from(buf.buffer,buf.byteOffset,buf.byteLength))}else if(Array.isArray(buf)){for(var i=0;i<buf.length;i++){this.append(buf[i])}}else if(this._isBufferList(buf)){for(var _i2=0;_i2<buf._bufs.length;_i2++){this.append(buf._bufs[_i2])}}else{if(typeof buf==="number"){buf=buf.toString()}this._appendBuffer(Buffer.from(buf))}return this};BufferList.prototype._appendBuffer=function appendBuffer(buf){this._bufs.push(buf);this.length+=buf.length};BufferList.prototype.indexOf=function(search,offset,encoding){if(encoding===undefined&&typeof offset==="string"){encoding=offset;offset=undefined}if(typeof search==="function"||Array.isArray(search)){throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.')}else if(typeof search==="number"){search=Buffer.from([search])}else if(typeof search==="string"){search=Buffer.from(search,encoding)}else if(this._isBufferList(search)){search=search.slice()}else if(Array.isArray(search.buffer)){search=Buffer.from(search.buffer,search.byteOffset,search.byteLength)}else if(!Buffer.isBuffer(search)){search=Buffer.from(search)}offset=Number(offset||0);if(isNaN(offset)){offset=0}if(offset<0){offset=this.length+offset}if(offset<0){offset=0}if(search.length===0){return offset>this.length?this.length:offset}var blOffset=this._offset(offset);var blIndex=blOffset[0];var buffOffset=blOffset[1];for(;blIndex<this._bufs.length;blIndex++){var buff=this._bufs[blIndex];while(buffOffset<buff.length){var availableWindow=buff.length-buffOffset;if(availableWindow>=search.length){var nativeSearchResult=buff.indexOf(search,buffOffset);if(nativeSearchResult!==-1){return this._reverseOffset([blIndex,nativeSearchResult])}buffOffset=buff.length-search.length+1}else{var revOffset=this._reverseOffset([blIndex,buffOffset]);if(this._match(revOffset,search)){return revOffset}buffOffset++}}buffOffset=0}return-1};BufferList.prototype._match=function(offset,search){if(this.length-offset<search.length){return false}for(var searchOffset=0;searchOffset<search.length;searchOffset++){if(this.get(offset+searchOffset)!==search[searchOffset]){return false}}return true};(function(){var methods={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1,readIntBE:null,readIntLE:null,readUIntBE:null,readUIntLE:null};for(var m in methods){(function(m){if(methods[m]===null){BufferList.prototype[m]=function(offset,byteLength){return this.slice(offset,offset+byteLength)[m](0,byteLength)}}else{BufferList.prototype[m]=function(offset){return this.slice(offset,offset+methods[m])[m](0)}}})(m)}})();BufferList.prototype._isBufferList=function _isBufferList(b){return b instanceof BufferList||BufferList.isBufferList(b)};BufferList.isBufferList=function isBufferList(b){return b!=null&&b[symbol]};module.exports=BufferList},{buffer:33}],29:[function(require,module,exports){"use strict";var DuplexStream=require("readable-stream").Duplex;var inherits=require("inherits");var BufferList=require("./BufferList");function BufferListStream(callback){if(!(this instanceof BufferListStream)){return new BufferListStream(callback)}if(typeof callback==="function"){this._callback=callback;var piper=function piper(err){if(this._callback){this._callback(err);this._callback=null}}.bind(this);this.on("pipe",(function onPipe(src){src.on("error",piper)}));this.on("unpipe",(function onUnpipe(src){src.removeListener("error",piper)}));callback=null}BufferList._init.call(this,callback);DuplexStream.call(this)}inherits(BufferListStream,DuplexStream);Object.assign(BufferListStream.prototype,BufferList.prototype);BufferListStream.prototype._new=function _new(callback){return new BufferListStream(callback)};BufferListStream.prototype._write=function _write(buf,encoding,callback){this._appendBuffer(buf);if(typeof callback==="function"){callback()}};BufferListStream.prototype._read=function _read(size){if(!this.length){return this.push(null)}size=Math.min(size,this.length);this.push(this.slice(0,size));this.consume(size)};BufferListStream.prototype.end=function end(chunk){DuplexStream.prototype.end.call(this,chunk);if(this._callback){this._callback(null,this.slice());this._callback=null}};BufferListStream.prototype._destroy=function _destroy(err,cb){this._bufs.length=0;this.length=0;cb(err)};BufferListStream.prototype._isBufferList=function _isBufferList(b){return b instanceof BufferListStream||b instanceof BufferList||BufferListStream.isBufferList(b)};BufferListStream.isBufferList=BufferList.isBufferList;module.exports=BufferListStream;module.exports.BufferListStream=BufferListStream;module.exports.BufferList=BufferList},{"./BufferList":28,inherits:120,"readable-stream":175}],30:[function(require,module,exports){(function(process,global,setImmediate){"use strict";function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}
|
|
2
2
|
/* @preserve
|
|
3
3
|
* The MIT License (MIT)
|
|
4
4
|
*
|
|
@@ -22,19 +22,19 @@
|
|
|
22
22
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
23
23
|
* THE SOFTWARE.
|
|
24
24
|
*
|
|
25
|
-
*/
|
|
26
|
-
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}((function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;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 _dereq_=="function"&&_dereq_;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise){var SomePromiseArray=Promise._SomePromiseArray;function any(promises){var ret=new SomePromiseArray(promises);var promise=ret.promise();ret.setHowMany(1);ret.setUnwrap();ret.init();return promise}Promise.any=function(promises){return any(promises)};Promise.prototype.any=function(){return any(this)}}},{}],2:[function(_dereq_,module,exports){"use strict";var firstLineError;try{throw new Error}catch(e){firstLineError=e}var schedule=_dereq_("./schedule");var Queue=_dereq_("./queue");function Async(){this._customScheduler=false;this._isTickUsed=false;this._lateQueue=new Queue(16);this._normalQueue=new Queue(16);this._haveDrainedQueues=false;var self=this;this.drainQueues=function(){self._drainQueues()};this._schedule=schedule}Async.prototype.setScheduler=function(fn){var prev=this._schedule;this._schedule=fn;this._customScheduler=true;return prev};Async.prototype.hasCustomScheduler=function(){return this._customScheduler};Async.prototype.haveItemsQueued=function(){return this._isTickUsed||this._haveDrainedQueues};Async.prototype.fatalError=function(e,isNode){if(isNode){process.stderr.write("Fatal "+(e instanceof Error?e.stack:e)+"\n");process.exit(2)}else{this.throwLater(e)}};Async.prototype.throwLater=function(fn,arg){if(arguments.length===1){arg=fn;fn=function(){throw arg}}if(typeof setTimeout!=="undefined"){setTimeout((function(){fn(arg)}),0)}else try{this._schedule((function(){fn(arg)}))}catch(e){throw new Error("No async scheduler available\n\n See http://goo.gl/MqrFmX\n")}};function AsyncInvokeLater(fn,receiver,arg){this._lateQueue.push(fn,receiver,arg);this._queueTick()}function AsyncInvoke(fn,receiver,arg){this._normalQueue.push(fn,receiver,arg);this._queueTick()}function AsyncSettlePromises(promise){this._normalQueue._pushOne(promise);this._queueTick()}Async.prototype.invokeLater=AsyncInvokeLater;Async.prototype.invoke=AsyncInvoke;Async.prototype.settlePromises=AsyncSettlePromises;function _drainQueue(queue){while(queue.length()>0){_drainQueueStep(queue)}}function _drainQueueStep(queue){var fn=queue.shift();if(typeof fn!=="function"){fn._settlePromises()}else{var receiver=queue.shift();var arg=queue.shift();fn.call(receiver,arg)}}Async.prototype._drainQueues=function(){_drainQueue(this._normalQueue);this._reset();this._haveDrainedQueues=true;_drainQueue(this._lateQueue)};Async.prototype._queueTick=function(){if(!this._isTickUsed){this._isTickUsed=true;this._schedule(this.drainQueues)}};Async.prototype._reset=function(){this._isTickUsed=false};module.exports=Async;module.exports.firstLineError=firstLineError},{"./queue":26,"./schedule":29}],3:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL,tryConvertToPromise,debug){var calledBind=false;var rejectThis=function(_,e){this._reject(e)};var targetRejected=function(e,context){context.promiseRejectionQueued=true;context.bindingPromise._then(rejectThis,rejectThis,null,this,e)};var bindingResolved=function(thisArg,context){if((this._bitField&50397184)===0){this._resolveCallback(context.target)}};var bindingRejected=function(e,context){if(!context.promiseRejectionQueued)this._reject(e)};Promise.prototype.bind=function(thisArg){if(!calledBind){calledBind=true;Promise.prototype._propagateFrom=debug.propagateFromFunction();Promise.prototype._boundValue=debug.boundValueFunction()}var maybePromise=tryConvertToPromise(thisArg);var ret=new Promise(INTERNAL);ret._propagateFrom(this,1);var target=this._target();ret._setBoundTo(maybePromise);if(maybePromise instanceof Promise){var context={promiseRejectionQueued:false,promise:ret,target:target,bindingPromise:maybePromise};target._then(INTERNAL,targetRejected,undefined,ret,context);maybePromise._then(bindingResolved,bindingRejected,undefined,ret,context);ret._setOnCancel(maybePromise)}else{ret._resolveCallback(target)}return ret};Promise.prototype._setBoundTo=function(obj){if(obj!==undefined){this._bitField=this._bitField|2097152;this._boundTo=obj}else{this._bitField=this._bitField&~2097152}};Promise.prototype._isBound=function(){return(this._bitField&2097152)===2097152};Promise.bind=function(thisArg,value){return Promise.resolve(value).bind(thisArg)}}},{}],4:[function(_dereq_,module,exports){"use strict";var old;if(typeof Promise!=="undefined")old=Promise;function noConflict(){try{if(Promise===bluebird)Promise=old}catch(e){}return bluebird}var bluebird=_dereq_("./promise")();bluebird.noConflict=noConflict;module.exports=bluebird},{"./promise":22}],5:[function(_dereq_,module,exports){"use strict";var cr=Object.create;if(cr){var callerCache=cr(null);var getterCache=cr(null);callerCache[" size"]=getterCache[" size"]=0}module.exports=function(Promise){var util=_dereq_("./util");var canEvaluate=util.canEvaluate;var isIdentifier=util.isIdentifier;var getMethodCaller;var getGetter;if(!true){var makeMethodCaller=function(methodName){return new Function("ensureMethod"," \n return function(obj) { \n 'use strict' \n var len = this.length; \n ensureMethod(obj, 'methodName'); \n switch(len) { \n case 1: return obj.methodName(this[0]); \n case 2: return obj.methodName(this[0], this[1]); \n case 3: return obj.methodName(this[0], this[1], this[2]); \n case 0: return obj.methodName(); \n default: \n return obj.methodName.apply(obj, this); \n } \n }; \n ".replace(/methodName/g,methodName))(ensureMethod)};var makeGetter=function(propertyName){return new Function("obj"," \n 'use strict'; \n return obj.propertyName; \n ".replace("propertyName",propertyName))};var getCompiled=function(name,compiler,cache){var ret=cache[name];if(typeof ret!=="function"){if(!isIdentifier(name)){return null}ret=compiler(name);cache[name]=ret;cache[" size"]++;if(cache[" size"]>512){var keys=Object.keys(cache);for(var i=0;i<256;++i)delete cache[keys[i]];cache[" size"]=keys.length-256}}return ret};getMethodCaller=function(name){return getCompiled(name,makeMethodCaller,callerCache)};getGetter=function(name){return getCompiled(name,makeGetter,getterCache)}}function ensureMethod(obj,methodName){var fn;if(obj!=null)fn=obj[methodName];if(typeof fn!=="function"){var message="Object "+util.classString(obj)+" has no method '"+util.toString(methodName)+"'";throw new Promise.TypeError(message)}return fn}function caller(obj){var methodName=this.pop();var fn=ensureMethod(obj,methodName);return fn.apply(obj,this)}Promise.prototype.call=function(methodName){var args=[].slice.call(arguments,1);if(!true){if(canEvaluate){var maybeCaller=getMethodCaller(methodName);if(maybeCaller!==null){return this._then(maybeCaller,undefined,undefined,args,undefined)}}}args.push(methodName);return this._then(caller,undefined,undefined,args,undefined)};function namedGetter(obj){return obj[this]}function indexedGetter(obj){var index=+this;if(index<0)index=Math.max(0,index+obj.length);return obj[index]}Promise.prototype.get=function(propertyName){var isIndex=typeof propertyName==="number";var getter;if(!isIndex){if(canEvaluate){var maybeGetter=getGetter(propertyName);getter=maybeGetter!==null?maybeGetter:namedGetter}else{getter=namedGetter}}else{getter=indexedGetter}return this._then(getter,undefined,undefined,propertyName,undefined)}}},{"./util":36}],6:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,apiRejection,debug){var util=_dereq_("./util");var tryCatch=util.tryCatch;var errorObj=util.errorObj;var async=Promise._async;Promise.prototype["break"]=Promise.prototype.cancel=function(){if(!debug.cancellation())return this._warn("cancellation is disabled");var promise=this;var child=promise;while(promise._isCancellable()){if(!promise._cancelBy(child)){if(child._isFollowing()){child._followee().cancel()}else{child._cancelBranched()}break}var parent=promise._cancellationParent;if(parent==null||!parent._isCancellable()){if(promise._isFollowing()){promise._followee().cancel()}else{promise._cancelBranched()}break}else{if(promise._isFollowing())promise._followee().cancel();promise._setWillBeCancelled();child=promise;promise=parent}}};Promise.prototype._branchHasCancelled=function(){this._branchesRemainingToCancel--};Promise.prototype._enoughBranchesHaveCancelled=function(){return this._branchesRemainingToCancel===undefined||this._branchesRemainingToCancel<=0};Promise.prototype._cancelBy=function(canceller){if(canceller===this){this._branchesRemainingToCancel=0;this._invokeOnCancel();return true}else{this._branchHasCancelled();if(this._enoughBranchesHaveCancelled()){this._invokeOnCancel();return true}}return false};Promise.prototype._cancelBranched=function(){if(this._enoughBranchesHaveCancelled()){this._cancel()}};Promise.prototype._cancel=function(){if(!this._isCancellable())return;this._setCancelled();async.invoke(this._cancelPromises,this,undefined)};Promise.prototype._cancelPromises=function(){if(this._length()>0)this._settlePromises()};Promise.prototype._unsetOnCancel=function(){this._onCancelField=undefined};Promise.prototype._isCancellable=function(){return this.isPending()&&!this._isCancelled()};Promise.prototype.isCancellable=function(){return this.isPending()&&!this.isCancelled()};Promise.prototype._doInvokeOnCancel=function(onCancelCallback,internalOnly){if(util.isArray(onCancelCallback)){for(var i=0;i<onCancelCallback.length;++i){this._doInvokeOnCancel(onCancelCallback[i],internalOnly)}}else if(onCancelCallback!==undefined){if(typeof onCancelCallback==="function"){if(!internalOnly){var e=tryCatch(onCancelCallback).call(this._boundValue());if(e===errorObj){this._attachExtraTrace(e.e);async.throwLater(e.e)}}}else{onCancelCallback._resultCancelled(this)}}};Promise.prototype._invokeOnCancel=function(){var onCancelCallback=this._onCancel();this._unsetOnCancel();async.invoke(this._doInvokeOnCancel,this,onCancelCallback)};Promise.prototype._invokeInternalOnCancel=function(){if(this._isCancellable()){this._doInvokeOnCancel(this._onCancel(),true);this._unsetOnCancel()}};Promise.prototype._resultCancelled=function(){this.cancel()}}},{"./util":36}],7:[function(_dereq_,module,exports){"use strict";module.exports=function(NEXT_FILTER){var util=_dereq_("./util");var getKeys=_dereq_("./es5").keys;var tryCatch=util.tryCatch;var errorObj=util.errorObj;function catchFilter(instances,cb,promise){return function(e){var boundTo=promise._boundValue();predicateLoop:for(var i=0;i<instances.length;++i){var item=instances[i];if(item===Error||item!=null&&item.prototype instanceof Error){if(e instanceof item){return tryCatch(cb).call(boundTo,e)}}else if(typeof item==="function"){var matchesPredicate=tryCatch(item).call(boundTo,e);if(matchesPredicate===errorObj){return matchesPredicate}else if(matchesPredicate){return tryCatch(cb).call(boundTo,e)}}else if(util.isObject(e)){var keys=getKeys(item);for(var j=0;j<keys.length;++j){var key=keys[j];if(item[key]!=e[key]){continue predicateLoop}}return tryCatch(cb).call(boundTo,e)}}return NEXT_FILTER}}return catchFilter}},{"./es5":13,"./util":36}],8:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise){var longStackTraces=false;var contextStack=[];Promise.prototype._promiseCreated=function(){};Promise.prototype._pushContext=function(){};Promise.prototype._popContext=function(){return null};Promise._peekContext=Promise.prototype._peekContext=function(){};function Context(){this._trace=new Context.CapturedTrace(peekContext())}Context.prototype._pushContext=function(){if(this._trace!==undefined){this._trace._promiseCreated=null;contextStack.push(this._trace)}};Context.prototype._popContext=function(){if(this._trace!==undefined){var trace=contextStack.pop();var ret=trace._promiseCreated;trace._promiseCreated=null;return ret}return null};function createContext(){if(longStackTraces)return new Context}function peekContext(){var lastIndex=contextStack.length-1;if(lastIndex>=0){return contextStack[lastIndex]}return undefined}Context.CapturedTrace=null;Context.create=createContext;Context.deactivateLongStackTraces=function(){};Context.activateLongStackTraces=function(){var Promise_pushContext=Promise.prototype._pushContext;var Promise_popContext=Promise.prototype._popContext;var Promise_PeekContext=Promise._peekContext;var Promise_peekContext=Promise.prototype._peekContext;var Promise_promiseCreated=Promise.prototype._promiseCreated;Context.deactivateLongStackTraces=function(){Promise.prototype._pushContext=Promise_pushContext;Promise.prototype._popContext=Promise_popContext;Promise._peekContext=Promise_PeekContext;Promise.prototype._peekContext=Promise_peekContext;Promise.prototype._promiseCreated=Promise_promiseCreated;longStackTraces=false};longStackTraces=true;Promise.prototype._pushContext=Context.prototype._pushContext;Promise.prototype._popContext=Context.prototype._popContext;Promise._peekContext=Promise.prototype._peekContext=peekContext;Promise.prototype._promiseCreated=function(){var ctx=this._peekContext();if(ctx&&ctx._promiseCreated==null)ctx._promiseCreated=this}};return Context}},{}],9:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,Context,enableAsyncHooks,disableAsyncHooks){var async=Promise._async;var Warning=_dereq_("./errors").Warning;var util=_dereq_("./util");var es5=_dereq_("./es5");var canAttachTrace=util.canAttachTrace;var unhandledRejectionHandled;var possiblyUnhandledRejection;var bluebirdFramePattern=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/;var nodeFramePattern=/\((?:timers\.js):\d+:\d+\)/;var parseLinePattern=/[\/<\(](.+?):(\d+):(\d+)\)?\s*$/;var stackFramePattern=null;var formatStack=null;var indentStackFrames=false;var printWarning;var debugging=!!(util.env("BLUEBIRD_DEBUG")!=0&&(true||util.env("BLUEBIRD_DEBUG")||util.env("NODE_ENV")==="development"));var warnings=!!(util.env("BLUEBIRD_WARNINGS")!=0&&(debugging||util.env("BLUEBIRD_WARNINGS")));var longStackTraces=!!(util.env("BLUEBIRD_LONG_STACK_TRACES")!=0&&(debugging||util.env("BLUEBIRD_LONG_STACK_TRACES")));var wForgottenReturn=util.env("BLUEBIRD_W_FORGOTTEN_RETURN")!=0&&(warnings||!!util.env("BLUEBIRD_W_FORGOTTEN_RETURN"));var deferUnhandledRejectionCheck;(function(){var promises=[];function unhandledRejectionCheck(){for(var i=0;i<promises.length;++i){promises[i]._notifyUnhandledRejection()}unhandledRejectionClear()}function unhandledRejectionClear(){promises.length=0}deferUnhandledRejectionCheck=function(promise){promises.push(promise);setTimeout(unhandledRejectionCheck,1)};es5.defineProperty(Promise,"_unhandledRejectionCheck",{value:unhandledRejectionCheck});es5.defineProperty(Promise,"_unhandledRejectionClear",{value:unhandledRejectionClear})})();Promise.prototype.suppressUnhandledRejections=function(){var target=this._target();target._bitField=target._bitField&~1048576|524288};Promise.prototype._ensurePossibleRejectionHandled=function(){if((this._bitField&524288)!==0)return;this._setRejectionIsUnhandled();deferUnhandledRejectionCheck(this)};Promise.prototype._notifyUnhandledRejectionIsHandled=function(){fireRejectionEvent("rejectionHandled",unhandledRejectionHandled,undefined,this)};Promise.prototype._setReturnedNonUndefined=function(){this._bitField=this._bitField|268435456};Promise.prototype._returnedNonUndefined=function(){return(this._bitField&268435456)!==0};Promise.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var reason=this._settledValue();this._setUnhandledRejectionIsNotified();fireRejectionEvent("unhandledRejection",possiblyUnhandledRejection,reason,this)}};Promise.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=this._bitField|262144};Promise.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=this._bitField&~262144};Promise.prototype._isUnhandledRejectionNotified=function(){return(this._bitField&262144)>0};Promise.prototype._setRejectionIsUnhandled=function(){this._bitField=this._bitField|1048576};Promise.prototype._unsetRejectionIsUnhandled=function(){this._bitField=this._bitField&~1048576;if(this._isUnhandledRejectionNotified()){this._unsetUnhandledRejectionIsNotified();this._notifyUnhandledRejectionIsHandled()}};Promise.prototype._isRejectionUnhandled=function(){return(this._bitField&1048576)>0};Promise.prototype._warn=function(message,shouldUseOwnTrace,promise){return warn(message,shouldUseOwnTrace,promise||this)};Promise.onPossiblyUnhandledRejection=function(fn){var context=Promise._getContext();possiblyUnhandledRejection=util.contextBind(context,fn)};Promise.onUnhandledRejectionHandled=function(fn){var context=Promise._getContext();unhandledRejectionHandled=util.contextBind(context,fn)};var disableLongStackTraces=function(){};Promise.longStackTraces=function(){if(async.haveItemsQueued()&&!config.longStackTraces){throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n")}if(!config.longStackTraces&&longStackTracesIsSupported()){var Promise_captureStackTrace=Promise.prototype._captureStackTrace;var Promise_attachExtraTrace=Promise.prototype._attachExtraTrace;var Promise_dereferenceTrace=Promise.prototype._dereferenceTrace;config.longStackTraces=true;disableLongStackTraces=function(){if(async.haveItemsQueued()&&!config.longStackTraces){throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n")}Promise.prototype._captureStackTrace=Promise_captureStackTrace;Promise.prototype._attachExtraTrace=Promise_attachExtraTrace;Promise.prototype._dereferenceTrace=Promise_dereferenceTrace;Context.deactivateLongStackTraces();config.longStackTraces=false};Promise.prototype._captureStackTrace=longStackTracesCaptureStackTrace;Promise.prototype._attachExtraTrace=longStackTracesAttachExtraTrace;Promise.prototype._dereferenceTrace=longStackTracesDereferenceTrace;Context.activateLongStackTraces()}};Promise.hasLongStackTraces=function(){return config.longStackTraces&&longStackTracesIsSupported()};var legacyHandlers={unhandledrejection:{before:function(){var ret=util.global.onunhandledrejection;util.global.onunhandledrejection=null;return ret},after:function(fn){util.global.onunhandledrejection=fn}},rejectionhandled:{before:function(){var ret=util.global.onrejectionhandled;util.global.onrejectionhandled=null;return ret},after:function(fn){util.global.onrejectionhandled=fn}}};var fireDomEvent=function(){var dispatch=function(legacy,e){if(legacy){var fn;try{fn=legacy.before();return!util.global.dispatchEvent(e)}finally{legacy.after(fn)}}else{return!util.global.dispatchEvent(e)}};try{if(typeof CustomEvent==="function"){var event=new CustomEvent("CustomEvent");util.global.dispatchEvent(event);return function(name,event){name=name.toLowerCase();var eventData={detail:event,cancelable:true};var domEvent=new CustomEvent(name,eventData);es5.defineProperty(domEvent,"promise",{value:event.promise});es5.defineProperty(domEvent,"reason",{value:event.reason});return dispatch(legacyHandlers[name],domEvent)}}else if(typeof Event==="function"){var event=new Event("CustomEvent");util.global.dispatchEvent(event);return function(name,event){name=name.toLowerCase();var domEvent=new Event(name,{cancelable:true});domEvent.detail=event;es5.defineProperty(domEvent,"promise",{value:event.promise});es5.defineProperty(domEvent,"reason",{value:event.reason});return dispatch(legacyHandlers[name],domEvent)}}else{var event=document.createEvent("CustomEvent");event.initCustomEvent("testingtheevent",false,true,{});util.global.dispatchEvent(event);return function(name,event){name=name.toLowerCase();var domEvent=document.createEvent("CustomEvent");domEvent.initCustomEvent(name,false,true,event);return dispatch(legacyHandlers[name],domEvent)}}}catch(e){}return function(){return false}}();var fireGlobalEvent=function(){if(util.isNode){return function(){return process.emit.apply(process,arguments)}}else{if(!util.global){return function(){return false}}return function(name){var methodName="on"+name.toLowerCase();var method=util.global[methodName];if(!method)return false;method.apply(util.global,[].slice.call(arguments,1));return true}}}();function generatePromiseLifecycleEventObject(name,promise){return{promise:promise}}var eventToObjectGenerator={promiseCreated:generatePromiseLifecycleEventObject,promiseFulfilled:generatePromiseLifecycleEventObject,promiseRejected:generatePromiseLifecycleEventObject,promiseResolved:generatePromiseLifecycleEventObject,promiseCancelled:generatePromiseLifecycleEventObject,promiseChained:function(name,promise,child){return{promise:promise,child:child}},warning:function(name,warning){return{warning:warning}},unhandledRejection:function(name,reason,promise){return{reason:reason,promise:promise}},rejectionHandled:generatePromiseLifecycleEventObject};var activeFireEvent=function(name){var globalEventFired=false;try{globalEventFired=fireGlobalEvent.apply(null,arguments)}catch(e){async.throwLater(e);globalEventFired=true}var domEventFired=false;try{domEventFired=fireDomEvent(name,eventToObjectGenerator[name].apply(null,arguments))}catch(e){async.throwLater(e);domEventFired=true}return domEventFired||globalEventFired};Promise.config=function(opts){opts=Object(opts);if("longStackTraces"in opts){if(opts.longStackTraces){Promise.longStackTraces()}else if(!opts.longStackTraces&&Promise.hasLongStackTraces()){disableLongStackTraces()}}if("warnings"in opts){var warningsOption=opts.warnings;config.warnings=!!warningsOption;wForgottenReturn=config.warnings;if(util.isObject(warningsOption)){if("wForgottenReturn"in warningsOption){wForgottenReturn=!!warningsOption.wForgottenReturn}}}if("cancellation"in opts&&opts.cancellation&&!config.cancellation){if(async.haveItemsQueued()){throw new Error("cannot enable cancellation after promises are in use")}Promise.prototype._clearCancellationData=cancellationClearCancellationData;Promise.prototype._propagateFrom=cancellationPropagateFrom;Promise.prototype._onCancel=cancellationOnCancel;Promise.prototype._setOnCancel=cancellationSetOnCancel;Promise.prototype._attachCancellationCallback=cancellationAttachCancellationCallback;Promise.prototype._execute=cancellationExecute;propagateFromFunction=cancellationPropagateFrom;config.cancellation=true}if("monitoring"in opts){if(opts.monitoring&&!config.monitoring){config.monitoring=true;Promise.prototype._fireEvent=activeFireEvent}else if(!opts.monitoring&&config.monitoring){config.monitoring=false;Promise.prototype._fireEvent=defaultFireEvent}}if("asyncHooks"in opts&&util.nodeSupportsAsyncResource){var prev=config.asyncHooks;var cur=!!opts.asyncHooks;if(prev!==cur){config.asyncHooks=cur;if(cur){enableAsyncHooks()}else{disableAsyncHooks()}}}return Promise};function defaultFireEvent(){return false}Promise.prototype._fireEvent=defaultFireEvent;Promise.prototype._execute=function(executor,resolve,reject){try{executor(resolve,reject)}catch(e){return e}};Promise.prototype._onCancel=function(){};Promise.prototype._setOnCancel=function(handler){};Promise.prototype._attachCancellationCallback=function(onCancel){};Promise.prototype._captureStackTrace=function(){};Promise.prototype._attachExtraTrace=function(){};Promise.prototype._dereferenceTrace=function(){};Promise.prototype._clearCancellationData=function(){};Promise.prototype._propagateFrom=function(parent,flags){};function cancellationExecute(executor,resolve,reject){var promise=this;try{executor(resolve,reject,(function(onCancel){if(typeof onCancel!=="function"){throw new TypeError("onCancel must be a function, got: "+util.toString(onCancel))}promise._attachCancellationCallback(onCancel)}))}catch(e){return e}}function cancellationAttachCancellationCallback(onCancel){if(!this._isCancellable())return this;var previousOnCancel=this._onCancel();if(previousOnCancel!==undefined){if(util.isArray(previousOnCancel)){previousOnCancel.push(onCancel)}else{this._setOnCancel([previousOnCancel,onCancel])}}else{this._setOnCancel(onCancel)}}function cancellationOnCancel(){return this._onCancelField}function cancellationSetOnCancel(onCancel){this._onCancelField=onCancel}function cancellationClearCancellationData(){this._cancellationParent=undefined;this._onCancelField=undefined}function cancellationPropagateFrom(parent,flags){if((flags&1)!==0){this._cancellationParent=parent;var branchesRemainingToCancel=parent._branchesRemainingToCancel;if(branchesRemainingToCancel===undefined){branchesRemainingToCancel=0}parent._branchesRemainingToCancel=branchesRemainingToCancel+1}if((flags&2)!==0&&parent._isBound()){this._setBoundTo(parent._boundTo)}}function bindingPropagateFrom(parent,flags){if((flags&2)!==0&&parent._isBound()){this._setBoundTo(parent._boundTo)}}var propagateFromFunction=bindingPropagateFrom;function boundValueFunction(){var ret=this._boundTo;if(ret!==undefined){if(ret instanceof Promise){if(ret.isFulfilled()){return ret.value()}else{return undefined}}}return ret}function longStackTracesCaptureStackTrace(){this._trace=new CapturedTrace(this._peekContext())}function longStackTracesAttachExtraTrace(error,ignoreSelf){if(canAttachTrace(error)){var trace=this._trace;if(trace!==undefined){if(ignoreSelf)trace=trace._parent}if(trace!==undefined){trace.attachExtraTrace(error)}else if(!error.__stackCleaned__){var parsed=parseStackAndMessage(error);util.notEnumerableProp(error,"stack",parsed.message+"\n"+parsed.stack.join("\n"));util.notEnumerableProp(error,"__stackCleaned__",true)}}}function longStackTracesDereferenceTrace(){this._trace=undefined}function checkForgottenReturns(returnValue,promiseCreated,name,promise,parent){if(returnValue===undefined&&promiseCreated!==null&&wForgottenReturn){if(parent!==undefined&&parent._returnedNonUndefined())return;if((promise._bitField&65535)===0)return;if(name)name=name+" ";var handlerLine="";var creatorLine="";if(promiseCreated._trace){var traceLines=promiseCreated._trace.stack.split("\n");var stack=cleanStack(traceLines);for(var i=stack.length-1;i>=0;--i){var line=stack[i];if(!nodeFramePattern.test(line)){var lineMatches=line.match(parseLinePattern);if(lineMatches){handlerLine="at "+lineMatches[1]+":"+lineMatches[2]+":"+lineMatches[3]+" "}break}}if(stack.length>0){var firstUserLine=stack[0];for(var i=0;i<traceLines.length;++i){if(traceLines[i]===firstUserLine){if(i>0){creatorLine="\n"+traceLines[i-1]}break}}}}var msg="a promise was created in a "+name+"handler "+handlerLine+"but was not returned from it, "+"see http://goo.gl/rRqMUw"+creatorLine;promise._warn(msg,true,promiseCreated)}}function deprecated(name,replacement){var message=name+" is deprecated and will be removed in a future version.";if(replacement)message+=" Use "+replacement+" instead.";return warn(message)}function warn(message,shouldUseOwnTrace,promise){if(!config.warnings)return;var warning=new Warning(message);var ctx;if(shouldUseOwnTrace){promise._attachExtraTrace(warning)}else if(config.longStackTraces&&(ctx=Promise._peekContext())){ctx.attachExtraTrace(warning)}else{var parsed=parseStackAndMessage(warning);warning.stack=parsed.message+"\n"+parsed.stack.join("\n")}if(!activeFireEvent("warning",warning)){formatAndLogError(warning,"",true)}}function reconstructStack(message,stacks){for(var i=0;i<stacks.length-1;++i){stacks[i].push("From previous event:");stacks[i]=stacks[i].join("\n")}if(i<stacks.length){stacks[i]=stacks[i].join("\n")}return message+"\n"+stacks.join("\n")}function removeDuplicateOrEmptyJumps(stacks){for(var i=0;i<stacks.length;++i){if(stacks[i].length===0||i+1<stacks.length&&stacks[i][0]===stacks[i+1][0]){stacks.splice(i,1);i--}}}function removeCommonRoots(stacks){var current=stacks[0];for(var i=1;i<stacks.length;++i){var prev=stacks[i];var currentLastIndex=current.length-1;var currentLastLine=current[currentLastIndex];var commonRootMeetPoint=-1;for(var j=prev.length-1;j>=0;--j){if(prev[j]===currentLastLine){commonRootMeetPoint=j;break}}for(var j=commonRootMeetPoint;j>=0;--j){var line=prev[j];if(current[currentLastIndex]===line){current.pop();currentLastIndex--}else{break}}current=prev}}function cleanStack(stack){var ret=[];for(var i=0;i<stack.length;++i){var line=stack[i];var isTraceLine=" (No stack trace)"===line||stackFramePattern.test(line);var isInternalFrame=isTraceLine&&shouldIgnore(line);if(isTraceLine&&!isInternalFrame){if(indentStackFrames&&line.charAt(0)!==" "){line=" "+line}ret.push(line)}}return ret}function stackFramesAsArray(error){var stack=error.stack.replace(/\s+$/g,"").split("\n");for(var i=0;i<stack.length;++i){var line=stack[i];if(" (No stack trace)"===line||stackFramePattern.test(line)){break}}if(i>0&&error.name!="SyntaxError"){stack=stack.slice(i)}return stack}function parseStackAndMessage(error){var stack=error.stack;var message=error.toString();stack=typeof stack==="string"&&stack.length>0?stackFramesAsArray(error):[" (No stack trace)"];return{message:message,stack:error.name=="SyntaxError"?stack:cleanStack(stack)}}function formatAndLogError(error,title,isSoft){if(typeof console!=="undefined"){var message;if(util.isObject(error)){var stack=error.stack;message=title+formatStack(stack,error)}else{message=title+String(error)}if(typeof printWarning==="function"){printWarning(message,isSoft)}else if(typeof console.log==="function"||typeof console.log==="object"){console.log(message)}}}function fireRejectionEvent(name,localHandler,reason,promise){var localEventFired=false;try{if(typeof localHandler==="function"){localEventFired=true;if(name==="rejectionHandled"){localHandler(promise)}else{localHandler(reason,promise)}}}catch(e){async.throwLater(e)}if(name==="unhandledRejection"){if(!activeFireEvent(name,reason,promise)&&!localEventFired){formatAndLogError(reason,"Unhandled rejection ")}}else{activeFireEvent(name,promise)}}function formatNonError(obj){var str;if(typeof obj==="function"){str="[function "+(obj.name||"anonymous")+"]"}else{str=obj&&typeof obj.toString==="function"?obj.toString():util.toString(obj);var ruselessToString=/\[object [a-zA-Z0-9$_]+\]/;if(ruselessToString.test(str)){try{var newStr=JSON.stringify(obj);str=newStr}catch(e){}}if(str.length===0){str="(empty array)"}}return"(<"+snip(str)+">, no stack trace)"}function snip(str){var maxChars=41;if(str.length<maxChars){return str}return str.substr(0,maxChars-3)+"..."}function longStackTracesIsSupported(){return typeof captureStackTrace==="function"}var shouldIgnore=function(){return false};var parseLineInfoRegex=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;function parseLineInfo(line){var matches=line.match(parseLineInfoRegex);if(matches){return{fileName:matches[1],line:parseInt(matches[2],10)}}}function setBounds(firstLineError,lastLineError){if(!longStackTracesIsSupported())return;var firstStackLines=(firstLineError.stack||"").split("\n");var lastStackLines=(lastLineError.stack||"").split("\n");var firstIndex=-1;var lastIndex=-1;var firstFileName;var lastFileName;for(var i=0;i<firstStackLines.length;++i){var result=parseLineInfo(firstStackLines[i]);if(result){firstFileName=result.fileName;firstIndex=result.line;break}}for(var i=0;i<lastStackLines.length;++i){var result=parseLineInfo(lastStackLines[i]);if(result){lastFileName=result.fileName;lastIndex=result.line;break}}if(firstIndex<0||lastIndex<0||!firstFileName||!lastFileName||firstFileName!==lastFileName||firstIndex>=lastIndex){return}shouldIgnore=function(line){if(bluebirdFramePattern.test(line))return true;var info=parseLineInfo(line);if(info){if(info.fileName===firstFileName&&(firstIndex<=info.line&&info.line<=lastIndex)){return true}}return false}}function CapturedTrace(parent){this._parent=parent;this._promisesCreated=0;var length=this._length=1+(parent===undefined?0:parent._length);captureStackTrace(this,CapturedTrace);if(length>32)this.uncycle()}util.inherits(CapturedTrace,Error);Context.CapturedTrace=CapturedTrace;CapturedTrace.prototype.uncycle=function(){var length=this._length;if(length<2)return;var nodes=[];var stackToIndex={};for(var i=0,node=this;node!==undefined;++i){nodes.push(node);node=node._parent}length=this._length=i;for(var i=length-1;i>=0;--i){var stack=nodes[i].stack;if(stackToIndex[stack]===undefined){stackToIndex[stack]=i}}for(var i=0;i<length;++i){var currentStack=nodes[i].stack;var index=stackToIndex[currentStack];if(index!==undefined&&index!==i){if(index>0){nodes[index-1]._parent=undefined;nodes[index-1]._length=1}nodes[i]._parent=undefined;nodes[i]._length=1;var cycleEdgeNode=i>0?nodes[i-1]:this;if(index<length-1){cycleEdgeNode._parent=nodes[index+1];cycleEdgeNode._parent.uncycle();cycleEdgeNode._length=cycleEdgeNode._parent._length+1}else{cycleEdgeNode._parent=undefined;cycleEdgeNode._length=1}var currentChildLength=cycleEdgeNode._length+1;for(var j=i-2;j>=0;--j){nodes[j]._length=currentChildLength;currentChildLength++}return}}};CapturedTrace.prototype.attachExtraTrace=function(error){if(error.__stackCleaned__)return;this.uncycle();var parsed=parseStackAndMessage(error);var message=parsed.message;var stacks=[parsed.stack];var trace=this;while(trace!==undefined){stacks.push(cleanStack(trace.stack.split("\n")));trace=trace._parent}removeCommonRoots(stacks);removeDuplicateOrEmptyJumps(stacks);util.notEnumerableProp(error,"stack",reconstructStack(message,stacks));util.notEnumerableProp(error,"__stackCleaned__",true)};var captureStackTrace=function stackDetection(){var v8stackFramePattern=/^\s*at\s*/;var v8stackFormatter=function(stack,error){if(typeof stack==="string")return stack;if(error.name!==undefined&&error.message!==undefined){return error.toString()}return formatNonError(error)};if(typeof Error.stackTraceLimit==="number"&&typeof Error.captureStackTrace==="function"){Error.stackTraceLimit+=6;stackFramePattern=v8stackFramePattern;formatStack=v8stackFormatter;var captureStackTrace=Error.captureStackTrace;shouldIgnore=function(line){return bluebirdFramePattern.test(line)};return function(receiver,ignoreUntil){Error.stackTraceLimit+=6;captureStackTrace(receiver,ignoreUntil);Error.stackTraceLimit-=6}}var err=new Error;if(typeof err.stack==="string"&&err.stack.split("\n")[0].indexOf("stackDetection@")>=0){stackFramePattern=/@/;formatStack=v8stackFormatter;indentStackFrames=true;return function captureStackTrace(o){o.stack=(new Error).stack}}var hasStackAfterThrow;try{throw new Error}catch(e){hasStackAfterThrow="stack"in e}if(!("stack"in err)&&hasStackAfterThrow&&typeof Error.stackTraceLimit==="number"){stackFramePattern=v8stackFramePattern;formatStack=v8stackFormatter;return function captureStackTrace(o){Error.stackTraceLimit+=6;try{throw new Error}catch(e){o.stack=e.stack}Error.stackTraceLimit-=6}}formatStack=function(stack,error){if(typeof stack==="string")return stack;if((typeof error==="object"||typeof error==="function")&&error.name!==undefined&&error.message!==undefined){return error.toString()}return formatNonError(error)};return null}([]);if(typeof console!=="undefined"&&typeof console.warn!=="undefined"){printWarning=function(message){console.warn(message)};if(util.isNode&&process.stderr.isTTY){printWarning=function(message,isSoft){var color=isSoft?"[33m":"[31m";console.warn(color+message+"[0m\n")}}else if(!util.isNode&&typeof(new Error).stack==="string"){printWarning=function(message,isSoft){console.warn("%c"+message,isSoft?"color: darkorange":"color: red")}}}var config={warnings:warnings,longStackTraces:false,cancellation:false,monitoring:false,asyncHooks:false};if(longStackTraces)Promise.longStackTraces();return{asyncHooks:function(){return config.asyncHooks},longStackTraces:function(){return config.longStackTraces},warnings:function(){return config.warnings},cancellation:function(){return config.cancellation},monitoring:function(){return config.monitoring},propagateFromFunction:function(){return propagateFromFunction},boundValueFunction:function(){return boundValueFunction},checkForgottenReturns:checkForgottenReturns,setBounds:setBounds,warn:warn,deprecated:deprecated,CapturedTrace:CapturedTrace,fireDomEvent:fireDomEvent,fireGlobalEvent:fireGlobalEvent}}},{"./errors":12,"./es5":13,"./util":36}],10:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise){function returner(){return this.value}function thrower(){throw this.reason}Promise.prototype["return"]=Promise.prototype.thenReturn=function(value){if(value instanceof Promise)value.suppressUnhandledRejections();return this._then(returner,undefined,undefined,{value:value},undefined)};Promise.prototype["throw"]=Promise.prototype.thenThrow=function(reason){return this._then(thrower,undefined,undefined,{reason:reason},undefined)};Promise.prototype.catchThrow=function(reason){if(arguments.length<=1){return this._then(undefined,thrower,undefined,{reason:reason},undefined)}else{var _reason=arguments[1];var handler=function(){throw _reason};return this.caught(reason,handler)}};Promise.prototype.catchReturn=function(value){if(arguments.length<=1){if(value instanceof Promise)value.suppressUnhandledRejections();return this._then(undefined,returner,undefined,{value:value},undefined)}else{var _value=arguments[1];if(_value instanceof Promise)_value.suppressUnhandledRejections();var handler=function(){return _value};return this.caught(value,handler)}}}},{}],11:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL){var PromiseReduce=Promise.reduce;var PromiseAll=Promise.all;function promiseAllThis(){return PromiseAll(this)}function PromiseMapSeries(promises,fn){return PromiseReduce(promises,fn,INTERNAL,INTERNAL)}Promise.prototype.each=function(fn){return PromiseReduce(this,fn,INTERNAL,0)._then(promiseAllThis,undefined,undefined,this,undefined)};Promise.prototype.mapSeries=function(fn){return PromiseReduce(this,fn,INTERNAL,INTERNAL)};Promise.each=function(promises,fn){return PromiseReduce(promises,fn,INTERNAL,0)._then(promiseAllThis,undefined,undefined,promises,undefined)};Promise.mapSeries=PromiseMapSeries}},{}],12:[function(_dereq_,module,exports){"use strict";var es5=_dereq_("./es5");var Objectfreeze=es5.freeze;var util=_dereq_("./util");var inherits=util.inherits;var notEnumerableProp=util.notEnumerableProp;function subError(nameProperty,defaultMessage){function SubError(message){if(!(this instanceof SubError))return new SubError(message);notEnumerableProp(this,"message",typeof message==="string"?message:defaultMessage);notEnumerableProp(this,"name",nameProperty);if(Error.captureStackTrace){Error.captureStackTrace(this,this.constructor)}else{Error.call(this)}}inherits(SubError,Error);return SubError}var _TypeError,_RangeError;var Warning=subError("Warning","warning");var CancellationError=subError("CancellationError","cancellation error");var TimeoutError=subError("TimeoutError","timeout error");var AggregateError=subError("AggregateError","aggregate error");try{_TypeError=TypeError;_RangeError=RangeError}catch(e){_TypeError=subError("TypeError","type error");_RangeError=subError("RangeError","range error")}var methods=("join pop push shift unshift slice filter forEach some "+"every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");for(var i=0;i<methods.length;++i){if(typeof Array.prototype[methods[i]]==="function"){AggregateError.prototype[methods[i]]=Array.prototype[methods[i]]}}es5.defineProperty(AggregateError.prototype,"length",{value:0,configurable:false,writable:true,enumerable:true});AggregateError.prototype["isOperational"]=true;var level=0;AggregateError.prototype.toString=function(){var indent=Array(level*4+1).join(" ");var ret="\n"+indent+"AggregateError of:"+"\n";level++;indent=Array(level*4+1).join(" ");for(var i=0;i<this.length;++i){var str=this[i]===this?"[Circular AggregateError]":this[i]+"";var lines=str.split("\n");for(var j=0;j<lines.length;++j){lines[j]=indent+lines[j]}str=lines.join("\n");ret+=str+"\n"}level--;return ret};function OperationalError(message){if(!(this instanceof OperationalError))return new OperationalError(message);notEnumerableProp(this,"name","OperationalError");notEnumerableProp(this,"message",message);this.cause=message;this["isOperational"]=true;if(message instanceof Error){notEnumerableProp(this,"message",message.message);notEnumerableProp(this,"stack",message.stack)}else if(Error.captureStackTrace){Error.captureStackTrace(this,this.constructor)}}inherits(OperationalError,Error);var errorTypes=Error["__BluebirdErrorTypes__"];if(!errorTypes){errorTypes=Objectfreeze({CancellationError:CancellationError,TimeoutError:TimeoutError,OperationalError:OperationalError,RejectionError:OperationalError,AggregateError:AggregateError});es5.defineProperty(Error,"__BluebirdErrorTypes__",{value:errorTypes,writable:false,enumerable:false,configurable:false})}module.exports={Error:Error,TypeError:_TypeError,RangeError:_RangeError,CancellationError:errorTypes.CancellationError,OperationalError:errorTypes.OperationalError,TimeoutError:errorTypes.TimeoutError,AggregateError:errorTypes.AggregateError,Warning:Warning}},{"./es5":13,"./util":36}],13:[function(_dereq_,module,exports){var isES5=function(){"use strict";return this===undefined}();if(isES5){module.exports={freeze:Object.freeze,defineProperty:Object.defineProperty,getDescriptor:Object.getOwnPropertyDescriptor,keys:Object.keys,names:Object.getOwnPropertyNames,getPrototypeOf:Object.getPrototypeOf,isArray:Array.isArray,isES5:isES5,propertyIsWritable:function(obj,prop){var descriptor=Object.getOwnPropertyDescriptor(obj,prop);return!!(!descriptor||descriptor.writable||descriptor.set)}}}else{var has={}.hasOwnProperty;var str={}.toString;var proto={}.constructor.prototype;var ObjectKeys=function(o){var ret=[];for(var key in o){if(has.call(o,key)){ret.push(key)}}return ret};var ObjectGetDescriptor=function(o,key){return{value:o[key]}};var ObjectDefineProperty=function(o,key,desc){o[key]=desc.value;return o};var ObjectFreeze=function(obj){return obj};var ObjectGetPrototypeOf=function(obj){try{return Object(obj).constructor.prototype}catch(e){return proto}};var ArrayIsArray=function(obj){try{return str.call(obj)==="[object Array]"}catch(e){return false}};module.exports={isArray:ArrayIsArray,keys:ObjectKeys,names:ObjectKeys,defineProperty:ObjectDefineProperty,getDescriptor:ObjectGetDescriptor,freeze:ObjectFreeze,getPrototypeOf:ObjectGetPrototypeOf,isES5:isES5,propertyIsWritable:function(){return true}}}},{}],14:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL){var PromiseMap=Promise.map;Promise.prototype.filter=function(fn,options){return PromiseMap(this,fn,options,INTERNAL)};Promise.filter=function(promises,fn,options){return PromiseMap(promises,fn,options,INTERNAL)}}},{}],15:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,tryConvertToPromise,NEXT_FILTER){var util=_dereq_("./util");var CancellationError=Promise.CancellationError;var errorObj=util.errorObj;var catchFilter=_dereq_("./catch_filter")(NEXT_FILTER);function PassThroughHandlerContext(promise,type,handler){this.promise=promise;this.type=type;this.handler=handler;this.called=false;this.cancelPromise=null}PassThroughHandlerContext.prototype.isFinallyHandler=function(){return this.type===0};function FinallyHandlerCancelReaction(finallyHandler){this.finallyHandler=finallyHandler}FinallyHandlerCancelReaction.prototype._resultCancelled=function(){checkCancel(this.finallyHandler)};function checkCancel(ctx,reason){if(ctx.cancelPromise!=null){if(arguments.length>1){ctx.cancelPromise._reject(reason)}else{ctx.cancelPromise._cancel()}ctx.cancelPromise=null;return true}return false}function succeed(){return finallyHandler.call(this,this.promise._target()._settledValue())}function fail(reason){if(checkCancel(this,reason))return;errorObj.e=reason;return errorObj}function finallyHandler(reasonOrValue){var promise=this.promise;var handler=this.handler;if(!this.called){this.called=true;var ret=this.isFinallyHandler()?handler.call(promise._boundValue()):handler.call(promise._boundValue(),reasonOrValue);if(ret===NEXT_FILTER){return ret}else if(ret!==undefined){promise._setReturnedNonUndefined();var maybePromise=tryConvertToPromise(ret,promise);if(maybePromise instanceof Promise){if(this.cancelPromise!=null){if(maybePromise._isCancelled()){var reason=new CancellationError("late cancellation observer");promise._attachExtraTrace(reason);errorObj.e=reason;return errorObj}else if(maybePromise.isPending()){maybePromise._attachCancellationCallback(new FinallyHandlerCancelReaction(this))}}return maybePromise._then(succeed,fail,undefined,this,undefined)}}}if(promise.isRejected()){checkCancel(this);errorObj.e=reasonOrValue;return errorObj}else{checkCancel(this);return reasonOrValue}}Promise.prototype._passThrough=function(handler,type,success,fail){if(typeof handler!=="function")return this.then();return this._then(success,fail,undefined,new PassThroughHandlerContext(this,type,handler),undefined)};Promise.prototype.lastly=Promise.prototype["finally"]=function(handler){return this._passThrough(handler,0,finallyHandler,finallyHandler)};Promise.prototype.tap=function(handler){return this._passThrough(handler,1,finallyHandler)};Promise.prototype.tapCatch=function(handlerOrPredicate){var len=arguments.length;if(len===1){return this._passThrough(handlerOrPredicate,1,undefined,finallyHandler)}else{var catchInstances=new Array(len-1),j=0,i;for(i=0;i<len-1;++i){var item=arguments[i];if(util.isObject(item)){catchInstances[j++]=item}else{return Promise.reject(new TypeError("tapCatch statement predicate: "+"expecting an object but got "+util.classString(item)))}}catchInstances.length=j;var handler=arguments[i];return this._passThrough(catchFilter(catchInstances,handler,this),1,undefined,finallyHandler)}};return PassThroughHandlerContext}},{"./catch_filter":7,"./util":36}],16:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,apiRejection,INTERNAL,tryConvertToPromise,Proxyable,debug){var errors=_dereq_("./errors");var TypeError=errors.TypeError;var util=_dereq_("./util");var errorObj=util.errorObj;var tryCatch=util.tryCatch;var yieldHandlers=[];function promiseFromYieldHandler(value,yieldHandlers,traceParent){for(var i=0;i<yieldHandlers.length;++i){traceParent._pushContext();var result=tryCatch(yieldHandlers[i])(value);traceParent._popContext();if(result===errorObj){traceParent._pushContext();var ret=Promise.reject(errorObj.e);traceParent._popContext();return ret}var maybePromise=tryConvertToPromise(result,traceParent);if(maybePromise instanceof Promise)return maybePromise}return null}function PromiseSpawn(generatorFunction,receiver,yieldHandler,stack){if(debug.cancellation()){var internal=new Promise(INTERNAL);var _finallyPromise=this._finallyPromise=new Promise(INTERNAL);this._promise=internal.lastly((function(){return _finallyPromise}));internal._captureStackTrace();internal._setOnCancel(this)}else{var promise=this._promise=new Promise(INTERNAL);promise._captureStackTrace()}this._stack=stack;this._generatorFunction=generatorFunction;this._receiver=receiver;this._generator=undefined;this._yieldHandlers=typeof yieldHandler==="function"?[yieldHandler].concat(yieldHandlers):yieldHandlers;this._yieldedPromise=null;this._cancellationPhase=false}util.inherits(PromiseSpawn,Proxyable);PromiseSpawn.prototype._isResolved=function(){return this._promise===null};PromiseSpawn.prototype._cleanup=function(){this._promise=this._generator=null;if(debug.cancellation()&&this._finallyPromise!==null){this._finallyPromise._fulfill();this._finallyPromise=null}};PromiseSpawn.prototype._promiseCancelled=function(){if(this._isResolved())return;var implementsReturn=typeof this._generator["return"]!=="undefined";var result;if(!implementsReturn){var reason=new Promise.CancellationError("generator .return() sentinel");Promise.coroutine.returnSentinel=reason;this._promise._attachExtraTrace(reason);this._promise._pushContext();result=tryCatch(this._generator["throw"]).call(this._generator,reason);this._promise._popContext()}else{this._promise._pushContext();result=tryCatch(this._generator["return"]).call(this._generator,undefined);this._promise._popContext()}this._cancellationPhase=true;this._yieldedPromise=null;this._continue(result)};PromiseSpawn.prototype._promiseFulfilled=function(value){this._yieldedPromise=null;this._promise._pushContext();var result=tryCatch(this._generator.next).call(this._generator,value);this._promise._popContext();this._continue(result)};PromiseSpawn.prototype._promiseRejected=function(reason){this._yieldedPromise=null;this._promise._attachExtraTrace(reason);this._promise._pushContext();var result=tryCatch(this._generator["throw"]).call(this._generator,reason);this._promise._popContext();this._continue(result)};PromiseSpawn.prototype._resultCancelled=function(){if(this._yieldedPromise instanceof Promise){var promise=this._yieldedPromise;this._yieldedPromise=null;promise.cancel()}};PromiseSpawn.prototype.promise=function(){return this._promise};PromiseSpawn.prototype._run=function(){this._generator=this._generatorFunction.call(this._receiver);this._receiver=this._generatorFunction=undefined;this._promiseFulfilled(undefined)};PromiseSpawn.prototype._continue=function(result){var promise=this._promise;if(result===errorObj){this._cleanup();if(this._cancellationPhase){return promise.cancel()}else{return promise._rejectCallback(result.e,false)}}var value=result.value;if(result.done===true){this._cleanup();if(this._cancellationPhase){return promise.cancel()}else{return promise._resolveCallback(value)}}else{var maybePromise=tryConvertToPromise(value,this._promise);if(!(maybePromise instanceof Promise)){maybePromise=promiseFromYieldHandler(maybePromise,this._yieldHandlers,this._promise);if(maybePromise===null){this._promiseRejected(new TypeError("A value %s was yielded that could not be treated as a promise\n\n See http://goo.gl/MqrFmX\n\n".replace("%s",String(value))+"From coroutine:\n"+this._stack.split("\n").slice(1,-7).join("\n")));return}}maybePromise=maybePromise._target();var bitField=maybePromise._bitField;if((bitField&50397184)===0){this._yieldedPromise=maybePromise;maybePromise._proxy(this,null)}else if((bitField&33554432)!==0){Promise._async.invoke(this._promiseFulfilled,this,maybePromise._value())}else if((bitField&16777216)!==0){Promise._async.invoke(this._promiseRejected,this,maybePromise._reason())}else{this._promiseCancelled()}}};Promise.coroutine=function(generatorFunction,options){if(typeof generatorFunction!=="function"){throw new TypeError("generatorFunction must be a function\n\n See http://goo.gl/MqrFmX\n")}var yieldHandler=Object(options).yieldHandler;var PromiseSpawn$=PromiseSpawn;var stack=(new Error).stack;return function(){var generator=generatorFunction.apply(this,arguments);var spawn=new PromiseSpawn$(undefined,undefined,yieldHandler,stack);var ret=spawn.promise();spawn._generator=generator;spawn._promiseFulfilled(undefined);return ret}};Promise.coroutine.addYieldHandler=function(fn){if(typeof fn!=="function"){throw new TypeError("expecting a function but got "+util.classString(fn))}yieldHandlers.push(fn)};Promise.spawn=function(generatorFunction){debug.deprecated("Promise.spawn()","Promise.coroutine()");if(typeof generatorFunction!=="function"){return apiRejection("generatorFunction must be a function\n\n See http://goo.gl/MqrFmX\n")}var spawn=new PromiseSpawn(generatorFunction,this);var ret=spawn.promise();spawn._run(Promise.spawn);return ret}}},{"./errors":12,"./util":36}],17:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,tryConvertToPromise,INTERNAL,async){var util=_dereq_("./util");var canEvaluate=util.canEvaluate;var tryCatch=util.tryCatch;var errorObj=util.errorObj;var reject;if(!true){if(canEvaluate){var thenCallback=function(i){return new Function("value","holder"," \n 'use strict'; \n holder.pIndex = value; \n holder.checkFulfillment(this); \n ".replace(/Index/g,i))};var promiseSetter=function(i){return new Function("promise","holder"," \n 'use strict'; \n holder.pIndex = promise; \n ".replace(/Index/g,i))};var generateHolderClass=function(total){var props=new Array(total);for(var i=0;i<props.length;++i){props[i]="this.p"+(i+1)}var assignment=props.join(" = ")+" = null;";var cancellationCode="var promise;\n"+props.map((function(prop){return" \n promise = "+prop+"; \n if (promise instanceof Promise) { \n promise.cancel(); \n } \n "})).join("\n");var passedArguments=props.join(", ");var name="Holder$"+total;var code="return function(tryCatch, errorObj, Promise, async) { \n 'use strict'; \n function [TheName](fn) { \n [TheProperties] \n this.fn = fn; \n this.asyncNeeded = true; \n this.now = 0; \n } \n \n [TheName].prototype._callFunction = function(promise) { \n promise._pushContext(); \n var ret = tryCatch(this.fn)([ThePassedArguments]); \n promise._popContext(); \n if (ret === errorObj) { \n promise._rejectCallback(ret.e, false); \n } else { \n promise._resolveCallback(ret); \n } \n }; \n \n [TheName].prototype.checkFulfillment = function(promise) { \n var now = ++this.now; \n if (now === [TheTotal]) { \n if (this.asyncNeeded) { \n async.invoke(this._callFunction, this, promise); \n } else { \n this._callFunction(promise); \n } \n \n } \n }; \n \n [TheName].prototype._resultCancelled = function() { \n [CancellationCode] \n }; \n \n return [TheName]; \n }(tryCatch, errorObj, Promise, async); \n ";code=code.replace(/\[TheName\]/g,name).replace(/\[TheTotal\]/g,total).replace(/\[ThePassedArguments\]/g,passedArguments).replace(/\[TheProperties\]/g,assignment).replace(/\[CancellationCode\]/g,cancellationCode);return new Function("tryCatch","errorObj","Promise","async",code)(tryCatch,errorObj,Promise,async)};var holderClasses=[];var thenCallbacks=[];var promiseSetters=[];for(var i=0;i<8;++i){holderClasses.push(generateHolderClass(i+1));thenCallbacks.push(thenCallback(i+1));promiseSetters.push(promiseSetter(i+1))}reject=function(reason){this._reject(reason)}}}Promise.join=function(){var last=arguments.length-1;var fn;if(last>0&&typeof arguments[last]==="function"){fn=arguments[last];if(!true){if(last<=8&&canEvaluate){var ret=new Promise(INTERNAL);ret._captureStackTrace();var HolderClass=holderClasses[last-1];var holder=new HolderClass(fn);var callbacks=thenCallbacks;for(var i=0;i<last;++i){var maybePromise=tryConvertToPromise(arguments[i],ret);if(maybePromise instanceof Promise){maybePromise=maybePromise._target();var bitField=maybePromise._bitField;if((bitField&50397184)===0){maybePromise._then(callbacks[i],reject,undefined,ret,holder);promiseSetters[i](maybePromise,holder);holder.asyncNeeded=false}else if((bitField&33554432)!==0){callbacks[i].call(ret,maybePromise._value(),holder)}else if((bitField&16777216)!==0){ret._reject(maybePromise._reason())}else{ret._cancel()}}else{callbacks[i].call(ret,maybePromise,holder)}}if(!ret._isFateSealed()){if(holder.asyncNeeded){var context=Promise._getContext();holder.fn=util.contextBind(context,holder.fn)}ret._setAsyncGuaranteed();ret._setOnCancel(holder)}return ret}}}var args=[].slice.call(arguments);if(fn)args.pop();var ret=new PromiseArray(args).promise();return fn!==undefined?ret.spread(fn):ret}}},{"./util":36}],18:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,apiRejection,tryConvertToPromise,INTERNAL,debug){var util=_dereq_("./util");var tryCatch=util.tryCatch;var errorObj=util.errorObj;var async=Promise._async;function MappingPromiseArray(promises,fn,limit,_filter){this.constructor$(promises);this._promise._captureStackTrace();var context=Promise._getContext();this._callback=util.contextBind(context,fn);this._preservedValues=_filter===INTERNAL?new Array(this.length()):null;this._limit=limit;this._inFlight=0;this._queue=[];async.invoke(this._asyncInit,this,undefined);if(util.isArray(promises)){for(var i=0;i<promises.length;++i){var maybePromise=promises[i];if(maybePromise instanceof Promise){maybePromise.suppressUnhandledRejections()}}}}util.inherits(MappingPromiseArray,PromiseArray);MappingPromiseArray.prototype._asyncInit=function(){this._init$(undefined,-2)};MappingPromiseArray.prototype._init=function(){};MappingPromiseArray.prototype._promiseFulfilled=function(value,index){var values=this._values;var length=this.length();var preservedValues=this._preservedValues;var limit=this._limit;if(index<0){index=index*-1-1;values[index]=value;if(limit>=1){this._inFlight--;this._drainQueue();if(this._isResolved())return true}}else{if(limit>=1&&this._inFlight>=limit){values[index]=value;this._queue.push(index);return false}if(preservedValues!==null)preservedValues[index]=value;var promise=this._promise;var callback=this._callback;var receiver=promise._boundValue();promise._pushContext();var ret=tryCatch(callback).call(receiver,value,index,length);var promiseCreated=promise._popContext();debug.checkForgottenReturns(ret,promiseCreated,preservedValues!==null?"Promise.filter":"Promise.map",promise);if(ret===errorObj){this._reject(ret.e);return true}var maybePromise=tryConvertToPromise(ret,this._promise);if(maybePromise instanceof Promise){maybePromise=maybePromise._target();var bitField=maybePromise._bitField;if((bitField&50397184)===0){if(limit>=1)this._inFlight++;values[index]=maybePromise;maybePromise._proxy(this,(index+1)*-1);return false}else if((bitField&33554432)!==0){ret=maybePromise._value()}else if((bitField&16777216)!==0){this._reject(maybePromise._reason());return true}else{this._cancel();return true}}values[index]=ret}var totalResolved=++this._totalResolved;if(totalResolved>=length){if(preservedValues!==null){this._filter(values,preservedValues)}else{this._resolve(values)}return true}return false};MappingPromiseArray.prototype._drainQueue=function(){var queue=this._queue;var limit=this._limit;var values=this._values;while(queue.length>0&&this._inFlight<limit){if(this._isResolved())return;var index=queue.pop();this._promiseFulfilled(values[index],index)}};MappingPromiseArray.prototype._filter=function(booleans,values){var len=values.length;var ret=new Array(len);var j=0;for(var i=0;i<len;++i){if(booleans[i])ret[j++]=values[i]}ret.length=j;this._resolve(ret)};MappingPromiseArray.prototype.preservedValues=function(){return this._preservedValues};function map(promises,fn,options,_filter){if(typeof fn!=="function"){return apiRejection("expecting a function but got "+util.classString(fn))}var limit=0;if(options!==undefined){if(typeof options==="object"&&options!==null){if(typeof options.concurrency!=="number"){return Promise.reject(new TypeError("'concurrency' must be a number but it is "+util.classString(options.concurrency)))}limit=options.concurrency}else{return Promise.reject(new TypeError("options argument must be an object but it is "+util.classString(options)))}}limit=typeof limit==="number"&&isFinite(limit)&&limit>=1?limit:0;return new MappingPromiseArray(promises,fn,limit,_filter).promise()}Promise.prototype.map=function(fn,options){return map(this,fn,options,null)};Promise.map=function(promises,fn,options,_filter){return map(promises,fn,options,_filter)}}},{"./util":36}],19:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL,tryConvertToPromise,apiRejection,debug){var util=_dereq_("./util");var tryCatch=util.tryCatch;Promise.method=function(fn){if(typeof fn!=="function"){throw new Promise.TypeError("expecting a function but got "+util.classString(fn))}return function(){var ret=new Promise(INTERNAL);ret._captureStackTrace();ret._pushContext();var value=tryCatch(fn).apply(this,arguments);var promiseCreated=ret._popContext();debug.checkForgottenReturns(value,promiseCreated,"Promise.method",ret);ret._resolveFromSyncValue(value);return ret}};Promise.attempt=Promise["try"]=function(fn){if(typeof fn!=="function"){return apiRejection("expecting a function but got "+util.classString(fn))}var ret=new Promise(INTERNAL);ret._captureStackTrace();ret._pushContext();var value;if(arguments.length>1){debug.deprecated("calling Promise.try with more than 1 argument");var arg=arguments[1];var ctx=arguments[2];value=util.isArray(arg)?tryCatch(fn).apply(ctx,arg):tryCatch(fn).call(ctx,arg)}else{value=tryCatch(fn)()}var promiseCreated=ret._popContext();debug.checkForgottenReturns(value,promiseCreated,"Promise.try",ret);ret._resolveFromSyncValue(value);return ret};Promise.prototype._resolveFromSyncValue=function(value){if(value===util.errorObj){this._rejectCallback(value.e,false)}else{this._resolveCallback(value,true)}}}},{"./util":36}],20:[function(_dereq_,module,exports){"use strict";var util=_dereq_("./util");var maybeWrapAsError=util.maybeWrapAsError;var errors=_dereq_("./errors");var OperationalError=errors.OperationalError;var es5=_dereq_("./es5");function isUntypedError(obj){return obj instanceof Error&&es5.getPrototypeOf(obj)===Error.prototype}var rErrorKey=/^(?:name|message|stack|cause)$/;function wrapAsOperationalError(obj){var ret;if(isUntypedError(obj)){ret=new OperationalError(obj);ret.name=obj.name;ret.message=obj.message;ret.stack=obj.stack;var keys=es5.keys(obj);for(var i=0;i<keys.length;++i){var key=keys[i];if(!rErrorKey.test(key)){ret[key]=obj[key]}}return ret}util.markAsOriginatingFromRejection(obj);return obj}function nodebackForPromise(promise,multiArgs){return function(err,value){if(promise===null)return;if(err){var wrapped=wrapAsOperationalError(maybeWrapAsError(err));promise._attachExtraTrace(wrapped);promise._reject(wrapped)}else if(!multiArgs){promise._fulfill(value)}else{var args=[].slice.call(arguments,1);promise._fulfill(args)}promise=null}}module.exports=nodebackForPromise},{"./errors":12,"./es5":13,"./util":36}],21:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise){var util=_dereq_("./util");var async=Promise._async;var tryCatch=util.tryCatch;var errorObj=util.errorObj;function spreadAdapter(val,nodeback){var promise=this;if(!util.isArray(val))return successAdapter.call(promise,val,nodeback);var ret=tryCatch(nodeback).apply(promise._boundValue(),[null].concat(val));if(ret===errorObj){async.throwLater(ret.e)}}function successAdapter(val,nodeback){var promise=this;var receiver=promise._boundValue();var ret=val===undefined?tryCatch(nodeback).call(receiver,null):tryCatch(nodeback).call(receiver,null,val);if(ret===errorObj){async.throwLater(ret.e)}}function errorAdapter(reason,nodeback){var promise=this;if(!reason){var newReason=new Error(reason+"");newReason.cause=reason;reason=newReason}var ret=tryCatch(nodeback).call(promise._boundValue(),reason);if(ret===errorObj){async.throwLater(ret.e)}}Promise.prototype.asCallback=Promise.prototype.nodeify=function(nodeback,options){if(typeof nodeback=="function"){var adapter=successAdapter;if(options!==undefined&&Object(options).spread){adapter=spreadAdapter}this._then(adapter,errorAdapter,undefined,this,nodeback)}return this}}},{"./util":36}],22:[function(_dereq_,module,exports){"use strict";module.exports=function(){var makeSelfResolutionError=function(){return new TypeError("circular promise resolution chain\n\n See http://goo.gl/MqrFmX\n")};var reflectHandler=function(){return new Promise.PromiseInspection(this._target())};var apiRejection=function(msg){return Promise.reject(new TypeError(msg))};function Proxyable(){}var UNDEFINED_BINDING={};var util=_dereq_("./util");util.setReflectHandler(reflectHandler);var getDomain=function(){var domain=process.domain;if(domain===undefined){return null}return domain};var getContextDefault=function(){return null};var getContextDomain=function(){return{domain:getDomain(),async:null}};var AsyncResource=util.isNode&&util.nodeSupportsAsyncResource?_dereq_("async_hooks").AsyncResource:null;var getContextAsyncHooks=function(){return{domain:getDomain(),async:new AsyncResource("Bluebird::Promise")}};var getContext=util.isNode?getContextDomain:getContextDefault;util.notEnumerableProp(Promise,"_getContext",getContext);var enableAsyncHooks=function(){getContext=getContextAsyncHooks;util.notEnumerableProp(Promise,"_getContext",getContextAsyncHooks)};var disableAsyncHooks=function(){getContext=getContextDomain;util.notEnumerableProp(Promise,"_getContext",getContextDomain)};var es5=_dereq_("./es5");var Async=_dereq_("./async");var async=new Async;es5.defineProperty(Promise,"_async",{value:async});var errors=_dereq_("./errors");var TypeError=Promise.TypeError=errors.TypeError;Promise.RangeError=errors.RangeError;var CancellationError=Promise.CancellationError=errors.CancellationError;Promise.TimeoutError=errors.TimeoutError;Promise.OperationalError=errors.OperationalError;Promise.RejectionError=errors.OperationalError;Promise.AggregateError=errors.AggregateError;var INTERNAL=function(){};var APPLY={};var NEXT_FILTER={};var tryConvertToPromise=_dereq_("./thenables")(Promise,INTERNAL);var PromiseArray=_dereq_("./promise_array")(Promise,INTERNAL,tryConvertToPromise,apiRejection,Proxyable);var Context=_dereq_("./context")(Promise);var createContext=Context.create;var debug=_dereq_("./debuggability")(Promise,Context,enableAsyncHooks,disableAsyncHooks);var CapturedTrace=debug.CapturedTrace;var PassThroughHandlerContext=_dereq_("./finally")(Promise,tryConvertToPromise,NEXT_FILTER);var catchFilter=_dereq_("./catch_filter")(NEXT_FILTER);var nodebackForPromise=_dereq_("./nodeback");var errorObj=util.errorObj;var tryCatch=util.tryCatch;function check(self,executor){if(self==null||self.constructor!==Promise){throw new TypeError("the promise constructor cannot be invoked directly\n\n See http://goo.gl/MqrFmX\n")}if(typeof executor!=="function"){throw new TypeError("expecting a function but got "+util.classString(executor))}}function Promise(executor){if(executor!==INTERNAL){check(this,executor)}this._bitField=0;this._fulfillmentHandler0=undefined;this._rejectionHandler0=undefined;this._promise0=undefined;this._receiver0=undefined;this._resolveFromExecutor(executor);this._promiseCreated();this._fireEvent("promiseCreated",this)}Promise.prototype.toString=function(){return"[object Promise]"};Promise.prototype.caught=Promise.prototype["catch"]=function(fn){var len=arguments.length;if(len>1){var catchInstances=new Array(len-1),j=0,i;for(i=0;i<len-1;++i){var item=arguments[i];if(util.isObject(item)){catchInstances[j++]=item}else{return apiRejection("Catch statement predicate: "+"expecting an object but got "+util.classString(item))}}catchInstances.length=j;fn=arguments[i];if(typeof fn!=="function"){throw new TypeError("The last argument to .catch() "+"must be a function, got "+util.toString(fn))}return this.then(undefined,catchFilter(catchInstances,fn,this))}return this.then(undefined,fn)};Promise.prototype.reflect=function(){return this._then(reflectHandler,reflectHandler,undefined,this,undefined)};Promise.prototype.then=function(didFulfill,didReject){if(debug.warnings()&&arguments.length>0&&typeof didFulfill!=="function"&&typeof didReject!=="function"){var msg=".then() only accepts functions but was passed: "+util.classString(didFulfill);if(arguments.length>1){msg+=", "+util.classString(didReject)}this._warn(msg)}return this._then(didFulfill,didReject,undefined,undefined,undefined)};Promise.prototype.done=function(didFulfill,didReject){var promise=this._then(didFulfill,didReject,undefined,undefined,undefined);promise._setIsFinal()};Promise.prototype.spread=function(fn){if(typeof fn!=="function"){return apiRejection("expecting a function but got "+util.classString(fn))}return this.all()._then(fn,undefined,undefined,APPLY,undefined)};Promise.prototype.toJSON=function(){var ret={isFulfilled:false,isRejected:false,fulfillmentValue:undefined,rejectionReason:undefined};if(this.isFulfilled()){ret.fulfillmentValue=this.value();ret.isFulfilled=true}else if(this.isRejected()){ret.rejectionReason=this.reason();ret.isRejected=true}return ret};Promise.prototype.all=function(){if(arguments.length>0){this._warn(".all() was passed arguments but it does not take any")}return new PromiseArray(this).promise()};Promise.prototype.error=function(fn){return this.caught(util.originatesFromRejection,fn)};Promise.getNewLibraryCopy=module.exports;Promise.is=function(val){return val instanceof Promise};Promise.fromNode=Promise.fromCallback=function(fn){var ret=new Promise(INTERNAL);ret._captureStackTrace();var multiArgs=arguments.length>1?!!Object(arguments[1]).multiArgs:false;var result=tryCatch(fn)(nodebackForPromise(ret,multiArgs));if(result===errorObj){ret._rejectCallback(result.e,true)}if(!ret._isFateSealed())ret._setAsyncGuaranteed();return ret};Promise.all=function(promises){return new PromiseArray(promises).promise()};Promise.cast=function(obj){var ret=tryConvertToPromise(obj);if(!(ret instanceof Promise)){ret=new Promise(INTERNAL);ret._captureStackTrace();ret._setFulfilled();ret._rejectionHandler0=obj}return ret};Promise.resolve=Promise.fulfilled=Promise.cast;Promise.reject=Promise.rejected=function(reason){var ret=new Promise(INTERNAL);ret._captureStackTrace();ret._rejectCallback(reason,true);return ret};Promise.setScheduler=function(fn){if(typeof fn!=="function"){throw new TypeError("expecting a function but got "+util.classString(fn))}return async.setScheduler(fn)};Promise.prototype._then=function(didFulfill,didReject,_,receiver,internalData){var haveInternalData=internalData!==undefined;var promise=haveInternalData?internalData:new Promise(INTERNAL);var target=this._target();var bitField=target._bitField;if(!haveInternalData){promise._propagateFrom(this,3);promise._captureStackTrace();if(receiver===undefined&&(this._bitField&2097152)!==0){if(!((bitField&50397184)===0)){receiver=this._boundValue()}else{receiver=target===this?undefined:this._boundTo}}this._fireEvent("promiseChained",this,promise)}var context=getContext();if(!((bitField&50397184)===0)){var handler,value,settler=target._settlePromiseCtx;if((bitField&33554432)!==0){value=target._rejectionHandler0;handler=didFulfill}else if((bitField&16777216)!==0){value=target._fulfillmentHandler0;handler=didReject;target._unsetRejectionIsUnhandled()}else{settler=target._settlePromiseLateCancellationObserver;value=new CancellationError("late cancellation observer");target._attachExtraTrace(value);handler=didReject}async.invoke(settler,target,{handler:util.contextBind(context,handler),promise:promise,receiver:receiver,value:value})}else{target._addCallbacks(didFulfill,didReject,promise,receiver,context)}return promise};Promise.prototype._length=function(){return this._bitField&65535};Promise.prototype._isFateSealed=function(){return(this._bitField&117506048)!==0};Promise.prototype._isFollowing=function(){return(this._bitField&67108864)===67108864};Promise.prototype._setLength=function(len){this._bitField=this._bitField&-65536|len&65535};Promise.prototype._setFulfilled=function(){this._bitField=this._bitField|33554432;this._fireEvent("promiseFulfilled",this)};Promise.prototype._setRejected=function(){this._bitField=this._bitField|16777216;this._fireEvent("promiseRejected",this)};Promise.prototype._setFollowing=function(){this._bitField=this._bitField|67108864;this._fireEvent("promiseResolved",this)};Promise.prototype._setIsFinal=function(){this._bitField=this._bitField|4194304};Promise.prototype._isFinal=function(){return(this._bitField&4194304)>0};Promise.prototype._unsetCancelled=function(){this._bitField=this._bitField&~65536};Promise.prototype._setCancelled=function(){this._bitField=this._bitField|65536;this._fireEvent("promiseCancelled",this)};Promise.prototype._setWillBeCancelled=function(){this._bitField=this._bitField|8388608};Promise.prototype._setAsyncGuaranteed=function(){if(async.hasCustomScheduler())return;var bitField=this._bitField;this._bitField=bitField|(bitField&536870912)>>2^134217728};Promise.prototype._setNoAsyncGuarantee=function(){this._bitField=(this._bitField|536870912)&~134217728};Promise.prototype._receiverAt=function(index){var ret=index===0?this._receiver0:this[index*4-4+3];if(ret===UNDEFINED_BINDING){return undefined}else if(ret===undefined&&this._isBound()){return this._boundValue()}return ret};Promise.prototype._promiseAt=function(index){return this[index*4-4+2]};Promise.prototype._fulfillmentHandlerAt=function(index){return this[index*4-4+0]};Promise.prototype._rejectionHandlerAt=function(index){return this[index*4-4+1]};Promise.prototype._boundValue=function(){};Promise.prototype._migrateCallback0=function(follower){var bitField=follower._bitField;var fulfill=follower._fulfillmentHandler0;var reject=follower._rejectionHandler0;var promise=follower._promise0;var receiver=follower._receiverAt(0);if(receiver===undefined)receiver=UNDEFINED_BINDING;this._addCallbacks(fulfill,reject,promise,receiver,null)};Promise.prototype._migrateCallbackAt=function(follower,index){var fulfill=follower._fulfillmentHandlerAt(index);var reject=follower._rejectionHandlerAt(index);var promise=follower._promiseAt(index);var receiver=follower._receiverAt(index);if(receiver===undefined)receiver=UNDEFINED_BINDING;this._addCallbacks(fulfill,reject,promise,receiver,null)};Promise.prototype._addCallbacks=function(fulfill,reject,promise,receiver,context){var index=this._length();if(index>=65535-4){index=0;this._setLength(0)}if(index===0){this._promise0=promise;this._receiver0=receiver;if(typeof fulfill==="function"){this._fulfillmentHandler0=util.contextBind(context,fulfill)}if(typeof reject==="function"){this._rejectionHandler0=util.contextBind(context,reject)}}else{var base=index*4-4;this[base+2]=promise;this[base+3]=receiver;if(typeof fulfill==="function"){this[base+0]=util.contextBind(context,fulfill)}if(typeof reject==="function"){this[base+1]=util.contextBind(context,reject)}}this._setLength(index+1);return index};Promise.prototype._proxy=function(proxyable,arg){this._addCallbacks(undefined,undefined,arg,proxyable,null)};Promise.prototype._resolveCallback=function(value,shouldBind){if((this._bitField&117506048)!==0)return;if(value===this)return this._rejectCallback(makeSelfResolutionError(),false);var maybePromise=tryConvertToPromise(value,this);if(!(maybePromise instanceof Promise))return this._fulfill(value);if(shouldBind)this._propagateFrom(maybePromise,2);var promise=maybePromise._target();if(promise===this){this._reject(makeSelfResolutionError());return}var bitField=promise._bitField;if((bitField&50397184)===0){var len=this._length();if(len>0)promise._migrateCallback0(this);for(var i=1;i<len;++i){promise._migrateCallbackAt(this,i)}this._setFollowing();this._setLength(0);this._setFollowee(maybePromise)}else if((bitField&33554432)!==0){this._fulfill(promise._value())}else if((bitField&16777216)!==0){this._reject(promise._reason())}else{var reason=new CancellationError("late cancellation observer");promise._attachExtraTrace(reason);this._reject(reason)}};Promise.prototype._rejectCallback=function(reason,synchronous,ignoreNonErrorWarnings){var trace=util.ensureErrorObject(reason);var hasStack=trace===reason;if(!hasStack&&!ignoreNonErrorWarnings&&debug.warnings()){var message="a promise was rejected with a non-error: "+util.classString(reason);this._warn(message,true)}this._attachExtraTrace(trace,synchronous?hasStack:false);this._reject(reason)};Promise.prototype._resolveFromExecutor=function(executor){if(executor===INTERNAL)return;var promise=this;this._captureStackTrace();this._pushContext();var synchronous=true;var r=this._execute(executor,(function(value){promise._resolveCallback(value)}),(function(reason){promise._rejectCallback(reason,synchronous)}));synchronous=false;this._popContext();if(r!==undefined){promise._rejectCallback(r,true)}};Promise.prototype._settlePromiseFromHandler=function(handler,receiver,value,promise){var bitField=promise._bitField;if((bitField&65536)!==0)return;promise._pushContext();var x;if(receiver===APPLY){if(!value||typeof value.length!=="number"){x=errorObj;x.e=new TypeError("cannot .spread() a non-array: "+util.classString(value))}else{x=tryCatch(handler).apply(this._boundValue(),value)}}else{x=tryCatch(handler).call(receiver,value)}var promiseCreated=promise._popContext();bitField=promise._bitField;if((bitField&65536)!==0)return;if(x===NEXT_FILTER){promise._reject(value)}else if(x===errorObj){promise._rejectCallback(x.e,false)}else{debug.checkForgottenReturns(x,promiseCreated,"",promise,this);promise._resolveCallback(x)}};Promise.prototype._target=function(){var ret=this;while(ret._isFollowing())ret=ret._followee();return ret};Promise.prototype._followee=function(){return this._rejectionHandler0};Promise.prototype._setFollowee=function(promise){this._rejectionHandler0=promise};Promise.prototype._settlePromise=function(promise,handler,receiver,value){var isPromise=promise instanceof Promise;var bitField=this._bitField;var asyncGuaranteed=(bitField&134217728)!==0;if((bitField&65536)!==0){if(isPromise)promise._invokeInternalOnCancel();if(receiver instanceof PassThroughHandlerContext&&receiver.isFinallyHandler()){receiver.cancelPromise=promise;if(tryCatch(handler).call(receiver,value)===errorObj){promise._reject(errorObj.e)}}else if(handler===reflectHandler){promise._fulfill(reflectHandler.call(receiver))}else if(receiver instanceof Proxyable){receiver._promiseCancelled(promise)}else if(isPromise||promise instanceof PromiseArray){promise._cancel()}else{receiver.cancel()}}else if(typeof handler==="function"){if(!isPromise){handler.call(receiver,value,promise)}else{if(asyncGuaranteed)promise._setAsyncGuaranteed();this._settlePromiseFromHandler(handler,receiver,value,promise)}}else if(receiver instanceof Proxyable){if(!receiver._isResolved()){if((bitField&33554432)!==0){receiver._promiseFulfilled(value,promise)}else{receiver._promiseRejected(value,promise)}}}else if(isPromise){if(asyncGuaranteed)promise._setAsyncGuaranteed();if((bitField&33554432)!==0){promise._fulfill(value)}else{promise._reject(value)}}};Promise.prototype._settlePromiseLateCancellationObserver=function(ctx){var handler=ctx.handler;var promise=ctx.promise;var receiver=ctx.receiver;var value=ctx.value;if(typeof handler==="function"){if(!(promise instanceof Promise)){handler.call(receiver,value,promise)}else{this._settlePromiseFromHandler(handler,receiver,value,promise)}}else if(promise instanceof Promise){promise._reject(value)}};Promise.prototype._settlePromiseCtx=function(ctx){this._settlePromise(ctx.promise,ctx.handler,ctx.receiver,ctx.value)};Promise.prototype._settlePromise0=function(handler,value,bitField){var promise=this._promise0;var receiver=this._receiverAt(0);this._promise0=undefined;this._receiver0=undefined;this._settlePromise(promise,handler,receiver,value)};Promise.prototype._clearCallbackDataAtIndex=function(index){var base=index*4-4;this[base+2]=this[base+3]=this[base+0]=this[base+1]=undefined};Promise.prototype._fulfill=function(value){var bitField=this._bitField;if((bitField&117506048)>>>16)return;if(value===this){var err=makeSelfResolutionError();this._attachExtraTrace(err);return this._reject(err)}this._setFulfilled();this._rejectionHandler0=value;if((bitField&65535)>0){if((bitField&134217728)!==0){this._settlePromises()}else{async.settlePromises(this)}this._dereferenceTrace()}};Promise.prototype._reject=function(reason){var bitField=this._bitField;if((bitField&117506048)>>>16)return;this._setRejected();this._fulfillmentHandler0=reason;if(this._isFinal()){return async.fatalError(reason,util.isNode)}if((bitField&65535)>0){async.settlePromises(this)}else{this._ensurePossibleRejectionHandled()}};Promise.prototype._fulfillPromises=function(len,value){for(var i=1;i<len;i++){var handler=this._fulfillmentHandlerAt(i);var promise=this._promiseAt(i);var receiver=this._receiverAt(i);this._clearCallbackDataAtIndex(i);this._settlePromise(promise,handler,receiver,value)}};Promise.prototype._rejectPromises=function(len,reason){for(var i=1;i<len;i++){var handler=this._rejectionHandlerAt(i);var promise=this._promiseAt(i);var receiver=this._receiverAt(i);this._clearCallbackDataAtIndex(i);this._settlePromise(promise,handler,receiver,reason)}};Promise.prototype._settlePromises=function(){var bitField=this._bitField;var len=bitField&65535;if(len>0){if((bitField&16842752)!==0){var reason=this._fulfillmentHandler0;this._settlePromise0(this._rejectionHandler0,reason,bitField);this._rejectPromises(len,reason)}else{var value=this._rejectionHandler0;this._settlePromise0(this._fulfillmentHandler0,value,bitField);this._fulfillPromises(len,value)}this._setLength(0)}this._clearCancellationData()};Promise.prototype._settledValue=function(){var bitField=this._bitField;if((bitField&33554432)!==0){return this._rejectionHandler0}else if((bitField&16777216)!==0){return this._fulfillmentHandler0}};if(typeof Symbol!=="undefined"&&Symbol.toStringTag){es5.defineProperty(Promise.prototype,Symbol.toStringTag,{get:function(){return"Object"}})}function deferResolve(v){this.promise._resolveCallback(v)}function deferReject(v){this.promise._rejectCallback(v,false)}Promise.defer=Promise.pending=function(){debug.deprecated("Promise.defer","new Promise");var promise=new Promise(INTERNAL);return{promise:promise,resolve:deferResolve,reject:deferReject}};util.notEnumerableProp(Promise,"_makeSelfResolutionError",makeSelfResolutionError);_dereq_("./method")(Promise,INTERNAL,tryConvertToPromise,apiRejection,debug);_dereq_("./bind")(Promise,INTERNAL,tryConvertToPromise,debug);_dereq_("./cancel")(Promise,PromiseArray,apiRejection,debug);_dereq_("./direct_resolve")(Promise);_dereq_("./synchronous_inspection")(Promise);_dereq_("./join")(Promise,PromiseArray,tryConvertToPromise,INTERNAL,async);Promise.Promise=Promise;Promise.version="3.7.2";_dereq_("./call_get.js")(Promise);_dereq_("./generators.js")(Promise,apiRejection,INTERNAL,tryConvertToPromise,Proxyable,debug);_dereq_("./map.js")(Promise,PromiseArray,apiRejection,tryConvertToPromise,INTERNAL,debug);_dereq_("./nodeify.js")(Promise);_dereq_("./promisify.js")(Promise,INTERNAL);_dereq_("./props.js")(Promise,PromiseArray,tryConvertToPromise,apiRejection);_dereq_("./race.js")(Promise,INTERNAL,tryConvertToPromise,apiRejection);_dereq_("./reduce.js")(Promise,PromiseArray,apiRejection,tryConvertToPromise,INTERNAL,debug);_dereq_("./settle.js")(Promise,PromiseArray,debug);_dereq_("./some.js")(Promise,PromiseArray,apiRejection);_dereq_("./timers.js")(Promise,INTERNAL,debug);_dereq_("./using.js")(Promise,apiRejection,tryConvertToPromise,createContext,INTERNAL,debug);_dereq_("./any.js")(Promise);_dereq_("./each.js")(Promise,INTERNAL);_dereq_("./filter.js")(Promise,INTERNAL);util.toFastProperties(Promise);util.toFastProperties(Promise.prototype);function fillTypes(value){var p=new Promise(INTERNAL);p._fulfillmentHandler0=value;p._rejectionHandler0=value;p._promise0=value;p._receiver0=value}fillTypes({a:1});fillTypes({b:2});fillTypes({c:3});fillTypes(1);fillTypes((function(){}));fillTypes(undefined);fillTypes(false);fillTypes(new Promise(INTERNAL));debug.setBounds(Async.firstLineError,util.lastLineError);return Promise}},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36,async_hooks:undefined}],23:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL,tryConvertToPromise,apiRejection,Proxyable){var util=_dereq_("./util");var isArray=util.isArray;function toResolutionValue(val){switch(val){case-2:return[];case-3:return{};case-6:return new Map}}function PromiseArray(values){var promise=this._promise=new Promise(INTERNAL);if(values instanceof Promise){promise._propagateFrom(values,3);values.suppressUnhandledRejections()}promise._setOnCancel(this);this._values=values;this._length=0;this._totalResolved=0;this._init(undefined,-2)}util.inherits(PromiseArray,Proxyable);PromiseArray.prototype.length=function(){return this._length};PromiseArray.prototype.promise=function(){return this._promise};PromiseArray.prototype._init=function init(_,resolveValueIfEmpty){var values=tryConvertToPromise(this._values,this._promise);if(values instanceof Promise){values=values._target();var bitField=values._bitField;this._values=values;if((bitField&50397184)===0){this._promise._setAsyncGuaranteed();return values._then(init,this._reject,undefined,this,resolveValueIfEmpty)}else if((bitField&33554432)!==0){values=values._value()}else if((bitField&16777216)!==0){return this._reject(values._reason())}else{return this._cancel()}}values=util.asArray(values);if(values===null){var err=apiRejection("expecting an array or an iterable object but got "+util.classString(values)).reason();this._promise._rejectCallback(err,false);return}if(values.length===0){if(resolveValueIfEmpty===-5){this._resolveEmptyArray()}else{this._resolve(toResolutionValue(resolveValueIfEmpty))}return}this._iterate(values)};PromiseArray.prototype._iterate=function(values){var len=this.getActualLength(values.length);this._length=len;this._values=this.shouldCopyValues()?new Array(len):this._values;var result=this._promise;var isResolved=false;var bitField=null;for(var i=0;i<len;++i){var maybePromise=tryConvertToPromise(values[i],result);if(maybePromise instanceof Promise){maybePromise=maybePromise._target();bitField=maybePromise._bitField}else{bitField=null}if(isResolved){if(bitField!==null){maybePromise.suppressUnhandledRejections()}}else if(bitField!==null){if((bitField&50397184)===0){maybePromise._proxy(this,i);this._values[i]=maybePromise}else if((bitField&33554432)!==0){isResolved=this._promiseFulfilled(maybePromise._value(),i)}else if((bitField&16777216)!==0){isResolved=this._promiseRejected(maybePromise._reason(),i)}else{isResolved=this._promiseCancelled(i)}}else{isResolved=this._promiseFulfilled(maybePromise,i)}}if(!isResolved)result._setAsyncGuaranteed()};PromiseArray.prototype._isResolved=function(){return this._values===null};PromiseArray.prototype._resolve=function(value){this._values=null;this._promise._fulfill(value)};PromiseArray.prototype._cancel=function(){if(this._isResolved()||!this._promise._isCancellable())return;this._values=null;this._promise._cancel()};PromiseArray.prototype._reject=function(reason){this._values=null;this._promise._rejectCallback(reason,false)};PromiseArray.prototype._promiseFulfilled=function(value,index){this._values[index]=value;var totalResolved=++this._totalResolved;if(totalResolved>=this._length){this._resolve(this._values);return true}return false};PromiseArray.prototype._promiseCancelled=function(){this._cancel();return true};PromiseArray.prototype._promiseRejected=function(reason){this._totalResolved++;this._reject(reason);return true};PromiseArray.prototype._resultCancelled=function(){if(this._isResolved())return;var values=this._values;this._cancel();if(values instanceof Promise){values.cancel()}else{for(var i=0;i<values.length;++i){if(values[i]instanceof Promise){values[i].cancel()}}}};PromiseArray.prototype.shouldCopyValues=function(){return true};PromiseArray.prototype.getActualLength=function(len){return len};return PromiseArray}},{"./util":36}],24:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL){var THIS={};var util=_dereq_("./util");var nodebackForPromise=_dereq_("./nodeback");var withAppended=util.withAppended;var maybeWrapAsError=util.maybeWrapAsError;var canEvaluate=util.canEvaluate;var TypeError=_dereq_("./errors").TypeError;var defaultSuffix="Async";var defaultPromisified={__isPromisified__:true};var noCopyProps=["arity","length","name","arguments","caller","callee","prototype","__isPromisified__"];var noCopyPropsPattern=new RegExp("^(?:"+noCopyProps.join("|")+")$");var defaultFilter=function(name){return util.isIdentifier(name)&&name.charAt(0)!=="_"&&name!=="constructor"};function propsFilter(key){return!noCopyPropsPattern.test(key)}function isPromisified(fn){try{return fn.__isPromisified__===true}catch(e){return false}}function hasPromisified(obj,key,suffix){var val=util.getDataPropertyOrDefault(obj,key+suffix,defaultPromisified);return val?isPromisified(val):false}function checkValid(ret,suffix,suffixRegexp){for(var i=0;i<ret.length;i+=2){var key=ret[i];if(suffixRegexp.test(key)){var keyWithoutAsyncSuffix=key.replace(suffixRegexp,"");for(var j=0;j<ret.length;j+=2){if(ret[j]===keyWithoutAsyncSuffix){throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\n\n See http://goo.gl/MqrFmX\n".replace("%s",suffix))}}}}}function promisifiableMethods(obj,suffix,suffixRegexp,filter){var keys=util.inheritedDataKeys(obj);var ret=[];for(var i=0;i<keys.length;++i){var key=keys[i];var value=obj[key];var passesDefaultFilter=filter===defaultFilter?true:defaultFilter(key,value,obj);if(typeof value==="function"&&!isPromisified(value)&&!hasPromisified(obj,key,suffix)&&filter(key,value,obj,passesDefaultFilter)){ret.push(key,value)}}checkValid(ret,suffix,suffixRegexp);return ret}var escapeIdentRegex=function(str){return str.replace(/([$])/,"\\$")};var makeNodePromisifiedEval;if(!true){var switchCaseArgumentOrder=function(likelyArgumentCount){var ret=[likelyArgumentCount];var min=Math.max(0,likelyArgumentCount-1-3);for(var i=likelyArgumentCount-1;i>=min;--i){ret.push(i)}for(var i=likelyArgumentCount+1;i<=3;++i){ret.push(i)}return ret};var argumentSequence=function(argumentCount){return util.filledRange(argumentCount,"_arg","")};var parameterDeclaration=function(parameterCount){return util.filledRange(Math.max(parameterCount,3),"_arg","")};var parameterCount=function(fn){if(typeof fn.length==="number"){return Math.max(Math.min(fn.length,1023+1),0)}return 0};makeNodePromisifiedEval=function(callback,receiver,originalName,fn,_,multiArgs){var newParameterCount=Math.max(0,parameterCount(fn)-1);var argumentOrder=switchCaseArgumentOrder(newParameterCount);var shouldProxyThis=typeof callback==="string"||receiver===THIS;function generateCallForArgumentCount(count){var args=argumentSequence(count).join(", ");var comma=count>0?", ":"";var ret;if(shouldProxyThis){ret="ret = callback.call(this, {{args}}, nodeback); break;\n"}else{ret=receiver===undefined?"ret = callback({{args}}, nodeback); break;\n":"ret = callback.call(receiver, {{args}}, nodeback); break;\n"}return ret.replace("{{args}}",args).replace(", ",comma)}function generateArgumentSwitchCase(){var ret="";for(var i=0;i<argumentOrder.length;++i){ret+="case "+argumentOrder[i]+":"+generateCallForArgumentCount(argumentOrder[i])}ret+=" \n default: \n var args = new Array(len + 1); \n var i = 0; \n for (var i = 0; i < len; ++i) { \n args[i] = arguments[i]; \n } \n args[i] = nodeback; \n [CodeForCall] \n break; \n ".replace("[CodeForCall]",shouldProxyThis?"ret = callback.apply(this, args);\n":"ret = callback.apply(receiver, args);\n");return ret}var getFunctionCode=typeof callback==="string"?"this != null ? this['"+callback+"'] : fn":"fn";var body="'use strict'; \n var ret = function (Parameters) { \n 'use strict'; \n var len = arguments.length; \n var promise = new Promise(INTERNAL); \n promise._captureStackTrace(); \n var nodeback = nodebackForPromise(promise, "+multiArgs+"); \n var ret; \n var callback = tryCatch([GetFunctionCode]); \n switch(len) { \n [CodeForSwitchCase] \n } \n if (ret === errorObj) { \n promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n } \n if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n return promise; \n }; \n notEnumerableProp(ret, '__isPromisified__', true); \n return ret; \n ".replace("[CodeForSwitchCase]",generateArgumentSwitchCase()).replace("[GetFunctionCode]",getFunctionCode);body=body.replace("Parameters",parameterDeclaration(newParameterCount));return new Function("Promise","fn","receiver","withAppended","maybeWrapAsError","nodebackForPromise","tryCatch","errorObj","notEnumerableProp","INTERNAL",body)(Promise,fn,receiver,withAppended,maybeWrapAsError,nodebackForPromise,util.tryCatch,util.errorObj,util.notEnumerableProp,INTERNAL)}}function makeNodePromisifiedClosure(callback,receiver,_,fn,__,multiArgs){var defaultThis=function(){return this}();var method=callback;if(typeof method==="string"){callback=fn}function promisified(){var _receiver=receiver;if(receiver===THIS)_receiver=this;var promise=new Promise(INTERNAL);promise._captureStackTrace();var cb=typeof method==="string"&&this!==defaultThis?this[method]:callback;var fn=nodebackForPromise(promise,multiArgs);try{cb.apply(_receiver,withAppended(arguments,fn))}catch(e){promise._rejectCallback(maybeWrapAsError(e),true,true)}if(!promise._isFateSealed())promise._setAsyncGuaranteed();return promise}util.notEnumerableProp(promisified,"__isPromisified__",true);return promisified}var makeNodePromisified=canEvaluate?makeNodePromisifiedEval:makeNodePromisifiedClosure;function promisifyAll(obj,suffix,filter,promisifier,multiArgs){var suffixRegexp=new RegExp(escapeIdentRegex(suffix)+"$");var methods=promisifiableMethods(obj,suffix,suffixRegexp,filter);for(var i=0,len=methods.length;i<len;i+=2){var key=methods[i];var fn=methods[i+1];var promisifiedKey=key+suffix;if(promisifier===makeNodePromisified){obj[promisifiedKey]=makeNodePromisified(key,THIS,key,fn,suffix,multiArgs)}else{var promisified=promisifier(fn,(function(){return makeNodePromisified(key,THIS,key,fn,suffix,multiArgs)}));util.notEnumerableProp(promisified,"__isPromisified__",true);obj[promisifiedKey]=promisified}}util.toFastProperties(obj);return obj}function promisify(callback,receiver,multiArgs){return makeNodePromisified(callback,receiver,undefined,callback,null,multiArgs)}Promise.promisify=function(fn,options){if(typeof fn!=="function"){throw new TypeError("expecting a function but got "+util.classString(fn))}if(isPromisified(fn)){return fn}options=Object(options);var receiver=options.context===undefined?THIS:options.context;var multiArgs=!!options.multiArgs;var ret=promisify(fn,receiver,multiArgs);util.copyDescriptors(fn,ret,propsFilter);return ret};Promise.promisifyAll=function(target,options){if(typeof target!=="function"&&typeof target!=="object"){throw new TypeError("the target of promisifyAll must be an object or a function\n\n See http://goo.gl/MqrFmX\n")}options=Object(options);var multiArgs=!!options.multiArgs;var suffix=options.suffix;if(typeof suffix!=="string")suffix=defaultSuffix;var filter=options.filter;if(typeof filter!=="function")filter=defaultFilter;var promisifier=options.promisifier;if(typeof promisifier!=="function")promisifier=makeNodePromisified;if(!util.isIdentifier(suffix)){throw new RangeError("suffix must be a valid identifier\n\n See http://goo.gl/MqrFmX\n")}var keys=util.inheritedDataKeys(target);for(var i=0;i<keys.length;++i){var value=target[keys[i]];if(keys[i]!=="constructor"&&util.isClass(value)){promisifyAll(value.prototype,suffix,filter,promisifier,multiArgs);promisifyAll(value,suffix,filter,promisifier,multiArgs)}}return promisifyAll(target,suffix,filter,promisifier,multiArgs)}}},{"./errors":12,"./nodeback":20,"./util":36}],25:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,tryConvertToPromise,apiRejection){var util=_dereq_("./util");var isObject=util.isObject;var es5=_dereq_("./es5");var Es6Map;if(typeof Map==="function")Es6Map=Map;var mapToEntries=function(){var index=0;var size=0;function extractEntry(value,key){this[index]=value;this[index+size]=key;index++}return function mapToEntries(map){size=map.size;index=0;var ret=new Array(map.size*2);map.forEach(extractEntry,ret);return ret}}();var entriesToMap=function(entries){var ret=new Es6Map;var length=entries.length/2|0;for(var i=0;i<length;++i){var key=entries[length+i];var value=entries[i];ret.set(key,value)}return ret};function PropertiesPromiseArray(obj){var isMap=false;var entries;if(Es6Map!==undefined&&obj instanceof Es6Map){entries=mapToEntries(obj);isMap=true}else{var keys=es5.keys(obj);var len=keys.length;entries=new Array(len*2);for(var i=0;i<len;++i){var key=keys[i];entries[i]=obj[key];entries[i+len]=key}}this.constructor$(entries);this._isMap=isMap;this._init$(undefined,isMap?-6:-3)}util.inherits(PropertiesPromiseArray,PromiseArray);PropertiesPromiseArray.prototype._init=function(){};PropertiesPromiseArray.prototype._promiseFulfilled=function(value,index){this._values[index]=value;var totalResolved=++this._totalResolved;if(totalResolved>=this._length){var val;if(this._isMap){val=entriesToMap(this._values)}else{val={};var keyOffset=this.length();for(var i=0,len=this.length();i<len;++i){val[this._values[i+keyOffset]]=this._values[i]}}this._resolve(val);return true}return false};PropertiesPromiseArray.prototype.shouldCopyValues=function(){return false};PropertiesPromiseArray.prototype.getActualLength=function(len){return len>>1};function props(promises){var ret;var castValue=tryConvertToPromise(promises);if(!isObject(castValue)){return apiRejection("cannot await properties of a non-object\n\n See http://goo.gl/MqrFmX\n")}else if(castValue instanceof Promise){ret=castValue._then(Promise.props,undefined,undefined,undefined,undefined)}else{ret=new PropertiesPromiseArray(castValue).promise()}if(castValue instanceof Promise){ret._propagateFrom(castValue,2)}return ret}Promise.prototype.props=function(){return props(this)};Promise.props=function(promises){return props(promises)}}},{"./es5":13,"./util":36}],26:[function(_dereq_,module,exports){"use strict";function arrayMove(src,srcIndex,dst,dstIndex,len){for(var j=0;j<len;++j){dst[j+dstIndex]=src[j+srcIndex];src[j+srcIndex]=void 0}}function Queue(capacity){this._capacity=capacity;this._length=0;this._front=0}Queue.prototype._willBeOverCapacity=function(size){return this._capacity<size};Queue.prototype._pushOne=function(arg){var length=this.length();this._checkCapacity(length+1);var i=this._front+length&this._capacity-1;this[i]=arg;this._length=length+1};Queue.prototype.push=function(fn,receiver,arg){var length=this.length()+3;if(this._willBeOverCapacity(length)){this._pushOne(fn);this._pushOne(receiver);this._pushOne(arg);return}var j=this._front+length-3;this._checkCapacity(length);var wrapMask=this._capacity-1;this[j+0&wrapMask]=fn;this[j+1&wrapMask]=receiver;this[j+2&wrapMask]=arg;this._length=length};Queue.prototype.shift=function(){var front=this._front,ret=this[front];this[front]=undefined;this._front=front+1&this._capacity-1;this._length--;return ret};Queue.prototype.length=function(){return this._length};Queue.prototype._checkCapacity=function(size){if(this._capacity<size){this._resizeTo(this._capacity<<1)}};Queue.prototype._resizeTo=function(capacity){var oldCapacity=this._capacity;this._capacity=capacity;var front=this._front;var length=this._length;var moveItemsCount=front+length&oldCapacity-1;arrayMove(this,0,this,oldCapacity,moveItemsCount)};module.exports=Queue},{}],27:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL,tryConvertToPromise,apiRejection){var util=_dereq_("./util");var raceLater=function(promise){return promise.then((function(array){return race(array,promise)}))};function race(promises,parent){var maybePromise=tryConvertToPromise(promises);if(maybePromise instanceof Promise){return raceLater(maybePromise)}else{promises=util.asArray(promises);if(promises===null)return apiRejection("expecting an array or an iterable object but got "+util.classString(promises))}var ret=new Promise(INTERNAL);if(parent!==undefined){ret._propagateFrom(parent,3)}var fulfill=ret._fulfill;var reject=ret._reject;for(var i=0,len=promises.length;i<len;++i){var val=promises[i];if(val===undefined&&!(i in promises)){continue}Promise.cast(val)._then(fulfill,reject,undefined,ret,null)}return ret}Promise.race=function(promises){return race(promises,undefined)};Promise.prototype.race=function(){return race(this,undefined)}}},{"./util":36}],28:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,apiRejection,tryConvertToPromise,INTERNAL,debug){var util=_dereq_("./util");var tryCatch=util.tryCatch;function ReductionPromiseArray(promises,fn,initialValue,_each){this.constructor$(promises);var context=Promise._getContext();this._fn=util.contextBind(context,fn);if(initialValue!==undefined){initialValue=Promise.resolve(initialValue);initialValue._attachCancellationCallback(this)}this._initialValue=initialValue;this._currentCancellable=null;if(_each===INTERNAL){this._eachValues=Array(this._length)}else if(_each===0){this._eachValues=null}else{this._eachValues=undefined}this._promise._captureStackTrace();this._init$(undefined,-5)}util.inherits(ReductionPromiseArray,PromiseArray);ReductionPromiseArray.prototype._gotAccum=function(accum){if(this._eachValues!==undefined&&this._eachValues!==null&&accum!==INTERNAL){this._eachValues.push(accum)}};ReductionPromiseArray.prototype._eachComplete=function(value){if(this._eachValues!==null){this._eachValues.push(value)}return this._eachValues};ReductionPromiseArray.prototype._init=function(){};ReductionPromiseArray.prototype._resolveEmptyArray=function(){this._resolve(this._eachValues!==undefined?this._eachValues:this._initialValue)};ReductionPromiseArray.prototype.shouldCopyValues=function(){return false};ReductionPromiseArray.prototype._resolve=function(value){this._promise._resolveCallback(value);this._values=null};ReductionPromiseArray.prototype._resultCancelled=function(sender){if(sender===this._initialValue)return this._cancel();if(this._isResolved())return;this._resultCancelled$();if(this._currentCancellable instanceof Promise){this._currentCancellable.cancel()}if(this._initialValue instanceof Promise){this._initialValue.cancel()}};ReductionPromiseArray.prototype._iterate=function(values){this._values=values;var value;var i;var length=values.length;if(this._initialValue!==undefined){value=this._initialValue;i=0}else{value=Promise.resolve(values[0]);i=1}this._currentCancellable=value;for(var j=i;j<length;++j){var maybePromise=values[j];if(maybePromise instanceof Promise){maybePromise.suppressUnhandledRejections()}}if(!value.isRejected()){for(;i<length;++i){var ctx={accum:null,value:values[i],index:i,length:length,array:this};value=value._then(gotAccum,undefined,undefined,ctx,undefined);if((i&127)===0){value._setNoAsyncGuarantee()}}}if(this._eachValues!==undefined){value=value._then(this._eachComplete,undefined,undefined,this,undefined)}value._then(completed,completed,undefined,value,this)};Promise.prototype.reduce=function(fn,initialValue){return reduce(this,fn,initialValue,null)};Promise.reduce=function(promises,fn,initialValue,_each){return reduce(promises,fn,initialValue,_each)};function completed(valueOrReason,array){if(this.isFulfilled()){array._resolve(valueOrReason)}else{array._reject(valueOrReason)}}function reduce(promises,fn,initialValue,_each){if(typeof fn!=="function"){return apiRejection("expecting a function but got "+util.classString(fn))}var array=new ReductionPromiseArray(promises,fn,initialValue,_each);return array.promise()}function gotAccum(accum){this.accum=accum;this.array._gotAccum(accum);var value=tryConvertToPromise(this.value,this.array._promise);if(value instanceof Promise){this.array._currentCancellable=value;return value._then(gotValue,undefined,undefined,this,undefined)}else{return gotValue.call(this,value)}}function gotValue(value){var array=this.array;var promise=array._promise;var fn=tryCatch(array._fn);promise._pushContext();var ret;if(array._eachValues!==undefined){ret=fn.call(promise._boundValue(),value,this.index,this.length)}else{ret=fn.call(promise._boundValue(),this.accum,value,this.index,this.length)}if(ret instanceof Promise){array._currentCancellable=ret}var promiseCreated=promise._popContext();debug.checkForgottenReturns(ret,promiseCreated,array._eachValues!==undefined?"Promise.each":"Promise.reduce",promise);return ret}}},{"./util":36}],29:[function(_dereq_,module,exports){"use strict";var util=_dereq_("./util");var schedule;var noAsyncScheduler=function(){throw new Error("No async scheduler available\n\n See http://goo.gl/MqrFmX\n")};var NativePromise=util.getNativePromise();if(util.isNode&&typeof MutationObserver==="undefined"){var GlobalSetImmediate=global.setImmediate;var ProcessNextTick=process.nextTick;schedule=util.isRecentNode?function(fn){GlobalSetImmediate.call(global,fn)}:function(fn){ProcessNextTick.call(process,fn)}}else if(typeof NativePromise==="function"&&typeof NativePromise.resolve==="function"){var nativePromise=NativePromise.resolve();schedule=function(fn){nativePromise.then(fn)}}else if(typeof MutationObserver!=="undefined"&&!(typeof window!=="undefined"&&window.navigator&&(window.navigator.standalone||window.cordova))&&"classList"in document.documentElement){schedule=function(){var div=document.createElement("div");var opts={attributes:true};var toggleScheduled=false;var div2=document.createElement("div");var o2=new MutationObserver((function(){div.classList.toggle("foo");toggleScheduled=false}));o2.observe(div2,opts);var scheduleToggle=function(){if(toggleScheduled)return;toggleScheduled=true;div2.classList.toggle("foo")};return function schedule(fn){var o=new MutationObserver((function(){o.disconnect();fn()}));o.observe(div,opts);scheduleToggle()}}()}else if(typeof setImmediate!=="undefined"){schedule=function(fn){setImmediate(fn)}}else if(typeof setTimeout!=="undefined"){schedule=function(fn){setTimeout(fn,0)}}else{schedule=noAsyncScheduler}module.exports=schedule},{"./util":36}],30:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,debug){var PromiseInspection=Promise.PromiseInspection;var util=_dereq_("./util");function SettledPromiseArray(values){this.constructor$(values)}util.inherits(SettledPromiseArray,PromiseArray);SettledPromiseArray.prototype._promiseResolved=function(index,inspection){this._values[index]=inspection;var totalResolved=++this._totalResolved;if(totalResolved>=this._length){this._resolve(this._values);return true}return false};SettledPromiseArray.prototype._promiseFulfilled=function(value,index){var ret=new PromiseInspection;ret._bitField=33554432;ret._settledValueField=value;return this._promiseResolved(index,ret)};SettledPromiseArray.prototype._promiseRejected=function(reason,index){var ret=new PromiseInspection;ret._bitField=16777216;ret._settledValueField=reason;return this._promiseResolved(index,ret)};Promise.settle=function(promises){debug.deprecated(".settle()",".reflect()");return new SettledPromiseArray(promises).promise()};Promise.allSettled=function(promises){return new SettledPromiseArray(promises).promise()};Promise.prototype.settle=function(){return Promise.settle(this)}}},{"./util":36}],31:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,apiRejection){var util=_dereq_("./util");var RangeError=_dereq_("./errors").RangeError;var AggregateError=_dereq_("./errors").AggregateError;var isArray=util.isArray;var CANCELLATION={};function SomePromiseArray(values){this.constructor$(values);this._howMany=0;this._unwrap=false;this._initialized=false}util.inherits(SomePromiseArray,PromiseArray);SomePromiseArray.prototype._init=function(){if(!this._initialized){return}if(this._howMany===0){this._resolve([]);return}this._init$(undefined,-5);var isArrayResolved=isArray(this._values);if(!this._isResolved()&&isArrayResolved&&this._howMany>this._canPossiblyFulfill()){this._reject(this._getRangeError(this.length()))}};SomePromiseArray.prototype.init=function(){this._initialized=true;this._init()};SomePromiseArray.prototype.setUnwrap=function(){this._unwrap=true};SomePromiseArray.prototype.howMany=function(){return this._howMany};SomePromiseArray.prototype.setHowMany=function(count){this._howMany=count};SomePromiseArray.prototype._promiseFulfilled=function(value){this._addFulfilled(value);if(this._fulfilled()===this.howMany()){this._values.length=this.howMany();if(this.howMany()===1&&this._unwrap){this._resolve(this._values[0])}else{this._resolve(this._values)}return true}return false};SomePromiseArray.prototype._promiseRejected=function(reason){this._addRejected(reason);return this._checkOutcome()};SomePromiseArray.prototype._promiseCancelled=function(){if(this._values instanceof Promise||this._values==null){return this._cancel()}this._addRejected(CANCELLATION);return this._checkOutcome()};SomePromiseArray.prototype._checkOutcome=function(){if(this.howMany()>this._canPossiblyFulfill()){var e=new AggregateError;for(var i=this.length();i<this._values.length;++i){if(this._values[i]!==CANCELLATION){e.push(this._values[i])}}if(e.length>0){this._reject(e)}else{this._cancel()}return true}return false};SomePromiseArray.prototype._fulfilled=function(){return this._totalResolved};SomePromiseArray.prototype._rejected=function(){return this._values.length-this.length()};SomePromiseArray.prototype._addRejected=function(reason){this._values.push(reason)};SomePromiseArray.prototype._addFulfilled=function(value){this._values[this._totalResolved++]=value};SomePromiseArray.prototype._canPossiblyFulfill=function(){return this.length()-this._rejected()};SomePromiseArray.prototype._getRangeError=function(count){var message="Input array must contain at least "+this._howMany+" items but contains only "+count+" items";return new RangeError(message)};SomePromiseArray.prototype._resolveEmptyArray=function(){this._reject(this._getRangeError(0))};function some(promises,howMany){if((howMany|0)!==howMany||howMany<0){return apiRejection("expecting a positive integer\n\n See http://goo.gl/MqrFmX\n")}var ret=new SomePromiseArray(promises);var promise=ret.promise();ret.setHowMany(howMany);ret.init();return promise}Promise.some=function(promises,howMany){return some(promises,howMany)};Promise.prototype.some=function(howMany){return some(this,howMany)};Promise._SomePromiseArray=SomePromiseArray}},{"./errors":12,"./util":36}],32:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise){function PromiseInspection(promise){if(promise!==undefined){promise=promise._target();this._bitField=promise._bitField;this._settledValueField=promise._isFateSealed()?promise._settledValue():undefined}else{this._bitField=0;this._settledValueField=undefined}}PromiseInspection.prototype._settledValue=function(){return this._settledValueField};var value=PromiseInspection.prototype.value=function(){if(!this.isFulfilled()){throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/MqrFmX\n")}return this._settledValue()};var reason=PromiseInspection.prototype.error=PromiseInspection.prototype.reason=function(){if(!this.isRejected()){throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/MqrFmX\n")}return this._settledValue()};var isFulfilled=PromiseInspection.prototype.isFulfilled=function(){return(this._bitField&33554432)!==0};var isRejected=PromiseInspection.prototype.isRejected=function(){return(this._bitField&16777216)!==0};var isPending=PromiseInspection.prototype.isPending=function(){return(this._bitField&50397184)===0};var isResolved=PromiseInspection.prototype.isResolved=function(){return(this._bitField&50331648)!==0};PromiseInspection.prototype.isCancelled=function(){return(this._bitField&8454144)!==0};Promise.prototype.__isCancelled=function(){return(this._bitField&65536)===65536};Promise.prototype._isCancelled=function(){return this._target().__isCancelled()};Promise.prototype.isCancelled=function(){return(this._target()._bitField&8454144)!==0};Promise.prototype.isPending=function(){return isPending.call(this._target())};Promise.prototype.isRejected=function(){return isRejected.call(this._target())};Promise.prototype.isFulfilled=function(){return isFulfilled.call(this._target())};Promise.prototype.isResolved=function(){return isResolved.call(this._target())};Promise.prototype.value=function(){return value.call(this._target())};Promise.prototype.reason=function(){var target=this._target();target._unsetRejectionIsUnhandled();return reason.call(target)};Promise.prototype._value=function(){return this._settledValue()};Promise.prototype._reason=function(){this._unsetRejectionIsUnhandled();return this._settledValue()};Promise.PromiseInspection=PromiseInspection}},{}],33:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL){var util=_dereq_("./util");var errorObj=util.errorObj;var isObject=util.isObject;function tryConvertToPromise(obj,context){if(isObject(obj)){if(obj instanceof Promise)return obj;var then=getThen(obj);if(then===errorObj){if(context)context._pushContext();var ret=Promise.reject(then.e);if(context)context._popContext();return ret}else if(typeof then==="function"){if(isAnyBluebirdPromise(obj)){var ret=new Promise(INTERNAL);obj._then(ret._fulfill,ret._reject,undefined,ret,null);return ret}return doThenable(obj,then,context)}}return obj}function doGetThen(obj){return obj.then}function getThen(obj){try{return doGetThen(obj)}catch(e){errorObj.e=e;return errorObj}}var hasProp={}.hasOwnProperty;function isAnyBluebirdPromise(obj){try{return hasProp.call(obj,"_promise0")}catch(e){return false}}function doThenable(x,then,context){var promise=new Promise(INTERNAL);var ret=promise;if(context)context._pushContext();promise._captureStackTrace();if(context)context._popContext();var synchronous=true;var result=util.tryCatch(then).call(x,resolve,reject);synchronous=false;if(promise&&result===errorObj){promise._rejectCallback(result.e,true,true);promise=null}function resolve(value){if(!promise)return;promise._resolveCallback(value);promise=null}function reject(reason){if(!promise)return;promise._rejectCallback(reason,synchronous,true);promise=null}return ret}return tryConvertToPromise}},{"./util":36}],34:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL,debug){var util=_dereq_("./util");var TimeoutError=Promise.TimeoutError;function HandleWrapper(handle){this.handle=handle}HandleWrapper.prototype._resultCancelled=function(){clearTimeout(this.handle)};var afterValue=function(value){return delay(+this).thenReturn(value)};var delay=Promise.delay=function(ms,value){var ret;var handle;if(value!==undefined){ret=Promise.resolve(value)._then(afterValue,null,null,ms,undefined);if(debug.cancellation()&&value instanceof Promise){ret._setOnCancel(value)}}else{ret=new Promise(INTERNAL);handle=setTimeout((function(){ret._fulfill()}),+ms);if(debug.cancellation()){ret._setOnCancel(new HandleWrapper(handle))}ret._captureStackTrace()}ret._setAsyncGuaranteed();return ret};Promise.prototype.delay=function(ms){return delay(ms,this)};var afterTimeout=function(promise,message,parent){var err;if(typeof message!=="string"){if(message instanceof Error){err=message}else{err=new TimeoutError("operation timed out")}}else{err=new TimeoutError(message)}util.markAsOriginatingFromRejection(err);promise._attachExtraTrace(err);promise._reject(err);if(parent!=null){parent.cancel()}};function successClear(value){clearTimeout(this.handle);return value}function failureClear(reason){clearTimeout(this.handle);throw reason}Promise.prototype.timeout=function(ms,message){ms=+ms;var ret,parent;var handleWrapper=new HandleWrapper(setTimeout((function timeoutTimeout(){if(ret.isPending()){afterTimeout(ret,message,parent)}}),ms));if(debug.cancellation()){parent=this.then();ret=parent._then(successClear,failureClear,undefined,handleWrapper,undefined);ret._setOnCancel(handleWrapper)}else{ret=this._then(successClear,failureClear,undefined,handleWrapper,undefined)}return ret}}},{"./util":36}],35:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,apiRejection,tryConvertToPromise,createContext,INTERNAL,debug){var util=_dereq_("./util");var TypeError=_dereq_("./errors").TypeError;var inherits=_dereq_("./util").inherits;var errorObj=util.errorObj;var tryCatch=util.tryCatch;var NULL={};function thrower(e){setTimeout((function(){throw e}),0)}function castPreservingDisposable(thenable){var maybePromise=tryConvertToPromise(thenable);if(maybePromise!==thenable&&typeof thenable._isDisposable==="function"&&typeof thenable._getDisposer==="function"&&thenable._isDisposable()){maybePromise._setDisposable(thenable._getDisposer())}return maybePromise}function dispose(resources,inspection){var i=0;var len=resources.length;var ret=new Promise(INTERNAL);function iterator(){if(i>=len)return ret._fulfill();var maybePromise=castPreservingDisposable(resources[i++]);if(maybePromise instanceof Promise&&maybePromise._isDisposable()){try{maybePromise=tryConvertToPromise(maybePromise._getDisposer().tryDispose(inspection),resources.promise)}catch(e){return thrower(e)}if(maybePromise instanceof Promise){return maybePromise._then(iterator,thrower,null,null,null)}}iterator()}iterator();return ret}function Disposer(data,promise,context){this._data=data;this._promise=promise;this._context=context}Disposer.prototype.data=function(){return this._data};Disposer.prototype.promise=function(){return this._promise};Disposer.prototype.resource=function(){if(this.promise().isFulfilled()){return this.promise().value()}return NULL};Disposer.prototype.tryDispose=function(inspection){var resource=this.resource();var context=this._context;if(context!==undefined)context._pushContext();var ret=resource!==NULL?this.doDispose(resource,inspection):null;if(context!==undefined)context._popContext();this._promise._unsetDisposable();this._data=null;return ret};Disposer.isDisposer=function(d){return d!=null&&typeof d.resource==="function"&&typeof d.tryDispose==="function"};function FunctionDisposer(fn,promise,context){this.constructor$(fn,promise,context)}inherits(FunctionDisposer,Disposer);FunctionDisposer.prototype.doDispose=function(resource,inspection){var fn=this.data();return fn.call(resource,resource,inspection)};function maybeUnwrapDisposer(value){if(Disposer.isDisposer(value)){this.resources[this.index]._setDisposable(value);return value.promise()}return value}function ResourceList(length){this.length=length;this.promise=null;this[length-1]=null}ResourceList.prototype._resultCancelled=function(){var len=this.length;for(var i=0;i<len;++i){var item=this[i];if(item instanceof Promise){item.cancel()}}};Promise.using=function(){var len=arguments.length;if(len<2)return apiRejection("you must pass at least 2 arguments to Promise.using");var fn=arguments[len-1];if(typeof fn!=="function"){return apiRejection("expecting a function but got "+util.classString(fn))}var input;var spreadArgs=true;if(len===2&&Array.isArray(arguments[0])){input=arguments[0];len=input.length;spreadArgs=false}else{input=arguments;len--}var resources=new ResourceList(len);for(var i=0;i<len;++i){var resource=input[i];if(Disposer.isDisposer(resource)){var disposer=resource;resource=resource.promise();resource._setDisposable(disposer)}else{var maybePromise=tryConvertToPromise(resource);if(maybePromise instanceof Promise){resource=maybePromise._then(maybeUnwrapDisposer,null,null,{resources:resources,index:i},undefined)}}resources[i]=resource}var reflectedResources=new Array(resources.length);for(var i=0;i<reflectedResources.length;++i){reflectedResources[i]=Promise.resolve(resources[i]).reflect()}var resultPromise=Promise.all(reflectedResources).then((function(inspections){for(var i=0;i<inspections.length;++i){var inspection=inspections[i];if(inspection.isRejected()){errorObj.e=inspection.error();return errorObj}else if(!inspection.isFulfilled()){resultPromise.cancel();return}inspections[i]=inspection.value()}promise._pushContext();fn=tryCatch(fn);var ret=spreadArgs?fn.apply(undefined,inspections):fn(inspections);var promiseCreated=promise._popContext();debug.checkForgottenReturns(ret,promiseCreated,"Promise.using",promise);return ret}));var promise=resultPromise.lastly((function(){var inspection=new Promise.PromiseInspection(resultPromise);return dispose(resources,inspection)}));resources.promise=promise;promise._setOnCancel(resources);return promise};Promise.prototype._setDisposable=function(disposer){this._bitField=this._bitField|131072;this._disposer=disposer};Promise.prototype._isDisposable=function(){return(this._bitField&131072)>0};Promise.prototype._getDisposer=function(){return this._disposer};Promise.prototype._unsetDisposable=function(){this._bitField=this._bitField&~131072;this._disposer=undefined};Promise.prototype.disposer=function(fn){if(typeof fn==="function"){return new FunctionDisposer(fn,this,createContext())}throw new TypeError}}},{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){"use strict";var es5=_dereq_("./es5");var canEvaluate=typeof navigator=="undefined";var errorObj={e:{}};var tryCatchTarget;var globalObject=typeof self!=="undefined"?self:typeof window!=="undefined"?window:typeof global!=="undefined"?global:this!==undefined?this:null;function tryCatcher(){try{var target=tryCatchTarget;tryCatchTarget=null;return target.apply(this,arguments)}catch(e){errorObj.e=e;return errorObj}}function tryCatch(fn){tryCatchTarget=fn;return tryCatcher}var inherits=function(Child,Parent){var hasProp={}.hasOwnProperty;function T(){this.constructor=Child;this.constructor$=Parent;for(var propertyName in Parent.prototype){if(hasProp.call(Parent.prototype,propertyName)&&propertyName.charAt(propertyName.length-1)!=="$"){this[propertyName+"$"]=Parent.prototype[propertyName]}}}T.prototype=Parent.prototype;Child.prototype=new T;return Child.prototype};function isPrimitive(val){return val==null||val===true||val===false||typeof val==="string"||typeof val==="number"}function isObject(value){return typeof value==="function"||typeof value==="object"&&value!==null}function maybeWrapAsError(maybeError){if(!isPrimitive(maybeError))return maybeError;return new Error(safeToString(maybeError))}function withAppended(target,appendee){var len=target.length;var ret=new Array(len+1);var i;for(i=0;i<len;++i){ret[i]=target[i]}ret[i]=appendee;return ret}function getDataPropertyOrDefault(obj,key,defaultValue){if(es5.isES5){var desc=Object.getOwnPropertyDescriptor(obj,key);if(desc!=null){return desc.get==null&&desc.set==null?desc.value:defaultValue}}else{return{}.hasOwnProperty.call(obj,key)?obj[key]:undefined}}function notEnumerableProp(obj,name,value){if(isPrimitive(obj))return obj;var descriptor={value:value,configurable:true,enumerable:false,writable:true};es5.defineProperty(obj,name,descriptor);return obj}function thrower(r){throw r}var inheritedDataKeys=function(){var excludedPrototypes=[Array.prototype,Object.prototype,Function.prototype];var isExcludedProto=function(val){for(var i=0;i<excludedPrototypes.length;++i){if(excludedPrototypes[i]===val){return true}}return false};if(es5.isES5){var getKeys=Object.getOwnPropertyNames;return function(obj){var ret=[];var visitedKeys=Object.create(null);while(obj!=null&&!isExcludedProto(obj)){var keys;try{keys=getKeys(obj)}catch(e){return ret}for(var i=0;i<keys.length;++i){var key=keys[i];if(visitedKeys[key])continue;visitedKeys[key]=true;var desc=Object.getOwnPropertyDescriptor(obj,key);if(desc!=null&&desc.get==null&&desc.set==null){ret.push(key)}}obj=es5.getPrototypeOf(obj)}return ret}}else{var hasProp={}.hasOwnProperty;return function(obj){if(isExcludedProto(obj))return[];var ret=[];enumeration:for(var key in obj){if(hasProp.call(obj,key)){ret.push(key)}else{for(var i=0;i<excludedPrototypes.length;++i){if(hasProp.call(excludedPrototypes[i],key)){continue enumeration}}ret.push(key)}}return ret}}}();var thisAssignmentPattern=/this\s*\.\s*\S+\s*=/;function isClass(fn){try{if(typeof fn==="function"){var keys=es5.names(fn.prototype);var hasMethods=es5.isES5&&keys.length>1;var hasMethodsOtherThanConstructor=keys.length>0&&!(keys.length===1&&keys[0]==="constructor");var hasThisAssignmentAndStaticMethods=thisAssignmentPattern.test(fn+"")&&es5.names(fn).length>0;if(hasMethods||hasMethodsOtherThanConstructor||hasThisAssignmentAndStaticMethods){return true}}return false}catch(e){return false}}function toFastProperties(obj){function FakeConstructor(){}FakeConstructor.prototype=obj;var receiver=new FakeConstructor;function ic(){return typeof receiver.foo}ic();ic();return obj;eval(obj)}var rident=/^[a-z$_][a-z$_0-9]*$/i;function isIdentifier(str){return rident.test(str)}function filledRange(count,prefix,suffix){var ret=new Array(count);for(var i=0;i<count;++i){ret[i]=prefix+i+suffix}return ret}function safeToString(obj){try{return obj+""}catch(e){return"[no string representation]"}}function isError(obj){return obj instanceof Error||obj!==null&&typeof obj==="object"&&typeof obj.message==="string"&&typeof obj.name==="string"}function markAsOriginatingFromRejection(e){try{notEnumerableProp(e,"isOperational",true)}catch(ignore){}}function originatesFromRejection(e){if(e==null)return false;return e instanceof Error["__BluebirdErrorTypes__"].OperationalError||e["isOperational"]===true}function canAttachTrace(obj){return isError(obj)&&es5.propertyIsWritable(obj,"stack")}var ensureErrorObject=function(){if(!("stack"in new Error)){return function(value){if(canAttachTrace(value))return value;try{throw new Error(safeToString(value))}catch(err){return err}}}else{return function(value){if(canAttachTrace(value))return value;return new Error(safeToString(value))}}}();function classString(obj){return{}.toString.call(obj)}function copyDescriptors(from,to,filter){var keys=es5.names(from);for(var i=0;i<keys.length;++i){var key=keys[i];if(filter(key)){try{es5.defineProperty(to,key,es5.getDescriptor(from,key))}catch(ignore){}}}}var asArray=function(v){if(es5.isArray(v)){return v}return null};if(typeof Symbol!=="undefined"&&Symbol.iterator){var ArrayFrom=typeof Array.from==="function"?function(v){return Array.from(v)}:function(v){var ret=[];var it=v[Symbol.iterator]();var itResult;while(!(itResult=it.next()).done){ret.push(itResult.value)}return ret};asArray=function(v){if(es5.isArray(v)){return v}else if(v!=null&&typeof v[Symbol.iterator]==="function"){return ArrayFrom(v)}return null}}var isNode=typeof process!=="undefined"&&classString(process).toLowerCase()==="[object process]";var hasEnvVariables=typeof process!=="undefined"&&typeof process.env!=="undefined";function env(key){return hasEnvVariables?process.env[key]:undefined}function getNativePromise(){if(typeof Promise==="function"){try{var promise=new Promise((function(){}));if(classString(promise)==="[object Promise]"){return Promise}}catch(e){}}}var reflectHandler;function contextBind(ctx,cb){if(ctx===null||typeof cb!=="function"||cb===reflectHandler){return cb}if(ctx.domain!==null){cb=ctx.domain.bind(cb)}var async=ctx.async;if(async!==null){var old=cb;cb=function(){var args=new Array(2).concat([].slice.call(arguments));args[0]=old;args[1]=this;return async.runInAsyncScope.apply(async,args)}}return cb}var ret={setReflectHandler:function(fn){reflectHandler=fn},isClass:isClass,isIdentifier:isIdentifier,inheritedDataKeys:inheritedDataKeys,getDataPropertyOrDefault:getDataPropertyOrDefault,thrower:thrower,isArray:es5.isArray,asArray:asArray,notEnumerableProp:notEnumerableProp,isPrimitive:isPrimitive,isObject:isObject,isError:isError,canEvaluate:canEvaluate,errorObj:errorObj,tryCatch:tryCatch,inherits:inherits,withAppended:withAppended,maybeWrapAsError:maybeWrapAsError,toFastProperties:toFastProperties,filledRange:filledRange,toString:safeToString,canAttachTrace:canAttachTrace,ensureErrorObject:ensureErrorObject,originatesFromRejection:originatesFromRejection,markAsOriginatingFromRejection:markAsOriginatingFromRejection,classString:classString,copyDescriptors:copyDescriptors,isNode:isNode,hasEnvVariables:hasEnvVariables,env:env,global:globalObject,getNativePromise:getNativePromise,contextBind:contextBind};ret.isRecentNode=ret.isNode&&function(){var version;if(process.versions&&process.versions.node){version=process.versions.node.split(".").map(Number)}else if(process.version){version=process.version.split(".").map(Number)}return version[0]===0&&version[1]>10||version[0]>0}();ret.nodeSupportsAsyncResource=ret.isNode&&function(){var supportsAsync=false;try{var res=_dereq_("async_hooks").AsyncResource;supportsAsync=typeof res.prototype.runInAsyncScope==="function"}catch(e){supportsAsync=false}return supportsAsync}();if(ret.isNode)ret.toFastProperties(process);try{throw new Error}catch(e){ret.lastLineError=e}module.exports=ret},{"./es5":13,async_hooks:undefined}]},{},[4])(4)}));if(typeof window!=="undefined"&&window!==null){window.P=window.Promise}else if(typeof self!=="undefined"&&self!==null){self.P=self.Promise}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},require("timers").setImmediate)},{_process:171,timers:191}],71:[function(require,module,exports){},{}],72:[function(require,module,exports){arguments[4][71][0].apply(exports,arguments)},{dup:71}],73:[function(require,module,exports){var objectCreate=Object.create||objectCreatePolyfill;var objectKeys=Object.keys||objectKeysPolyfill;var bind=Function.prototype.bind||functionBindPolyfill;function EventEmitter(){if(!this._events||!Object.prototype.hasOwnProperty.call(this,"_events")){this._events=objectCreate(null);this._eventsCount=0}this._maxListeners=this._maxListeners||undefined}module.exports=EventEmitter;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;var defaultMaxListeners=10;var hasDefineProperty;try{var o={};if(Object.defineProperty)Object.defineProperty(o,"x",{value:0});hasDefineProperty=o.x===0}catch(err){hasDefineProperty=false}if(hasDefineProperty){Object.defineProperty(EventEmitter,"defaultMaxListeners",{enumerable:true,get:function(){return defaultMaxListeners},set:function(arg){if(typeof arg!=="number"||arg<0||arg!==arg)throw new TypeError('"defaultMaxListeners" must be a positive number');defaultMaxListeners=arg}})}else{EventEmitter.defaultMaxListeners=defaultMaxListeners}EventEmitter.prototype.setMaxListeners=function setMaxListeners(n){if(typeof n!=="number"||n<0||isNaN(n))throw new TypeError('"n" argument must be a positive number');this._maxListeners=n;return this};function $getMaxListeners(that){if(that._maxListeners===undefined)return EventEmitter.defaultMaxListeners;return that._maxListeners}EventEmitter.prototype.getMaxListeners=function getMaxListeners(){return $getMaxListeners(this)};function emitNone(handler,isFn,self){if(isFn)handler.call(self);else{var len=handler.length;var listeners=arrayClone(handler,len);for(var i=0;i<len;++i)listeners[i].call(self)}}function emitOne(handler,isFn,self,arg1){if(isFn)handler.call(self,arg1);else{var len=handler.length;var listeners=arrayClone(handler,len);for(var i=0;i<len;++i)listeners[i].call(self,arg1)}}function emitTwo(handler,isFn,self,arg1,arg2){if(isFn)handler.call(self,arg1,arg2);else{var len=handler.length;var listeners=arrayClone(handler,len);for(var i=0;i<len;++i)listeners[i].call(self,arg1,arg2)}}function emitThree(handler,isFn,self,arg1,arg2,arg3){if(isFn)handler.call(self,arg1,arg2,arg3);else{var len=handler.length;var listeners=arrayClone(handler,len);for(var i=0;i<len;++i)listeners[i].call(self,arg1,arg2,arg3)}}function emitMany(handler,isFn,self,args){if(isFn)handler.apply(self,args);else{var len=handler.length;var listeners=arrayClone(handler,len);for(var i=0;i<len;++i)listeners[i].apply(self,args)}}EventEmitter.prototype.emit=function emit(type){var er,handler,len,args,i,events;var doError=type==="error";events=this._events;if(events)doError=doError&&events.error==null;else if(!doError)return false;if(doError){if(arguments.length>1)er=arguments[1];if(er instanceof Error){throw er}else{var err=new Error('Unhandled "error" event. ('+er+")");err.context=er;throw err}return false}handler=events[type];if(!handler)return false;var isFn=typeof handler==="function";len=arguments.length;switch(len){case 1:emitNone(handler,isFn,this);break;case 2:emitOne(handler,isFn,this,arguments[1]);break;case 3:emitTwo(handler,isFn,this,arguments[1],arguments[2]);break;case 4:emitThree(handler,isFn,this,arguments[1],arguments[2],arguments[3]);break;default:args=new Array(len-1);for(i=1;i<len;i++)args[i-1]=arguments[i];emitMany(handler,isFn,this,args)}return true};function _addListener(target,type,listener,prepend){var m;var events;var existing;if(typeof listener!=="function")throw new TypeError('"listener" argument must be a function');events=target._events;if(!events){events=target._events=objectCreate(null);target._eventsCount=0}else{if(events.newListener){target.emit("newListener",type,listener.listener?listener.listener:listener);events=target._events}existing=events[type]}if(!existing){existing=events[type]=listener;++target._eventsCount}else{if(typeof existing==="function"){existing=events[type]=prepend?[listener,existing]:[existing,listener]}else{if(prepend){existing.unshift(listener)}else{existing.push(listener)}}if(!existing.warned){m=$getMaxListeners(target);if(m&&m>0&&existing.length>m){existing.warned=true;var w=new Error("Possible EventEmitter memory leak detected. "+existing.length+' "'+String(type)+'" listeners '+"added. Use emitter.setMaxListeners() to "+"increase limit.");w.name="MaxListenersExceededWarning";w.emitter=target;w.type=type;w.count=existing.length;if(typeof console==="object"&&console.warn){console.warn("%s: %s",w.name,w.message)}}}}return target}EventEmitter.prototype.addListener=function addListener(type,listener){return _addListener(this,type,listener,false)};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.prependListener=function prependListener(type,listener){return _addListener(this,type,listener,true)};function onceWrapper(){if(!this.fired){this.target.removeListener(this.type,this.wrapFn);this.fired=true;switch(arguments.length){case 0:return this.listener.call(this.target);case 1:return this.listener.call(this.target,arguments[0]);case 2:return this.listener.call(this.target,arguments[0],arguments[1]);case 3:return this.listener.call(this.target,arguments[0],arguments[1],arguments[2]);default:var args=new Array(arguments.length);for(var i=0;i<args.length;++i)args[i]=arguments[i];this.listener.apply(this.target,args)}}}function _onceWrap(target,type,listener){var state={fired:false,wrapFn:undefined,target:target,type:type,listener:listener};var wrapped=bind.call(onceWrapper,state);wrapped.listener=listener;state.wrapFn=wrapped;return wrapped}EventEmitter.prototype.once=function once(type,listener){if(typeof listener!=="function")throw new TypeError('"listener" argument must be a function');this.on(type,_onceWrap(this,type,listener));return this};EventEmitter.prototype.prependOnceListener=function prependOnceListener(type,listener){if(typeof listener!=="function")throw new TypeError('"listener" argument must be a function');this.prependListener(type,_onceWrap(this,type,listener));return this};EventEmitter.prototype.removeListener=function removeListener(type,listener){var list,events,position,i,originalListener;if(typeof listener!=="function")throw new TypeError('"listener" argument must be a function');events=this._events;if(!events)return this;list=events[type];if(!list)return this;if(list===listener||list.listener===listener){if(--this._eventsCount===0)this._events=objectCreate(null);else{delete events[type];if(events.removeListener)this.emit("removeListener",type,list.listener||listener)}}else if(typeof list!=="function"){position=-1;for(i=list.length-1;i>=0;i--){if(list[i]===listener||list[i].listener===listener){originalListener=list[i].listener;position=i;break}}if(position<0)return this;if(position===0)list.shift();else spliceOne(list,position);if(list.length===1)events[type]=list[0];if(events.removeListener)this.emit("removeListener",type,originalListener||listener)}return this};EventEmitter.prototype.removeAllListeners=function removeAllListeners(type){var listeners,events,i;events=this._events;if(!events)return this;if(!events.removeListener){if(arguments.length===0){this._events=objectCreate(null);this._eventsCount=0}else if(events[type]){if(--this._eventsCount===0)this._events=objectCreate(null);else delete events[type]}return this}if(arguments.length===0){var keys=objectKeys(events);var key;for(i=0;i<keys.length;++i){key=keys[i];if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events=objectCreate(null);this._eventsCount=0;return this}listeners=events[type];if(typeof listeners==="function"){this.removeListener(type,listeners)}else if(listeners){for(i=listeners.length-1;i>=0;i--){this.removeListener(type,listeners[i])}}return this};function _listeners(target,type,unwrap){var events=target._events;if(!events)return[];var evlistener=events[type];if(!evlistener)return[];if(typeof evlistener==="function")return unwrap?[evlistener.listener||evlistener]:[evlistener];return unwrap?unwrapListeners(evlistener):arrayClone(evlistener,evlistener.length)}EventEmitter.prototype.listeners=function listeners(type){return _listeners(this,type,true)};EventEmitter.prototype.rawListeners=function rawListeners(type){return _listeners(this,type,false)};EventEmitter.listenerCount=function(emitter,type){if(typeof emitter.listenerCount==="function"){return emitter.listenerCount(type)}else{return listenerCount.call(emitter,type)}};EventEmitter.prototype.listenerCount=listenerCount;function listenerCount(type){var events=this._events;if(events){var evlistener=events[type];if(typeof evlistener==="function"){return 1}else if(evlistener){return evlistener.length}}return 0}EventEmitter.prototype.eventNames=function eventNames(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};function spliceOne(list,index){for(var i=index,k=i+1,n=list.length;k<n;i+=1,k+=1)list[i]=list[k];list.pop()}function arrayClone(arr,n){var copy=new Array(n);for(var i=0;i<n;++i)copy[i]=arr[i];return copy}function unwrapListeners(arr){var ret=new Array(arr.length);for(var i=0;i<ret.length;++i){ret[i]=arr[i].listener||arr[i]}return ret}function objectCreatePolyfill(proto){var F=function(){};F.prototype=proto;return new F}function objectKeysPolyfill(obj){var keys=[];for(var k in obj)if(Object.prototype.hasOwnProperty.call(obj,k)){keys.push(k)}return k}function functionBindPolyfill(context){var fn=this;return function(){return fn.apply(context,arguments)}}},{}],74:[function(require,module,exports){(function(Buffer){(function(){"use strict";function btoa(str){var buffer;if(str instanceof Buffer){buffer=str}else{buffer=Buffer.from(str.toString(),"binary")}return buffer.toString("base64")}module.exports=btoa})()}).call(this,require("buffer").Buffer)},{buffer:75}],75:[function(require,module,exports){(function(Buffer){
|
|
25
|
+
*/!function(e){if("object"==(typeof exports==="undefined"?"undefined":_typeof(exports))&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}((function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;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 _dereq_=="function"&&_dereq_;for(var o=0;o<r.length;o++){s(r[o])}return s}({1:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise){var SomePromiseArray=Promise._SomePromiseArray;function any(promises){var ret=new SomePromiseArray(promises);var promise=ret.promise();ret.setHowMany(1);ret.setUnwrap();ret.init();return promise}Promise.any=function(promises){return any(promises)};Promise.prototype.any=function(){return any(this)}}},{}],2:[function(_dereq_,module,exports){"use strict";var firstLineError;try{throw new Error}catch(e){firstLineError=e}var schedule=_dereq_("./schedule");var Queue=_dereq_("./queue");function Async(){this._customScheduler=false;this._isTickUsed=false;this._lateQueue=new Queue(16);this._normalQueue=new Queue(16);this._haveDrainedQueues=false;var self=this;this.drainQueues=function(){self._drainQueues()};this._schedule=schedule}Async.prototype.setScheduler=function(fn){var prev=this._schedule;this._schedule=fn;this._customScheduler=true;return prev};Async.prototype.hasCustomScheduler=function(){return this._customScheduler};Async.prototype.haveItemsQueued=function(){return this._isTickUsed||this._haveDrainedQueues};Async.prototype.fatalError=function(e,isNode){if(isNode){process.stderr.write("Fatal "+(e instanceof Error?e.stack:e)+"\n");process.exit(2)}else{this.throwLater(e)}};Async.prototype.throwLater=function(fn,arg){if(arguments.length===1){arg=fn;fn=function fn(){throw arg}}if(typeof setTimeout!=="undefined"){setTimeout((function(){fn(arg)}),0)}else try{this._schedule((function(){fn(arg)}))}catch(e){throw new Error("No async scheduler available\n\n See http://goo.gl/MqrFmX\n")}};function AsyncInvokeLater(fn,receiver,arg){this._lateQueue.push(fn,receiver,arg);this._queueTick()}function AsyncInvoke(fn,receiver,arg){this._normalQueue.push(fn,receiver,arg);this._queueTick()}function AsyncSettlePromises(promise){this._normalQueue._pushOne(promise);this._queueTick()}Async.prototype.invokeLater=AsyncInvokeLater;Async.prototype.invoke=AsyncInvoke;Async.prototype.settlePromises=AsyncSettlePromises;function _drainQueue(queue){while(queue.length()>0){_drainQueueStep(queue)}}function _drainQueueStep(queue){var fn=queue.shift();if(typeof fn!=="function"){fn._settlePromises()}else{var receiver=queue.shift();var arg=queue.shift();fn.call(receiver,arg)}}Async.prototype._drainQueues=function(){_drainQueue(this._normalQueue);this._reset();this._haveDrainedQueues=true;_drainQueue(this._lateQueue)};Async.prototype._queueTick=function(){if(!this._isTickUsed){this._isTickUsed=true;this._schedule(this.drainQueues)}};Async.prototype._reset=function(){this._isTickUsed=false};module.exports=Async;module.exports.firstLineError=firstLineError},{"./queue":26,"./schedule":29}],3:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL,tryConvertToPromise,debug){var calledBind=false;var rejectThis=function rejectThis(_,e){this._reject(e)};var targetRejected=function targetRejected(e,context){context.promiseRejectionQueued=true;context.bindingPromise._then(rejectThis,rejectThis,null,this,e)};var bindingResolved=function bindingResolved(thisArg,context){if((this._bitField&50397184)===0){this._resolveCallback(context.target)}};var bindingRejected=function bindingRejected(e,context){if(!context.promiseRejectionQueued)this._reject(e)};Promise.prototype.bind=function(thisArg){if(!calledBind){calledBind=true;Promise.prototype._propagateFrom=debug.propagateFromFunction();Promise.prototype._boundValue=debug.boundValueFunction()}var maybePromise=tryConvertToPromise(thisArg);var ret=new Promise(INTERNAL);ret._propagateFrom(this,1);var target=this._target();ret._setBoundTo(maybePromise);if(maybePromise instanceof Promise){var context={promiseRejectionQueued:false,promise:ret,target:target,bindingPromise:maybePromise};target._then(INTERNAL,targetRejected,undefined,ret,context);maybePromise._then(bindingResolved,bindingRejected,undefined,ret,context);ret._setOnCancel(maybePromise)}else{ret._resolveCallback(target)}return ret};Promise.prototype._setBoundTo=function(obj){if(obj!==undefined){this._bitField=this._bitField|2097152;this._boundTo=obj}else{this._bitField=this._bitField&~2097152}};Promise.prototype._isBound=function(){return(this._bitField&2097152)===2097152};Promise.bind=function(thisArg,value){return Promise.resolve(value).bind(thisArg)}}},{}],4:[function(_dereq_,module,exports){"use strict";var old;if(typeof Promise!=="undefined")old=Promise;function noConflict(){try{if(Promise===bluebird)Promise=old}catch(e){}return bluebird}var bluebird=_dereq_("./promise")();bluebird.noConflict=noConflict;module.exports=bluebird},{"./promise":22}],5:[function(_dereq_,module,exports){"use strict";var cr=Object.create;if(cr){var callerCache=cr(null);var getterCache=cr(null);callerCache[" size"]=getterCache[" size"]=0}module.exports=function(Promise){var util=_dereq_("./util");var canEvaluate=util.canEvaluate;var isIdentifier=util.isIdentifier;var getMethodCaller;var getGetter;if(!true){var makeMethodCaller=function makeMethodCaller(methodName){return new Function("ensureMethod"," \n return function(obj) { \n 'use strict' \n var len = this.length; \n ensureMethod(obj, 'methodName'); \n switch(len) { \n case 1: return obj.methodName(this[0]); \n case 2: return obj.methodName(this[0], this[1]); \n case 3: return obj.methodName(this[0], this[1], this[2]); \n case 0: return obj.methodName(); \n default: \n return obj.methodName.apply(obj, this); \n } \n }; \n ".replace(/methodName/g,methodName))(ensureMethod)};var makeGetter=function makeGetter(propertyName){return new Function("obj"," \n 'use strict'; \n return obj.propertyName; \n ".replace("propertyName",propertyName))};var getCompiled=function getCompiled(name,compiler,cache){var ret=cache[name];if(typeof ret!=="function"){if(!isIdentifier(name)){return null}ret=compiler(name);cache[name]=ret;cache[" size"]++;if(cache[" size"]>512){var keys=Object.keys(cache);for(var i=0;i<256;++i){delete cache[keys[i]]}cache[" size"]=keys.length-256}}return ret};getMethodCaller=function getMethodCaller(name){return getCompiled(name,makeMethodCaller,callerCache)};getGetter=function getGetter(name){return getCompiled(name,makeGetter,getterCache)}}function ensureMethod(obj,methodName){var fn;if(obj!=null)fn=obj[methodName];if(typeof fn!=="function"){var message="Object "+util.classString(obj)+" has no method '"+util.toString(methodName)+"'";throw new Promise.TypeError(message)}return fn}function caller(obj){var methodName=this.pop();var fn=ensureMethod(obj,methodName);return fn.apply(obj,this)}Promise.prototype.call=function(methodName){var args=[].slice.call(arguments,1);if(!true){if(canEvaluate){var maybeCaller=getMethodCaller(methodName);if(maybeCaller!==null){return this._then(maybeCaller,undefined,undefined,args,undefined)}}}args.push(methodName);return this._then(caller,undefined,undefined,args,undefined)};function namedGetter(obj){return obj[this]}function indexedGetter(obj){var index=+this;if(index<0)index=Math.max(0,index+obj.length);return obj[index]}Promise.prototype.get=function(propertyName){var isIndex=typeof propertyName==="number";var getter;if(!isIndex){if(canEvaluate){var maybeGetter=getGetter(propertyName);getter=maybeGetter!==null?maybeGetter:namedGetter}else{getter=namedGetter}}else{getter=indexedGetter}return this._then(getter,undefined,undefined,propertyName,undefined)}}},{"./util":36}],6:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,apiRejection,debug){var util=_dereq_("./util");var tryCatch=util.tryCatch;var errorObj=util.errorObj;var async=Promise._async;Promise.prototype["break"]=Promise.prototype.cancel=function(){if(!debug.cancellation())return this._warn("cancellation is disabled");var promise=this;var child=promise;while(promise._isCancellable()){if(!promise._cancelBy(child)){if(child._isFollowing()){child._followee().cancel()}else{child._cancelBranched()}break}var parent=promise._cancellationParent;if(parent==null||!parent._isCancellable()){if(promise._isFollowing()){promise._followee().cancel()}else{promise._cancelBranched()}break}else{if(promise._isFollowing())promise._followee().cancel();promise._setWillBeCancelled();child=promise;promise=parent}}};Promise.prototype._branchHasCancelled=function(){this._branchesRemainingToCancel--};Promise.prototype._enoughBranchesHaveCancelled=function(){return this._branchesRemainingToCancel===undefined||this._branchesRemainingToCancel<=0};Promise.prototype._cancelBy=function(canceller){if(canceller===this){this._branchesRemainingToCancel=0;this._invokeOnCancel();return true}else{this._branchHasCancelled();if(this._enoughBranchesHaveCancelled()){this._invokeOnCancel();return true}}return false};Promise.prototype._cancelBranched=function(){if(this._enoughBranchesHaveCancelled()){this._cancel()}};Promise.prototype._cancel=function(){if(!this._isCancellable())return;this._setCancelled();async.invoke(this._cancelPromises,this,undefined)};Promise.prototype._cancelPromises=function(){if(this._length()>0)this._settlePromises()};Promise.prototype._unsetOnCancel=function(){this._onCancelField=undefined};Promise.prototype._isCancellable=function(){return this.isPending()&&!this._isCancelled()};Promise.prototype.isCancellable=function(){return this.isPending()&&!this.isCancelled()};Promise.prototype._doInvokeOnCancel=function(onCancelCallback,internalOnly){if(util.isArray(onCancelCallback)){for(var i=0;i<onCancelCallback.length;++i){this._doInvokeOnCancel(onCancelCallback[i],internalOnly)}}else if(onCancelCallback!==undefined){if(typeof onCancelCallback==="function"){if(!internalOnly){var e=tryCatch(onCancelCallback).call(this._boundValue());if(e===errorObj){this._attachExtraTrace(e.e);async.throwLater(e.e)}}}else{onCancelCallback._resultCancelled(this)}}};Promise.prototype._invokeOnCancel=function(){var onCancelCallback=this._onCancel();this._unsetOnCancel();async.invoke(this._doInvokeOnCancel,this,onCancelCallback)};Promise.prototype._invokeInternalOnCancel=function(){if(this._isCancellable()){this._doInvokeOnCancel(this._onCancel(),true);this._unsetOnCancel()}};Promise.prototype._resultCancelled=function(){this.cancel()}}},{"./util":36}],7:[function(_dereq_,module,exports){"use strict";module.exports=function(NEXT_FILTER){var util=_dereq_("./util");var getKeys=_dereq_("./es5").keys;var tryCatch=util.tryCatch;var errorObj=util.errorObj;function catchFilter(instances,cb,promise){return function(e){var boundTo=promise._boundValue();predicateLoop:for(var i=0;i<instances.length;++i){var item=instances[i];if(item===Error||item!=null&&item.prototype instanceof Error){if(e instanceof item){return tryCatch(cb).call(boundTo,e)}}else if(typeof item==="function"){var matchesPredicate=tryCatch(item).call(boundTo,e);if(matchesPredicate===errorObj){return matchesPredicate}else if(matchesPredicate){return tryCatch(cb).call(boundTo,e)}}else if(util.isObject(e)){var keys=getKeys(item);for(var j=0;j<keys.length;++j){var key=keys[j];if(item[key]!=e[key]){continue predicateLoop}}return tryCatch(cb).call(boundTo,e)}}return NEXT_FILTER}}return catchFilter}},{"./es5":13,"./util":36}],8:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise){var longStackTraces=false;var contextStack=[];Promise.prototype._promiseCreated=function(){};Promise.prototype._pushContext=function(){};Promise.prototype._popContext=function(){return null};Promise._peekContext=Promise.prototype._peekContext=function(){};function Context(){this._trace=new Context.CapturedTrace(peekContext())}Context.prototype._pushContext=function(){if(this._trace!==undefined){this._trace._promiseCreated=null;contextStack.push(this._trace)}};Context.prototype._popContext=function(){if(this._trace!==undefined){var trace=contextStack.pop();var ret=trace._promiseCreated;trace._promiseCreated=null;return ret}return null};function createContext(){if(longStackTraces)return new Context}function peekContext(){var lastIndex=contextStack.length-1;if(lastIndex>=0){return contextStack[lastIndex]}return undefined}Context.CapturedTrace=null;Context.create=createContext;Context.deactivateLongStackTraces=function(){};Context.activateLongStackTraces=function(){var Promise_pushContext=Promise.prototype._pushContext;var Promise_popContext=Promise.prototype._popContext;var Promise_PeekContext=Promise._peekContext;var Promise_peekContext=Promise.prototype._peekContext;var Promise_promiseCreated=Promise.prototype._promiseCreated;Context.deactivateLongStackTraces=function(){Promise.prototype._pushContext=Promise_pushContext;Promise.prototype._popContext=Promise_popContext;Promise._peekContext=Promise_PeekContext;Promise.prototype._peekContext=Promise_peekContext;Promise.prototype._promiseCreated=Promise_promiseCreated;longStackTraces=false};longStackTraces=true;Promise.prototype._pushContext=Context.prototype._pushContext;Promise.prototype._popContext=Context.prototype._popContext;Promise._peekContext=Promise.prototype._peekContext=peekContext;Promise.prototype._promiseCreated=function(){var ctx=this._peekContext();if(ctx&&ctx._promiseCreated==null)ctx._promiseCreated=this}};return Context}},{}],9:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,Context,enableAsyncHooks,disableAsyncHooks){var async=Promise._async;var Warning=_dereq_("./errors").Warning;var util=_dereq_("./util");var es5=_dereq_("./es5");var canAttachTrace=util.canAttachTrace;var unhandledRejectionHandled;var possiblyUnhandledRejection;var bluebirdFramePattern=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/;var nodeFramePattern=/\((?:timers\.js):\d+:\d+\)/;var parseLinePattern=/[\/<\(](.+?):(\d+):(\d+)\)?\s*$/;var stackFramePattern=null;var formatStack=null;var indentStackFrames=false;var printWarning;var debugging=!!(util.env("BLUEBIRD_DEBUG")!=0&&(true||util.env("BLUEBIRD_DEBUG")||util.env("NODE_ENV")==="development"));var warnings=!!(util.env("BLUEBIRD_WARNINGS")!=0&&(debugging||util.env("BLUEBIRD_WARNINGS")));var longStackTraces=!!(util.env("BLUEBIRD_LONG_STACK_TRACES")!=0&&(debugging||util.env("BLUEBIRD_LONG_STACK_TRACES")));var wForgottenReturn=util.env("BLUEBIRD_W_FORGOTTEN_RETURN")!=0&&(warnings||!!util.env("BLUEBIRD_W_FORGOTTEN_RETURN"));var deferUnhandledRejectionCheck;(function(){var promises=[];function unhandledRejectionCheck(){for(var i=0;i<promises.length;++i){promises[i]._notifyUnhandledRejection()}unhandledRejectionClear()}function unhandledRejectionClear(){promises.length=0}deferUnhandledRejectionCheck=function deferUnhandledRejectionCheck(promise){promises.push(promise);setTimeout(unhandledRejectionCheck,1)};es5.defineProperty(Promise,"_unhandledRejectionCheck",{value:unhandledRejectionCheck});es5.defineProperty(Promise,"_unhandledRejectionClear",{value:unhandledRejectionClear})})();Promise.prototype.suppressUnhandledRejections=function(){var target=this._target();target._bitField=target._bitField&~1048576|524288};Promise.prototype._ensurePossibleRejectionHandled=function(){if((this._bitField&524288)!==0)return;this._setRejectionIsUnhandled();deferUnhandledRejectionCheck(this)};Promise.prototype._notifyUnhandledRejectionIsHandled=function(){fireRejectionEvent("rejectionHandled",unhandledRejectionHandled,undefined,this)};Promise.prototype._setReturnedNonUndefined=function(){this._bitField=this._bitField|268435456};Promise.prototype._returnedNonUndefined=function(){return(this._bitField&268435456)!==0};Promise.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var reason=this._settledValue();this._setUnhandledRejectionIsNotified();fireRejectionEvent("unhandledRejection",possiblyUnhandledRejection,reason,this)}};Promise.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=this._bitField|262144};Promise.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=this._bitField&~262144};Promise.prototype._isUnhandledRejectionNotified=function(){return(this._bitField&262144)>0};Promise.prototype._setRejectionIsUnhandled=function(){this._bitField=this._bitField|1048576};Promise.prototype._unsetRejectionIsUnhandled=function(){this._bitField=this._bitField&~1048576;if(this._isUnhandledRejectionNotified()){this._unsetUnhandledRejectionIsNotified();this._notifyUnhandledRejectionIsHandled()}};Promise.prototype._isRejectionUnhandled=function(){return(this._bitField&1048576)>0};Promise.prototype._warn=function(message,shouldUseOwnTrace,promise){return warn(message,shouldUseOwnTrace,promise||this)};Promise.onPossiblyUnhandledRejection=function(fn){var context=Promise._getContext();possiblyUnhandledRejection=util.contextBind(context,fn)};Promise.onUnhandledRejectionHandled=function(fn){var context=Promise._getContext();unhandledRejectionHandled=util.contextBind(context,fn)};var disableLongStackTraces=function disableLongStackTraces(){};Promise.longStackTraces=function(){if(async.haveItemsQueued()&&!config.longStackTraces){throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n")}if(!config.longStackTraces&&longStackTracesIsSupported()){var Promise_captureStackTrace=Promise.prototype._captureStackTrace;var Promise_attachExtraTrace=Promise.prototype._attachExtraTrace;var Promise_dereferenceTrace=Promise.prototype._dereferenceTrace;config.longStackTraces=true;disableLongStackTraces=function disableLongStackTraces(){if(async.haveItemsQueued()&&!config.longStackTraces){throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n")}Promise.prototype._captureStackTrace=Promise_captureStackTrace;Promise.prototype._attachExtraTrace=Promise_attachExtraTrace;Promise.prototype._dereferenceTrace=Promise_dereferenceTrace;Context.deactivateLongStackTraces();config.longStackTraces=false};Promise.prototype._captureStackTrace=longStackTracesCaptureStackTrace;Promise.prototype._attachExtraTrace=longStackTracesAttachExtraTrace;Promise.prototype._dereferenceTrace=longStackTracesDereferenceTrace;Context.activateLongStackTraces()}};Promise.hasLongStackTraces=function(){return config.longStackTraces&&longStackTracesIsSupported()};var legacyHandlers={unhandledrejection:{before:function before(){var ret=util.global.onunhandledrejection;util.global.onunhandledrejection=null;return ret},after:function after(fn){util.global.onunhandledrejection=fn}},rejectionhandled:{before:function before(){var ret=util.global.onrejectionhandled;util.global.onrejectionhandled=null;return ret},after:function after(fn){util.global.onrejectionhandled=fn}}};var fireDomEvent=function(){var dispatch=function dispatch(legacy,e){if(legacy){var fn;try{fn=legacy.before();return!util.global.dispatchEvent(e)}finally{legacy.after(fn)}}else{return!util.global.dispatchEvent(e)}};try{if(typeof CustomEvent==="function"){var event=new CustomEvent("CustomEvent");util.global.dispatchEvent(event);return function(name,event){name=name.toLowerCase();var eventData={detail:event,cancelable:true};var domEvent=new CustomEvent(name,eventData);es5.defineProperty(domEvent,"promise",{value:event.promise});es5.defineProperty(domEvent,"reason",{value:event.reason});return dispatch(legacyHandlers[name],domEvent)}}else if(typeof Event==="function"){var event=new Event("CustomEvent");util.global.dispatchEvent(event);return function(name,event){name=name.toLowerCase();var domEvent=new Event(name,{cancelable:true});domEvent.detail=event;es5.defineProperty(domEvent,"promise",{value:event.promise});es5.defineProperty(domEvent,"reason",{value:event.reason});return dispatch(legacyHandlers[name],domEvent)}}else{var event=document.createEvent("CustomEvent");event.initCustomEvent("testingtheevent",false,true,{});util.global.dispatchEvent(event);return function(name,event){name=name.toLowerCase();var domEvent=document.createEvent("CustomEvent");domEvent.initCustomEvent(name,false,true,event);return dispatch(legacyHandlers[name],domEvent)}}}catch(e){}return function(){return false}}();var fireGlobalEvent=function(){if(util.isNode){return function(){return process.emit.apply(process,arguments)}}else{if(!util.global){return function(){return false}}return function(name){var methodName="on"+name.toLowerCase();var method=util.global[methodName];if(!method)return false;method.apply(util.global,[].slice.call(arguments,1));return true}}}();function generatePromiseLifecycleEventObject(name,promise){return{promise:promise}}var eventToObjectGenerator={promiseCreated:generatePromiseLifecycleEventObject,promiseFulfilled:generatePromiseLifecycleEventObject,promiseRejected:generatePromiseLifecycleEventObject,promiseResolved:generatePromiseLifecycleEventObject,promiseCancelled:generatePromiseLifecycleEventObject,promiseChained:function promiseChained(name,promise,child){return{promise:promise,child:child}},warning:function warning(name,_warning){return{warning:_warning}},unhandledRejection:function unhandledRejection(name,reason,promise){return{reason:reason,promise:promise}},rejectionHandled:generatePromiseLifecycleEventObject};var activeFireEvent=function activeFireEvent(name){var globalEventFired=false;try{globalEventFired=fireGlobalEvent.apply(null,arguments)}catch(e){async.throwLater(e);globalEventFired=true}var domEventFired=false;try{domEventFired=fireDomEvent(name,eventToObjectGenerator[name].apply(null,arguments))}catch(e){async.throwLater(e);domEventFired=true}return domEventFired||globalEventFired};Promise.config=function(opts){opts=Object(opts);if("longStackTraces"in opts){if(opts.longStackTraces){Promise.longStackTraces()}else if(!opts.longStackTraces&&Promise.hasLongStackTraces()){disableLongStackTraces()}}if("warnings"in opts){var warningsOption=opts.warnings;config.warnings=!!warningsOption;wForgottenReturn=config.warnings;if(util.isObject(warningsOption)){if("wForgottenReturn"in warningsOption){wForgottenReturn=!!warningsOption.wForgottenReturn}}}if("cancellation"in opts&&opts.cancellation&&!config.cancellation){if(async.haveItemsQueued()){throw new Error("cannot enable cancellation after promises are in use")}Promise.prototype._clearCancellationData=cancellationClearCancellationData;Promise.prototype._propagateFrom=cancellationPropagateFrom;Promise.prototype._onCancel=cancellationOnCancel;Promise.prototype._setOnCancel=cancellationSetOnCancel;Promise.prototype._attachCancellationCallback=cancellationAttachCancellationCallback;Promise.prototype._execute=cancellationExecute;_propagateFromFunction=cancellationPropagateFrom;config.cancellation=true}if("monitoring"in opts){if(opts.monitoring&&!config.monitoring){config.monitoring=true;Promise.prototype._fireEvent=activeFireEvent}else if(!opts.monitoring&&config.monitoring){config.monitoring=false;Promise.prototype._fireEvent=defaultFireEvent}}if("asyncHooks"in opts&&util.nodeSupportsAsyncResource){var prev=config.asyncHooks;var cur=!!opts.asyncHooks;if(prev!==cur){config.asyncHooks=cur;if(cur){enableAsyncHooks()}else{disableAsyncHooks()}}}return Promise};function defaultFireEvent(){return false}Promise.prototype._fireEvent=defaultFireEvent;Promise.prototype._execute=function(executor,resolve,reject){try{executor(resolve,reject)}catch(e){return e}};Promise.prototype._onCancel=function(){};Promise.prototype._setOnCancel=function(handler){};Promise.prototype._attachCancellationCallback=function(onCancel){};Promise.prototype._captureStackTrace=function(){};Promise.prototype._attachExtraTrace=function(){};Promise.prototype._dereferenceTrace=function(){};Promise.prototype._clearCancellationData=function(){};Promise.prototype._propagateFrom=function(parent,flags){};function cancellationExecute(executor,resolve,reject){var promise=this;try{executor(resolve,reject,(function(onCancel){if(typeof onCancel!=="function"){throw new TypeError("onCancel must be a function, got: "+util.toString(onCancel))}promise._attachCancellationCallback(onCancel)}))}catch(e){return e}}function cancellationAttachCancellationCallback(onCancel){if(!this._isCancellable())return this;var previousOnCancel=this._onCancel();if(previousOnCancel!==undefined){if(util.isArray(previousOnCancel)){previousOnCancel.push(onCancel)}else{this._setOnCancel([previousOnCancel,onCancel])}}else{this._setOnCancel(onCancel)}}function cancellationOnCancel(){return this._onCancelField}function cancellationSetOnCancel(onCancel){this._onCancelField=onCancel}function cancellationClearCancellationData(){this._cancellationParent=undefined;this._onCancelField=undefined}function cancellationPropagateFrom(parent,flags){if((flags&1)!==0){this._cancellationParent=parent;var branchesRemainingToCancel=parent._branchesRemainingToCancel;if(branchesRemainingToCancel===undefined){branchesRemainingToCancel=0}parent._branchesRemainingToCancel=branchesRemainingToCancel+1}if((flags&2)!==0&&parent._isBound()){this._setBoundTo(parent._boundTo)}}function bindingPropagateFrom(parent,flags){if((flags&2)!==0&&parent._isBound()){this._setBoundTo(parent._boundTo)}}var _propagateFromFunction=bindingPropagateFrom;function _boundValueFunction(){var ret=this._boundTo;if(ret!==undefined){if(ret instanceof Promise){if(ret.isFulfilled()){return ret.value()}else{return undefined}}}return ret}function longStackTracesCaptureStackTrace(){this._trace=new CapturedTrace(this._peekContext())}function longStackTracesAttachExtraTrace(error,ignoreSelf){if(canAttachTrace(error)){var trace=this._trace;if(trace!==undefined){if(ignoreSelf)trace=trace._parent}if(trace!==undefined){trace.attachExtraTrace(error)}else if(!error.__stackCleaned__){var parsed=parseStackAndMessage(error);util.notEnumerableProp(error,"stack",parsed.message+"\n"+parsed.stack.join("\n"));util.notEnumerableProp(error,"__stackCleaned__",true)}}}function longStackTracesDereferenceTrace(){this._trace=undefined}function checkForgottenReturns(returnValue,promiseCreated,name,promise,parent){if(returnValue===undefined&&promiseCreated!==null&&wForgottenReturn){if(parent!==undefined&&parent._returnedNonUndefined())return;if((promise._bitField&65535)===0)return;if(name)name=name+" ";var handlerLine="";var creatorLine="";if(promiseCreated._trace){var traceLines=promiseCreated._trace.stack.split("\n");var stack=cleanStack(traceLines);for(var i=stack.length-1;i>=0;--i){var line=stack[i];if(!nodeFramePattern.test(line)){var lineMatches=line.match(parseLinePattern);if(lineMatches){handlerLine="at "+lineMatches[1]+":"+lineMatches[2]+":"+lineMatches[3]+" "}break}}if(stack.length>0){var firstUserLine=stack[0];for(var i=0;i<traceLines.length;++i){if(traceLines[i]===firstUserLine){if(i>0){creatorLine="\n"+traceLines[i-1]}break}}}}var msg="a promise was created in a "+name+"handler "+handlerLine+"but was not returned from it, "+"see http://goo.gl/rRqMUw"+creatorLine;promise._warn(msg,true,promiseCreated)}}function deprecated(name,replacement){var message=name+" is deprecated and will be removed in a future version.";if(replacement)message+=" Use "+replacement+" instead.";return warn(message)}function warn(message,shouldUseOwnTrace,promise){if(!config.warnings)return;var warning=new Warning(message);var ctx;if(shouldUseOwnTrace){promise._attachExtraTrace(warning)}else if(config.longStackTraces&&(ctx=Promise._peekContext())){ctx.attachExtraTrace(warning)}else{var parsed=parseStackAndMessage(warning);warning.stack=parsed.message+"\n"+parsed.stack.join("\n")}if(!activeFireEvent("warning",warning)){formatAndLogError(warning,"",true)}}function reconstructStack(message,stacks){for(var i=0;i<stacks.length-1;++i){stacks[i].push("From previous event:");stacks[i]=stacks[i].join("\n")}if(i<stacks.length){stacks[i]=stacks[i].join("\n")}return message+"\n"+stacks.join("\n")}function removeDuplicateOrEmptyJumps(stacks){for(var i=0;i<stacks.length;++i){if(stacks[i].length===0||i+1<stacks.length&&stacks[i][0]===stacks[i+1][0]){stacks.splice(i,1);i--}}}function removeCommonRoots(stacks){var current=stacks[0];for(var i=1;i<stacks.length;++i){var prev=stacks[i];var currentLastIndex=current.length-1;var currentLastLine=current[currentLastIndex];var commonRootMeetPoint=-1;for(var j=prev.length-1;j>=0;--j){if(prev[j]===currentLastLine){commonRootMeetPoint=j;break}}for(var j=commonRootMeetPoint;j>=0;--j){var line=prev[j];if(current[currentLastIndex]===line){current.pop();currentLastIndex--}else{break}}current=prev}}function cleanStack(stack){var ret=[];for(var i=0;i<stack.length;++i){var line=stack[i];var isTraceLine=" (No stack trace)"===line||stackFramePattern.test(line);var isInternalFrame=isTraceLine&&shouldIgnore(line);if(isTraceLine&&!isInternalFrame){if(indentStackFrames&&line.charAt(0)!==" "){line=" "+line}ret.push(line)}}return ret}function stackFramesAsArray(error){var stack=error.stack.replace(/\s+$/g,"").split("\n");for(var i=0;i<stack.length;++i){var line=stack[i];if(" (No stack trace)"===line||stackFramePattern.test(line)){break}}if(i>0&&error.name!="SyntaxError"){stack=stack.slice(i)}return stack}function parseStackAndMessage(error){var stack=error.stack;var message=error.toString();stack=typeof stack==="string"&&stack.length>0?stackFramesAsArray(error):[" (No stack trace)"];return{message:message,stack:error.name=="SyntaxError"?stack:cleanStack(stack)}}function formatAndLogError(error,title,isSoft){if(typeof console!=="undefined"){var message;if(util.isObject(error)){var stack=error.stack;message=title+formatStack(stack,error)}else{message=title+String(error)}if(typeof printWarning==="function"){printWarning(message,isSoft)}else if(typeof console.log==="function"||_typeof(console.log)==="object"){console.log(message)}}}function fireRejectionEvent(name,localHandler,reason,promise){var localEventFired=false;try{if(typeof localHandler==="function"){localEventFired=true;if(name==="rejectionHandled"){localHandler(promise)}else{localHandler(reason,promise)}}}catch(e){async.throwLater(e)}if(name==="unhandledRejection"){if(!activeFireEvent(name,reason,promise)&&!localEventFired){formatAndLogError(reason,"Unhandled rejection ")}}else{activeFireEvent(name,promise)}}function formatNonError(obj){var str;if(typeof obj==="function"){str="[function "+(obj.name||"anonymous")+"]"}else{str=obj&&typeof obj.toString==="function"?obj.toString():util.toString(obj);var ruselessToString=/\[object [a-zA-Z0-9$_]+\]/;if(ruselessToString.test(str)){try{var newStr=JSON.stringify(obj);str=newStr}catch(e){}}if(str.length===0){str="(empty array)"}}return"(<"+snip(str)+">, no stack trace)"}function snip(str){var maxChars=41;if(str.length<maxChars){return str}return str.substr(0,maxChars-3)+"..."}function longStackTracesIsSupported(){return typeof captureStackTrace==="function"}var shouldIgnore=function shouldIgnore(){return false};var parseLineInfoRegex=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;function parseLineInfo(line){var matches=line.match(parseLineInfoRegex);if(matches){return{fileName:matches[1],line:parseInt(matches[2],10)}}}function setBounds(firstLineError,lastLineError){if(!longStackTracesIsSupported())return;var firstStackLines=(firstLineError.stack||"").split("\n");var lastStackLines=(lastLineError.stack||"").split("\n");var firstIndex=-1;var lastIndex=-1;var firstFileName;var lastFileName;for(var i=0;i<firstStackLines.length;++i){var result=parseLineInfo(firstStackLines[i]);if(result){firstFileName=result.fileName;firstIndex=result.line;break}}for(var i=0;i<lastStackLines.length;++i){var result=parseLineInfo(lastStackLines[i]);if(result){lastFileName=result.fileName;lastIndex=result.line;break}}if(firstIndex<0||lastIndex<0||!firstFileName||!lastFileName||firstFileName!==lastFileName||firstIndex>=lastIndex){return}shouldIgnore=function shouldIgnore(line){if(bluebirdFramePattern.test(line))return true;var info=parseLineInfo(line);if(info){if(info.fileName===firstFileName&&firstIndex<=info.line&&info.line<=lastIndex){return true}}return false}}function CapturedTrace(parent){this._parent=parent;this._promisesCreated=0;var length=this._length=1+(parent===undefined?0:parent._length);captureStackTrace(this,CapturedTrace);if(length>32)this.uncycle()}util.inherits(CapturedTrace,Error);Context.CapturedTrace=CapturedTrace;CapturedTrace.prototype.uncycle=function(){var length=this._length;if(length<2)return;var nodes=[];var stackToIndex={};for(var i=0,node=this;node!==undefined;++i){nodes.push(node);node=node._parent}length=this._length=i;for(var i=length-1;i>=0;--i){var stack=nodes[i].stack;if(stackToIndex[stack]===undefined){stackToIndex[stack]=i}}for(var i=0;i<length;++i){var currentStack=nodes[i].stack;var index=stackToIndex[currentStack];if(index!==undefined&&index!==i){if(index>0){nodes[index-1]._parent=undefined;nodes[index-1]._length=1}nodes[i]._parent=undefined;nodes[i]._length=1;var cycleEdgeNode=i>0?nodes[i-1]:this;if(index<length-1){cycleEdgeNode._parent=nodes[index+1];cycleEdgeNode._parent.uncycle();cycleEdgeNode._length=cycleEdgeNode._parent._length+1}else{cycleEdgeNode._parent=undefined;cycleEdgeNode._length=1}var currentChildLength=cycleEdgeNode._length+1;for(var j=i-2;j>=0;--j){nodes[j]._length=currentChildLength;currentChildLength++}return}}};CapturedTrace.prototype.attachExtraTrace=function(error){if(error.__stackCleaned__)return;this.uncycle();var parsed=parseStackAndMessage(error);var message=parsed.message;var stacks=[parsed.stack];var trace=this;while(trace!==undefined){stacks.push(cleanStack(trace.stack.split("\n")));trace=trace._parent}removeCommonRoots(stacks);removeDuplicateOrEmptyJumps(stacks);util.notEnumerableProp(error,"stack",reconstructStack(message,stacks));util.notEnumerableProp(error,"__stackCleaned__",true)};var captureStackTrace=function stackDetection(){var v8stackFramePattern=/^\s*at\s*/;var v8stackFormatter=function v8stackFormatter(stack,error){if(typeof stack==="string")return stack;if(error.name!==undefined&&error.message!==undefined){return error.toString()}return formatNonError(error)};if(typeof Error.stackTraceLimit==="number"&&typeof Error.captureStackTrace==="function"){Error.stackTraceLimit+=6;stackFramePattern=v8stackFramePattern;formatStack=v8stackFormatter;var captureStackTrace=Error.captureStackTrace;shouldIgnore=function shouldIgnore(line){return bluebirdFramePattern.test(line)};return function(receiver,ignoreUntil){Error.stackTraceLimit+=6;captureStackTrace(receiver,ignoreUntil);Error.stackTraceLimit-=6}}var err=new Error;if(typeof err.stack==="string"&&err.stack.split("\n")[0].indexOf("stackDetection@")>=0){stackFramePattern=/@/;formatStack=v8stackFormatter;indentStackFrames=true;return function captureStackTrace(o){o.stack=(new Error).stack}}var hasStackAfterThrow;try{throw new Error}catch(e){hasStackAfterThrow="stack"in e}if(!("stack"in err)&&hasStackAfterThrow&&typeof Error.stackTraceLimit==="number"){stackFramePattern=v8stackFramePattern;formatStack=v8stackFormatter;return function captureStackTrace(o){Error.stackTraceLimit+=6;try{throw new Error}catch(e){o.stack=e.stack}Error.stackTraceLimit-=6}}formatStack=function formatStack(stack,error){if(typeof stack==="string")return stack;if((_typeof(error)==="object"||typeof error==="function")&&error.name!==undefined&&error.message!==undefined){return error.toString()}return formatNonError(error)};return null}([]);if(typeof console!=="undefined"&&typeof console.warn!=="undefined"){printWarning=function printWarning(message){console.warn(message)};if(util.isNode&&process.stderr.isTTY){printWarning=function printWarning(message,isSoft){var color=isSoft?"[33m":"[31m";console.warn(color+message+"[0m\n")}}else if(!util.isNode&&typeof(new Error).stack==="string"){printWarning=function printWarning(message,isSoft){console.warn("%c"+message,isSoft?"color: darkorange":"color: red")}}}var config={warnings:warnings,longStackTraces:false,cancellation:false,monitoring:false,asyncHooks:false};if(longStackTraces)Promise.longStackTraces();return{asyncHooks:function asyncHooks(){return config.asyncHooks},longStackTraces:function longStackTraces(){return config.longStackTraces},warnings:function warnings(){return config.warnings},cancellation:function cancellation(){return config.cancellation},monitoring:function monitoring(){return config.monitoring},propagateFromFunction:function propagateFromFunction(){return _propagateFromFunction},boundValueFunction:function boundValueFunction(){return _boundValueFunction},checkForgottenReturns:checkForgottenReturns,setBounds:setBounds,warn:warn,deprecated:deprecated,CapturedTrace:CapturedTrace,fireDomEvent:fireDomEvent,fireGlobalEvent:fireGlobalEvent}}},{"./errors":12,"./es5":13,"./util":36}],10:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise){function returner(){return this.value}function thrower(){throw this.reason}Promise.prototype["return"]=Promise.prototype.thenReturn=function(value){if(value instanceof Promise)value.suppressUnhandledRejections();return this._then(returner,undefined,undefined,{value:value},undefined)};Promise.prototype["throw"]=Promise.prototype.thenThrow=function(reason){return this._then(thrower,undefined,undefined,{reason:reason},undefined)};Promise.prototype.catchThrow=function(reason){if(arguments.length<=1){return this._then(undefined,thrower,undefined,{reason:reason},undefined)}else{var _reason=arguments[1];var handler=function handler(){throw _reason};return this.caught(reason,handler)}};Promise.prototype.catchReturn=function(value){if(arguments.length<=1){if(value instanceof Promise)value.suppressUnhandledRejections();return this._then(undefined,returner,undefined,{value:value},undefined)}else{var _value=arguments[1];if(_value instanceof Promise)_value.suppressUnhandledRejections();var handler=function handler(){return _value};return this.caught(value,handler)}}}},{}],11:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL){var PromiseReduce=Promise.reduce;var PromiseAll=Promise.all;function promiseAllThis(){return PromiseAll(this)}function PromiseMapSeries(promises,fn){return PromiseReduce(promises,fn,INTERNAL,INTERNAL)}Promise.prototype.each=function(fn){return PromiseReduce(this,fn,INTERNAL,0)._then(promiseAllThis,undefined,undefined,this,undefined)};Promise.prototype.mapSeries=function(fn){return PromiseReduce(this,fn,INTERNAL,INTERNAL)};Promise.each=function(promises,fn){return PromiseReduce(promises,fn,INTERNAL,0)._then(promiseAllThis,undefined,undefined,promises,undefined)};Promise.mapSeries=PromiseMapSeries}},{}],12:[function(_dereq_,module,exports){"use strict";var es5=_dereq_("./es5");var Objectfreeze=es5.freeze;var util=_dereq_("./util");var inherits=util.inherits;var notEnumerableProp=util.notEnumerableProp;function subError(nameProperty,defaultMessage){function SubError(message){if(!(this instanceof SubError))return new SubError(message);notEnumerableProp(this,"message",typeof message==="string"?message:defaultMessage);notEnumerableProp(this,"name",nameProperty);if(Error.captureStackTrace){Error.captureStackTrace(this,this.constructor)}else{Error.call(this)}}inherits(SubError,Error);return SubError}var _TypeError,_RangeError;var Warning=subError("Warning","warning");var CancellationError=subError("CancellationError","cancellation error");var TimeoutError=subError("TimeoutError","timeout error");var AggregateError=subError("AggregateError","aggregate error");try{_TypeError=TypeError;_RangeError=RangeError}catch(e){_TypeError=subError("TypeError","type error");_RangeError=subError("RangeError","range error")}var methods=("join pop push shift unshift slice filter forEach some "+"every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");for(var i=0;i<methods.length;++i){if(typeof Array.prototype[methods[i]]==="function"){AggregateError.prototype[methods[i]]=Array.prototype[methods[i]]}}es5.defineProperty(AggregateError.prototype,"length",{value:0,configurable:false,writable:true,enumerable:true});AggregateError.prototype["isOperational"]=true;var level=0;AggregateError.prototype.toString=function(){var indent=Array(level*4+1).join(" ");var ret="\n"+indent+"AggregateError of:"+"\n";level++;indent=Array(level*4+1).join(" ");for(var i=0;i<this.length;++i){var str=this[i]===this?"[Circular AggregateError]":this[i]+"";var lines=str.split("\n");for(var j=0;j<lines.length;++j){lines[j]=indent+lines[j]}str=lines.join("\n");ret+=str+"\n"}level--;return ret};function OperationalError(message){if(!(this instanceof OperationalError))return new OperationalError(message);notEnumerableProp(this,"name","OperationalError");notEnumerableProp(this,"message",message);this.cause=message;this["isOperational"]=true;if(message instanceof Error){notEnumerableProp(this,"message",message.message);notEnumerableProp(this,"stack",message.stack)}else if(Error.captureStackTrace){Error.captureStackTrace(this,this.constructor)}}inherits(OperationalError,Error);var errorTypes=Error["__BluebirdErrorTypes__"];if(!errorTypes){errorTypes=Objectfreeze({CancellationError:CancellationError,TimeoutError:TimeoutError,OperationalError:OperationalError,RejectionError:OperationalError,AggregateError:AggregateError});es5.defineProperty(Error,"__BluebirdErrorTypes__",{value:errorTypes,writable:false,enumerable:false,configurable:false})}module.exports={Error:Error,TypeError:_TypeError,RangeError:_RangeError,CancellationError:errorTypes.CancellationError,OperationalError:errorTypes.OperationalError,TimeoutError:errorTypes.TimeoutError,AggregateError:errorTypes.AggregateError,Warning:Warning}},{"./es5":13,"./util":36}],13:[function(_dereq_,module,exports){var isES5=function(){"use strict";return this===undefined}();if(isES5){module.exports={freeze:Object.freeze,defineProperty:Object.defineProperty,getDescriptor:Object.getOwnPropertyDescriptor,keys:Object.keys,names:Object.getOwnPropertyNames,getPrototypeOf:Object.getPrototypeOf,isArray:Array.isArray,isES5:isES5,propertyIsWritable:function propertyIsWritable(obj,prop){var descriptor=Object.getOwnPropertyDescriptor(obj,prop);return!!(!descriptor||descriptor.writable||descriptor.set)}}}else{var has={}.hasOwnProperty;var str={}.toString;var proto={}.constructor.prototype;var ObjectKeys=function ObjectKeys(o){var ret=[];for(var key in o){if(has.call(o,key)){ret.push(key)}}return ret};var ObjectGetDescriptor=function ObjectGetDescriptor(o,key){return{value:o[key]}};var ObjectDefineProperty=function ObjectDefineProperty(o,key,desc){o[key]=desc.value;return o};var ObjectFreeze=function ObjectFreeze(obj){return obj};var ObjectGetPrototypeOf=function ObjectGetPrototypeOf(obj){try{return Object(obj).constructor.prototype}catch(e){return proto}};var ArrayIsArray=function ArrayIsArray(obj){try{return str.call(obj)==="[object Array]"}catch(e){return false}};module.exports={isArray:ArrayIsArray,keys:ObjectKeys,names:ObjectKeys,defineProperty:ObjectDefineProperty,getDescriptor:ObjectGetDescriptor,freeze:ObjectFreeze,getPrototypeOf:ObjectGetPrototypeOf,isES5:isES5,propertyIsWritable:function propertyIsWritable(){return true}}}},{}],14:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL){var PromiseMap=Promise.map;Promise.prototype.filter=function(fn,options){return PromiseMap(this,fn,options,INTERNAL)};Promise.filter=function(promises,fn,options){return PromiseMap(promises,fn,options,INTERNAL)}}},{}],15:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,tryConvertToPromise,NEXT_FILTER){var util=_dereq_("./util");var CancellationError=Promise.CancellationError;var errorObj=util.errorObj;var catchFilter=_dereq_("./catch_filter")(NEXT_FILTER);function PassThroughHandlerContext(promise,type,handler){this.promise=promise;this.type=type;this.handler=handler;this.called=false;this.cancelPromise=null}PassThroughHandlerContext.prototype.isFinallyHandler=function(){return this.type===0};function FinallyHandlerCancelReaction(finallyHandler){this.finallyHandler=finallyHandler}FinallyHandlerCancelReaction.prototype._resultCancelled=function(){checkCancel(this.finallyHandler)};function checkCancel(ctx,reason){if(ctx.cancelPromise!=null){if(arguments.length>1){ctx.cancelPromise._reject(reason)}else{ctx.cancelPromise._cancel()}ctx.cancelPromise=null;return true}return false}function succeed(){return finallyHandler.call(this,this.promise._target()._settledValue())}function fail(reason){if(checkCancel(this,reason))return;errorObj.e=reason;return errorObj}function finallyHandler(reasonOrValue){var promise=this.promise;var handler=this.handler;if(!this.called){this.called=true;var ret=this.isFinallyHandler()?handler.call(promise._boundValue()):handler.call(promise._boundValue(),reasonOrValue);if(ret===NEXT_FILTER){return ret}else if(ret!==undefined){promise._setReturnedNonUndefined();var maybePromise=tryConvertToPromise(ret,promise);if(maybePromise instanceof Promise){if(this.cancelPromise!=null){if(maybePromise._isCancelled()){var reason=new CancellationError("late cancellation observer");promise._attachExtraTrace(reason);errorObj.e=reason;return errorObj}else if(maybePromise.isPending()){maybePromise._attachCancellationCallback(new FinallyHandlerCancelReaction(this))}}return maybePromise._then(succeed,fail,undefined,this,undefined)}}}if(promise.isRejected()){checkCancel(this);errorObj.e=reasonOrValue;return errorObj}else{checkCancel(this);return reasonOrValue}}Promise.prototype._passThrough=function(handler,type,success,fail){if(typeof handler!=="function")return this.then();return this._then(success,fail,undefined,new PassThroughHandlerContext(this,type,handler),undefined)};Promise.prototype.lastly=Promise.prototype["finally"]=function(handler){return this._passThrough(handler,0,finallyHandler,finallyHandler)};Promise.prototype.tap=function(handler){return this._passThrough(handler,1,finallyHandler)};Promise.prototype.tapCatch=function(handlerOrPredicate){var len=arguments.length;if(len===1){return this._passThrough(handlerOrPredicate,1,undefined,finallyHandler)}else{var catchInstances=new Array(len-1),j=0,i;for(i=0;i<len-1;++i){var item=arguments[i];if(util.isObject(item)){catchInstances[j++]=item}else{return Promise.reject(new TypeError("tapCatch statement predicate: "+"expecting an object but got "+util.classString(item)))}}catchInstances.length=j;var handler=arguments[i];return this._passThrough(catchFilter(catchInstances,handler,this),1,undefined,finallyHandler)}};return PassThroughHandlerContext}},{"./catch_filter":7,"./util":36}],16:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,apiRejection,INTERNAL,tryConvertToPromise,Proxyable,debug){var errors=_dereq_("./errors");var TypeError=errors.TypeError;var util=_dereq_("./util");var errorObj=util.errorObj;var tryCatch=util.tryCatch;var yieldHandlers=[];function promiseFromYieldHandler(value,yieldHandlers,traceParent){for(var i=0;i<yieldHandlers.length;++i){traceParent._pushContext();var result=tryCatch(yieldHandlers[i])(value);traceParent._popContext();if(result===errorObj){traceParent._pushContext();var ret=Promise.reject(errorObj.e);traceParent._popContext();return ret}var maybePromise=tryConvertToPromise(result,traceParent);if(maybePromise instanceof Promise)return maybePromise}return null}function PromiseSpawn(generatorFunction,receiver,yieldHandler,stack){if(debug.cancellation()){var internal=new Promise(INTERNAL);var _finallyPromise=this._finallyPromise=new Promise(INTERNAL);this._promise=internal.lastly((function(){return _finallyPromise}));internal._captureStackTrace();internal._setOnCancel(this)}else{var promise=this._promise=new Promise(INTERNAL);promise._captureStackTrace()}this._stack=stack;this._generatorFunction=generatorFunction;this._receiver=receiver;this._generator=undefined;this._yieldHandlers=typeof yieldHandler==="function"?[yieldHandler].concat(yieldHandlers):yieldHandlers;this._yieldedPromise=null;this._cancellationPhase=false}util.inherits(PromiseSpawn,Proxyable);PromiseSpawn.prototype._isResolved=function(){return this._promise===null};PromiseSpawn.prototype._cleanup=function(){this._promise=this._generator=null;if(debug.cancellation()&&this._finallyPromise!==null){this._finallyPromise._fulfill();this._finallyPromise=null}};PromiseSpawn.prototype._promiseCancelled=function(){if(this._isResolved())return;var implementsReturn=typeof this._generator["return"]!=="undefined";var result;if(!implementsReturn){var reason=new Promise.CancellationError("generator .return() sentinel");Promise.coroutine.returnSentinel=reason;this._promise._attachExtraTrace(reason);this._promise._pushContext();result=tryCatch(this._generator["throw"]).call(this._generator,reason);this._promise._popContext()}else{this._promise._pushContext();result=tryCatch(this._generator["return"]).call(this._generator,undefined);this._promise._popContext()}this._cancellationPhase=true;this._yieldedPromise=null;this._continue(result)};PromiseSpawn.prototype._promiseFulfilled=function(value){this._yieldedPromise=null;this._promise._pushContext();var result=tryCatch(this._generator.next).call(this._generator,value);this._promise._popContext();this._continue(result)};PromiseSpawn.prototype._promiseRejected=function(reason){this._yieldedPromise=null;this._promise._attachExtraTrace(reason);this._promise._pushContext();var result=tryCatch(this._generator["throw"]).call(this._generator,reason);this._promise._popContext();this._continue(result)};PromiseSpawn.prototype._resultCancelled=function(){if(this._yieldedPromise instanceof Promise){var promise=this._yieldedPromise;this._yieldedPromise=null;promise.cancel()}};PromiseSpawn.prototype.promise=function(){return this._promise};PromiseSpawn.prototype._run=function(){this._generator=this._generatorFunction.call(this._receiver);this._receiver=this._generatorFunction=undefined;this._promiseFulfilled(undefined)};PromiseSpawn.prototype._continue=function(result){var promise=this._promise;if(result===errorObj){this._cleanup();if(this._cancellationPhase){return promise.cancel()}else{return promise._rejectCallback(result.e,false)}}var value=result.value;if(result.done===true){this._cleanup();if(this._cancellationPhase){return promise.cancel()}else{return promise._resolveCallback(value)}}else{var maybePromise=tryConvertToPromise(value,this._promise);if(!(maybePromise instanceof Promise)){maybePromise=promiseFromYieldHandler(maybePromise,this._yieldHandlers,this._promise);if(maybePromise===null){this._promiseRejected(new TypeError("A value %s was yielded that could not be treated as a promise\n\n See http://goo.gl/MqrFmX\n\n".replace("%s",String(value))+"From coroutine:\n"+this._stack.split("\n").slice(1,-7).join("\n")));return}}maybePromise=maybePromise._target();var bitField=maybePromise._bitField;if((bitField&50397184)===0){this._yieldedPromise=maybePromise;maybePromise._proxy(this,null)}else if((bitField&33554432)!==0){Promise._async.invoke(this._promiseFulfilled,this,maybePromise._value())}else if((bitField&16777216)!==0){Promise._async.invoke(this._promiseRejected,this,maybePromise._reason())}else{this._promiseCancelled()}}};Promise.coroutine=function(generatorFunction,options){if(typeof generatorFunction!=="function"){throw new TypeError("generatorFunction must be a function\n\n See http://goo.gl/MqrFmX\n")}var yieldHandler=Object(options).yieldHandler;var PromiseSpawn$=PromiseSpawn;var stack=(new Error).stack;return function(){var generator=generatorFunction.apply(this,arguments);var spawn=new PromiseSpawn$(undefined,undefined,yieldHandler,stack);var ret=spawn.promise();spawn._generator=generator;spawn._promiseFulfilled(undefined);return ret}};Promise.coroutine.addYieldHandler=function(fn){if(typeof fn!=="function"){throw new TypeError("expecting a function but got "+util.classString(fn))}yieldHandlers.push(fn)};Promise.spawn=function(generatorFunction){debug.deprecated("Promise.spawn()","Promise.coroutine()");if(typeof generatorFunction!=="function"){return apiRejection("generatorFunction must be a function\n\n See http://goo.gl/MqrFmX\n")}var spawn=new PromiseSpawn(generatorFunction,this);var ret=spawn.promise();spawn._run(Promise.spawn);return ret}}},{"./errors":12,"./util":36}],17:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,tryConvertToPromise,INTERNAL,async){var util=_dereq_("./util");var canEvaluate=util.canEvaluate;var tryCatch=util.tryCatch;var errorObj=util.errorObj;var reject;if(!true){if(canEvaluate){var thenCallback=function thenCallback(i){return new Function("value","holder"," \n 'use strict'; \n holder.pIndex = value; \n holder.checkFulfillment(this); \n ".replace(/Index/g,i))};var promiseSetter=function promiseSetter(i){return new Function("promise","holder"," \n 'use strict'; \n holder.pIndex = promise; \n ".replace(/Index/g,i))};var generateHolderClass=function generateHolderClass(total){var props=new Array(total);for(var i=0;i<props.length;++i){props[i]="this.p"+(i+1)}var assignment=props.join(" = ")+" = null;";var cancellationCode="var promise;\n"+props.map((function(prop){return" \n promise = "+prop+"; \n if (promise instanceof Promise) { \n promise.cancel(); \n } \n "})).join("\n");var passedArguments=props.join(", ");var name="Holder$"+total;var code="return function(tryCatch, errorObj, Promise, async) { \n 'use strict'; \n function [TheName](fn) { \n [TheProperties] \n this.fn = fn; \n this.asyncNeeded = true; \n this.now = 0; \n } \n \n [TheName].prototype._callFunction = function(promise) { \n promise._pushContext(); \n var ret = tryCatch(this.fn)([ThePassedArguments]); \n promise._popContext(); \n if (ret === errorObj) { \n promise._rejectCallback(ret.e, false); \n } else { \n promise._resolveCallback(ret); \n } \n }; \n \n [TheName].prototype.checkFulfillment = function(promise) { \n var now = ++this.now; \n if (now === [TheTotal]) { \n if (this.asyncNeeded) { \n async.invoke(this._callFunction, this, promise); \n } else { \n this._callFunction(promise); \n } \n \n } \n }; \n \n [TheName].prototype._resultCancelled = function() { \n [CancellationCode] \n }; \n \n return [TheName]; \n }(tryCatch, errorObj, Promise, async); \n ";code=code.replace(/\[TheName\]/g,name).replace(/\[TheTotal\]/g,total).replace(/\[ThePassedArguments\]/g,passedArguments).replace(/\[TheProperties\]/g,assignment).replace(/\[CancellationCode\]/g,cancellationCode);return new Function("tryCatch","errorObj","Promise","async",code)(tryCatch,errorObj,Promise,async)};var holderClasses=[];var thenCallbacks=[];var promiseSetters=[];for(var i=0;i<8;++i){holderClasses.push(generateHolderClass(i+1));thenCallbacks.push(thenCallback(i+1));promiseSetters.push(promiseSetter(i+1))}reject=function reject(reason){this._reject(reason)}}}Promise.join=function(){var last=arguments.length-1;var fn;if(last>0&&typeof arguments[last]==="function"){fn=arguments[last];if(!true){if(last<=8&&canEvaluate){var ret=new Promise(INTERNAL);ret._captureStackTrace();var HolderClass=holderClasses[last-1];var holder=new HolderClass(fn);var callbacks=thenCallbacks;for(var i=0;i<last;++i){var maybePromise=tryConvertToPromise(arguments[i],ret);if(maybePromise instanceof Promise){maybePromise=maybePromise._target();var bitField=maybePromise._bitField;if((bitField&50397184)===0){maybePromise._then(callbacks[i],reject,undefined,ret,holder);promiseSetters[i](maybePromise,holder);holder.asyncNeeded=false}else if((bitField&33554432)!==0){callbacks[i].call(ret,maybePromise._value(),holder)}else if((bitField&16777216)!==0){ret._reject(maybePromise._reason())}else{ret._cancel()}}else{callbacks[i].call(ret,maybePromise,holder)}}if(!ret._isFateSealed()){if(holder.asyncNeeded){var context=Promise._getContext();holder.fn=util.contextBind(context,holder.fn)}ret._setAsyncGuaranteed();ret._setOnCancel(holder)}return ret}}}var args=[].slice.call(arguments);if(fn)args.pop();var ret=new PromiseArray(args).promise();return fn!==undefined?ret.spread(fn):ret}}},{"./util":36}],18:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,apiRejection,tryConvertToPromise,INTERNAL,debug){var util=_dereq_("./util");var tryCatch=util.tryCatch;var errorObj=util.errorObj;var async=Promise._async;function MappingPromiseArray(promises,fn,limit,_filter){this.constructor$(promises);this._promise._captureStackTrace();var context=Promise._getContext();this._callback=util.contextBind(context,fn);this._preservedValues=_filter===INTERNAL?new Array(this.length()):null;this._limit=limit;this._inFlight=0;this._queue=[];async.invoke(this._asyncInit,this,undefined);if(util.isArray(promises)){for(var i=0;i<promises.length;++i){var maybePromise=promises[i];if(maybePromise instanceof Promise){maybePromise.suppressUnhandledRejections()}}}}util.inherits(MappingPromiseArray,PromiseArray);MappingPromiseArray.prototype._asyncInit=function(){this._init$(undefined,-2)};MappingPromiseArray.prototype._init=function(){};MappingPromiseArray.prototype._promiseFulfilled=function(value,index){var values=this._values;var length=this.length();var preservedValues=this._preservedValues;var limit=this._limit;if(index<0){index=index*-1-1;values[index]=value;if(limit>=1){this._inFlight--;this._drainQueue();if(this._isResolved())return true}}else{if(limit>=1&&this._inFlight>=limit){values[index]=value;this._queue.push(index);return false}if(preservedValues!==null)preservedValues[index]=value;var promise=this._promise;var callback=this._callback;var receiver=promise._boundValue();promise._pushContext();var ret=tryCatch(callback).call(receiver,value,index,length);var promiseCreated=promise._popContext();debug.checkForgottenReturns(ret,promiseCreated,preservedValues!==null?"Promise.filter":"Promise.map",promise);if(ret===errorObj){this._reject(ret.e);return true}var maybePromise=tryConvertToPromise(ret,this._promise);if(maybePromise instanceof Promise){maybePromise=maybePromise._target();var bitField=maybePromise._bitField;if((bitField&50397184)===0){if(limit>=1)this._inFlight++;values[index]=maybePromise;maybePromise._proxy(this,(index+1)*-1);return false}else if((bitField&33554432)!==0){ret=maybePromise._value()}else if((bitField&16777216)!==0){this._reject(maybePromise._reason());return true}else{this._cancel();return true}}values[index]=ret}var totalResolved=++this._totalResolved;if(totalResolved>=length){if(preservedValues!==null){this._filter(values,preservedValues)}else{this._resolve(values)}return true}return false};MappingPromiseArray.prototype._drainQueue=function(){var queue=this._queue;var limit=this._limit;var values=this._values;while(queue.length>0&&this._inFlight<limit){if(this._isResolved())return;var index=queue.pop();this._promiseFulfilled(values[index],index)}};MappingPromiseArray.prototype._filter=function(booleans,values){var len=values.length;var ret=new Array(len);var j=0;for(var i=0;i<len;++i){if(booleans[i])ret[j++]=values[i]}ret.length=j;this._resolve(ret)};MappingPromiseArray.prototype.preservedValues=function(){return this._preservedValues};function map(promises,fn,options,_filter){if(typeof fn!=="function"){return apiRejection("expecting a function but got "+util.classString(fn))}var limit=0;if(options!==undefined){if(_typeof(options)==="object"&&options!==null){if(typeof options.concurrency!=="number"){return Promise.reject(new TypeError("'concurrency' must be a number but it is "+util.classString(options.concurrency)))}limit=options.concurrency}else{return Promise.reject(new TypeError("options argument must be an object but it is "+util.classString(options)))}}limit=typeof limit==="number"&&isFinite(limit)&&limit>=1?limit:0;return new MappingPromiseArray(promises,fn,limit,_filter).promise()}Promise.prototype.map=function(fn,options){return map(this,fn,options,null)};Promise.map=function(promises,fn,options,_filter){return map(promises,fn,options,_filter)}}},{"./util":36}],19:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL,tryConvertToPromise,apiRejection,debug){var util=_dereq_("./util");var tryCatch=util.tryCatch;Promise.method=function(fn){if(typeof fn!=="function"){throw new Promise.TypeError("expecting a function but got "+util.classString(fn))}return function(){var ret=new Promise(INTERNAL);ret._captureStackTrace();ret._pushContext();var value=tryCatch(fn).apply(this,arguments);var promiseCreated=ret._popContext();debug.checkForgottenReturns(value,promiseCreated,"Promise.method",ret);ret._resolveFromSyncValue(value);return ret}};Promise.attempt=Promise["try"]=function(fn){if(typeof fn!=="function"){return apiRejection("expecting a function but got "+util.classString(fn))}var ret=new Promise(INTERNAL);ret._captureStackTrace();ret._pushContext();var value;if(arguments.length>1){debug.deprecated("calling Promise.try with more than 1 argument");var arg=arguments[1];var ctx=arguments[2];value=util.isArray(arg)?tryCatch(fn).apply(ctx,arg):tryCatch(fn).call(ctx,arg)}else{value=tryCatch(fn)()}var promiseCreated=ret._popContext();debug.checkForgottenReturns(value,promiseCreated,"Promise.try",ret);ret._resolveFromSyncValue(value);return ret};Promise.prototype._resolveFromSyncValue=function(value){if(value===util.errorObj){this._rejectCallback(value.e,false)}else{this._resolveCallback(value,true)}}}},{"./util":36}],20:[function(_dereq_,module,exports){"use strict";var util=_dereq_("./util");var maybeWrapAsError=util.maybeWrapAsError;var errors=_dereq_("./errors");var OperationalError=errors.OperationalError;var es5=_dereq_("./es5");function isUntypedError(obj){return obj instanceof Error&&es5.getPrototypeOf(obj)===Error.prototype}var rErrorKey=/^(?:name|message|stack|cause)$/;function wrapAsOperationalError(obj){var ret;if(isUntypedError(obj)){ret=new OperationalError(obj);ret.name=obj.name;ret.message=obj.message;ret.stack=obj.stack;var keys=es5.keys(obj);for(var i=0;i<keys.length;++i){var key=keys[i];if(!rErrorKey.test(key)){ret[key]=obj[key]}}return ret}util.markAsOriginatingFromRejection(obj);return obj}function nodebackForPromise(promise,multiArgs){return function(err,value){if(promise===null)return;if(err){var wrapped=wrapAsOperationalError(maybeWrapAsError(err));promise._attachExtraTrace(wrapped);promise._reject(wrapped)}else if(!multiArgs){promise._fulfill(value)}else{var args=[].slice.call(arguments,1);promise._fulfill(args)}promise=null}}module.exports=nodebackForPromise},{"./errors":12,"./es5":13,"./util":36}],21:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise){var util=_dereq_("./util");var async=Promise._async;var tryCatch=util.tryCatch;var errorObj=util.errorObj;function spreadAdapter(val,nodeback){var promise=this;if(!util.isArray(val))return successAdapter.call(promise,val,nodeback);var ret=tryCatch(nodeback).apply(promise._boundValue(),[null].concat(val));if(ret===errorObj){async.throwLater(ret.e)}}function successAdapter(val,nodeback){var promise=this;var receiver=promise._boundValue();var ret=val===undefined?tryCatch(nodeback).call(receiver,null):tryCatch(nodeback).call(receiver,null,val);if(ret===errorObj){async.throwLater(ret.e)}}function errorAdapter(reason,nodeback){var promise=this;if(!reason){var newReason=new Error(reason+"");newReason.cause=reason;reason=newReason}var ret=tryCatch(nodeback).call(promise._boundValue(),reason);if(ret===errorObj){async.throwLater(ret.e)}}Promise.prototype.asCallback=Promise.prototype.nodeify=function(nodeback,options){if(typeof nodeback=="function"){var adapter=successAdapter;if(options!==undefined&&Object(options).spread){adapter=spreadAdapter}this._then(adapter,errorAdapter,undefined,this,nodeback)}return this}}},{"./util":36}],22:[function(_dereq_,module,exports){"use strict";module.exports=function(){var makeSelfResolutionError=function makeSelfResolutionError(){return new TypeError("circular promise resolution chain\n\n See http://goo.gl/MqrFmX\n")};var reflectHandler=function reflectHandler(){return new Promise.PromiseInspection(this._target())};var apiRejection=function apiRejection(msg){return Promise.reject(new TypeError(msg))};function Proxyable(){}var UNDEFINED_BINDING={};var util=_dereq_("./util");util.setReflectHandler(reflectHandler);var getDomain=function getDomain(){var domain=process.domain;if(domain===undefined){return null}return domain};var getContextDefault=function getContextDefault(){return null};var getContextDomain=function getContextDomain(){return{domain:getDomain(),async:null}};var AsyncResource=util.isNode&&util.nodeSupportsAsyncResource?_dereq_("async_hooks").AsyncResource:null;var getContextAsyncHooks=function getContextAsyncHooks(){return{domain:getDomain(),async:new AsyncResource("Bluebird::Promise")}};var getContext=util.isNode?getContextDomain:getContextDefault;util.notEnumerableProp(Promise,"_getContext",getContext);var enableAsyncHooks=function enableAsyncHooks(){getContext=getContextAsyncHooks;util.notEnumerableProp(Promise,"_getContext",getContextAsyncHooks)};var disableAsyncHooks=function disableAsyncHooks(){getContext=getContextDomain;util.notEnumerableProp(Promise,"_getContext",getContextDomain)};var es5=_dereq_("./es5");var Async=_dereq_("./async");var async=new Async;es5.defineProperty(Promise,"_async",{value:async});var errors=_dereq_("./errors");var TypeError=Promise.TypeError=errors.TypeError;Promise.RangeError=errors.RangeError;var CancellationError=Promise.CancellationError=errors.CancellationError;Promise.TimeoutError=errors.TimeoutError;Promise.OperationalError=errors.OperationalError;Promise.RejectionError=errors.OperationalError;Promise.AggregateError=errors.AggregateError;var INTERNAL=function INTERNAL(){};var APPLY={};var NEXT_FILTER={};var tryConvertToPromise=_dereq_("./thenables")(Promise,INTERNAL);var PromiseArray=_dereq_("./promise_array")(Promise,INTERNAL,tryConvertToPromise,apiRejection,Proxyable);var Context=_dereq_("./context")(Promise);var createContext=Context.create;var debug=_dereq_("./debuggability")(Promise,Context,enableAsyncHooks,disableAsyncHooks);var CapturedTrace=debug.CapturedTrace;var PassThroughHandlerContext=_dereq_("./finally")(Promise,tryConvertToPromise,NEXT_FILTER);var catchFilter=_dereq_("./catch_filter")(NEXT_FILTER);var nodebackForPromise=_dereq_("./nodeback");var errorObj=util.errorObj;var tryCatch=util.tryCatch;function check(self,executor){if(self==null||self.constructor!==Promise){throw new TypeError("the promise constructor cannot be invoked directly\n\n See http://goo.gl/MqrFmX\n")}if(typeof executor!=="function"){throw new TypeError("expecting a function but got "+util.classString(executor))}}function Promise(executor){if(executor!==INTERNAL){check(this,executor)}this._bitField=0;this._fulfillmentHandler0=undefined;this._rejectionHandler0=undefined;this._promise0=undefined;this._receiver0=undefined;this._resolveFromExecutor(executor);this._promiseCreated();this._fireEvent("promiseCreated",this)}Promise.prototype.toString=function(){return"[object Promise]"};Promise.prototype.caught=Promise.prototype["catch"]=function(fn){var len=arguments.length;if(len>1){var catchInstances=new Array(len-1),j=0,i;for(i=0;i<len-1;++i){var item=arguments[i];if(util.isObject(item)){catchInstances[j++]=item}else{return apiRejection("Catch statement predicate: "+"expecting an object but got "+util.classString(item))}}catchInstances.length=j;fn=arguments[i];if(typeof fn!=="function"){throw new TypeError("The last argument to .catch() "+"must be a function, got "+util.toString(fn))}return this.then(undefined,catchFilter(catchInstances,fn,this))}return this.then(undefined,fn)};Promise.prototype.reflect=function(){return this._then(reflectHandler,reflectHandler,undefined,this,undefined)};Promise.prototype.then=function(didFulfill,didReject){if(debug.warnings()&&arguments.length>0&&typeof didFulfill!=="function"&&typeof didReject!=="function"){var msg=".then() only accepts functions but was passed: "+util.classString(didFulfill);if(arguments.length>1){msg+=", "+util.classString(didReject)}this._warn(msg)}return this._then(didFulfill,didReject,undefined,undefined,undefined)};Promise.prototype.done=function(didFulfill,didReject){var promise=this._then(didFulfill,didReject,undefined,undefined,undefined);promise._setIsFinal()};Promise.prototype.spread=function(fn){if(typeof fn!=="function"){return apiRejection("expecting a function but got "+util.classString(fn))}return this.all()._then(fn,undefined,undefined,APPLY,undefined)};Promise.prototype.toJSON=function(){var ret={isFulfilled:false,isRejected:false,fulfillmentValue:undefined,rejectionReason:undefined};if(this.isFulfilled()){ret.fulfillmentValue=this.value();ret.isFulfilled=true}else if(this.isRejected()){ret.rejectionReason=this.reason();ret.isRejected=true}return ret};Promise.prototype.all=function(){if(arguments.length>0){this._warn(".all() was passed arguments but it does not take any")}return new PromiseArray(this).promise()};Promise.prototype.error=function(fn){return this.caught(util.originatesFromRejection,fn)};Promise.getNewLibraryCopy=module.exports;Promise.is=function(val){return val instanceof Promise};Promise.fromNode=Promise.fromCallback=function(fn){var ret=new Promise(INTERNAL);ret._captureStackTrace();var multiArgs=arguments.length>1?!!Object(arguments[1]).multiArgs:false;var result=tryCatch(fn)(nodebackForPromise(ret,multiArgs));if(result===errorObj){ret._rejectCallback(result.e,true)}if(!ret._isFateSealed())ret._setAsyncGuaranteed();return ret};Promise.all=function(promises){return new PromiseArray(promises).promise()};Promise.cast=function(obj){var ret=tryConvertToPromise(obj);if(!(ret instanceof Promise)){ret=new Promise(INTERNAL);ret._captureStackTrace();ret._setFulfilled();ret._rejectionHandler0=obj}return ret};Promise.resolve=Promise.fulfilled=Promise.cast;Promise.reject=Promise.rejected=function(reason){var ret=new Promise(INTERNAL);ret._captureStackTrace();ret._rejectCallback(reason,true);return ret};Promise.setScheduler=function(fn){if(typeof fn!=="function"){throw new TypeError("expecting a function but got "+util.classString(fn))}return async.setScheduler(fn)};Promise.prototype._then=function(didFulfill,didReject,_,receiver,internalData){var haveInternalData=internalData!==undefined;var promise=haveInternalData?internalData:new Promise(INTERNAL);var target=this._target();var bitField=target._bitField;if(!haveInternalData){promise._propagateFrom(this,3);promise._captureStackTrace();if(receiver===undefined&&(this._bitField&2097152)!==0){if(!((bitField&50397184)===0)){receiver=this._boundValue()}else{receiver=target===this?undefined:this._boundTo}}this._fireEvent("promiseChained",this,promise)}var context=getContext();if(!((bitField&50397184)===0)){var handler,value,settler=target._settlePromiseCtx;if((bitField&33554432)!==0){value=target._rejectionHandler0;handler=didFulfill}else if((bitField&16777216)!==0){value=target._fulfillmentHandler0;handler=didReject;target._unsetRejectionIsUnhandled()}else{settler=target._settlePromiseLateCancellationObserver;value=new CancellationError("late cancellation observer");target._attachExtraTrace(value);handler=didReject}async.invoke(settler,target,{handler:util.contextBind(context,handler),promise:promise,receiver:receiver,value:value})}else{target._addCallbacks(didFulfill,didReject,promise,receiver,context)}return promise};Promise.prototype._length=function(){return this._bitField&65535};Promise.prototype._isFateSealed=function(){return(this._bitField&117506048)!==0};Promise.prototype._isFollowing=function(){return(this._bitField&67108864)===67108864};Promise.prototype._setLength=function(len){this._bitField=this._bitField&-65536|len&65535};Promise.prototype._setFulfilled=function(){this._bitField=this._bitField|33554432;this._fireEvent("promiseFulfilled",this)};Promise.prototype._setRejected=function(){this._bitField=this._bitField|16777216;this._fireEvent("promiseRejected",this)};Promise.prototype._setFollowing=function(){this._bitField=this._bitField|67108864;this._fireEvent("promiseResolved",this)};Promise.prototype._setIsFinal=function(){this._bitField=this._bitField|4194304};Promise.prototype._isFinal=function(){return(this._bitField&4194304)>0};Promise.prototype._unsetCancelled=function(){this._bitField=this._bitField&~65536};Promise.prototype._setCancelled=function(){this._bitField=this._bitField|65536;this._fireEvent("promiseCancelled",this)};Promise.prototype._setWillBeCancelled=function(){this._bitField=this._bitField|8388608};Promise.prototype._setAsyncGuaranteed=function(){if(async.hasCustomScheduler())return;var bitField=this._bitField;this._bitField=bitField|(bitField&536870912)>>2^134217728};Promise.prototype._setNoAsyncGuarantee=function(){this._bitField=(this._bitField|536870912)&~134217728};Promise.prototype._receiverAt=function(index){var ret=index===0?this._receiver0:this[index*4-4+3];if(ret===UNDEFINED_BINDING){return undefined}else if(ret===undefined&&this._isBound()){return this._boundValue()}return ret};Promise.prototype._promiseAt=function(index){return this[index*4-4+2]};Promise.prototype._fulfillmentHandlerAt=function(index){return this[index*4-4+0]};Promise.prototype._rejectionHandlerAt=function(index){return this[index*4-4+1]};Promise.prototype._boundValue=function(){};Promise.prototype._migrateCallback0=function(follower){var bitField=follower._bitField;var fulfill=follower._fulfillmentHandler0;var reject=follower._rejectionHandler0;var promise=follower._promise0;var receiver=follower._receiverAt(0);if(receiver===undefined)receiver=UNDEFINED_BINDING;this._addCallbacks(fulfill,reject,promise,receiver,null)};Promise.prototype._migrateCallbackAt=function(follower,index){var fulfill=follower._fulfillmentHandlerAt(index);var reject=follower._rejectionHandlerAt(index);var promise=follower._promiseAt(index);var receiver=follower._receiverAt(index);if(receiver===undefined)receiver=UNDEFINED_BINDING;this._addCallbacks(fulfill,reject,promise,receiver,null)};Promise.prototype._addCallbacks=function(fulfill,reject,promise,receiver,context){var index=this._length();if(index>=65535-4){index=0;this._setLength(0)}if(index===0){this._promise0=promise;this._receiver0=receiver;if(typeof fulfill==="function"){this._fulfillmentHandler0=util.contextBind(context,fulfill)}if(typeof reject==="function"){this._rejectionHandler0=util.contextBind(context,reject)}}else{var base=index*4-4;this[base+2]=promise;this[base+3]=receiver;if(typeof fulfill==="function"){this[base+0]=util.contextBind(context,fulfill)}if(typeof reject==="function"){this[base+1]=util.contextBind(context,reject)}}this._setLength(index+1);return index};Promise.prototype._proxy=function(proxyable,arg){this._addCallbacks(undefined,undefined,arg,proxyable,null)};Promise.prototype._resolveCallback=function(value,shouldBind){if((this._bitField&117506048)!==0)return;if(value===this)return this._rejectCallback(makeSelfResolutionError(),false);var maybePromise=tryConvertToPromise(value,this);if(!(maybePromise instanceof Promise))return this._fulfill(value);if(shouldBind)this._propagateFrom(maybePromise,2);var promise=maybePromise._target();if(promise===this){this._reject(makeSelfResolutionError());return}var bitField=promise._bitField;if((bitField&50397184)===0){var len=this._length();if(len>0)promise._migrateCallback0(this);for(var i=1;i<len;++i){promise._migrateCallbackAt(this,i)}this._setFollowing();this._setLength(0);this._setFollowee(maybePromise)}else if((bitField&33554432)!==0){this._fulfill(promise._value())}else if((bitField&16777216)!==0){this._reject(promise._reason())}else{var reason=new CancellationError("late cancellation observer");promise._attachExtraTrace(reason);this._reject(reason)}};Promise.prototype._rejectCallback=function(reason,synchronous,ignoreNonErrorWarnings){var trace=util.ensureErrorObject(reason);var hasStack=trace===reason;if(!hasStack&&!ignoreNonErrorWarnings&&debug.warnings()){var message="a promise was rejected with a non-error: "+util.classString(reason);this._warn(message,true)}this._attachExtraTrace(trace,synchronous?hasStack:false);this._reject(reason)};Promise.prototype._resolveFromExecutor=function(executor){if(executor===INTERNAL)return;var promise=this;this._captureStackTrace();this._pushContext();var synchronous=true;var r=this._execute(executor,(function(value){promise._resolveCallback(value)}),(function(reason){promise._rejectCallback(reason,synchronous)}));synchronous=false;this._popContext();if(r!==undefined){promise._rejectCallback(r,true)}};Promise.prototype._settlePromiseFromHandler=function(handler,receiver,value,promise){var bitField=promise._bitField;if((bitField&65536)!==0)return;promise._pushContext();var x;if(receiver===APPLY){if(!value||typeof value.length!=="number"){x=errorObj;x.e=new TypeError("cannot .spread() a non-array: "+util.classString(value))}else{x=tryCatch(handler).apply(this._boundValue(),value)}}else{x=tryCatch(handler).call(receiver,value)}var promiseCreated=promise._popContext();bitField=promise._bitField;if((bitField&65536)!==0)return;if(x===NEXT_FILTER){promise._reject(value)}else if(x===errorObj){promise._rejectCallback(x.e,false)}else{debug.checkForgottenReturns(x,promiseCreated,"",promise,this);promise._resolveCallback(x)}};Promise.prototype._target=function(){var ret=this;while(ret._isFollowing()){ret=ret._followee()}return ret};Promise.prototype._followee=function(){return this._rejectionHandler0};Promise.prototype._setFollowee=function(promise){this._rejectionHandler0=promise};Promise.prototype._settlePromise=function(promise,handler,receiver,value){var isPromise=promise instanceof Promise;var bitField=this._bitField;var asyncGuaranteed=(bitField&134217728)!==0;if((bitField&65536)!==0){if(isPromise)promise._invokeInternalOnCancel();if(receiver instanceof PassThroughHandlerContext&&receiver.isFinallyHandler()){receiver.cancelPromise=promise;if(tryCatch(handler).call(receiver,value)===errorObj){promise._reject(errorObj.e)}}else if(handler===reflectHandler){promise._fulfill(reflectHandler.call(receiver))}else if(receiver instanceof Proxyable){receiver._promiseCancelled(promise)}else if(isPromise||promise instanceof PromiseArray){promise._cancel()}else{receiver.cancel()}}else if(typeof handler==="function"){if(!isPromise){handler.call(receiver,value,promise)}else{if(asyncGuaranteed)promise._setAsyncGuaranteed();this._settlePromiseFromHandler(handler,receiver,value,promise)}}else if(receiver instanceof Proxyable){if(!receiver._isResolved()){if((bitField&33554432)!==0){receiver._promiseFulfilled(value,promise)}else{receiver._promiseRejected(value,promise)}}}else if(isPromise){if(asyncGuaranteed)promise._setAsyncGuaranteed();if((bitField&33554432)!==0){promise._fulfill(value)}else{promise._reject(value)}}};Promise.prototype._settlePromiseLateCancellationObserver=function(ctx){var handler=ctx.handler;var promise=ctx.promise;var receiver=ctx.receiver;var value=ctx.value;if(typeof handler==="function"){if(!(promise instanceof Promise)){handler.call(receiver,value,promise)}else{this._settlePromiseFromHandler(handler,receiver,value,promise)}}else if(promise instanceof Promise){promise._reject(value)}};Promise.prototype._settlePromiseCtx=function(ctx){this._settlePromise(ctx.promise,ctx.handler,ctx.receiver,ctx.value)};Promise.prototype._settlePromise0=function(handler,value,bitField){var promise=this._promise0;var receiver=this._receiverAt(0);this._promise0=undefined;this._receiver0=undefined;this._settlePromise(promise,handler,receiver,value)};Promise.prototype._clearCallbackDataAtIndex=function(index){var base=index*4-4;this[base+2]=this[base+3]=this[base+0]=this[base+1]=undefined};Promise.prototype._fulfill=function(value){var bitField=this._bitField;if((bitField&117506048)>>>16)return;if(value===this){var err=makeSelfResolutionError();this._attachExtraTrace(err);return this._reject(err)}this._setFulfilled();this._rejectionHandler0=value;if((bitField&65535)>0){if((bitField&134217728)!==0){this._settlePromises()}else{async.settlePromises(this)}this._dereferenceTrace()}};Promise.prototype._reject=function(reason){var bitField=this._bitField;if((bitField&117506048)>>>16)return;this._setRejected();this._fulfillmentHandler0=reason;if(this._isFinal()){return async.fatalError(reason,util.isNode)}if((bitField&65535)>0){async.settlePromises(this)}else{this._ensurePossibleRejectionHandled()}};Promise.prototype._fulfillPromises=function(len,value){for(var i=1;i<len;i++){var handler=this._fulfillmentHandlerAt(i);var promise=this._promiseAt(i);var receiver=this._receiverAt(i);this._clearCallbackDataAtIndex(i);this._settlePromise(promise,handler,receiver,value)}};Promise.prototype._rejectPromises=function(len,reason){for(var i=1;i<len;i++){var handler=this._rejectionHandlerAt(i);var promise=this._promiseAt(i);var receiver=this._receiverAt(i);this._clearCallbackDataAtIndex(i);this._settlePromise(promise,handler,receiver,reason)}};Promise.prototype._settlePromises=function(){var bitField=this._bitField;var len=bitField&65535;if(len>0){if((bitField&16842752)!==0){var reason=this._fulfillmentHandler0;this._settlePromise0(this._rejectionHandler0,reason,bitField);this._rejectPromises(len,reason)}else{var value=this._rejectionHandler0;this._settlePromise0(this._fulfillmentHandler0,value,bitField);this._fulfillPromises(len,value)}this._setLength(0)}this._clearCancellationData()};Promise.prototype._settledValue=function(){var bitField=this._bitField;if((bitField&33554432)!==0){return this._rejectionHandler0}else if((bitField&16777216)!==0){return this._fulfillmentHandler0}};if(typeof Symbol!=="undefined"&&Symbol.toStringTag){es5.defineProperty(Promise.prototype,Symbol.toStringTag,{get:function get(){return"Object"}})}function deferResolve(v){this.promise._resolveCallback(v)}function deferReject(v){this.promise._rejectCallback(v,false)}Promise.defer=Promise.pending=function(){debug.deprecated("Promise.defer","new Promise");var promise=new Promise(INTERNAL);return{promise:promise,resolve:deferResolve,reject:deferReject}};util.notEnumerableProp(Promise,"_makeSelfResolutionError",makeSelfResolutionError);_dereq_("./method")(Promise,INTERNAL,tryConvertToPromise,apiRejection,debug);_dereq_("./bind")(Promise,INTERNAL,tryConvertToPromise,debug);_dereq_("./cancel")(Promise,PromiseArray,apiRejection,debug);_dereq_("./direct_resolve")(Promise);_dereq_("./synchronous_inspection")(Promise);_dereq_("./join")(Promise,PromiseArray,tryConvertToPromise,INTERNAL,async);Promise.Promise=Promise;Promise.version="3.7.2";_dereq_("./call_get.js")(Promise);_dereq_("./generators.js")(Promise,apiRejection,INTERNAL,tryConvertToPromise,Proxyable,debug);_dereq_("./map.js")(Promise,PromiseArray,apiRejection,tryConvertToPromise,INTERNAL,debug);_dereq_("./nodeify.js")(Promise);_dereq_("./promisify.js")(Promise,INTERNAL);_dereq_("./props.js")(Promise,PromiseArray,tryConvertToPromise,apiRejection);_dereq_("./race.js")(Promise,INTERNAL,tryConvertToPromise,apiRejection);_dereq_("./reduce.js")(Promise,PromiseArray,apiRejection,tryConvertToPromise,INTERNAL,debug);_dereq_("./settle.js")(Promise,PromiseArray,debug);_dereq_("./some.js")(Promise,PromiseArray,apiRejection);_dereq_("./timers.js")(Promise,INTERNAL,debug);_dereq_("./using.js")(Promise,apiRejection,tryConvertToPromise,createContext,INTERNAL,debug);_dereq_("./any.js")(Promise);_dereq_("./each.js")(Promise,INTERNAL);_dereq_("./filter.js")(Promise,INTERNAL);util.toFastProperties(Promise);util.toFastProperties(Promise.prototype);function fillTypes(value){var p=new Promise(INTERNAL);p._fulfillmentHandler0=value;p._rejectionHandler0=value;p._promise0=value;p._receiver0=value}fillTypes({a:1});fillTypes({b:2});fillTypes({c:3});fillTypes(1);fillTypes((function(){}));fillTypes(undefined);fillTypes(false);fillTypes(new Promise(INTERNAL));debug.setBounds(Async.firstLineError,util.lastLineError);return Promise}},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36,async_hooks:undefined}],23:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL,tryConvertToPromise,apiRejection,Proxyable){var util=_dereq_("./util");var isArray=util.isArray;function toResolutionValue(val){switch(val){case-2:return[];case-3:return{};case-6:return new Map}}function PromiseArray(values){var promise=this._promise=new Promise(INTERNAL);if(values instanceof Promise){promise._propagateFrom(values,3);values.suppressUnhandledRejections()}promise._setOnCancel(this);this._values=values;this._length=0;this._totalResolved=0;this._init(undefined,-2)}util.inherits(PromiseArray,Proxyable);PromiseArray.prototype.length=function(){return this._length};PromiseArray.prototype.promise=function(){return this._promise};PromiseArray.prototype._init=function init(_,resolveValueIfEmpty){var values=tryConvertToPromise(this._values,this._promise);if(values instanceof Promise){values=values._target();var bitField=values._bitField;this._values=values;if((bitField&50397184)===0){this._promise._setAsyncGuaranteed();return values._then(init,this._reject,undefined,this,resolveValueIfEmpty)}else if((bitField&33554432)!==0){values=values._value()}else if((bitField&16777216)!==0){return this._reject(values._reason())}else{return this._cancel()}}values=util.asArray(values);if(values===null){var err=apiRejection("expecting an array or an iterable object but got "+util.classString(values)).reason();this._promise._rejectCallback(err,false);return}if(values.length===0){if(resolveValueIfEmpty===-5){this._resolveEmptyArray()}else{this._resolve(toResolutionValue(resolveValueIfEmpty))}return}this._iterate(values)};PromiseArray.prototype._iterate=function(values){var len=this.getActualLength(values.length);this._length=len;this._values=this.shouldCopyValues()?new Array(len):this._values;var result=this._promise;var isResolved=false;var bitField=null;for(var i=0;i<len;++i){var maybePromise=tryConvertToPromise(values[i],result);if(maybePromise instanceof Promise){maybePromise=maybePromise._target();bitField=maybePromise._bitField}else{bitField=null}if(isResolved){if(bitField!==null){maybePromise.suppressUnhandledRejections()}}else if(bitField!==null){if((bitField&50397184)===0){maybePromise._proxy(this,i);this._values[i]=maybePromise}else if((bitField&33554432)!==0){isResolved=this._promiseFulfilled(maybePromise._value(),i)}else if((bitField&16777216)!==0){isResolved=this._promiseRejected(maybePromise._reason(),i)}else{isResolved=this._promiseCancelled(i)}}else{isResolved=this._promiseFulfilled(maybePromise,i)}}if(!isResolved)result._setAsyncGuaranteed()};PromiseArray.prototype._isResolved=function(){return this._values===null};PromiseArray.prototype._resolve=function(value){this._values=null;this._promise._fulfill(value)};PromiseArray.prototype._cancel=function(){if(this._isResolved()||!this._promise._isCancellable())return;this._values=null;this._promise._cancel()};PromiseArray.prototype._reject=function(reason){this._values=null;this._promise._rejectCallback(reason,false)};PromiseArray.prototype._promiseFulfilled=function(value,index){this._values[index]=value;var totalResolved=++this._totalResolved;if(totalResolved>=this._length){this._resolve(this._values);return true}return false};PromiseArray.prototype._promiseCancelled=function(){this._cancel();return true};PromiseArray.prototype._promiseRejected=function(reason){this._totalResolved++;this._reject(reason);return true};PromiseArray.prototype._resultCancelled=function(){if(this._isResolved())return;var values=this._values;this._cancel();if(values instanceof Promise){values.cancel()}else{for(var i=0;i<values.length;++i){if(values[i]instanceof Promise){values[i].cancel()}}}};PromiseArray.prototype.shouldCopyValues=function(){return true};PromiseArray.prototype.getActualLength=function(len){return len};return PromiseArray}},{"./util":36}],24:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL){var THIS={};var util=_dereq_("./util");var nodebackForPromise=_dereq_("./nodeback");var withAppended=util.withAppended;var maybeWrapAsError=util.maybeWrapAsError;var canEvaluate=util.canEvaluate;var TypeError=_dereq_("./errors").TypeError;var defaultSuffix="Async";var defaultPromisified={__isPromisified__:true};var noCopyProps=["arity","length","name","arguments","caller","callee","prototype","__isPromisified__"];var noCopyPropsPattern=new RegExp("^(?:"+noCopyProps.join("|")+")$");var defaultFilter=function defaultFilter(name){return util.isIdentifier(name)&&name.charAt(0)!=="_"&&name!=="constructor"};function propsFilter(key){return!noCopyPropsPattern.test(key)}function isPromisified(fn){try{return fn.__isPromisified__===true}catch(e){return false}}function hasPromisified(obj,key,suffix){var val=util.getDataPropertyOrDefault(obj,key+suffix,defaultPromisified);return val?isPromisified(val):false}function checkValid(ret,suffix,suffixRegexp){for(var i=0;i<ret.length;i+=2){var key=ret[i];if(suffixRegexp.test(key)){var keyWithoutAsyncSuffix=key.replace(suffixRegexp,"");for(var j=0;j<ret.length;j+=2){if(ret[j]===keyWithoutAsyncSuffix){throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\n\n See http://goo.gl/MqrFmX\n".replace("%s",suffix))}}}}}function promisifiableMethods(obj,suffix,suffixRegexp,filter){var keys=util.inheritedDataKeys(obj);var ret=[];for(var i=0;i<keys.length;++i){var key=keys[i];var value=obj[key];var passesDefaultFilter=filter===defaultFilter?true:defaultFilter(key,value,obj);if(typeof value==="function"&&!isPromisified(value)&&!hasPromisified(obj,key,suffix)&&filter(key,value,obj,passesDefaultFilter)){ret.push(key,value)}}checkValid(ret,suffix,suffixRegexp);return ret}var escapeIdentRegex=function escapeIdentRegex(str){return str.replace(/([$])/,"\\$")};var makeNodePromisifiedEval;if(!true){var switchCaseArgumentOrder=function switchCaseArgumentOrder(likelyArgumentCount){var ret=[likelyArgumentCount];var min=Math.max(0,likelyArgumentCount-1-3);for(var i=likelyArgumentCount-1;i>=min;--i){ret.push(i)}for(var i=likelyArgumentCount+1;i<=3;++i){ret.push(i)}return ret};var argumentSequence=function argumentSequence(argumentCount){return util.filledRange(argumentCount,"_arg","")};var parameterDeclaration=function parameterDeclaration(parameterCount){return util.filledRange(Math.max(parameterCount,3),"_arg","")};var parameterCount=function parameterCount(fn){if(typeof fn.length==="number"){return Math.max(Math.min(fn.length,1023+1),0)}return 0};makeNodePromisifiedEval=function makeNodePromisifiedEval(callback,receiver,originalName,fn,_,multiArgs){var newParameterCount=Math.max(0,parameterCount(fn)-1);var argumentOrder=switchCaseArgumentOrder(newParameterCount);var shouldProxyThis=typeof callback==="string"||receiver===THIS;function generateCallForArgumentCount(count){var args=argumentSequence(count).join(", ");var comma=count>0?", ":"";var ret;if(shouldProxyThis){ret="ret = callback.call(this, {{args}}, nodeback); break;\n"}else{ret=receiver===undefined?"ret = callback({{args}}, nodeback); break;\n":"ret = callback.call(receiver, {{args}}, nodeback); break;\n"}return ret.replace("{{args}}",args).replace(", ",comma)}function generateArgumentSwitchCase(){var ret="";for(var i=0;i<argumentOrder.length;++i){ret+="case "+argumentOrder[i]+":"+generateCallForArgumentCount(argumentOrder[i])}ret+=" \n default: \n var args = new Array(len + 1); \n var i = 0; \n for (var i = 0; i < len; ++i) { \n args[i] = arguments[i]; \n } \n args[i] = nodeback; \n [CodeForCall] \n break; \n ".replace("[CodeForCall]",shouldProxyThis?"ret = callback.apply(this, args);\n":"ret = callback.apply(receiver, args);\n");return ret}var getFunctionCode=typeof callback==="string"?"this != null ? this['"+callback+"'] : fn":"fn";var body="'use strict'; \n var ret = function (Parameters) { \n 'use strict'; \n var len = arguments.length; \n var promise = new Promise(INTERNAL); \n promise._captureStackTrace(); \n var nodeback = nodebackForPromise(promise, "+multiArgs+"); \n var ret; \n var callback = tryCatch([GetFunctionCode]); \n switch(len) { \n [CodeForSwitchCase] \n } \n if (ret === errorObj) { \n promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n } \n if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n return promise; \n }; \n notEnumerableProp(ret, '__isPromisified__', true); \n return ret; \n ".replace("[CodeForSwitchCase]",generateArgumentSwitchCase()).replace("[GetFunctionCode]",getFunctionCode);body=body.replace("Parameters",parameterDeclaration(newParameterCount));return new Function("Promise","fn","receiver","withAppended","maybeWrapAsError","nodebackForPromise","tryCatch","errorObj","notEnumerableProp","INTERNAL",body)(Promise,fn,receiver,withAppended,maybeWrapAsError,nodebackForPromise,util.tryCatch,util.errorObj,util.notEnumerableProp,INTERNAL)}}function makeNodePromisifiedClosure(callback,receiver,_,fn,__,multiArgs){var defaultThis=function(){return this}();var method=callback;if(typeof method==="string"){callback=fn}function promisified(){var _receiver=receiver;if(receiver===THIS)_receiver=this;var promise=new Promise(INTERNAL);promise._captureStackTrace();var cb=typeof method==="string"&&this!==defaultThis?this[method]:callback;var fn=nodebackForPromise(promise,multiArgs);try{cb.apply(_receiver,withAppended(arguments,fn))}catch(e){promise._rejectCallback(maybeWrapAsError(e),true,true)}if(!promise._isFateSealed())promise._setAsyncGuaranteed();return promise}util.notEnumerableProp(promisified,"__isPromisified__",true);return promisified}var makeNodePromisified=canEvaluate?makeNodePromisifiedEval:makeNodePromisifiedClosure;function promisifyAll(obj,suffix,filter,promisifier,multiArgs){var suffixRegexp=new RegExp(escapeIdentRegex(suffix)+"$");var methods=promisifiableMethods(obj,suffix,suffixRegexp,filter);for(var i=0,len=methods.length;i<len;i+=2){var key=methods[i];var fn=methods[i+1];var promisifiedKey=key+suffix;if(promisifier===makeNodePromisified){obj[promisifiedKey]=makeNodePromisified(key,THIS,key,fn,suffix,multiArgs)}else{var promisified=promisifier(fn,(function(){return makeNodePromisified(key,THIS,key,fn,suffix,multiArgs)}));util.notEnumerableProp(promisified,"__isPromisified__",true);obj[promisifiedKey]=promisified}}util.toFastProperties(obj);return obj}function promisify(callback,receiver,multiArgs){return makeNodePromisified(callback,receiver,undefined,callback,null,multiArgs)}Promise.promisify=function(fn,options){if(typeof fn!=="function"){throw new TypeError("expecting a function but got "+util.classString(fn))}if(isPromisified(fn)){return fn}options=Object(options);var receiver=options.context===undefined?THIS:options.context;var multiArgs=!!options.multiArgs;var ret=promisify(fn,receiver,multiArgs);util.copyDescriptors(fn,ret,propsFilter);return ret};Promise.promisifyAll=function(target,options){if(typeof target!=="function"&&_typeof(target)!=="object"){throw new TypeError("the target of promisifyAll must be an object or a function\n\n See http://goo.gl/MqrFmX\n")}options=Object(options);var multiArgs=!!options.multiArgs;var suffix=options.suffix;if(typeof suffix!=="string")suffix=defaultSuffix;var filter=options.filter;if(typeof filter!=="function")filter=defaultFilter;var promisifier=options.promisifier;if(typeof promisifier!=="function")promisifier=makeNodePromisified;if(!util.isIdentifier(suffix)){throw new RangeError("suffix must be a valid identifier\n\n See http://goo.gl/MqrFmX\n")}var keys=util.inheritedDataKeys(target);for(var i=0;i<keys.length;++i){var value=target[keys[i]];if(keys[i]!=="constructor"&&util.isClass(value)){promisifyAll(value.prototype,suffix,filter,promisifier,multiArgs);promisifyAll(value,suffix,filter,promisifier,multiArgs)}}return promisifyAll(target,suffix,filter,promisifier,multiArgs)}}},{"./errors":12,"./nodeback":20,"./util":36}],25:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,tryConvertToPromise,apiRejection){var util=_dereq_("./util");var isObject=util.isObject;var es5=_dereq_("./es5");var Es6Map;if(typeof Map==="function")Es6Map=Map;var mapToEntries=function(){var index=0;var size=0;function extractEntry(value,key){this[index]=value;this[index+size]=key;index++}return function mapToEntries(map){size=map.size;index=0;var ret=new Array(map.size*2);map.forEach(extractEntry,ret);return ret}}();var entriesToMap=function entriesToMap(entries){var ret=new Es6Map;var length=entries.length/2|0;for(var i=0;i<length;++i){var key=entries[length+i];var value=entries[i];ret.set(key,value)}return ret};function PropertiesPromiseArray(obj){var isMap=false;var entries;if(Es6Map!==undefined&&obj instanceof Es6Map){entries=mapToEntries(obj);isMap=true}else{var keys=es5.keys(obj);var len=keys.length;entries=new Array(len*2);for(var i=0;i<len;++i){var key=keys[i];entries[i]=obj[key];entries[i+len]=key}}this.constructor$(entries);this._isMap=isMap;this._init$(undefined,isMap?-6:-3)}util.inherits(PropertiesPromiseArray,PromiseArray);PropertiesPromiseArray.prototype._init=function(){};PropertiesPromiseArray.prototype._promiseFulfilled=function(value,index){this._values[index]=value;var totalResolved=++this._totalResolved;if(totalResolved>=this._length){var val;if(this._isMap){val=entriesToMap(this._values)}else{val={};var keyOffset=this.length();for(var i=0,len=this.length();i<len;++i){val[this._values[i+keyOffset]]=this._values[i]}}this._resolve(val);return true}return false};PropertiesPromiseArray.prototype.shouldCopyValues=function(){return false};PropertiesPromiseArray.prototype.getActualLength=function(len){return len>>1};function props(promises){var ret;var castValue=tryConvertToPromise(promises);if(!isObject(castValue)){return apiRejection("cannot await properties of a non-object\n\n See http://goo.gl/MqrFmX\n")}else if(castValue instanceof Promise){ret=castValue._then(Promise.props,undefined,undefined,undefined,undefined)}else{ret=new PropertiesPromiseArray(castValue).promise()}if(castValue instanceof Promise){ret._propagateFrom(castValue,2)}return ret}Promise.prototype.props=function(){return props(this)};Promise.props=function(promises){return props(promises)}}},{"./es5":13,"./util":36}],26:[function(_dereq_,module,exports){"use strict";function arrayMove(src,srcIndex,dst,dstIndex,len){for(var j=0;j<len;++j){dst[j+dstIndex]=src[j+srcIndex];src[j+srcIndex]=void 0}}function Queue(capacity){this._capacity=capacity;this._length=0;this._front=0}Queue.prototype._willBeOverCapacity=function(size){return this._capacity<size};Queue.prototype._pushOne=function(arg){var length=this.length();this._checkCapacity(length+1);var i=this._front+length&this._capacity-1;this[i]=arg;this._length=length+1};Queue.prototype.push=function(fn,receiver,arg){var length=this.length()+3;if(this._willBeOverCapacity(length)){this._pushOne(fn);this._pushOne(receiver);this._pushOne(arg);return}var j=this._front+length-3;this._checkCapacity(length);var wrapMask=this._capacity-1;this[j+0&wrapMask]=fn;this[j+1&wrapMask]=receiver;this[j+2&wrapMask]=arg;this._length=length};Queue.prototype.shift=function(){var front=this._front,ret=this[front];this[front]=undefined;this._front=front+1&this._capacity-1;this._length--;return ret};Queue.prototype.length=function(){return this._length};Queue.prototype._checkCapacity=function(size){if(this._capacity<size){this._resizeTo(this._capacity<<1)}};Queue.prototype._resizeTo=function(capacity){var oldCapacity=this._capacity;this._capacity=capacity;var front=this._front;var length=this._length;var moveItemsCount=front+length&oldCapacity-1;arrayMove(this,0,this,oldCapacity,moveItemsCount)};module.exports=Queue},{}],27:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL,tryConvertToPromise,apiRejection){var util=_dereq_("./util");var raceLater=function raceLater(promise){return promise.then((function(array){return race(array,promise)}))};function race(promises,parent){var maybePromise=tryConvertToPromise(promises);if(maybePromise instanceof Promise){return raceLater(maybePromise)}else{promises=util.asArray(promises);if(promises===null)return apiRejection("expecting an array or an iterable object but got "+util.classString(promises))}var ret=new Promise(INTERNAL);if(parent!==undefined){ret._propagateFrom(parent,3)}var fulfill=ret._fulfill;var reject=ret._reject;for(var i=0,len=promises.length;i<len;++i){var val=promises[i];if(val===undefined&&!(i in promises)){continue}Promise.cast(val)._then(fulfill,reject,undefined,ret,null)}return ret}Promise.race=function(promises){return race(promises,undefined)};Promise.prototype.race=function(){return race(this,undefined)}}},{"./util":36}],28:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,apiRejection,tryConvertToPromise,INTERNAL,debug){var util=_dereq_("./util");var tryCatch=util.tryCatch;function ReductionPromiseArray(promises,fn,initialValue,_each){this.constructor$(promises);var context=Promise._getContext();this._fn=util.contextBind(context,fn);if(initialValue!==undefined){initialValue=Promise.resolve(initialValue);initialValue._attachCancellationCallback(this)}this._initialValue=initialValue;this._currentCancellable=null;if(_each===INTERNAL){this._eachValues=Array(this._length)}else if(_each===0){this._eachValues=null}else{this._eachValues=undefined}this._promise._captureStackTrace();this._init$(undefined,-5)}util.inherits(ReductionPromiseArray,PromiseArray);ReductionPromiseArray.prototype._gotAccum=function(accum){if(this._eachValues!==undefined&&this._eachValues!==null&&accum!==INTERNAL){this._eachValues.push(accum)}};ReductionPromiseArray.prototype._eachComplete=function(value){if(this._eachValues!==null){this._eachValues.push(value)}return this._eachValues};ReductionPromiseArray.prototype._init=function(){};ReductionPromiseArray.prototype._resolveEmptyArray=function(){this._resolve(this._eachValues!==undefined?this._eachValues:this._initialValue)};ReductionPromiseArray.prototype.shouldCopyValues=function(){return false};ReductionPromiseArray.prototype._resolve=function(value){this._promise._resolveCallback(value);this._values=null};ReductionPromiseArray.prototype._resultCancelled=function(sender){if(sender===this._initialValue)return this._cancel();if(this._isResolved())return;this._resultCancelled$();if(this._currentCancellable instanceof Promise){this._currentCancellable.cancel()}if(this._initialValue instanceof Promise){this._initialValue.cancel()}};ReductionPromiseArray.prototype._iterate=function(values){this._values=values;var value;var i;var length=values.length;if(this._initialValue!==undefined){value=this._initialValue;i=0}else{value=Promise.resolve(values[0]);i=1}this._currentCancellable=value;for(var j=i;j<length;++j){var maybePromise=values[j];if(maybePromise instanceof Promise){maybePromise.suppressUnhandledRejections()}}if(!value.isRejected()){for(;i<length;++i){var ctx={accum:null,value:values[i],index:i,length:length,array:this};value=value._then(gotAccum,undefined,undefined,ctx,undefined);if((i&127)===0){value._setNoAsyncGuarantee()}}}if(this._eachValues!==undefined){value=value._then(this._eachComplete,undefined,undefined,this,undefined)}value._then(completed,completed,undefined,value,this)};Promise.prototype.reduce=function(fn,initialValue){return reduce(this,fn,initialValue,null)};Promise.reduce=function(promises,fn,initialValue,_each){return reduce(promises,fn,initialValue,_each)};function completed(valueOrReason,array){if(this.isFulfilled()){array._resolve(valueOrReason)}else{array._reject(valueOrReason)}}function reduce(promises,fn,initialValue,_each){if(typeof fn!=="function"){return apiRejection("expecting a function but got "+util.classString(fn))}var array=new ReductionPromiseArray(promises,fn,initialValue,_each);return array.promise()}function gotAccum(accum){this.accum=accum;this.array._gotAccum(accum);var value=tryConvertToPromise(this.value,this.array._promise);if(value instanceof Promise){this.array._currentCancellable=value;return value._then(gotValue,undefined,undefined,this,undefined)}else{return gotValue.call(this,value)}}function gotValue(value){var array=this.array;var promise=array._promise;var fn=tryCatch(array._fn);promise._pushContext();var ret;if(array._eachValues!==undefined){ret=fn.call(promise._boundValue(),value,this.index,this.length)}else{ret=fn.call(promise._boundValue(),this.accum,value,this.index,this.length)}if(ret instanceof Promise){array._currentCancellable=ret}var promiseCreated=promise._popContext();debug.checkForgottenReturns(ret,promiseCreated,array._eachValues!==undefined?"Promise.each":"Promise.reduce",promise);return ret}}},{"./util":36}],29:[function(_dereq_,module,exports){"use strict";var util=_dereq_("./util");var schedule;var noAsyncScheduler=function noAsyncScheduler(){throw new Error("No async scheduler available\n\n See http://goo.gl/MqrFmX\n")};var NativePromise=util.getNativePromise();if(util.isNode&&typeof MutationObserver==="undefined"){var GlobalSetImmediate=global.setImmediate;var ProcessNextTick=process.nextTick;schedule=util.isRecentNode?function(fn){GlobalSetImmediate.call(global,fn)}:function(fn){ProcessNextTick.call(process,fn)}}else if(typeof NativePromise==="function"&&typeof NativePromise.resolve==="function"){var nativePromise=NativePromise.resolve();schedule=function schedule(fn){nativePromise.then(fn)}}else if(typeof MutationObserver!=="undefined"&&!(typeof window!=="undefined"&&window.navigator&&(window.navigator.standalone||window.cordova))&&"classList"in document.documentElement){schedule=function(){var div=document.createElement("div");var opts={attributes:true};var toggleScheduled=false;var div2=document.createElement("div");var o2=new MutationObserver((function(){div.classList.toggle("foo");toggleScheduled=false}));o2.observe(div2,opts);var scheduleToggle=function scheduleToggle(){if(toggleScheduled)return;toggleScheduled=true;div2.classList.toggle("foo")};return function schedule(fn){var o=new MutationObserver((function(){o.disconnect();fn()}));o.observe(div,opts);scheduleToggle()}}()}else if(typeof setImmediate!=="undefined"){schedule=function schedule(fn){setImmediate(fn)}}else if(typeof setTimeout!=="undefined"){schedule=function schedule(fn){setTimeout(fn,0)}}else{schedule=noAsyncScheduler}module.exports=schedule},{"./util":36}],30:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,debug){var PromiseInspection=Promise.PromiseInspection;var util=_dereq_("./util");function SettledPromiseArray(values){this.constructor$(values)}util.inherits(SettledPromiseArray,PromiseArray);SettledPromiseArray.prototype._promiseResolved=function(index,inspection){this._values[index]=inspection;var totalResolved=++this._totalResolved;if(totalResolved>=this._length){this._resolve(this._values);return true}return false};SettledPromiseArray.prototype._promiseFulfilled=function(value,index){var ret=new PromiseInspection;ret._bitField=33554432;ret._settledValueField=value;return this._promiseResolved(index,ret)};SettledPromiseArray.prototype._promiseRejected=function(reason,index){var ret=new PromiseInspection;ret._bitField=16777216;ret._settledValueField=reason;return this._promiseResolved(index,ret)};Promise.settle=function(promises){debug.deprecated(".settle()",".reflect()");return new SettledPromiseArray(promises).promise()};Promise.allSettled=function(promises){return new SettledPromiseArray(promises).promise()};Promise.prototype.settle=function(){return Promise.settle(this)}}},{"./util":36}],31:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,apiRejection){var util=_dereq_("./util");var RangeError=_dereq_("./errors").RangeError;var AggregateError=_dereq_("./errors").AggregateError;var isArray=util.isArray;var CANCELLATION={};function SomePromiseArray(values){this.constructor$(values);this._howMany=0;this._unwrap=false;this._initialized=false}util.inherits(SomePromiseArray,PromiseArray);SomePromiseArray.prototype._init=function(){if(!this._initialized){return}if(this._howMany===0){this._resolve([]);return}this._init$(undefined,-5);var isArrayResolved=isArray(this._values);if(!this._isResolved()&&isArrayResolved&&this._howMany>this._canPossiblyFulfill()){this._reject(this._getRangeError(this.length()))}};SomePromiseArray.prototype.init=function(){this._initialized=true;this._init()};SomePromiseArray.prototype.setUnwrap=function(){this._unwrap=true};SomePromiseArray.prototype.howMany=function(){return this._howMany};SomePromiseArray.prototype.setHowMany=function(count){this._howMany=count};SomePromiseArray.prototype._promiseFulfilled=function(value){this._addFulfilled(value);if(this._fulfilled()===this.howMany()){this._values.length=this.howMany();if(this.howMany()===1&&this._unwrap){this._resolve(this._values[0])}else{this._resolve(this._values)}return true}return false};SomePromiseArray.prototype._promiseRejected=function(reason){this._addRejected(reason);return this._checkOutcome()};SomePromiseArray.prototype._promiseCancelled=function(){if(this._values instanceof Promise||this._values==null){return this._cancel()}this._addRejected(CANCELLATION);return this._checkOutcome()};SomePromiseArray.prototype._checkOutcome=function(){if(this.howMany()>this._canPossiblyFulfill()){var e=new AggregateError;for(var i=this.length();i<this._values.length;++i){if(this._values[i]!==CANCELLATION){e.push(this._values[i])}}if(e.length>0){this._reject(e)}else{this._cancel()}return true}return false};SomePromiseArray.prototype._fulfilled=function(){return this._totalResolved};SomePromiseArray.prototype._rejected=function(){return this._values.length-this.length()};SomePromiseArray.prototype._addRejected=function(reason){this._values.push(reason)};SomePromiseArray.prototype._addFulfilled=function(value){this._values[this._totalResolved++]=value};SomePromiseArray.prototype._canPossiblyFulfill=function(){return this.length()-this._rejected()};SomePromiseArray.prototype._getRangeError=function(count){var message="Input array must contain at least "+this._howMany+" items but contains only "+count+" items";return new RangeError(message)};SomePromiseArray.prototype._resolveEmptyArray=function(){this._reject(this._getRangeError(0))};function some(promises,howMany){if((howMany|0)!==howMany||howMany<0){return apiRejection("expecting a positive integer\n\n See http://goo.gl/MqrFmX\n")}var ret=new SomePromiseArray(promises);var promise=ret.promise();ret.setHowMany(howMany);ret.init();return promise}Promise.some=function(promises,howMany){return some(promises,howMany)};Promise.prototype.some=function(howMany){return some(this,howMany)};Promise._SomePromiseArray=SomePromiseArray}},{"./errors":12,"./util":36}],32:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise){function PromiseInspection(promise){if(promise!==undefined){promise=promise._target();this._bitField=promise._bitField;this._settledValueField=promise._isFateSealed()?promise._settledValue():undefined}else{this._bitField=0;this._settledValueField=undefined}}PromiseInspection.prototype._settledValue=function(){return this._settledValueField};var value=PromiseInspection.prototype.value=function(){if(!this.isFulfilled()){throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/MqrFmX\n")}return this._settledValue()};var reason=PromiseInspection.prototype.error=PromiseInspection.prototype.reason=function(){if(!this.isRejected()){throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/MqrFmX\n")}return this._settledValue()};var isFulfilled=PromiseInspection.prototype.isFulfilled=function(){return(this._bitField&33554432)!==0};var isRejected=PromiseInspection.prototype.isRejected=function(){return(this._bitField&16777216)!==0};var isPending=PromiseInspection.prototype.isPending=function(){return(this._bitField&50397184)===0};var isResolved=PromiseInspection.prototype.isResolved=function(){return(this._bitField&50331648)!==0};PromiseInspection.prototype.isCancelled=function(){return(this._bitField&8454144)!==0};Promise.prototype.__isCancelled=function(){return(this._bitField&65536)===65536};Promise.prototype._isCancelled=function(){return this._target().__isCancelled()};Promise.prototype.isCancelled=function(){return(this._target()._bitField&8454144)!==0};Promise.prototype.isPending=function(){return isPending.call(this._target())};Promise.prototype.isRejected=function(){return isRejected.call(this._target())};Promise.prototype.isFulfilled=function(){return isFulfilled.call(this._target())};Promise.prototype.isResolved=function(){return isResolved.call(this._target())};Promise.prototype.value=function(){return value.call(this._target())};Promise.prototype.reason=function(){var target=this._target();target._unsetRejectionIsUnhandled();return reason.call(target)};Promise.prototype._value=function(){return this._settledValue()};Promise.prototype._reason=function(){this._unsetRejectionIsUnhandled();return this._settledValue()};Promise.PromiseInspection=PromiseInspection}},{}],33:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL){var util=_dereq_("./util");var errorObj=util.errorObj;var isObject=util.isObject;function tryConvertToPromise(obj,context){if(isObject(obj)){if(obj instanceof Promise)return obj;var then=getThen(obj);if(then===errorObj){if(context)context._pushContext();var ret=Promise.reject(then.e);if(context)context._popContext();return ret}else if(typeof then==="function"){if(isAnyBluebirdPromise(obj)){var ret=new Promise(INTERNAL);obj._then(ret._fulfill,ret._reject,undefined,ret,null);return ret}return doThenable(obj,then,context)}}return obj}function doGetThen(obj){return obj.then}function getThen(obj){try{return doGetThen(obj)}catch(e){errorObj.e=e;return errorObj}}var hasProp={}.hasOwnProperty;function isAnyBluebirdPromise(obj){try{return hasProp.call(obj,"_promise0")}catch(e){return false}}function doThenable(x,then,context){var promise=new Promise(INTERNAL);var ret=promise;if(context)context._pushContext();promise._captureStackTrace();if(context)context._popContext();var synchronous=true;var result=util.tryCatch(then).call(x,resolve,reject);synchronous=false;if(promise&&result===errorObj){promise._rejectCallback(result.e,true,true);promise=null}function resolve(value){if(!promise)return;promise._resolveCallback(value);promise=null}function reject(reason){if(!promise)return;promise._rejectCallback(reason,synchronous,true);promise=null}return ret}return tryConvertToPromise}},{"./util":36}],34:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL,debug){var util=_dereq_("./util");var TimeoutError=Promise.TimeoutError;function HandleWrapper(handle){this.handle=handle}HandleWrapper.prototype._resultCancelled=function(){clearTimeout(this.handle)};var afterValue=function afterValue(value){return delay(+this).thenReturn(value)};var delay=Promise.delay=function(ms,value){var ret;var handle;if(value!==undefined){ret=Promise.resolve(value)._then(afterValue,null,null,ms,undefined);if(debug.cancellation()&&value instanceof Promise){ret._setOnCancel(value)}}else{ret=new Promise(INTERNAL);handle=setTimeout((function(){ret._fulfill()}),+ms);if(debug.cancellation()){ret._setOnCancel(new HandleWrapper(handle))}ret._captureStackTrace()}ret._setAsyncGuaranteed();return ret};Promise.prototype.delay=function(ms){return delay(ms,this)};var afterTimeout=function afterTimeout(promise,message,parent){var err;if(typeof message!=="string"){if(message instanceof Error){err=message}else{err=new TimeoutError("operation timed out")}}else{err=new TimeoutError(message)}util.markAsOriginatingFromRejection(err);promise._attachExtraTrace(err);promise._reject(err);if(parent!=null){parent.cancel()}};function successClear(value){clearTimeout(this.handle);return value}function failureClear(reason){clearTimeout(this.handle);throw reason}Promise.prototype.timeout=function(ms,message){ms=+ms;var ret,parent;var handleWrapper=new HandleWrapper(setTimeout((function timeoutTimeout(){if(ret.isPending()){afterTimeout(ret,message,parent)}}),ms));if(debug.cancellation()){parent=this.then();ret=parent._then(successClear,failureClear,undefined,handleWrapper,undefined);ret._setOnCancel(handleWrapper)}else{ret=this._then(successClear,failureClear,undefined,handleWrapper,undefined)}return ret}}},{"./util":36}],35:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,apiRejection,tryConvertToPromise,createContext,INTERNAL,debug){var util=_dereq_("./util");var TypeError=_dereq_("./errors").TypeError;var inherits=_dereq_("./util").inherits;var errorObj=util.errorObj;var tryCatch=util.tryCatch;var NULL={};function thrower(e){setTimeout((function(){throw e}),0)}function castPreservingDisposable(thenable){var maybePromise=tryConvertToPromise(thenable);if(maybePromise!==thenable&&typeof thenable._isDisposable==="function"&&typeof thenable._getDisposer==="function"&&thenable._isDisposable()){maybePromise._setDisposable(thenable._getDisposer())}return maybePromise}function dispose(resources,inspection){var i=0;var len=resources.length;var ret=new Promise(INTERNAL);function iterator(){if(i>=len)return ret._fulfill();var maybePromise=castPreservingDisposable(resources[i++]);if(maybePromise instanceof Promise&&maybePromise._isDisposable()){try{maybePromise=tryConvertToPromise(maybePromise._getDisposer().tryDispose(inspection),resources.promise)}catch(e){return thrower(e)}if(maybePromise instanceof Promise){return maybePromise._then(iterator,thrower,null,null,null)}}iterator()}iterator();return ret}function Disposer(data,promise,context){this._data=data;this._promise=promise;this._context=context}Disposer.prototype.data=function(){return this._data};Disposer.prototype.promise=function(){return this._promise};Disposer.prototype.resource=function(){if(this.promise().isFulfilled()){return this.promise().value()}return NULL};Disposer.prototype.tryDispose=function(inspection){var resource=this.resource();var context=this._context;if(context!==undefined)context._pushContext();var ret=resource!==NULL?this.doDispose(resource,inspection):null;if(context!==undefined)context._popContext();this._promise._unsetDisposable();this._data=null;return ret};Disposer.isDisposer=function(d){return d!=null&&typeof d.resource==="function"&&typeof d.tryDispose==="function"};function FunctionDisposer(fn,promise,context){this.constructor$(fn,promise,context)}inherits(FunctionDisposer,Disposer);FunctionDisposer.prototype.doDispose=function(resource,inspection){var fn=this.data();return fn.call(resource,resource,inspection)};function maybeUnwrapDisposer(value){if(Disposer.isDisposer(value)){this.resources[this.index]._setDisposable(value);return value.promise()}return value}function ResourceList(length){this.length=length;this.promise=null;this[length-1]=null}ResourceList.prototype._resultCancelled=function(){var len=this.length;for(var i=0;i<len;++i){var item=this[i];if(item instanceof Promise){item.cancel()}}};Promise.using=function(){var len=arguments.length;if(len<2)return apiRejection("you must pass at least 2 arguments to Promise.using");var fn=arguments[len-1];if(typeof fn!=="function"){return apiRejection("expecting a function but got "+util.classString(fn))}var input;var spreadArgs=true;if(len===2&&Array.isArray(arguments[0])){input=arguments[0];len=input.length;spreadArgs=false}else{input=arguments;len--}var resources=new ResourceList(len);for(var i=0;i<len;++i){var resource=input[i];if(Disposer.isDisposer(resource)){var disposer=resource;resource=resource.promise();resource._setDisposable(disposer)}else{var maybePromise=tryConvertToPromise(resource);if(maybePromise instanceof Promise){resource=maybePromise._then(maybeUnwrapDisposer,null,null,{resources:resources,index:i},undefined)}}resources[i]=resource}var reflectedResources=new Array(resources.length);for(var i=0;i<reflectedResources.length;++i){reflectedResources[i]=Promise.resolve(resources[i]).reflect()}var resultPromise=Promise.all(reflectedResources).then((function(inspections){for(var i=0;i<inspections.length;++i){var inspection=inspections[i];if(inspection.isRejected()){errorObj.e=inspection.error();return errorObj}else if(!inspection.isFulfilled()){resultPromise.cancel();return}inspections[i]=inspection.value()}promise._pushContext();fn=tryCatch(fn);var ret=spreadArgs?fn.apply(undefined,inspections):fn(inspections);var promiseCreated=promise._popContext();debug.checkForgottenReturns(ret,promiseCreated,"Promise.using",promise);return ret}));var promise=resultPromise.lastly((function(){var inspection=new Promise.PromiseInspection(resultPromise);return dispose(resources,inspection)}));resources.promise=promise;promise._setOnCancel(resources);return promise};Promise.prototype._setDisposable=function(disposer){this._bitField=this._bitField|131072;this._disposer=disposer};Promise.prototype._isDisposable=function(){return(this._bitField&131072)>0};Promise.prototype._getDisposer=function(){return this._disposer};Promise.prototype._unsetDisposable=function(){this._bitField=this._bitField&~131072;this._disposer=undefined};Promise.prototype.disposer=function(fn){if(typeof fn==="function"){return new FunctionDisposer(fn,this,createContext())}throw new TypeError}}},{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){"use strict";var es5=_dereq_("./es5");var canEvaluate=typeof navigator=="undefined";var errorObj={e:{}};var tryCatchTarget;var globalObject=typeof self!=="undefined"?self:typeof window!=="undefined"?window:typeof global!=="undefined"?global:this!==undefined?this:null;function tryCatcher(){try{var target=tryCatchTarget;tryCatchTarget=null;return target.apply(this,arguments)}catch(e){errorObj.e=e;return errorObj}}function tryCatch(fn){tryCatchTarget=fn;return tryCatcher}var inherits=function inherits(Child,Parent){var hasProp={}.hasOwnProperty;function T(){this.constructor=Child;this.constructor$=Parent;for(var propertyName in Parent.prototype){if(hasProp.call(Parent.prototype,propertyName)&&propertyName.charAt(propertyName.length-1)!=="$"){this[propertyName+"$"]=Parent.prototype[propertyName]}}}T.prototype=Parent.prototype;Child.prototype=new T;return Child.prototype};function isPrimitive(val){return val==null||val===true||val===false||typeof val==="string"||typeof val==="number"}function isObject(value){return typeof value==="function"||_typeof(value)==="object"&&value!==null}function maybeWrapAsError(maybeError){if(!isPrimitive(maybeError))return maybeError;return new Error(safeToString(maybeError))}function withAppended(target,appendee){var len=target.length;var ret=new Array(len+1);var i;for(i=0;i<len;++i){ret[i]=target[i]}ret[i]=appendee;return ret}function getDataPropertyOrDefault(obj,key,defaultValue){if(es5.isES5){var desc=Object.getOwnPropertyDescriptor(obj,key);if(desc!=null){return desc.get==null&&desc.set==null?desc.value:defaultValue}}else{return{}.hasOwnProperty.call(obj,key)?obj[key]:undefined}}function notEnumerableProp(obj,name,value){if(isPrimitive(obj))return obj;var descriptor={value:value,configurable:true,enumerable:false,writable:true};es5.defineProperty(obj,name,descriptor);return obj}function thrower(r){throw r}var inheritedDataKeys=function(){var excludedPrototypes=[Array.prototype,Object.prototype,Function.prototype];var isExcludedProto=function isExcludedProto(val){for(var i=0;i<excludedPrototypes.length;++i){if(excludedPrototypes[i]===val){return true}}return false};if(es5.isES5){var getKeys=Object.getOwnPropertyNames;return function(obj){var ret=[];var visitedKeys=Object.create(null);while(obj!=null&&!isExcludedProto(obj)){var keys;try{keys=getKeys(obj)}catch(e){return ret}for(var i=0;i<keys.length;++i){var key=keys[i];if(visitedKeys[key])continue;visitedKeys[key]=true;var desc=Object.getOwnPropertyDescriptor(obj,key);if(desc!=null&&desc.get==null&&desc.set==null){ret.push(key)}}obj=es5.getPrototypeOf(obj)}return ret}}else{var hasProp={}.hasOwnProperty;return function(obj){if(isExcludedProto(obj))return[];var ret=[];enumeration:for(var key in obj){if(hasProp.call(obj,key)){ret.push(key)}else{for(var i=0;i<excludedPrototypes.length;++i){if(hasProp.call(excludedPrototypes[i],key)){continue enumeration}}ret.push(key)}}return ret}}}();var thisAssignmentPattern=/this\s*\.\s*\S+\s*=/;function isClass(fn){try{if(typeof fn==="function"){var keys=es5.names(fn.prototype);var hasMethods=es5.isES5&&keys.length>1;var hasMethodsOtherThanConstructor=keys.length>0&&!(keys.length===1&&keys[0]==="constructor");var hasThisAssignmentAndStaticMethods=thisAssignmentPattern.test(fn+"")&&es5.names(fn).length>0;if(hasMethods||hasMethodsOtherThanConstructor||hasThisAssignmentAndStaticMethods){return true}}return false}catch(e){return false}}function toFastProperties(obj){function FakeConstructor(){}FakeConstructor.prototype=obj;var receiver=new FakeConstructor;function ic(){return _typeof(receiver.foo)}ic();ic();return obj;eval(obj)}var rident=/^[a-z$_][a-z$_0-9]*$/i;function isIdentifier(str){return rident.test(str)}function filledRange(count,prefix,suffix){var ret=new Array(count);for(var i=0;i<count;++i){ret[i]=prefix+i+suffix}return ret}function safeToString(obj){try{return obj+""}catch(e){return"[no string representation]"}}function isError(obj){return obj instanceof Error||obj!==null&&_typeof(obj)==="object"&&typeof obj.message==="string"&&typeof obj.name==="string"}function markAsOriginatingFromRejection(e){try{notEnumerableProp(e,"isOperational",true)}catch(ignore){}}function originatesFromRejection(e){if(e==null)return false;return e instanceof Error["__BluebirdErrorTypes__"].OperationalError||e["isOperational"]===true}function canAttachTrace(obj){return isError(obj)&&es5.propertyIsWritable(obj,"stack")}var ensureErrorObject=function(){if(!("stack"in new Error)){return function(value){if(canAttachTrace(value))return value;try{throw new Error(safeToString(value))}catch(err){return err}}}else{return function(value){if(canAttachTrace(value))return value;return new Error(safeToString(value))}}}();function classString(obj){return{}.toString.call(obj)}function copyDescriptors(from,to,filter){var keys=es5.names(from);for(var i=0;i<keys.length;++i){var key=keys[i];if(filter(key)){try{es5.defineProperty(to,key,es5.getDescriptor(from,key))}catch(ignore){}}}}var asArray=function asArray(v){if(es5.isArray(v)){return v}return null};if(typeof Symbol!=="undefined"&&Symbol.iterator){var ArrayFrom=typeof Array.from==="function"?function(v){return Array.from(v)}:function(v){var ret=[];var it=v[Symbol.iterator]();var itResult;while(!(itResult=it.next()).done){ret.push(itResult.value)}return ret};asArray=function asArray(v){if(es5.isArray(v)){return v}else if(v!=null&&typeof v[Symbol.iterator]==="function"){return ArrayFrom(v)}return null}}var isNode=typeof process!=="undefined"&&classString(process).toLowerCase()==="[object process]";var hasEnvVariables=typeof process!=="undefined"&&typeof process.env!=="undefined";function env(key){return hasEnvVariables?process.env[key]:undefined}function getNativePromise(){if(typeof Promise==="function"){try{var promise=new Promise((function(){}));if(classString(promise)==="[object Promise]"){return Promise}}catch(e){}}}var reflectHandler;function contextBind(ctx,cb){if(ctx===null||typeof cb!=="function"||cb===reflectHandler){return cb}if(ctx.domain!==null){cb=ctx.domain.bind(cb)}var async=ctx.async;if(async!==null){var old=cb;cb=function cb(){var args=new Array(2).concat([].slice.call(arguments));args[0]=old;args[1]=this;return async.runInAsyncScope.apply(async,args)}}return cb}var ret={setReflectHandler:function setReflectHandler(fn){reflectHandler=fn},isClass:isClass,isIdentifier:isIdentifier,inheritedDataKeys:inheritedDataKeys,getDataPropertyOrDefault:getDataPropertyOrDefault,thrower:thrower,isArray:es5.isArray,asArray:asArray,notEnumerableProp:notEnumerableProp,isPrimitive:isPrimitive,isObject:isObject,isError:isError,canEvaluate:canEvaluate,errorObj:errorObj,tryCatch:tryCatch,inherits:inherits,withAppended:withAppended,maybeWrapAsError:maybeWrapAsError,toFastProperties:toFastProperties,filledRange:filledRange,toString:safeToString,canAttachTrace:canAttachTrace,ensureErrorObject:ensureErrorObject,originatesFromRejection:originatesFromRejection,markAsOriginatingFromRejection:markAsOriginatingFromRejection,classString:classString,copyDescriptors:copyDescriptors,isNode:isNode,hasEnvVariables:hasEnvVariables,env:env,global:globalObject,getNativePromise:getNativePromise,contextBind:contextBind};ret.isRecentNode=ret.isNode&&function(){var version;if(process.versions&&process.versions.node){version=process.versions.node.split(".").map(Number)}else if(process.version){version=process.version.split(".").map(Number)}return version[0]===0&&version[1]>10||version[0]>0}();ret.nodeSupportsAsyncResource=ret.isNode&&function(){var supportsAsync=false;try{var res=_dereq_("async_hooks").AsyncResource;supportsAsync=typeof res.prototype.runInAsyncScope==="function"}catch(e){supportsAsync=false}return supportsAsync}();if(ret.isNode)ret.toFastProperties(process);try{throw new Error}catch(e){ret.lastLineError=e}module.exports=ret},{"./es5":13,async_hooks:undefined}]},{},[4])(4)}));if(typeof window!=="undefined"&&window!==null){window.P=window.Promise}else if(typeof self!=="undefined"&&self!==null){self.P=self.Promise}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},require("timers").setImmediate)},{_process:157,timers:180}],31:[function(require,module,exports){"use strict"},{}],32:[function(require,module,exports){arguments[4][31][0].apply(exports,arguments)},{dup:31}],33:[function(require,module,exports){(function(Buffer){
|
|
27
26
|
/*!
|
|
28
27
|
* The buffer module from node.js, for the browser.
|
|
29
28
|
*
|
|
30
29
|
* @author Feross Aboukhadijeh <https://feross.org>
|
|
31
30
|
* @license MIT
|
|
32
31
|
*/
|
|
33
|
-
"use strict";var base64=require("base64-js");var ieee754=require("ieee754");var customInspectSymbol=typeof Symbol==="function"&&typeof Symbol.for==="function"?Symbol.for("nodejs.util.inspect.custom"):null;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);var proto={foo:function(){return 42}};Object.setPrototypeOf(proto,Uint8Array.prototype);Object.setPrototypeOf(arr,proto);return arr.foo()===42}catch(e){return false}}Object.defineProperty(Buffer.prototype,"parent",{enumerable:true,get:function(){if(!Buffer.isBuffer(this))return undefined;return this.buffer}});Object.defineProperty(Buffer.prototype,"offset",{enumerable:true,get:function(){if(!Buffer.isBuffer(this))return undefined;return this.byteOffset}});function createBuffer(length){if(length>K_MAX_LENGTH){throw new RangeError('The value "'+length+'" is invalid for option "size"')}var buf=new Uint8Array(length);Object.setPrototypeOf(buf,Buffer.prototype);return buf}function Buffer(arg,encodingOrOffset,length){if(typeof arg==="number"){if(typeof encodingOrOffset==="string"){throw new TypeError('The "string" argument must be of type string. Received type number')}return allocUnsafe(arg)}return from(arg,encodingOrOffset,length)}if(typeof Symbol!=="undefined"&&Symbol.species!=null&&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==="string"){return fromString(value,encodingOrOffset)}if(ArrayBuffer.isView(value)){return fromArrayLike(value)}if(value==null){throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, "+"or Array-like Object. Received type "+typeof value)}if(isInstance(value,ArrayBuffer)||value&&isInstance(value.buffer,ArrayBuffer)){return fromArrayBuffer(value,encodingOrOffset,length)}if(typeof value==="number"){throw new TypeError('The "value" argument must not be of type number. Received type number')}var valueOf=value.valueOf&&value.valueOf();if(valueOf!=null&&valueOf!==value){return Buffer.from(valueOf,encodingOrOffset,length)}var b=fromObject(value);if(b)return b;if(typeof Symbol!=="undefined"&&Symbol.toPrimitive!=null&&typeof value[Symbol.toPrimitive]==="function"){return Buffer.from(value[Symbol.toPrimitive]("string"),encodingOrOffset,length)}throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, "+"or Array-like Object. Received type "+typeof value)}Buffer.from=function(value,encodingOrOffset,length){return from(value,encodingOrOffset,length)};Object.setPrototypeOf(Buffer.prototype,Uint8Array.prototype);Object.setPrototypeOf(Buffer,Uint8Array);function assertSize(size){if(typeof size!=="number"){throw new TypeError('"size" argument must be of type number')}else if(size<0){throw new RangeError('The value "'+size+'" is invalid for option "size"')}}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("Unknown encoding: "+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 outside of buffer bounds')}if(array.byteLength<byteOffset+(length||0)){throw new RangeError('"length" is outside of buffer 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)}Object.setPrototypeOf(buf,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.length!==undefined){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)}}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&&b!==Buffer.prototype};Buffer.compare=function compare(a,b){if(isInstance(a,Uint8Array))a=Buffer.from(a,a.offset,a.byteLength);if(isInstance(b,Uint8Array))b=Buffer.from(b,b.offset,b.byteLength);if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b)){throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array')}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(isInstance(buf,Uint8Array)){buf=Buffer.from(buf)}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(ArrayBuffer.isView(string)||isInstance(string,ArrayBuffer)){return string.byteLength}if(typeof string!=="string"){throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. '+"Received type "+typeof string)}var len=string.length;var mustMatch=arguments.length>2&&arguments[2]===true;if(!mustMatch&&len===0)return 0;var loweredCase=false;for(;;){switch(encoding){case"ascii":case"latin1":case"binary":return len;case"utf8":case"utf-8":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 mustMatch?-1: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.toLocaleString=Buffer.prototype.toString;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;str=this.toString("hex",0,max).replace(/(.{2})/g,"$1 ").trim();if(this.length>max)str+=" ... ";return"<Buffer "+str+">"};if(customInspectSymbol){Buffer.prototype[customInspectSymbol]=Buffer.prototype.inspect}Buffer.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(isInstance(target,Uint8Array)){target=Buffer.from(target,target.offset,target.byteLength)}if(!Buffer.isBuffer(target)){throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. '+"Received type "+typeof target)}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(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+=hexSliceLookupTable[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);Object.setPrototypeOf(newBuf,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,34028234663852886e22,-34028234663852886e22)}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,17976931348623157e292,-17976931348623157e292)}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(!Buffer.isBuffer(target))throw new TypeError("argument should be a Buffer");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("Index out of range");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;if(this===target&&typeof Uint8Array.prototype.copyWithin==="function"){this.copyWithin(targetStart,start,end)}else if(this===target&&start<targetStart&&targetStart<end){for(var i=len-1;i>=0;--i){target[i+targetStart]=this[i+start]}}else{Uint8Array.prototype.set.call(target,this.subarray(start,end),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(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)}if(val.length===1){var code=val.charCodeAt(0);if(encoding==="utf8"&&code<128||encoding==="latin1"){val=code}}}else if(typeof val==="number"){val=val&255}else if(typeof val==="boolean"){val=Number(val)}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:Buffer.from(val,encoding);var len=bytes.length;if(len===0){throw new TypeError('The value "'+val+'" is invalid for argument "value"')}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.split("=")[0];str=str.trim().replace(INVALID_BASE64_RE,"");if(str.length<2)return"";while(str.length%4!==0){str=str+"="}return str}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 isInstance(obj,type){return obj instanceof type||obj!=null&&obj.constructor!=null&&obj.constructor.name!=null&&obj.constructor.name===type.name}function numberIsNaN(obj){return obj!==obj}var hexSliceLookupTable=function(){var alphabet="0123456789abcdef";var table=new Array(256);for(var i=0;i<16;++i){var i16=i*16;for(var j=0;j<16;++j){table[i16+j]=alphabet[i]+alphabet[j]}}return table}()}).call(this,require("buffer").Buffer)},{"base64-js":68,buffer:75,ieee754:147}],76:[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":149}],77:[function(require,module,exports){"use strict";var isValue=require("type/value/is"),ensureValue=require("type/value/ensure"),ensurePlainFunction=require("type/plain-function/ensure"),copy=require("es5-ext/object/copy"),normalizeOptions=require("es5-ext/object/normalize-options"),map=require("es5-ext/object/map");var bind=Function.prototype.bind,defineProperty=Object.defineProperty,hasOwnProperty=Object.prototype.hasOwnProperty,define;define=function(name,desc,options){var value=ensureValue(desc)&&ensurePlainFunction(desc.value),dgs;dgs=copy(desc);delete dgs.writable;delete dgs.value;dgs.get=function(){if(!options.overwriteDefinition&&hasOwnProperty.call(this,name))return value;desc.value=bind.call(value,options.resolveContext?options.resolveContext(this):this);defineProperty(this,name,desc);return this[name]};return dgs};module.exports=function(props){var options=normalizeOptions(arguments[1]);if(isValue(options.resolveContext))ensurePlainFunction(options.resolveContext);return map(props,(function(desc,name){return define(name,desc,options)}))}},{"es5-ext/object/copy":101,"es5-ext/object/map":109,"es5-ext/object/normalize-options":110,"type/plain-function/ensure":198,"type/value/ensure":202,"type/value/is":203}],78:[function(require,module,exports){"use strict";var isValue=require("type/value/is"),isPlainFunction=require("type/plain-function/is"),assign=require("es5-ext/object/assign"),normalizeOpts=require("es5-ext/object/normalize-options"),contains=require("es5-ext/string/#/contains");var d=module.exports=function(dscr,value){var c,e,w,options,desc;if(arguments.length<2||typeof dscr!=="string"){options=value;value=dscr;dscr=null}else{options=arguments[2]}if(isValue(dscr)){c=contains.call(dscr,"c");e=contains.call(dscr,"e");w=contains.call(dscr,"w")}else{c=w=true;e=false}desc={value:value,configurable:c,enumerable:e,writable:w};return!options?desc:assign(normalizeOpts(options),desc)};d.gs=function(dscr,get,set){var c,e,options,desc;if(typeof dscr!=="string"){options=set;set=get;get=dscr;dscr=null}else{options=arguments[3]}if(!isValue(get)){get=undefined}else if(!isPlainFunction(get)){options=get;get=set=undefined}else if(!isValue(set)){set=undefined}else if(!isPlainFunction(set)){options=set;set=undefined}if(isValue(dscr)){c=contains.call(dscr,"c");e=contains.call(dscr,"e")}else{c=true;e=false}desc={get:get,set:set,configurable:c,enumerable:e};return!options?desc:assign(normalizeOpts(options),desc)}},{"es5-ext/object/assign":98,"es5-ext/object/normalize-options":110,"es5-ext/string/#/contains":117,"type/plain-function/is":199,"type/value/is":203}],79:[function(require,module,exports){(function(process,Buffer){var stream=require("readable-stream");var eos=require("end-of-stream");var inherits=require("inherits");var shift=require("stream-shift");var SIGNAL_FLUSH=Buffer.from&&Buffer.from!==Uint8Array.from?Buffer.from([0]):new Buffer([0]);var onuncork=function(self,fn){if(self._corked)self.once("uncork",fn);else fn()};var autoDestroy=function(self,err){if(self._autoDestroy)self.destroy(err)};var destroyer=function(self,end){return function(err){if(err)autoDestroy(self,err.message==="premature close"?null:err);else if(end&&!self._ended)self.end()}};var end=function(ws,fn){if(!ws)return fn();if(ws._writableState&&ws._writableState.finished)return fn();if(ws._writableState)return ws.end(fn);ws.end();fn()};var toStreams2=function(rs){return new stream.Readable({objectMode:true,highWaterMark:16}).wrap(rs)};var Duplexify=function(writable,readable,opts){if(!(this instanceof Duplexify))return new Duplexify(writable,readable,opts);stream.Duplex.call(this,opts);this._writable=null;this._readable=null;this._readable2=null;this._autoDestroy=!opts||opts.autoDestroy!==false;this._forwardDestroy=!opts||opts.destroy!==false;this._forwardEnd=!opts||opts.end!==false;this._corked=1;this._ondrain=null;this._drained=false;this._forwarding=false;this._unwrite=null;this._unread=null;this._ended=false;this.destroyed=false;if(writable)this.setWritable(writable);if(readable)this.setReadable(readable)};inherits(Duplexify,stream.Duplex);Duplexify.obj=function(writable,readable,opts){if(!opts)opts={};opts.objectMode=true;opts.highWaterMark=16;return new Duplexify(writable,readable,opts)};Duplexify.prototype.cork=function(){if(++this._corked===1)this.emit("cork")};Duplexify.prototype.uncork=function(){if(this._corked&&--this._corked===0)this.emit("uncork")};Duplexify.prototype.setWritable=function(writable){if(this._unwrite)this._unwrite();if(this.destroyed){if(writable&&writable.destroy)writable.destroy();return}if(writable===null||writable===false){this.end();return}var self=this;var unend=eos(writable,{writable:true,readable:false},destroyer(this,this._forwardEnd));var ondrain=function(){var ondrain=self._ondrain;self._ondrain=null;if(ondrain)ondrain()};var clear=function(){self._writable.removeListener("drain",ondrain);unend()};if(this._unwrite)process.nextTick(ondrain);this._writable=writable;this._writable.on("drain",ondrain);this._unwrite=clear;this.uncork()};Duplexify.prototype.setReadable=function(readable){if(this._unread)this._unread();if(this.destroyed){if(readable&&readable.destroy)readable.destroy();return}if(readable===null||readable===false){this.push(null);this.resume();return}var self=this;var unend=eos(readable,{writable:false,readable:true},destroyer(this));var onreadable=function(){self._forward()};var onend=function(){self.push(null)};var clear=function(){self._readable2.removeListener("readable",onreadable);self._readable2.removeListener("end",onend);unend()};this._drained=true;this._readable=readable;this._readable2=readable._readableState?readable:toStreams2(readable);this._readable2.on("readable",onreadable);this._readable2.on("end",onend);this._unread=clear;this._forward()};Duplexify.prototype._read=function(){this._drained=true;this._forward()};Duplexify.prototype._forward=function(){if(this._forwarding||!this._readable2||!this._drained)return;this._forwarding=true;var data;while(this._drained&&(data=shift(this._readable2))!==null){if(this.destroyed)continue;this._drained=this.push(data)}this._forwarding=false};Duplexify.prototype.destroy=function(err){if(this.destroyed)return;this.destroyed=true;var self=this;process.nextTick((function(){self._destroy(err)}))};Duplexify.prototype._destroy=function(err){if(err){var ondrain=this._ondrain;this._ondrain=null;if(ondrain)ondrain(err);else this.emit("error",err)}if(this._forwardDestroy){if(this._readable&&this._readable.destroy)this._readable.destroy();if(this._writable&&this._writable.destroy)this._writable.destroy()}this.emit("close")};Duplexify.prototype._write=function(data,enc,cb){if(this.destroyed)return cb();if(this._corked)return onuncork(this,this._write.bind(this,data,enc,cb));if(data===SIGNAL_FLUSH)return this._finish(cb);if(!this._writable)return cb();if(this._writable.write(data)===false)this._ondrain=cb;else cb()};Duplexify.prototype._finish=function(cb){var self=this;this.emit("preend");onuncork(this,(function(){end(self._forwardEnd&&self._writable,(function(){if(self._writableState.prefinished===false)self._writableState.prefinished=true;self.emit("prefinish");onuncork(self,cb)}))}))};Duplexify.prototype.end=function(data,enc,cb){if(typeof data==="function")return this.end(null,null,data);if(typeof enc==="function")return this.end(data,null,enc);this._ended=true;if(data)this.write(data);if(!this._writableState.ending)this.write(SIGNAL_FLUSH);return stream.Writable.prototype.end.call(this,cb)};module.exports=Duplexify}).call(this,require("_process"),require("buffer").Buffer)},{_process:171,buffer:75,"end-of-stream":80,inherits:148,"readable-stream":187,"stream-shift":190}],80:[function(require,module,exports){(function(process){var once=require("once");var noop=function(){};var isRequest=function(stream){return stream.setHeader&&typeof stream.abort==="function"};var isChildProcess=function(stream){return stream.stdio&&Array.isArray(stream.stdio)&&stream.stdio.length===3};var eos=function(stream,opts,callback){if(typeof opts==="function")return eos(stream,null,opts);if(!opts)opts={};callback=once(callback||noop);var ws=stream._writableState;var rs=stream._readableState;var readable=opts.readable||opts.readable!==false&&stream.readable;var writable=opts.writable||opts.writable!==false&&stream.writable;var cancelled=false;var onlegacyfinish=function(){if(!stream.writable)onfinish()};var onfinish=function(){writable=false;if(!readable)callback.call(stream)};var onend=function(){readable=false;if(!writable)callback.call(stream)};var onexit=function(exitCode){callback.call(stream,exitCode?new Error("exited with error code: "+exitCode):null)};var onerror=function(err){callback.call(stream,err)};var onclose=function(){process.nextTick(onclosenexttick)};var onclosenexttick=function(){if(cancelled)return;if(readable&&!(rs&&(rs.ended&&!rs.destroyed)))return callback.call(stream,new Error("premature close"));if(writable&&!(ws&&(ws.ended&&!ws.destroyed)))return callback.call(stream,new Error("premature close"))};var onrequest=function(){stream.req.on("finish",onfinish)};if(isRequest(stream)){stream.on("complete",onfinish);stream.on("abort",onclose);if(stream.req)onrequest();else stream.on("request",onrequest)}else if(writable&&!ws){stream.on("end",onlegacyfinish);stream.on("close",onlegacyfinish)}if(isChildProcess(stream))stream.on("exit",onexit);stream.on("end",onend);stream.on("finish",onfinish);if(opts.error!==false)stream.on("error",onerror);stream.on("close",onclose);return function(){cancelled=true;stream.removeListener("complete",onfinish);stream.removeListener("abort",onclose);stream.removeListener("request",onrequest);if(stream.req)stream.req.removeListener("finish",onfinish);stream.removeListener("end",onlegacyfinish);stream.removeListener("close",onlegacyfinish);stream.removeListener("finish",onfinish);stream.removeListener("exit",onexit);stream.removeListener("end",onend);stream.removeListener("error",onerror);stream.removeListener("close",onclose)}};module.exports=eos}).call(this,require("_process"))},{_process:171,once:169}],81:[function(require,module,exports){"use strict";var value=require("../../object/valid-value");module.exports=function(){value(this).length=0;return this}},{"../../object/valid-value":116}],82:[function(require,module,exports){"use strict";var numberIsNaN=require("../../number/is-nan"),toPosInt=require("../../number/to-pos-integer"),value=require("../../object/valid-value"),indexOf=Array.prototype.indexOf,objHasOwnProperty=Object.prototype.hasOwnProperty,abs=Math.abs,floor=Math.floor;module.exports=function(searchElement){var i,length,fromIndex,val;if(!numberIsNaN(searchElement))return indexOf.apply(this,arguments);length=toPosInt(value(this).length);fromIndex=arguments[1];if(isNaN(fromIndex))fromIndex=0;else if(fromIndex>=0)fromIndex=floor(fromIndex);else fromIndex=toPosInt(this.length)-floor(abs(fromIndex));for(i=fromIndex;i<length;++i){if(objHasOwnProperty.call(this,i)){val=this[i];if(numberIsNaN(val))return i}}return-1}},{"../../number/is-nan":92,"../../number/to-pos-integer":96,"../../object/valid-value":116}],83:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?Array.from:require("./shim")},{"./is-implemented":84,"./shim":85}],84:[function(require,module,exports){"use strict";module.exports=function(){var from=Array.from,arr,result;if(typeof from!=="function")return false;arr=["raz","dwa"];result=from(arr);return Boolean(result&&result!==arr&&result[1]==="dwa")}},{}],85:[function(require,module,exports){"use strict";var iteratorSymbol=require("es6-symbol").iterator,isArguments=require("../../function/is-arguments"),isFunction=require("../../function/is-function"),toPosInt=require("../../number/to-pos-integer"),callable=require("../../object/valid-callable"),validValue=require("../../object/valid-value"),isValue=require("../../object/is-value"),isString=require("../../string/is-string"),isArray=Array.isArray,call=Function.prototype.call,desc={configurable:true,enumerable:true,writable:true,value:null},defineProperty=Object.defineProperty;module.exports=function(arrayLike){var mapFn=arguments[1],thisArg=arguments[2],Context,i,j,arr,length,code,iterator,result,getIterator,value;arrayLike=Object(validValue(arrayLike));if(isValue(mapFn))callable(mapFn);if(!this||this===Array||!isFunction(this)){if(!mapFn){if(isArguments(arrayLike)){length=arrayLike.length;if(length!==1)return Array.apply(null,arrayLike);arr=new Array(1);arr[0]=arrayLike[0];return arr}if(isArray(arrayLike)){arr=new Array(length=arrayLike.length);for(i=0;i<length;++i)arr[i]=arrayLike[i];return arr}}arr=[]}else{Context=this}if(!isArray(arrayLike)){if((getIterator=arrayLike[iteratorSymbol])!==undefined){iterator=callable(getIterator).call(arrayLike);if(Context)arr=new Context;result=iterator.next();i=0;while(!result.done){value=mapFn?call.call(mapFn,thisArg,result.value,i):result.value;if(Context){desc.value=value;defineProperty(arr,i,desc)}else{arr[i]=value}result=iterator.next();++i}length=i}else if(isString(arrayLike)){length=arrayLike.length;if(Context)arr=new Context;for(i=0,j=0;i<length;++i){value=arrayLike[i];if(i+1<length){code=value.charCodeAt(0);if(code>=55296&&code<=56319)value+=arrayLike[++i]}value=mapFn?call.call(mapFn,thisArg,value,j):value;if(Context){desc.value=value;defineProperty(arr,j,desc)}else{arr[j]=value}++j}length=j}}if(length===undefined){length=toPosInt(arrayLike.length);if(Context)arr=new Context(length);for(i=0;i<length;++i){value=mapFn?call.call(mapFn,thisArg,arrayLike[i],i):arrayLike[i];if(Context){desc.value=value;defineProperty(arr,i,desc)}else{arr[i]=value}}}if(Context){desc.value=null;arr.length=length}return arr}},{"../../function/is-arguments":86,"../../function/is-function":87,"../../number/to-pos-integer":96,"../../object/is-value":105,"../../object/valid-callable":115,"../../object/valid-value":116,"../../string/is-string":120,"es6-symbol":134}],86:[function(require,module,exports){"use strict";var objToString=Object.prototype.toString,id=objToString.call(function(){return arguments}());module.exports=function(value){return objToString.call(value)===id}},{}],87:[function(require,module,exports){"use strict";var objToString=Object.prototype.toString,isFunctionStringTag=RegExp.prototype.test.bind(/^[object [A-Za-z0-9]*Function]$/);module.exports=function(value){return typeof value==="function"&&isFunctionStringTag(objToString.call(value))}},{}],88:[function(require,module,exports){"use strict";module.exports=function(){}},{}],89:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?Math.sign:require("./shim")},{"./is-implemented":90,"./shim":91}],90:[function(require,module,exports){"use strict";module.exports=function(){var sign=Math.sign;if(typeof sign!=="function")return false;return sign(10)===1&&sign(-20)===-1}},{}],91:[function(require,module,exports){"use strict";module.exports=function(value){value=Number(value);if(isNaN(value)||value===0)return value;return value>0?1:-1}},{}],92:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?Number.isNaN:require("./shim")},{"./is-implemented":93,"./shim":94}],93:[function(require,module,exports){"use strict";module.exports=function(){var numberIsNaN=Number.isNaN;if(typeof numberIsNaN!=="function")return false;return!numberIsNaN({})&&numberIsNaN(NaN)&&!numberIsNaN(34)}},{}],94:[function(require,module,exports){"use strict";module.exports=function(value){return value!==value}},{}],95:[function(require,module,exports){"use strict";var sign=require("../math/sign"),abs=Math.abs,floor=Math.floor;module.exports=function(value){if(isNaN(value))return 0;value=Number(value);if(value===0||!isFinite(value))return value;return sign(value)*floor(abs(value))}},{"../math/sign":89}],96:[function(require,module,exports){"use strict";var toInteger=require("./to-integer"),max=Math.max;module.exports=function(value){return max(0,toInteger(value))}},{"./to-integer":95}],97:[function(require,module,exports){"use strict";var callable=require("./valid-callable"),value=require("./valid-value"),bind=Function.prototype.bind,call=Function.prototype.call,keys=Object.keys,objPropertyIsEnumerable=Object.prototype.propertyIsEnumerable;module.exports=function(method,defVal){return function(obj,cb){var list,thisArg=arguments[2],compareFn=arguments[3];obj=Object(value(obj));callable(cb);list=keys(obj);if(compareFn){list.sort(typeof compareFn==="function"?bind.call(compareFn,obj):undefined)}if(typeof method!=="function")method=list[method];return call.call(method,list,(function(key,index){if(!objPropertyIsEnumerable.call(obj,key))return defVal;return call.call(cb,thisArg,obj[key],key,obj,index)}))}}},{"./valid-callable":115,"./valid-value":116}],98:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?Object.assign:require("./shim")},{"./is-implemented":99,"./shim":100}],99:[function(require,module,exports){"use strict";module.exports=function(){var assign=Object.assign,obj;if(typeof assign!=="function")return false;obj={foo:"raz"};assign(obj,{bar:"dwa"},{trzy:"trzy"});return obj.foo+obj.bar+obj.trzy==="razdwatrzy"}},{}],100:[function(require,module,exports){"use strict";var keys=require("../keys"),value=require("../valid-value"),max=Math.max;module.exports=function(dest,src){var error,i,length=max(arguments.length,2),assign;dest=Object(value(dest));assign=function(key){try{dest[key]=src[key]}catch(e){if(!error)error=e}};for(i=1;i<length;++i){src=arguments[i];keys(src).forEach(assign)}if(error!==undefined)throw error;return dest}},{"../keys":106,"../valid-value":116}],101:[function(require,module,exports){"use strict";var aFrom=require("../array/from"),assign=require("./assign"),value=require("./valid-value");module.exports=function(obj){var copy=Object(value(obj)),propertyNames=arguments[1],options=Object(arguments[2]);if(copy!==obj&&!propertyNames)return copy;var result={};if(propertyNames){aFrom(propertyNames,(function(propertyName){if(options.ensure||propertyName in obj)result[propertyName]=obj[propertyName]}))}else{assign(result,obj)}return result}},{"../array/from":83,"./assign":98,"./valid-value":116}],102:[function(require,module,exports){"use strict";var create=Object.create,shim;if(!require("./set-prototype-of/is-implemented")()){shim=require("./set-prototype-of/shim")}module.exports=function(){var nullObject,polyProps,desc;if(!shim)return create;if(shim.level!==1)return create;nullObject={};polyProps={};desc={configurable:false,enumerable:false,writable:true,value:undefined};Object.getOwnPropertyNames(Object.prototype).forEach((function(name){if(name==="__proto__"){polyProps[name]={configurable:true,enumerable:false,writable:true,value:undefined};return}polyProps[name]=desc}));Object.defineProperties(nullObject,polyProps);Object.defineProperty(shim,"nullPolyfill",{configurable:false,enumerable:false,writable:false,value:nullObject});return function(prototype,props){return create(prototype===null?nullObject:prototype,props)}}()},{"./set-prototype-of/is-implemented":113,"./set-prototype-of/shim":114}],103:[function(require,module,exports){"use strict";module.exports=require("./_iterate")("forEach")},{"./_iterate":97}],104:[function(require,module,exports){"use strict";var isValue=require("./is-value");var map={function:true,object:true};module.exports=function(value){return isValue(value)&&map[typeof value]||false}},{"./is-value":105}],105:[function(require,module,exports){"use strict";var _undefined=require("../function/noop")();module.exports=function(val){return val!==_undefined&&val!==null}},{"../function/noop":88}],106:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?Object.keys:require("./shim")},{"./is-implemented":107,"./shim":108}],107:[function(require,module,exports){"use strict";module.exports=function(){try{Object.keys("primitive");return true}catch(e){return false}}},{}],108:[function(require,module,exports){"use strict";var isValue=require("../is-value");var keys=Object.keys;module.exports=function(object){return keys(isValue(object)?Object(object):object)}},{"../is-value":105}],109:[function(require,module,exports){"use strict";var callable=require("./valid-callable"),forEach=require("./for-each"),call=Function.prototype.call;module.exports=function(obj,cb){var result={},thisArg=arguments[2];callable(cb);forEach(obj,(function(value,key,targetObj,index){result[key]=call.call(cb,thisArg,value,key,targetObj,index)}));return result}},{"./for-each":103,"./valid-callable":115}],110:[function(require,module,exports){"use strict";var isValue=require("./is-value");var forEach=Array.prototype.forEach,create=Object.create;var process=function(src,obj){var key;for(key in src)obj[key]=src[key]};module.exports=function(opts1){var result=create(null);forEach.call(arguments,(function(options){if(!isValue(options))return;process(Object(options),result)}));return result}},{"./is-value":105}],111:[function(require,module,exports){"use strict";var forEach=Array.prototype.forEach,create=Object.create;module.exports=function(arg){var set=create(null);forEach.call(arguments,(function(name){set[name]=true}));return set}},{}],112:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?Object.setPrototypeOf:require("./shim")},{"./is-implemented":113,"./shim":114}],113:[function(require,module,exports){"use strict";var create=Object.create,getPrototypeOf=Object.getPrototypeOf,plainObject={};module.exports=function(){var setPrototypeOf=Object.setPrototypeOf,customCreate=arguments[0]||create;if(typeof setPrototypeOf!=="function")return false;return getPrototypeOf(setPrototypeOf(customCreate(null),plainObject))===plainObject}},{}],114:[function(require,module,exports){"use strict";var isObject=require("../is-object"),value=require("../valid-value"),objIsPrototypeOf=Object.prototype.isPrototypeOf,defineProperty=Object.defineProperty,nullDesc={configurable:true,enumerable:false,writable:true,value:undefined},validate;validate=function(obj,prototype){value(obj);if(prototype===null||isObject(prototype))return obj;throw new TypeError("Prototype must be null or an object")};module.exports=function(status){var fn,set;if(!status)return null;if(status.level===2){if(status.set){set=status.set;fn=function(obj,prototype){set.call(validate(obj,prototype),prototype);return obj}}else{fn=function(obj,prototype){validate(obj,prototype).__proto__=prototype;return obj}}}else{fn=function self(obj,prototype){var isNullBase;validate(obj,prototype);isNullBase=objIsPrototypeOf.call(self.nullPolyfill,obj);if(isNullBase)delete self.nullPolyfill.__proto__;if(prototype===null)prototype=self.nullPolyfill;obj.__proto__=prototype;if(isNullBase)defineProperty(self.nullPolyfill,"__proto__",nullDesc);return obj}}return Object.defineProperty(fn,"level",{configurable:false,enumerable:false,writable:false,value:status.level})}(function(){var tmpObj1=Object.create(null),tmpObj2={},set,desc=Object.getOwnPropertyDescriptor(Object.prototype,"__proto__");if(desc){try{set=desc.set;set.call(tmpObj1,tmpObj2)}catch(ignore){}if(Object.getPrototypeOf(tmpObj1)===tmpObj2)return{set:set,level:2}}tmpObj1.__proto__=tmpObj2;if(Object.getPrototypeOf(tmpObj1)===tmpObj2)return{level:2};tmpObj1={};tmpObj1.__proto__=tmpObj2;if(Object.getPrototypeOf(tmpObj1)===tmpObj2)return{level:1};return false}());require("../create")},{"../create":102,"../is-object":104,"../valid-value":116}],115:[function(require,module,exports){"use strict";module.exports=function(fn){if(typeof fn!=="function")throw new TypeError(fn+" is not a function");return fn}},{}],116:[function(require,module,exports){"use strict";var isValue=require("./is-value");module.exports=function(value){if(!isValue(value))throw new TypeError("Cannot use null or undefined");return value}},{"./is-value":105}],117:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?String.prototype.contains:require("./shim")},{"./is-implemented":118,"./shim":119}],118:[function(require,module,exports){"use strict";var str="razdwatrzy";module.exports=function(){if(typeof str.contains!=="function")return false;return str.contains("dwa")===true&&str.contains("foo")===false}},{}],119:[function(require,module,exports){"use strict";var indexOf=String.prototype.indexOf;module.exports=function(searchString){return indexOf.call(this,searchString,arguments[1])>-1}},{}],120:[function(require,module,exports){"use strict";var objToString=Object.prototype.toString,id=objToString.call("");module.exports=function(value){return typeof value==="string"||value&&typeof value==="object"&&(value instanceof String||objToString.call(value)===id)||false}},{}],121:[function(require,module,exports){"use strict";var setPrototypeOf=require("es5-ext/object/set-prototype-of"),contains=require("es5-ext/string/#/contains"),d=require("d"),Symbol=require("es6-symbol"),Iterator=require("./");var defineProperty=Object.defineProperty,ArrayIterator;ArrayIterator=module.exports=function(arr,kind){if(!(this instanceof ArrayIterator))throw new TypeError("Constructor requires 'new'");Iterator.call(this,arr);if(!kind)kind="value";else if(contains.call(kind,"key+value"))kind="key+value";else if(contains.call(kind,"key"))kind="key";else kind="value";defineProperty(this,"__kind__",d("",kind))};if(setPrototypeOf)setPrototypeOf(ArrayIterator,Iterator);delete ArrayIterator.prototype.constructor;ArrayIterator.prototype=Object.create(Iterator.prototype,{_resolve:d((function(i){if(this.__kind__==="value")return this.__list__[i];if(this.__kind__==="key+value")return[i,this.__list__[i]];return i}))});defineProperty(ArrayIterator.prototype,Symbol.toStringTag,d("c","Array Iterator"))},{"./":124,d:78,"es5-ext/object/set-prototype-of":112,"es5-ext/string/#/contains":117,"es6-symbol":134}],122:[function(require,module,exports){"use strict";var isArguments=require("es5-ext/function/is-arguments"),callable=require("es5-ext/object/valid-callable"),isString=require("es5-ext/string/is-string"),get=require("./get");var isArray=Array.isArray,call=Function.prototype.call,some=Array.prototype.some;module.exports=function(iterable,cb){var mode,thisArg=arguments[2],result,doBreak,broken,i,length,char,code;if(isArray(iterable)||isArguments(iterable))mode="array";else if(isString(iterable))mode="string";else iterable=get(iterable);callable(cb);doBreak=function(){broken=true};if(mode==="array"){some.call(iterable,(function(value){call.call(cb,thisArg,value,doBreak);return broken}));return}if(mode==="string"){length=iterable.length;for(i=0;i<length;++i){char=iterable[i];if(i+1<length){code=char.charCodeAt(0);if(code>=55296&&code<=56319)char+=iterable[++i]}call.call(cb,thisArg,char,doBreak);if(broken)break}return}result=iterable.next();while(!result.done){call.call(cb,thisArg,result.value,doBreak);if(broken)return;result=iterable.next()}}},{"./get":123,"es5-ext/function/is-arguments":86,"es5-ext/object/valid-callable":115,"es5-ext/string/is-string":120}],123:[function(require,module,exports){"use strict";var isArguments=require("es5-ext/function/is-arguments"),isString=require("es5-ext/string/is-string"),ArrayIterator=require("./array"),StringIterator=require("./string"),iterable=require("./valid-iterable"),iteratorSymbol=require("es6-symbol").iterator;module.exports=function(obj){if(typeof iterable(obj)[iteratorSymbol]==="function")return obj[iteratorSymbol]();if(isArguments(obj))return new ArrayIterator(obj);if(isString(obj))return new StringIterator(obj);return new ArrayIterator(obj)}},{"./array":121,"./string":126,"./valid-iterable":127,"es5-ext/function/is-arguments":86,"es5-ext/string/is-string":120,"es6-symbol":134}],124:[function(require,module,exports){"use strict";var clear=require("es5-ext/array/#/clear"),assign=require("es5-ext/object/assign"),callable=require("es5-ext/object/valid-callable"),value=require("es5-ext/object/valid-value"),d=require("d"),autoBind=require("d/auto-bind"),Symbol=require("es6-symbol");var defineProperty=Object.defineProperty,defineProperties=Object.defineProperties,Iterator;module.exports=Iterator=function(list,context){if(!(this instanceof Iterator))throw new TypeError("Constructor requires 'new'");defineProperties(this,{__list__:d("w",value(list)),__context__:d("w",context),__nextIndex__:d("w",0)});if(!context)return;callable(context.on);context.on("_add",this._onAdd);context.on("_delete",this._onDelete);context.on("_clear",this._onClear)};delete Iterator.prototype.constructor;defineProperties(Iterator.prototype,assign({_next:d((function(){var i;if(!this.__list__)return undefined;if(this.__redo__){i=this.__redo__.shift();if(i!==undefined)return i}if(this.__nextIndex__<this.__list__.length)return this.__nextIndex__++;this._unBind();return undefined})),next:d((function(){return this._createResult(this._next())})),_createResult:d((function(i){if(i===undefined)return{done:true,value:undefined};return{done:false,value:this._resolve(i)}})),_resolve:d((function(i){return this.__list__[i]})),_unBind:d((function(){this.__list__=null;delete this.__redo__;if(!this.__context__)return;this.__context__.off("_add",this._onAdd);this.__context__.off("_delete",this._onDelete);this.__context__.off("_clear",this._onClear);this.__context__=null})),toString:d((function(){return"[object "+(this[Symbol.toStringTag]||"Object")+"]"}))},autoBind({_onAdd:d((function(index){if(index>=this.__nextIndex__)return;++this.__nextIndex__;if(!this.__redo__){defineProperty(this,"__redo__",d("c",[index]));return}this.__redo__.forEach((function(redo,i){if(redo>=index)this.__redo__[i]=++redo}),this);this.__redo__.push(index)})),_onDelete:d((function(index){var i;if(index>=this.__nextIndex__)return;--this.__nextIndex__;if(!this.__redo__)return;i=this.__redo__.indexOf(index);if(i!==-1)this.__redo__.splice(i,1);this.__redo__.forEach((function(redo,j){if(redo>index)this.__redo__[j]=--redo}),this)})),_onClear:d((function(){if(this.__redo__)clear.call(this.__redo__);this.__nextIndex__=0}))})));defineProperty(Iterator.prototype,Symbol.iterator,d((function(){return this})))},{d:78,"d/auto-bind":77,"es5-ext/array/#/clear":81,"es5-ext/object/assign":98,"es5-ext/object/valid-callable":115,"es5-ext/object/valid-value":116,"es6-symbol":134}],125:[function(require,module,exports){"use strict";var isArguments=require("es5-ext/function/is-arguments"),isValue=require("es5-ext/object/is-value"),isString=require("es5-ext/string/is-string");var iteratorSymbol=require("es6-symbol").iterator,isArray=Array.isArray;module.exports=function(value){if(!isValue(value))return false;if(isArray(value))return true;if(isString(value))return true;if(isArguments(value))return true;return typeof value[iteratorSymbol]==="function"}},{"es5-ext/function/is-arguments":86,"es5-ext/object/is-value":105,"es5-ext/string/is-string":120,"es6-symbol":134}],126:[function(require,module,exports){"use strict";var setPrototypeOf=require("es5-ext/object/set-prototype-of"),d=require("d"),Symbol=require("es6-symbol"),Iterator=require("./");var defineProperty=Object.defineProperty,StringIterator;StringIterator=module.exports=function(str){if(!(this instanceof StringIterator))throw new TypeError("Constructor requires 'new'");str=String(str);Iterator.call(this,str);defineProperty(this,"__length__",d("",str.length))};if(setPrototypeOf)setPrototypeOf(StringIterator,Iterator);delete StringIterator.prototype.constructor;StringIterator.prototype=Object.create(Iterator.prototype,{_next:d((function(){if(!this.__list__)return undefined;if(this.__nextIndex__<this.__length__)return this.__nextIndex__++;this._unBind();return undefined})),_resolve:d((function(i){var char=this.__list__[i],code;if(this.__nextIndex__===this.__length__)return char;code=char.charCodeAt(0);if(code>=55296&&code<=56319)return char+this.__list__[this.__nextIndex__++];return char}))});defineProperty(StringIterator.prototype,Symbol.toStringTag,d("c","String Iterator"))},{"./":124,d:78,"es5-ext/object/set-prototype-of":112,"es6-symbol":134}],127:[function(require,module,exports){"use strict";var isIterable=require("./is-iterable");module.exports=function(value){if(!isIterable(value))throw new TypeError(value+" is not iterable");return value}},{"./is-iterable":125}],128:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?Map:require("./polyfill")},{"./is-implemented":129,"./polyfill":133}],129:[function(require,module,exports){"use strict";module.exports=function(){var map,iterator,result;if(typeof Map!=="function")return false;try{map=new Map([["raz","one"],["dwa","two"],["trzy","three"]])}catch(e){return false}if(String(map)!=="[object Map]")return false;if(map.size!==3)return false;if(typeof map.clear!=="function")return false;if(typeof map.delete!=="function")return false;if(typeof map.entries!=="function")return false;if(typeof map.forEach!=="function")return false;if(typeof map.get!=="function")return false;if(typeof map.has!=="function")return false;if(typeof map.keys!=="function")return false;if(typeof map.set!=="function")return false;if(typeof map.values!=="function")return false;iterator=map.entries();result=iterator.next();if(result.done!==false)return false;if(!result.value)return false;if(result.value[0]!=="raz")return false;if(result.value[1]!=="one")return false;return true}},{}],130:[function(require,module,exports){"use strict";module.exports=function(){if(typeof Map==="undefined")return false;return Object.prototype.toString.call(new Map)==="[object Map]"}()},{}],131:[function(require,module,exports){"use strict";module.exports=require("es5-ext/object/primitive-set")("key","value","key+value")},{"es5-ext/object/primitive-set":111}],132:[function(require,module,exports){"use strict";var setPrototypeOf=require("es5-ext/object/set-prototype-of"),d=require("d"),Iterator=require("es6-iterator"),toStringTagSymbol=require("es6-symbol").toStringTag,kinds=require("./iterator-kinds"),defineProperties=Object.defineProperties,unBind=Iterator.prototype._unBind,MapIterator;MapIterator=module.exports=function(map,kind){if(!(this instanceof MapIterator))return new MapIterator(map,kind);Iterator.call(this,map.__mapKeysData__,map);if(!kind||!kinds[kind])kind="key+value";defineProperties(this,{__kind__:d("",kind),__values__:d("w",map.__mapValuesData__)})};if(setPrototypeOf)setPrototypeOf(MapIterator,Iterator);MapIterator.prototype=Object.create(Iterator.prototype,{constructor:d(MapIterator),_resolve:d((function(i){if(this.__kind__==="value")return this.__values__[i];if(this.__kind__==="key")return this.__list__[i];return[this.__list__[i],this.__values__[i]]})),_unBind:d((function(){this.__values__=null;unBind.call(this)})),toString:d((function(){return"[object Map Iterator]"}))});Object.defineProperty(MapIterator.prototype,toStringTagSymbol,d("c","Map Iterator"))},{"./iterator-kinds":131,d:78,"es5-ext/object/set-prototype-of":112,"es6-iterator":124,"es6-symbol":134}],133:[function(require,module,exports){"use strict";var clear=require("es5-ext/array/#/clear"),eIndexOf=require("es5-ext/array/#/e-index-of"),setPrototypeOf=require("es5-ext/object/set-prototype-of"),callable=require("es5-ext/object/valid-callable"),validValue=require("es5-ext/object/valid-value"),d=require("d"),ee=require("event-emitter"),Symbol=require("es6-symbol"),iterator=require("es6-iterator/valid-iterable"),forOf=require("es6-iterator/for-of"),Iterator=require("./lib/iterator"),isNative=require("./is-native-implemented"),call=Function.prototype.call,defineProperties=Object.defineProperties,getPrototypeOf=Object.getPrototypeOf,MapPoly;module.exports=MapPoly=function(){var iterable=arguments[0],keys,values,self;if(!(this instanceof MapPoly))throw new TypeError("Constructor requires 'new'");if(isNative&&setPrototypeOf&&Map!==MapPoly){self=setPrototypeOf(new Map,getPrototypeOf(this))}else{self=this}if(iterable!=null)iterator(iterable);defineProperties(self,{__mapKeysData__:d("c",keys=[]),__mapValuesData__:d("c",values=[])});if(!iterable)return self;forOf(iterable,(function(value){var key=validValue(value)[0];value=value[1];if(eIndexOf.call(keys,key)!==-1)return;keys.push(key);values.push(value)}),self);return self};if(isNative){if(setPrototypeOf)setPrototypeOf(MapPoly,Map);MapPoly.prototype=Object.create(Map.prototype,{constructor:d(MapPoly)})}ee(defineProperties(MapPoly.prototype,{clear:d((function(){if(!this.__mapKeysData__.length)return;clear.call(this.__mapKeysData__);clear.call(this.__mapValuesData__);this.emit("_clear")})),delete:d((function(key){var index=eIndexOf.call(this.__mapKeysData__,key);if(index===-1)return false;this.__mapKeysData__.splice(index,1);this.__mapValuesData__.splice(index,1);this.emit("_delete",index,key);return true})),entries:d((function(){return new Iterator(this,"key+value")})),forEach:d((function(cb){var thisArg=arguments[1],iterator,result;callable(cb);iterator=this.entries();result=iterator._next();while(result!==undefined){call.call(cb,thisArg,this.__mapValuesData__[result],this.__mapKeysData__[result],this);result=iterator._next()}})),get:d((function(key){var index=eIndexOf.call(this.__mapKeysData__,key);if(index===-1)return;return this.__mapValuesData__[index]})),has:d((function(key){return eIndexOf.call(this.__mapKeysData__,key)!==-1})),keys:d((function(){return new Iterator(this,"key")})),set:d((function(key,value){var index=eIndexOf.call(this.__mapKeysData__,key),emit;if(index===-1){index=this.__mapKeysData__.push(key)-1;emit=true}this.__mapValuesData__[index]=value;if(emit)this.emit("_add",index,key);return this})),size:d.gs((function(){return this.__mapKeysData__.length})),values:d((function(){return new Iterator(this,"value")})),toString:d((function(){return"[object Map]"}))}));Object.defineProperty(MapPoly.prototype,Symbol.iterator,d((function(){return this.entries()})));Object.defineProperty(MapPoly.prototype,Symbol.toStringTag,d("c","Map"))},{"./is-native-implemented":130,"./lib/iterator":132,d:78,"es5-ext/array/#/clear":81,"es5-ext/array/#/e-index-of":82,"es5-ext/object/set-prototype-of":112,"es5-ext/object/valid-callable":115,"es5-ext/object/valid-value":116,"es6-iterator/for-of":122,"es6-iterator/valid-iterable":127,"es6-symbol":134,"event-emitter":142}],134:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?require("ext/global-this").Symbol:require("./polyfill")},{"./is-implemented":135,"./polyfill":140,"ext/global-this":144}],135:[function(require,module,exports){"use strict";var global=require("ext/global-this"),validTypes={object:true,symbol:true};module.exports=function(){var Symbol=global.Symbol;var symbol;if(typeof Symbol!=="function")return false;symbol=Symbol("test symbol");try{String(symbol)}catch(e){return false}if(!validTypes[typeof Symbol.iterator])return false;if(!validTypes[typeof Symbol.toPrimitive])return false;if(!validTypes[typeof Symbol.toStringTag])return false;return true}},{"ext/global-this":144}],136:[function(require,module,exports){"use strict";module.exports=function(value){if(!value)return false;if(typeof value==="symbol")return true;if(!value.constructor)return false;if(value.constructor.name!=="Symbol")return false;return value[value.constructor.toStringTag]==="Symbol"}},{}],137:[function(require,module,exports){"use strict";var d=require("d");var create=Object.create,defineProperty=Object.defineProperty,objPrototype=Object.prototype;var created=create(null);module.exports=function(desc){var postfix=0,name,ie11BugWorkaround;while(created[desc+(postfix||"")])++postfix;desc+=postfix||"";created[desc]=true;name="@@"+desc;defineProperty(objPrototype,name,d.gs(null,(function(value){if(ie11BugWorkaround)return;ie11BugWorkaround=true;defineProperty(this,name,d(value));ie11BugWorkaround=false})));return name}},{d:78}],138:[function(require,module,exports){"use strict";var d=require("d"),NativeSymbol=require("ext/global-this").Symbol;module.exports=function(SymbolPolyfill){return Object.defineProperties(SymbolPolyfill,{hasInstance:d("",NativeSymbol&&NativeSymbol.hasInstance||SymbolPolyfill("hasInstance")),isConcatSpreadable:d("",NativeSymbol&&NativeSymbol.isConcatSpreadable||SymbolPolyfill("isConcatSpreadable")),iterator:d("",NativeSymbol&&NativeSymbol.iterator||SymbolPolyfill("iterator")),match:d("",NativeSymbol&&NativeSymbol.match||SymbolPolyfill("match")),replace:d("",NativeSymbol&&NativeSymbol.replace||SymbolPolyfill("replace")),search:d("",NativeSymbol&&NativeSymbol.search||SymbolPolyfill("search")),species:d("",NativeSymbol&&NativeSymbol.species||SymbolPolyfill("species")),split:d("",NativeSymbol&&NativeSymbol.split||SymbolPolyfill("split")),toPrimitive:d("",NativeSymbol&&NativeSymbol.toPrimitive||SymbolPolyfill("toPrimitive")),toStringTag:d("",NativeSymbol&&NativeSymbol.toStringTag||SymbolPolyfill("toStringTag")),unscopables:d("",NativeSymbol&&NativeSymbol.unscopables||SymbolPolyfill("unscopables"))})}},{d:78,"ext/global-this":144}],139:[function(require,module,exports){"use strict";var d=require("d"),validateSymbol=require("../../../validate-symbol");var registry=Object.create(null);module.exports=function(SymbolPolyfill){return Object.defineProperties(SymbolPolyfill,{for:d((function(key){if(registry[key])return registry[key];return registry[key]=SymbolPolyfill(String(key))})),keyFor:d((function(symbol){var key;validateSymbol(symbol);for(key in registry){if(registry[key]===symbol)return key}return undefined}))})}},{"../../../validate-symbol":141,d:78}],140:[function(require,module,exports){"use strict";var d=require("d"),validateSymbol=require("./validate-symbol"),NativeSymbol=require("ext/global-this").Symbol,generateName=require("./lib/private/generate-name"),setupStandardSymbols=require("./lib/private/setup/standard-symbols"),setupSymbolRegistry=require("./lib/private/setup/symbol-registry");var create=Object.create,defineProperties=Object.defineProperties,defineProperty=Object.defineProperty;var SymbolPolyfill,HiddenSymbol,isNativeSafe;if(typeof NativeSymbol==="function"){try{String(NativeSymbol());isNativeSafe=true}catch(ignore){}}else{NativeSymbol=null}HiddenSymbol=function Symbol(description){if(this instanceof HiddenSymbol)throw new TypeError("Symbol is not a constructor");return SymbolPolyfill(description)};module.exports=SymbolPolyfill=function Symbol(description){var symbol;if(this instanceof Symbol)throw new TypeError("Symbol is not a constructor");if(isNativeSafe)return NativeSymbol(description);symbol=create(HiddenSymbol.prototype);description=description===undefined?"":String(description);return defineProperties(symbol,{__description__:d("",description),__name__:d("",generateName(description))})};setupStandardSymbols(SymbolPolyfill);setupSymbolRegistry(SymbolPolyfill);defineProperties(HiddenSymbol.prototype,{constructor:d(SymbolPolyfill),toString:d("",(function(){return this.__name__}))});defineProperties(SymbolPolyfill.prototype,{toString:d((function(){return"Symbol ("+validateSymbol(this).__description__+")"})),valueOf:d((function(){return validateSymbol(this)}))});defineProperty(SymbolPolyfill.prototype,SymbolPolyfill.toPrimitive,d("",(function(){var symbol=validateSymbol(this);if(typeof symbol==="symbol")return symbol;return symbol.toString()})));defineProperty(SymbolPolyfill.prototype,SymbolPolyfill.toStringTag,d("c","Symbol"));defineProperty(HiddenSymbol.prototype,SymbolPolyfill.toStringTag,d("c",SymbolPolyfill.prototype[SymbolPolyfill.toStringTag]));defineProperty(HiddenSymbol.prototype,SymbolPolyfill.toPrimitive,d("c",SymbolPolyfill.prototype[SymbolPolyfill.toPrimitive]))},{"./lib/private/generate-name":137,"./lib/private/setup/standard-symbols":138,"./lib/private/setup/symbol-registry":139,"./validate-symbol":141,d:78,"ext/global-this":144}],141:[function(require,module,exports){"use strict";var isSymbol=require("./is-symbol");module.exports=function(value){if(!isSymbol(value))throw new TypeError(value+" is not a symbol");return value}},{"./is-symbol":136}],142:[function(require,module,exports){"use strict";var d=require("d"),callable=require("es5-ext/object/valid-callable"),apply=Function.prototype.apply,call=Function.prototype.call,create=Object.create,defineProperty=Object.defineProperty,defineProperties=Object.defineProperties,hasOwnProperty=Object.prototype.hasOwnProperty,descriptor={configurable:true,enumerable:false,writable:true},on,once,off,emit,methods,descriptors,base;on=function(type,listener){var data;callable(listener);if(!hasOwnProperty.call(this,"__ee__")){data=descriptor.value=create(null);defineProperty(this,"__ee__",descriptor);descriptor.value=null}else{data=this.__ee__}if(!data[type])data[type]=listener;else if(typeof data[type]==="object")data[type].push(listener);else data[type]=[data[type],listener];return this};once=function(type,listener){var once,self;callable(listener);self=this;on.call(this,type,once=function(){off.call(self,type,once);apply.call(listener,this,arguments)});once.__eeOnceListener__=listener;return this};off=function(type,listener){var data,listeners,candidate,i;callable(listener);if(!hasOwnProperty.call(this,"__ee__"))return this;data=this.__ee__;if(!data[type])return this;listeners=data[type];if(typeof listeners==="object"){for(i=0;candidate=listeners[i];++i){if(candidate===listener||candidate.__eeOnceListener__===listener){if(listeners.length===2)data[type]=listeners[i?0:1];else listeners.splice(i,1)}}}else{if(listeners===listener||listeners.__eeOnceListener__===listener){delete data[type]}}return this};emit=function(type){var i,l,listener,listeners,args;if(!hasOwnProperty.call(this,"__ee__"))return;listeners=this.__ee__[type];if(!listeners)return;if(typeof listeners==="object"){l=arguments.length;args=new Array(l-1);for(i=1;i<l;++i)args[i-1]=arguments[i];listeners=listeners.slice();for(i=0;listener=listeners[i];++i){apply.call(listener,this,args)}}else{switch(arguments.length){case 1:call.call(listeners,this);break;case 2:call.call(listeners,this,arguments[1]);break;case 3:call.call(listeners,this,arguments[1],arguments[2]);break;default:l=arguments.length;args=new Array(l-1);for(i=1;i<l;++i){args[i-1]=arguments[i]}apply.call(listeners,this,args)}}};methods={on:on,once:once,off:off,emit:emit};descriptors={on:d(on),once:d(once),off:d(off),emit:d(emit)};base=defineProperties({},descriptors);module.exports=exports=function(o){return o==null?create(base):defineProperties(Object(o),descriptors)};exports.methods=methods},{d:78,"es5-ext/object/valid-callable":115}],143:[function(require,module,exports){var naiveFallback=function(){if(typeof self==="object"&&self)return self;if(typeof window==="object"&&window)return window;throw new Error("Unable to resolve global `this`")};module.exports=function(){if(this)return this;try{Object.defineProperty(Object.prototype,"__global__",{get:function(){return this},configurable:true})}catch(error){return naiveFallback()}try{if(!__global__)return naiveFallback();return __global__}finally{delete Object.prototype.__global__}}()},{}],144:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?globalThis:require("./implementation")},{"./implementation":143,"./is-implemented":145}],145:[function(require,module,exports){"use strict";module.exports=function(){if(typeof globalThis!=="object")return false;if(!globalThis)return false;return globalThis.Array===Array}},{}],146:[function(require,module,exports){module.exports=typeof self=="object"?self.FormData:window.FormData},{}],147:[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}},{}],148:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){if(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){if(superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}}},{}],149:[function(require,module,exports){
|
|
32
|
+
"use strict";function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}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 foo(){return 42}};return arr.foo()===42}catch(e){return false}}Object.defineProperty(Buffer.prototype,"parent",{enumerable:true,get:function get(){if(!Buffer.isBuffer(this))return undefined;return this.buffer}});Object.defineProperty(Buffer.prototype,"offset",{enumerable:true,get:function get(){if(!Buffer.isBuffer(this))return undefined;return this.byteOffset}});function createBuffer(length){if(length>K_MAX_LENGTH){throw new RangeError('The value "'+length+'" is invalid for option "size"')}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 TypeError('The "string" argument must be of type string. Received type number')}return allocUnsafe(arg)}return from(arg,encodingOrOffset,length)}if(typeof Symbol!=="undefined"&&Symbol.species!=null&&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==="string"){return fromString(value,encodingOrOffset)}if(ArrayBuffer.isView(value)){return fromArrayLike(value)}if(value==null){throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, "+"or Array-like Object. Received type "+_typeof(value))}if(isInstance(value,ArrayBuffer)||value&&isInstance(value.buffer,ArrayBuffer)){return fromArrayBuffer(value,encodingOrOffset,length)}if(typeof value==="number"){throw new TypeError('The "value" argument must not be of type number. Received type number')}var valueOf=value.valueOf&&value.valueOf();if(valueOf!=null&&valueOf!==value){return Buffer.from(valueOf,encodingOrOffset,length)}var b=fromObject(value);if(b)return b;if(typeof Symbol!=="undefined"&&Symbol.toPrimitive!=null&&typeof value[Symbol.toPrimitive]==="function"){return Buffer.from(value[Symbol.toPrimitive]("string"),encodingOrOffset,length)}throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, "+"or Array-like Object. Received type "+_typeof(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 of type number')}else if(size<0){throw new RangeError('The value "'+size+'" is invalid for option "size"')}}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("Unknown encoding: "+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 outside of buffer bounds')}if(array.byteLength<byteOffset+(length||0)){throw new RangeError('"length" is outside of buffer 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.length!==undefined){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)}}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&&b!==Buffer.prototype};Buffer.compare=function compare(a,b){if(isInstance(a,Uint8Array))a=Buffer.from(a,a.offset,a.byteLength);if(isInstance(b,Uint8Array))b=Buffer.from(b,b.offset,b.byteLength);if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b)){throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array')}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(isInstance(buf,Uint8Array)){buf=Buffer.from(buf)}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(ArrayBuffer.isView(string)||isInstance(string,ArrayBuffer)){return string.byteLength}if(typeof string!=="string"){throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. '+"Received type "+_typeof(string))}var len=string.length;var mustMatch=arguments.length>2&&arguments[2]===true;if(!mustMatch&&len===0)return 0;var loweredCase=false;for(;;){switch(encoding){case"ascii":case"latin1":case"binary":return len;case"utf8":case"utf-8":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 mustMatch?-1: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.toLocaleString=Buffer.prototype.toString;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;str=this.toString("hex",0,max).replace(/(.{2})/g,"$1 ").trim();if(this.length>max)str+=" ... ";return"<Buffer "+str+">"};Buffer.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(isInstance(target,Uint8Array)){target=Buffer.from(target,target.offset,target.byteLength)}if(!Buffer.isBuffer(target)){throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. '+"Received type "+_typeof(target))}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(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,34028234663852886e22,-34028234663852886e22)}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,17976931348623157e292,-17976931348623157e292)}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(!Buffer.isBuffer(target))throw new TypeError("argument should be a Buffer");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("Index out of range");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;if(this===target&&typeof Uint8Array.prototype.copyWithin==="function"){this.copyWithin(targetStart,start,end)}else if(this===target&&start<targetStart&&targetStart<end){for(var i=len-1;i>=0;--i){target[i+targetStart]=this[i+start]}}else{Uint8Array.prototype.set.call(target,this.subarray(start,end),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(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)}if(val.length===1){var code=val.charCodeAt(0);if(encoding==="utf8"&&code<128||encoding==="latin1"){val=code}}}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:Buffer.from(val,encoding);var len=bytes.length;if(len===0){throw new TypeError('The value "'+val+'" is invalid for argument "value"')}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.split("=")[0];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 isInstance(obj,type){return obj instanceof type||obj!=null&&obj.constructor!=null&&obj.constructor.name!=null&&obj.constructor.name===type.name}function numberIsNaN(obj){return obj!==obj}}).call(this,require("buffer").Buffer)},{"base64-js":27,buffer:33,ieee754:119}],34:[function(require,module,exports){"use strict";function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}var objectCreate=Object.create||objectCreatePolyfill;var objectKeys=Object.keys||objectKeysPolyfill;var bind=Function.prototype.bind||functionBindPolyfill;function EventEmitter(){if(!this._events||!Object.prototype.hasOwnProperty.call(this,"_events")){this._events=objectCreate(null);this._eventsCount=0}this._maxListeners=this._maxListeners||undefined}module.exports=EventEmitter;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;var defaultMaxListeners=10;var hasDefineProperty;try{var o={};if(Object.defineProperty)Object.defineProperty(o,"x",{value:0});hasDefineProperty=o.x===0}catch(err){hasDefineProperty=false}if(hasDefineProperty){Object.defineProperty(EventEmitter,"defaultMaxListeners",{enumerable:true,get:function get(){return defaultMaxListeners},set:function set(arg){if(typeof arg!=="number"||arg<0||arg!==arg)throw new TypeError('"defaultMaxListeners" must be a positive number');defaultMaxListeners=arg}})}else{EventEmitter.defaultMaxListeners=defaultMaxListeners}EventEmitter.prototype.setMaxListeners=function setMaxListeners(n){if(typeof n!=="number"||n<0||isNaN(n))throw new TypeError('"n" argument must be a positive number');this._maxListeners=n;return this};function $getMaxListeners(that){if(that._maxListeners===undefined)return EventEmitter.defaultMaxListeners;return that._maxListeners}EventEmitter.prototype.getMaxListeners=function getMaxListeners(){return $getMaxListeners(this)};function emitNone(handler,isFn,self){if(isFn)handler.call(self);else{var len=handler.length;var listeners=arrayClone(handler,len);for(var i=0;i<len;++i){listeners[i].call(self)}}}function emitOne(handler,isFn,self,arg1){if(isFn)handler.call(self,arg1);else{var len=handler.length;var listeners=arrayClone(handler,len);for(var i=0;i<len;++i){listeners[i].call(self,arg1)}}}function emitTwo(handler,isFn,self,arg1,arg2){if(isFn)handler.call(self,arg1,arg2);else{var len=handler.length;var listeners=arrayClone(handler,len);for(var i=0;i<len;++i){listeners[i].call(self,arg1,arg2)}}}function emitThree(handler,isFn,self,arg1,arg2,arg3){if(isFn)handler.call(self,arg1,arg2,arg3);else{var len=handler.length;var listeners=arrayClone(handler,len);for(var i=0;i<len;++i){listeners[i].call(self,arg1,arg2,arg3)}}}function emitMany(handler,isFn,self,args){if(isFn)handler.apply(self,args);else{var len=handler.length;var listeners=arrayClone(handler,len);for(var i=0;i<len;++i){listeners[i].apply(self,args)}}}EventEmitter.prototype.emit=function emit(type){var er,handler,len,args,i,events;var doError=type==="error";events=this._events;if(events)doError=doError&&events.error==null;else if(!doError)return false;if(doError){if(arguments.length>1)er=arguments[1];if(er instanceof Error){throw er}else{var err=new Error('Unhandled "error" event. ('+er+")");err.context=er;throw err}return false}handler=events[type];if(!handler)return false;var isFn=typeof handler==="function";len=arguments.length;switch(len){case 1:emitNone(handler,isFn,this);break;case 2:emitOne(handler,isFn,this,arguments[1]);break;case 3:emitTwo(handler,isFn,this,arguments[1],arguments[2]);break;case 4:emitThree(handler,isFn,this,arguments[1],arguments[2],arguments[3]);break;default:args=new Array(len-1);for(i=1;i<len;i++){args[i-1]=arguments[i]}emitMany(handler,isFn,this,args)}return true};function _addListener(target,type,listener,prepend){var m;var events;var existing;if(typeof listener!=="function")throw new TypeError('"listener" argument must be a function');events=target._events;if(!events){events=target._events=objectCreate(null);target._eventsCount=0}else{if(events.newListener){target.emit("newListener",type,listener.listener?listener.listener:listener);events=target._events}existing=events[type]}if(!existing){existing=events[type]=listener;++target._eventsCount}else{if(typeof existing==="function"){existing=events[type]=prepend?[listener,existing]:[existing,listener]}else{if(prepend){existing.unshift(listener)}else{existing.push(listener)}}if(!existing.warned){m=$getMaxListeners(target);if(m&&m>0&&existing.length>m){existing.warned=true;var w=new Error("Possible EventEmitter memory leak detected. "+existing.length+' "'+String(type)+'" listeners '+"added. Use emitter.setMaxListeners() to "+"increase limit.");w.name="MaxListenersExceededWarning";w.emitter=target;w.type=type;w.count=existing.length;if((typeof console==="undefined"?"undefined":_typeof(console))==="object"&&console.warn){console.warn("%s: %s",w.name,w.message)}}}}return target}EventEmitter.prototype.addListener=function addListener(type,listener){return _addListener(this,type,listener,false)};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.prependListener=function prependListener(type,listener){return _addListener(this,type,listener,true)};function onceWrapper(){if(!this.fired){this.target.removeListener(this.type,this.wrapFn);this.fired=true;switch(arguments.length){case 0:return this.listener.call(this.target);case 1:return this.listener.call(this.target,arguments[0]);case 2:return this.listener.call(this.target,arguments[0],arguments[1]);case 3:return this.listener.call(this.target,arguments[0],arguments[1],arguments[2]);default:var args=new Array(arguments.length);for(var i=0;i<args.length;++i){args[i]=arguments[i]}this.listener.apply(this.target,args)}}}function _onceWrap(target,type,listener){var state={fired:false,wrapFn:undefined,target:target,type:type,listener:listener};var wrapped=bind.call(onceWrapper,state);wrapped.listener=listener;state.wrapFn=wrapped;return wrapped}EventEmitter.prototype.once=function once(type,listener){if(typeof listener!=="function")throw new TypeError('"listener" argument must be a function');this.on(type,_onceWrap(this,type,listener));return this};EventEmitter.prototype.prependOnceListener=function prependOnceListener(type,listener){if(typeof listener!=="function")throw new TypeError('"listener" argument must be a function');this.prependListener(type,_onceWrap(this,type,listener));return this};EventEmitter.prototype.removeListener=function removeListener(type,listener){var list,events,position,i,originalListener;if(typeof listener!=="function")throw new TypeError('"listener" argument must be a function');events=this._events;if(!events)return this;list=events[type];if(!list)return this;if(list===listener||list.listener===listener){if(--this._eventsCount===0)this._events=objectCreate(null);else{delete events[type];if(events.removeListener)this.emit("removeListener",type,list.listener||listener)}}else if(typeof list!=="function"){position=-1;for(i=list.length-1;i>=0;i--){if(list[i]===listener||list[i].listener===listener){originalListener=list[i].listener;position=i;break}}if(position<0)return this;if(position===0)list.shift();else spliceOne(list,position);if(list.length===1)events[type]=list[0];if(events.removeListener)this.emit("removeListener",type,originalListener||listener)}return this};EventEmitter.prototype.removeAllListeners=function removeAllListeners(type){var listeners,events,i;events=this._events;if(!events)return this;if(!events.removeListener){if(arguments.length===0){this._events=objectCreate(null);this._eventsCount=0}else if(events[type]){if(--this._eventsCount===0)this._events=objectCreate(null);else delete events[type]}return this}if(arguments.length===0){var keys=objectKeys(events);var key;for(i=0;i<keys.length;++i){key=keys[i];if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events=objectCreate(null);this._eventsCount=0;return this}listeners=events[type];if(typeof listeners==="function"){this.removeListener(type,listeners)}else if(listeners){for(i=listeners.length-1;i>=0;i--){this.removeListener(type,listeners[i])}}return this};function _listeners(target,type,unwrap){var events=target._events;if(!events)return[];var evlistener=events[type];if(!evlistener)return[];if(typeof evlistener==="function")return unwrap?[evlistener.listener||evlistener]:[evlistener];return unwrap?unwrapListeners(evlistener):arrayClone(evlistener,evlistener.length)}EventEmitter.prototype.listeners=function listeners(type){return _listeners(this,type,true)};EventEmitter.prototype.rawListeners=function rawListeners(type){return _listeners(this,type,false)};EventEmitter.listenerCount=function(emitter,type){if(typeof emitter.listenerCount==="function"){return emitter.listenerCount(type)}else{return listenerCount.call(emitter,type)}};EventEmitter.prototype.listenerCount=listenerCount;function listenerCount(type){var events=this._events;if(events){var evlistener=events[type];if(typeof evlistener==="function"){return 1}else if(evlistener){return evlistener.length}}return 0}EventEmitter.prototype.eventNames=function eventNames(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};function spliceOne(list,index){for(var i=index,k=i+1,n=list.length;k<n;i+=1,k+=1){list[i]=list[k]}list.pop()}function arrayClone(arr,n){var copy=new Array(n);for(var i=0;i<n;++i){copy[i]=arr[i]}return copy}function unwrapListeners(arr){var ret=new Array(arr.length);for(var i=0;i<ret.length;++i){ret[i]=arr[i].listener||arr[i]}return ret}function objectCreatePolyfill(proto){var F=function F(){};F.prototype=proto;return new F}function objectKeysPolyfill(obj){var keys=[];for(var k in obj){if(Object.prototype.hasOwnProperty.call(obj,k)){keys.push(k)}}return k}function functionBindPolyfill(context){var fn=this;return function(){return fn.apply(context,arguments)}}},{}],35:[function(require,module,exports){(function(global){"use strict";function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}
|
|
33
|
+
/*! https://mths.be/punycode v1.4.1 by @mathias */(function(root){var freeExports=(typeof exports==="undefined"?"undefined":_typeof(exports))=="object"&&exports&&!exports.nodeType&&exports;var freeModule=(typeof module==="undefined"?"undefined":_typeof(module))=="object"&&module&&!module.nodeType&&module;var freeGlobal=(typeof global==="undefined"?"undefined":_typeof(global))=="object"&&global;if(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal||freeGlobal.self===freeGlobal){root=freeGlobal}var punycode,maxInt=2147483647,base=36,tMin=1,tMax=26,skew=38,damp=700,initialBias=72,initialN=128,delimiter="-",regexPunycode=/^xn--/,regexNonASCII=/[^\x20-\x7E]/,regexSeparators=/[\x2E\u3002\uFF0E\uFF61]/g,errors={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},baseMinusTMin=base-tMin,floor=Math.floor,stringFromCharCode=String.fromCharCode,key;function error(type){throw new RangeError(errors[type])}function map(array,fn){var length=array.length;var result=[];while(length--){result[length]=fn(array[length])}return result}function mapDomain(string,fn){var parts=string.split("@");var result="";if(parts.length>1){result=parts[0]+"@";string=parts[1]}string=string.replace(regexSeparators,".");var labels=string.split(".");var encoded=map(labels,fn).join(".");return result+encoded}function ucs2decode(string){var output=[],counter=0,length=string.length,value,extra;while(counter<length){value=string.charCodeAt(counter++);if(value>=55296&&value<=56319&&counter<length){extra=string.charCodeAt(counter++);if((extra&64512)==56320){output.push(((value&1023)<<10)+(extra&1023)+65536)}else{output.push(value);counter--}}else{output.push(value)}}return output}function ucs2encode(array){return map(array,(function(value){var output="";if(value>65535){value-=65536;output+=stringFromCharCode(value>>>10&1023|55296);value=56320|value&1023}output+=stringFromCharCode(value);return output})).join("")}function basicToDigit(codePoint){if(codePoint-48<10){return codePoint-22}if(codePoint-65<26){return codePoint-65}if(codePoint-97<26){return codePoint-97}return base}function digitToBasic(digit,flag){return digit+22+75*(digit<26)-((flag!=0)<<5)}function adapt(delta,numPoints,firstTime){var k=0;delta=firstTime?floor(delta/damp):delta>>1;delta+=floor(delta/numPoints);for(;delta>baseMinusTMin*tMax>>1;k+=base){delta=floor(delta/baseMinusTMin)}return floor(k+(baseMinusTMin+1)*delta/(delta+skew))}function decode(input){var output=[],inputLength=input.length,out,i=0,n=initialN,bias=initialBias,basic,j,index,oldi,w,k,digit,t,baseMinusT;basic=input.lastIndexOf(delimiter);if(basic<0){basic=0}for(j=0;j<basic;++j){if(input.charCodeAt(j)>=128){error("not-basic")}output.push(input.charCodeAt(j))}for(index=basic>0?basic+1:0;index<inputLength;){for(oldi=i,w=1,k=base;;k+=base){if(index>=inputLength){error("invalid-input")}digit=basicToDigit(input.charCodeAt(index++));if(digit>=base||digit>floor((maxInt-i)/w)){error("overflow")}i+=digit*w;t=k<=bias?tMin:k>=bias+tMax?tMax:k-bias;if(digit<t){break}baseMinusT=base-t;if(w>floor(maxInt/baseMinusT)){error("overflow")}w*=baseMinusT}out=output.length+1;bias=adapt(i-oldi,out,oldi==0);if(floor(i/out)>maxInt-n){error("overflow")}n+=floor(i/out);i%=out;output.splice(i++,0,n)}return ucs2encode(output)}function encode(input){var n,delta,handledCPCount,basicLength,bias,j,m,q,k,t,currentValue,output=[],inputLength,handledCPCountPlusOne,baseMinusT,qMinusT;input=ucs2decode(input);inputLength=input.length;n=initialN;delta=0;bias=initialBias;for(j=0;j<inputLength;++j){currentValue=input[j];if(currentValue<128){output.push(stringFromCharCode(currentValue))}}handledCPCount=basicLength=output.length;if(basicLength){output.push(delimiter)}while(handledCPCount<inputLength){for(m=maxInt,j=0;j<inputLength;++j){currentValue=input[j];if(currentValue>=n&¤tValue<m){m=currentValue}}handledCPCountPlusOne=handledCPCount+1;if(m-n>floor((maxInt-delta)/handledCPCountPlusOne)){error("overflow")}delta+=(m-n)*handledCPCountPlusOne;n=m;for(j=0;j<inputLength;++j){currentValue=input[j];if(currentValue<n&&++delta>maxInt){error("overflow")}if(currentValue==n){for(q=delta,k=base;;k+=base){t=k<=bias?tMin:k>=bias+tMax?tMax:k-bias;if(q<t){break}qMinusT=q-t;baseMinusT=base-t;output.push(stringFromCharCode(digitToBasic(t+qMinusT%baseMinusT,0)));q=floor(qMinusT/baseMinusT)}output.push(stringFromCharCode(digitToBasic(q,0)));bias=adapt(delta,handledCPCountPlusOne,handledCPCount==basicLength);delta=0;++handledCPCount}}++delta;++n}return output.join("")}function toUnicode(input){return mapDomain(input,(function(string){return regexPunycode.test(string)?decode(string.slice(4).toLowerCase()):string}))}function toASCII(input){return mapDomain(input,(function(string){return regexNonASCII.test(string)?"xn--"+encode(string):string}))}punycode={version:"1.4.1",ucs2:{decode:ucs2decode,encode:ucs2encode},decode:decode,encode:encode,toASCII:toASCII,toUnicode:toUnicode};if(typeof define=="function"&&_typeof(define.amd)=="object"&&define.amd){define("punycode",(function(){return punycode}))}else if(freeExports&&freeModule){if(module.exports==freeExports){freeModule.exports=punycode}else{for(key in punycode){punycode.hasOwnProperty(key)&&(freeExports[key]=punycode[key])}}}else{root.punycode=punycode}})(void 0)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],36:[function(require,module,exports){(function(Buffer){"use strict";(function(){"use strict";function btoa(str){var buffer;if(str instanceof Buffer){buffer=str}else{buffer=Buffer.from(str.toString(),"binary")}return buffer.toString("base64")}module.exports=btoa})()}).call(this,require("buffer").Buffer)},{buffer:33}],37:[function(require,module,exports){(function(Buffer){"use strict";function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}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":121}],38:[function(require,module,exports){"use strict";var isValue=require("type/value/is"),ensureValue=require("type/value/ensure"),ensurePlainFunction=require("type/plain-function/ensure"),copy=require("es5-ext/object/copy"),normalizeOptions=require("es5-ext/object/normalize-options"),map=require("es5-ext/object/map");var bind=Function.prototype.bind,defineProperty=Object.defineProperty,hasOwnProperty=Object.prototype.hasOwnProperty,define;define=function define(name,desc,options){var value=ensureValue(desc)&&ensurePlainFunction(desc.value),dgs;dgs=copy(desc);delete dgs.writable;delete dgs.value;dgs.get=function(){if(!options.overwriteDefinition&&hasOwnProperty.call(this,name))return value;desc.value=bind.call(value,options.resolveContext?options.resolveContext(this):this);defineProperty(this,name,desc);return this[name]};return dgs};module.exports=function(props){var options=normalizeOptions(arguments[1]);if(isValue(options.resolveContext))ensurePlainFunction(options.resolveContext);return map(props,(function(desc,name){return define(name,desc,options)}))}},{"es5-ext/object/copy":73,"es5-ext/object/map":81,"es5-ext/object/normalize-options":82,"type/plain-function/ensure":187,"type/value/ensure":191,"type/value/is":192}],39:[function(require,module,exports){"use strict";var isValue=require("type/value/is"),isPlainFunction=require("type/plain-function/is"),assign=require("es5-ext/object/assign"),normalizeOpts=require("es5-ext/object/normalize-options"),contains=require("es5-ext/string/#/contains");var d=module.exports=function(dscr,value){var c,e,w,options,desc;if(arguments.length<2||typeof dscr!=="string"){options=value;value=dscr;dscr=null}else{options=arguments[2]}if(isValue(dscr)){c=contains.call(dscr,"c");e=contains.call(dscr,"e");w=contains.call(dscr,"w")}else{c=w=true;e=false}desc={value:value,configurable:c,enumerable:e,writable:w};return!options?desc:assign(normalizeOpts(options),desc)};d.gs=function(dscr,get,set){var c,e,options,desc;if(typeof dscr!=="string"){options=set;set=get;get=dscr;dscr=null}else{options=arguments[3]}if(!isValue(get)){get=undefined}else if(!isPlainFunction(get)){options=get;get=set=undefined}else if(!isValue(set)){set=undefined}else if(!isPlainFunction(set)){options=set;set=undefined}if(isValue(dscr)){c=contains.call(dscr,"c");e=contains.call(dscr,"e")}else{c=true;e=false}desc={get:get,set:set,configurable:c,enumerable:e};return!options?desc:assign(normalizeOpts(options),desc)}},{"es5-ext/object/assign":70,"es5-ext/object/normalize-options":82,"es5-ext/string/#/contains":89,"type/plain-function/is":188,"type/value/is":192}],40:[function(require,module,exports){(function(process,Buffer){"use strict";var stream=require("readable-stream");var eos=require("end-of-stream");var inherits=require("inherits");var shift=require("stream-shift");var SIGNAL_FLUSH=Buffer.from&&Buffer.from!==Uint8Array.from?Buffer.from([0]):new Buffer([0]);var onuncork=function onuncork(self,fn){if(self._corked)self.once("uncork",fn);else fn()};var autoDestroy=function autoDestroy(self,err){if(self._autoDestroy)self.destroy(err)};var destroyer=function destroyer(self,end){return function(err){if(err)autoDestroy(self,err.message==="premature close"?null:err);else if(end&&!self._ended)self.end()}};var end=function end(ws,fn){if(!ws)return fn();if(ws._writableState&&ws._writableState.finished)return fn();if(ws._writableState)return ws.end(fn);ws.end();fn()};var toStreams2=function toStreams2(rs){return new stream.Readable({objectMode:true,highWaterMark:16}).wrap(rs)};var Duplexify=function Duplexify(writable,readable,opts){if(!(this instanceof Duplexify))return new Duplexify(writable,readable,opts);stream.Duplex.call(this,opts);this._writable=null;this._readable=null;this._readable2=null;this._autoDestroy=!opts||opts.autoDestroy!==false;this._forwardDestroy=!opts||opts.destroy!==false;this._forwardEnd=!opts||opts.end!==false;this._corked=1;this._ondrain=null;this._drained=false;this._forwarding=false;this._unwrite=null;this._unread=null;this._ended=false;this.destroyed=false;if(writable)this.setWritable(writable);if(readable)this.setReadable(readable)};inherits(Duplexify,stream.Duplex);Duplexify.obj=function(writable,readable,opts){if(!opts)opts={};opts.objectMode=true;opts.highWaterMark=16;return new Duplexify(writable,readable,opts)};Duplexify.prototype.cork=function(){if(++this._corked===1)this.emit("cork")};Duplexify.prototype.uncork=function(){if(this._corked&&--this._corked===0)this.emit("uncork")};Duplexify.prototype.setWritable=function(writable){if(this._unwrite)this._unwrite();if(this.destroyed){if(writable&&writable.destroy)writable.destroy();return}if(writable===null||writable===false){this.end();return}var self=this;var unend=eos(writable,{writable:true,readable:false},destroyer(this,this._forwardEnd));var ondrain=function ondrain(){var ondrain=self._ondrain;self._ondrain=null;if(ondrain)ondrain()};var clear=function clear(){self._writable.removeListener("drain",ondrain);unend()};if(this._unwrite)process.nextTick(ondrain);this._writable=writable;this._writable.on("drain",ondrain);this._unwrite=clear;this.uncork()};Duplexify.prototype.setReadable=function(readable){if(this._unread)this._unread();if(this.destroyed){if(readable&&readable.destroy)readable.destroy();return}if(readable===null||readable===false){this.push(null);this.resume();return}var self=this;var unend=eos(readable,{writable:false,readable:true},destroyer(this));var onreadable=function onreadable(){self._forward()};var onend=function onend(){self.push(null)};var clear=function clear(){self._readable2.removeListener("readable",onreadable);self._readable2.removeListener("end",onend);unend()};this._drained=true;this._readable=readable;this._readable2=readable._readableState?readable:toStreams2(readable);this._readable2.on("readable",onreadable);this._readable2.on("end",onend);this._unread=clear;this._forward()};Duplexify.prototype._read=function(){this._drained=true;this._forward()};Duplexify.prototype._forward=function(){if(this._forwarding||!this._readable2||!this._drained)return;this._forwarding=true;var data;while(this._drained&&(data=shift(this._readable2))!==null){if(this.destroyed)continue;this._drained=this.push(data)}this._forwarding=false};Duplexify.prototype.destroy=function(err){if(this.destroyed)return;this.destroyed=true;var self=this;process.nextTick((function(){self._destroy(err)}))};Duplexify.prototype._destroy=function(err){if(err){var ondrain=this._ondrain;this._ondrain=null;if(ondrain)ondrain(err);else this.emit("error",err)}if(this._forwardDestroy){if(this._readable&&this._readable.destroy)this._readable.destroy();if(this._writable&&this._writable.destroy)this._writable.destroy()}this.emit("close")};Duplexify.prototype._write=function(data,enc,cb){if(this.destroyed)return cb();if(this._corked)return onuncork(this,this._write.bind(this,data,enc,cb));if(data===SIGNAL_FLUSH)return this._finish(cb);if(!this._writable)return cb();if(this._writable.write(data)===false)this._ondrain=cb;else cb()};Duplexify.prototype._finish=function(cb){var self=this;this.emit("preend");onuncork(this,(function(){end(self._forwardEnd&&self._writable,(function(){if(self._writableState.prefinished===false)self._writableState.prefinished=true;self.emit("prefinish");onuncork(self,cb)}))}))};Duplexify.prototype.end=function(data,enc,cb){if(typeof data==="function")return this.end(null,null,data);if(typeof enc==="function")return this.end(data,null,enc);this._ended=true;if(data)this.write(data);if(!this._writableState.ending)this.write(SIGNAL_FLUSH);return stream.Writable.prototype.end.call(this,cb)};module.exports=Duplexify}).call(this,require("_process"),require("buffer").Buffer)},{_process:157,buffer:33,"end-of-stream":52,inherits:120,"readable-stream":49,"stream-shift":178}],41:[function(require,module,exports){"use strict";var pna=require("process-nextick-args");var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj){keys.push(key)}return keys};module.exports=Duplex;var util=Object.create(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)}Object.defineProperty(Duplex.prototype,"writableHighWaterMark",{enumerable:false,get:function get(){return this._writableState.highWaterMark}});function onend(){if(this.allowHalfOpen||this._writableState.ended)return;pna.nextTick(onEndNT,this)}function onEndNT(self){self.end()}Object.defineProperty(Duplex.prototype,"destroyed",{get:function get(){if(this._readableState===undefined||this._writableState===undefined){return false}return this._readableState.destroyed&&this._writableState.destroyed},set:function set(value){if(this._readableState===undefined||this._writableState===undefined){return}this._readableState.destroyed=value;this._writableState.destroyed=value}});Duplex.prototype._destroy=function(err,cb){this.push(null);this.end();pna.nextTick(cb,err)}},{"./_stream_readable":43,"./_stream_writable":45,"core-util-is":37,inherits:120,"process-nextick-args":156}],42:[function(require,module,exports){"use strict";module.exports=PassThrough;var Transform=require("./_stream_transform");var util=Object.create(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":44,"core-util-is":37,inherits:120}],43:[function(require,module,exports){(function(process,global){"use strict";var pna=require("process-nextick-args");module.exports=Readable;var isArray=require("isarray");var Duplex;Readable.ReadableState=ReadableState;var EE=require("events").EventEmitter;var EElistenerCount=function EElistenerCount(emitter,type){return emitter.listeners(type).length};var Stream=require("./internal/streams/stream");var Buffer=require("safe-buffer").Buffer;var OurUint8Array=global.Uint8Array||function(){};function _uint8ArrayToBuffer(chunk){return Buffer.from(chunk)}function _isUint8Array(obj){return Buffer.isBuffer(obj)||obj instanceof OurUint8Array}var util=Object.create(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 debug(){}}var BufferList=require("./internal/streams/BufferList");var destroyImpl=require("./internal/streams/destroy");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);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||{};var isDuplex=stream instanceof Duplex;this.objectMode=!!options.objectMode;if(isDuplex)this.objectMode=this.objectMode||!!options.readableObjectMode;var hwm=options.highWaterMark;var readableHwm=options.readableHighWaterMark;var defaultHwm=this.objectMode?16:16*1024;if(hwm||hwm===0)this.highWaterMark=hwm;else if(isDuplex&&(readableHwm||readableHwm===0))this.highWaterMark=readableHwm;else this.highWaterMark=defaultHwm;this.highWaterMark=Math.floor(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.destroyed=false;this.defaultEncoding=options.defaultEncoding||"utf8";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){if(typeof options.read==="function")this._read=options.read;if(typeof options.destroy==="function")this._destroy=options.destroy}Stream.call(this)}Object.defineProperty(Readable.prototype,"destroyed",{get:function get(){if(this._readableState===undefined){return false}return this._readableState.destroyed},set:function set(value){if(!this._readableState){return}this._readableState.destroyed=value}});Readable.prototype.destroy=destroyImpl.destroy;Readable.prototype._undestroy=destroyImpl.undestroy;Readable.prototype._destroy=function(err,cb){this.push(null);cb(err)};Readable.prototype.push=function(chunk,encoding){var state=this._readableState;var skipChunkCheck;if(!state.objectMode){if(typeof chunk==="string"){encoding=encoding||state.defaultEncoding;if(encoding!==state.encoding){chunk=Buffer.from(chunk,encoding);encoding=""}skipChunkCheck=true}}else{skipChunkCheck=true}return readableAddChunk(this,chunk,encoding,false,skipChunkCheck)};Readable.prototype.unshift=function(chunk){return readableAddChunk(this,chunk,null,true,false)};function readableAddChunk(stream,chunk,encoding,addToFront,skipChunkCheck){var state=stream._readableState;if(chunk===null){state.reading=false;onEofChunk(stream,state)}else{var er;if(!skipChunkCheck)er=chunkInvalid(state,chunk);if(er){stream.emit("error",er)}else if(state.objectMode||chunk&&chunk.length>0){if(typeof chunk!=="string"&&!state.objectMode&&Object.getPrototypeOf(chunk)!==Buffer.prototype){chunk=_uint8ArrayToBuffer(chunk)}if(addToFront){if(state.endEmitted)stream.emit("error",new Error("stream.unshift() after end event"));else addChunk(stream,state,chunk,true)}else if(state.ended){stream.emit("error",new Error("stream.push() after EOF"))}else{state.reading=false;if(state.decoder&&!encoding){chunk=state.decoder.write(chunk);if(state.objectMode||chunk.length!==0)addChunk(stream,state,chunk,false);else maybeReadMore(stream,state)}else{addChunk(stream,state,chunk,false)}}}else if(!addToFront){state.reading=false}}return needMoreData(state)}function addChunk(stream,state,chunk,addToFront){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)}function chunkInvalid(state,chunk){var er;if(!_isUint8Array(chunk)&&typeof chunk!=="string"&&chunk!==undefined&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}return er}function needMoreData(state){return!state.ended&&(state.needReadable||state.length<state.highWaterMark||state.length===0)}Readable.prototype.isPaused=function(){return this._readableState.flowing===false};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 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)pna.nextTick(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;pna.nextTick(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:unpipe;if(state.endEmitted)pna.nextTick(endFn);else src.once("end",endFn);dest.on("unpipe",onunpipe);function onunpipe(readable,unpipeInfo){debug("onunpipe");if(readable===src){if(unpipeInfo&&unpipeInfo.hasUnpiped===false){unpipeInfo.hasUnpiped=true;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",unpipe);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;var unpipeInfo={hasUnpiped:false};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,unpipeInfo);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,unpipeInfo)}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,unpipeInfo);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){pna.nextTick(nReadingNextTick,this)}else if(state.length){emitReadable(this)}}}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;pna.nextTick(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 _this=this;var state=this._readableState;var paused=false;stream.on("end",(function(){debug("wrapped end");if(state.decoder&&!state.ended){var chunk=state.decoder.end();if(chunk&&chunk.length)_this.push(chunk)}_this.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=_this.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],this.emit.bind(this,kProxyEvents[n]))}this._read=function(n){debug("wrapped _read",n);if(paused){paused=false;stream.resume()}};return this};Object.defineProperty(Readable.prototype,"readableHighWaterMark",{enumerable:false,get:function get(){return this._readableState.highWaterMark}});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=Buffer.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;pna.nextTick(endReadableNT,state,stream)}}function endReadableNT(state,stream){if(!state.endEmitted&&state.length===0){state.endEmitted=true;stream.readable=false;stream.emit("end")}}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"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./_stream_duplex":41,"./internal/streams/BufferList":46,"./internal/streams/destroy":47,"./internal/streams/stream":48,_process:157,"core-util-is":37,events:34,inherits:120,isarray:122,"process-nextick-args":156,"safe-buffer":50,"string_decoder/":51,util:31}],44:[function(require,module,exports){"use strict";module.exports=Transform;var Duplex=require("./_stream_duplex");var util=Object.create(require("core-util-is"));util.inherits=require("inherits");util.inherits(Transform,Duplex);function afterTransform(er,data){var ts=this._transformState;ts.transforming=false;var cb=ts.writecb;if(!cb){return this.emit("error",new Error("write callback called multiple times"))}ts.writechunk=null;ts.writecb=null;if(data!=null)this.push(data);cb(er);var rs=this._readableState;rs.reading=false;if(rs.needReadable||rs.length<rs.highWaterMark){this._read(rs.highWaterMark)}}function Transform(options){if(!(this instanceof Transform))return new Transform(options);Duplex.call(this,options);this._transformState={afterTransform:afterTransform.bind(this),needTransform:false,transforming:false,writecb:null,writechunk:null,writeencoding:null};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.on("prefinish",prefinish)}function prefinish(){var _this=this;if(typeof this._flush==="function"){this._flush((function(er,data){done(_this,er,data)}))}else{done(this,null,null)}}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}};Transform.prototype._destroy=function(err,cb){var _this2=this;Duplex.prototype._destroy.call(this,err,(function(err2){cb(err2);_this2.emit("close")}))};function done(stream,er,data){if(er)return stream.emit("error",er);if(data!=null)stream.push(data);if(stream._writableState.length)throw new Error("Calling transform done when ws.length != 0");if(stream._transformState.transforming)throw new Error("Calling transform done when still transforming");return stream.push(null)}},{"./_stream_duplex":41,"core-util-is":37,inherits:120}],45:[function(require,module,exports){(function(process,global,setImmediate){"use strict";var pna=require("process-nextick-args");module.exports=Writable;function WriteReq(chunk,encoding,cb){this.chunk=chunk;this.encoding=encoding;this.callback=cb;this.next=null}function CorkedRequest(state){var _this=this;this.next=null;this.entry=null;this.finish=function(){onCorkedFinish(_this,state)}}var asyncWrite=!process.browser&&["v0.10","v0.9."].indexOf(process.version.slice(0,5))>-1?setImmediate:pna.nextTick;var Duplex;Writable.WritableState=WritableState;var util=Object.create(require("core-util-is"));util.inherits=require("inherits");var internalUtil={deprecate:require("util-deprecate")};var Stream=require("./internal/streams/stream");var Buffer=require("safe-buffer").Buffer;var OurUint8Array=global.Uint8Array||function(){};function _uint8ArrayToBuffer(chunk){return Buffer.from(chunk)}function _isUint8Array(obj){return Buffer.isBuffer(obj)||obj instanceof OurUint8Array}var destroyImpl=require("./internal/streams/destroy");util.inherits(Writable,Stream);function nop(){}function WritableState(options,stream){Duplex=Duplex||require("./_stream_duplex");options=options||{};var isDuplex=stream instanceof Duplex;this.objectMode=!!options.objectMode;if(isDuplex)this.objectMode=this.objectMode||!!options.writableObjectMode;var hwm=options.highWaterMark;var writableHwm=options.writableHighWaterMark;var defaultHwm=this.objectMode?16:16*1024;if(hwm||hwm===0)this.highWaterMark=hwm;else if(isDuplex&&(writableHwm||writableHwm===0))this.highWaterMark=writableHwm;else this.highWaterMark=defaultHwm;this.highWaterMark=Math.floor(this.highWaterMark);this.finalCalled=false;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;this.destroyed=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.","DEP0003")})}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 value(object){if(realHasInstance.call(this,object))return true;if(this!==Writable)return false;return object&&object._writableState instanceof WritableState}})}else{realHasInstance=function realHasInstance(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;if(typeof options.destroy==="function")this._destroy=options.destroy;if(typeof options["final"]==="function")this._final=options["final"]}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);pna.nextTick(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);pna.nextTick(cb,er);valid=false}return valid}Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState;var ret=false;var isBuf=!state.objectMode&&_isUint8Array(chunk);if(isBuf&&!Buffer.isBuffer(chunk)){chunk=_uint8ArrayToBuffer(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=Buffer.from(chunk,encoding)}return chunk}Object.defineProperty(Writable.prototype,"writableHighWaterMark",{enumerable:false,get:function get(){return this._writableState.highWaterMark}});function writeOrBuffer(stream,state,isBuf,chunk,encoding,cb){if(!isBuf){var newChunk=decodeChunk(state,chunk,encoding);if(chunk!==newChunk){isBuf=true;encoding="buffer";chunk=newChunk}}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={chunk:chunk,encoding:encoding,isBuf:isBuf,callback:cb,next:null};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){pna.nextTick(cb,er);pna.nextTick(finishMaybe,stream,state);stream._writableState.errorEmitted=true;stream.emit("error",er)}else{cb(er);stream._writableState.errorEmitted=true;stream.emit("error",er);finishMaybe(stream,state)}}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;var allBuffers=true;while(entry){buffer[count]=entry;if(!entry.isBuf)allBuffers=false;entry=entry.next;count+=1}buffer.allBuffers=allBuffers;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)}state.bufferedRequestCount=0}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;state.bufferedRequestCount--;if(state.writing){break}}if(entry===null)state.lastBufferedRequest=null}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 callFinal(stream,state){stream._final((function(err){state.pendingcb--;if(err){stream.emit("error",err)}state.prefinished=true;stream.emit("prefinish");finishMaybe(stream,state)}))}function prefinish(stream,state){if(!state.prefinished&&!state.finalCalled){if(typeof stream._final==="function"){state.pendingcb++;state.finalCalled=true;pna.nextTick(callFinal,stream,state)}else{state.prefinished=true;stream.emit("prefinish")}}}function finishMaybe(stream,state){var need=needFinish(state);if(need){prefinish(stream,state);if(state.pendingcb===0){state.finished=true;stream.emit("finish")}}return need}function endWritable(stream,state,cb){state.ending=true;finishMaybe(stream,state);if(cb){if(state.finished)pna.nextTick(cb);else stream.once("finish",cb)}state.ended=true;stream.writable=false}function onCorkedFinish(corkReq,state,err){var entry=corkReq.entry;corkReq.entry=null;while(entry){var cb=entry.callback;state.pendingcb--;cb(err);entry=entry.next}if(state.corkedRequestsFree){state.corkedRequestsFree.next=corkReq}else{state.corkedRequestsFree=corkReq}}Object.defineProperty(Writable.prototype,"destroyed",{get:function get(){if(this._writableState===undefined){return false}return this._writableState.destroyed},set:function set(value){if(!this._writableState){return}this._writableState.destroyed=value}});Writable.prototype.destroy=destroyImpl.destroy;Writable.prototype._undestroy=destroyImpl.undestroy;Writable.prototype._destroy=function(err,cb){this.end();cb(err)}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},require("timers").setImmediate)},{"./_stream_duplex":41,"./internal/streams/destroy":47,"./internal/streams/stream":48,_process:157,"core-util-is":37,inherits:120,"process-nextick-args":156,"safe-buffer":50,timers:180,"util-deprecate":195}],46:[function(require,module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var Buffer=require("safe-buffer").Buffer;var util=require("util");function copyBuffer(src,target,offset){src.copy(target,offset)}module.exports=function(){function BufferList(){_classCallCheck(this,BufferList);this.head=null;this.tail=null;this.length=0}BufferList.prototype.push=function push(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 unshift(v){var entry={data:v,next:this.head};if(this.length===0)this.tail=entry;this.head=entry;++this.length};BufferList.prototype.shift=function shift(){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 clear(){this.head=this.tail=null;this.length=0};BufferList.prototype.join=function join(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 concat(n){if(this.length===0)return Buffer.alloc(0);if(this.length===1)return this.head.data;var ret=Buffer.allocUnsafe(n>>>0);var p=this.head;var i=0;while(p){copyBuffer(p.data,ret,i);i+=p.data.length;p=p.next}return ret};return BufferList}();if(util&&util.inspect&&util.inspect.custom){module.exports.prototype[util.inspect.custom]=function(){var obj=util.inspect({length:this.length});return this.constructor.name+" "+obj}}},{"safe-buffer":50,util:31}],47:[function(require,module,exports){"use strict";var pna=require("process-nextick-args");function destroy(err,cb){var _this=this;var readableDestroyed=this._readableState&&this._readableState.destroyed;var writableDestroyed=this._writableState&&this._writableState.destroyed;if(readableDestroyed||writableDestroyed){if(cb){cb(err)}else if(err&&(!this._writableState||!this._writableState.errorEmitted)){pna.nextTick(emitErrorNT,this,err)}return this}if(this._readableState){this._readableState.destroyed=true}if(this._writableState){this._writableState.destroyed=true}this._destroy(err||null,(function(err){if(!cb&&err){pna.nextTick(emitErrorNT,_this,err);if(_this._writableState){_this._writableState.errorEmitted=true}}else if(cb){cb(err)}}));return this}function undestroy(){if(this._readableState){this._readableState.destroyed=false;this._readableState.reading=false;this._readableState.ended=false;this._readableState.endEmitted=false}if(this._writableState){this._writableState.destroyed=false;this._writableState.ended=false;this._writableState.ending=false;this._writableState.finished=false;this._writableState.errorEmitted=false}}function emitErrorNT(self,err){self.emit("error",err)}module.exports={destroy:destroy,undestroy:undestroy}},{"process-nextick-args":156}],48:[function(require,module,exports){"use strict";module.exports=require("events").EventEmitter},{events:34}],49:[function(require,module,exports){"use strict";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":41,"./lib/_stream_passthrough.js":42,"./lib/_stream_readable.js":43,"./lib/_stream_transform.js":44,"./lib/_stream_writable.js":45}],50:[function(require,module,exports){"use strict";var buffer=require("buffer");var Buffer=buffer.Buffer;function copyProps(src,dst){for(var key in src){dst[key]=src[key]}}if(Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow){module.exports=buffer}else{copyProps(buffer,exports);exports.Buffer=SafeBuffer}function SafeBuffer(arg,encodingOrOffset,length){return Buffer(arg,encodingOrOffset,length)}copyProps(Buffer,SafeBuffer);SafeBuffer.from=function(arg,encodingOrOffset,length){if(typeof arg==="number"){throw new TypeError("Argument must not be a number")}return Buffer(arg,encodingOrOffset,length)};SafeBuffer.alloc=function(size,fill,encoding){if(typeof size!=="number"){throw new TypeError("Argument must be a number")}var buf=Buffer(size);if(fill!==undefined){if(typeof encoding==="string"){buf.fill(fill,encoding)}else{buf.fill(fill)}}else{buf.fill(0)}return buf};SafeBuffer.allocUnsafe=function(size){if(typeof size!=="number"){throw new TypeError("Argument must be a number")}return Buffer(size)};SafeBuffer.allocUnsafeSlow=function(size){if(typeof size!=="number"){throw new TypeError("Argument must be a number")}return buffer.SlowBuffer(size)}},{buffer:33}],51:[function(require,module,exports){"use strict";var Buffer=require("safe-buffer").Buffer;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=Buffer.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 _byte>>6===2?-1:-2}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||nb===-2)return 0;nb=utf8CheckByte(buf[j]);if(nb>=0){if(nb>0)self.lastNeed=nb-2;return nb}if(--j<i||nb===-2)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"�"}if(self.lastNeed>1&&buf.length>1){if((buf[1]&192)!==128){self.lastNeed=1;return"�"}if(self.lastNeed>2&&buf.length>2){if((buf[2]&192)!==128){self.lastNeed=2;return"�"}}}}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+"�";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):""}},{"safe-buffer":50}],52:[function(require,module,exports){(function(process){"use strict";var once=require("once");var noop=function noop(){};var isRequest=function isRequest(stream){return stream.setHeader&&typeof stream.abort==="function"};var isChildProcess=function isChildProcess(stream){return stream.stdio&&Array.isArray(stream.stdio)&&stream.stdio.length===3};var eos=function eos(stream,opts,callback){if(typeof opts==="function")return eos(stream,null,opts);if(!opts)opts={};callback=once(callback||noop);var ws=stream._writableState;var rs=stream._readableState;var readable=opts.readable||opts.readable!==false&&stream.readable;var writable=opts.writable||opts.writable!==false&&stream.writable;var cancelled=false;var onlegacyfinish=function onlegacyfinish(){if(!stream.writable)onfinish()};var onfinish=function onfinish(){writable=false;if(!readable)callback.call(stream)};var onend=function onend(){readable=false;if(!writable)callback.call(stream)};var onexit=function onexit(exitCode){callback.call(stream,exitCode?new Error("exited with error code: "+exitCode):null)};var onerror=function onerror(err){callback.call(stream,err)};var onclose=function onclose(){process.nextTick(onclosenexttick)};var onclosenexttick=function onclosenexttick(){if(cancelled)return;if(readable&&!(rs&&rs.ended&&!rs.destroyed))return callback.call(stream,new Error("premature close"));if(writable&&!(ws&&ws.ended&&!ws.destroyed))return callback.call(stream,new Error("premature close"))};var onrequest=function onrequest(){stream.req.on("finish",onfinish)};if(isRequest(stream)){stream.on("complete",onfinish);stream.on("abort",onclose);if(stream.req)onrequest();else stream.on("request",onrequest)}else if(writable&&!ws){stream.on("end",onlegacyfinish);stream.on("close",onlegacyfinish)}if(isChildProcess(stream))stream.on("exit",onexit);stream.on("end",onend);stream.on("finish",onfinish);if(opts.error!==false)stream.on("error",onerror);stream.on("close",onclose);return function(){cancelled=true;stream.removeListener("complete",onfinish);stream.removeListener("abort",onclose);stream.removeListener("request",onrequest);if(stream.req)stream.req.removeListener("finish",onfinish);stream.removeListener("end",onlegacyfinish);stream.removeListener("close",onlegacyfinish);stream.removeListener("finish",onfinish);stream.removeListener("exit",onexit);stream.removeListener("end",onend);stream.removeListener("error",onerror);stream.removeListener("close",onclose)}};module.exports=eos}).call(this,require("_process"))},{_process:157,once:155}],53:[function(require,module,exports){"use strict";var value=require("../../object/valid-value");module.exports=function(){value(this).length=0;return this}},{"../../object/valid-value":88}],54:[function(require,module,exports){"use strict";var numberIsNaN=require("../../number/is-nan"),toPosInt=require("../../number/to-pos-integer"),value=require("../../object/valid-value"),indexOf=Array.prototype.indexOf,objHasOwnProperty=Object.prototype.hasOwnProperty,abs=Math.abs,floor=Math.floor;module.exports=function(searchElement){var i,length,fromIndex,val;if(!numberIsNaN(searchElement))return indexOf.apply(this,arguments);length=toPosInt(value(this).length);fromIndex=arguments[1];if(isNaN(fromIndex))fromIndex=0;else if(fromIndex>=0)fromIndex=floor(fromIndex);else fromIndex=toPosInt(this.length)-floor(abs(fromIndex));for(i=fromIndex;i<length;++i){if(objHasOwnProperty.call(this,i)){val=this[i];if(numberIsNaN(val))return i}}return-1}},{"../../number/is-nan":64,"../../number/to-pos-integer":68,"../../object/valid-value":88}],55:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?Array.from:require("./shim")},{"./is-implemented":56,"./shim":57}],56:[function(require,module,exports){"use strict";module.exports=function(){var from=Array.from,arr,result;if(typeof from!=="function")return false;arr=["raz","dwa"];result=from(arr);return Boolean(result&&result!==arr&&result[1]==="dwa")}},{}],57:[function(require,module,exports){"use strict";var iteratorSymbol=require("es6-symbol").iterator,isArguments=require("../../function/is-arguments"),isFunction=require("../../function/is-function"),toPosInt=require("../../number/to-pos-integer"),callable=require("../../object/valid-callable"),validValue=require("../../object/valid-value"),isValue=require("../../object/is-value"),isString=require("../../string/is-string"),isArray=Array.isArray,call=Function.prototype.call,desc={configurable:true,enumerable:true,writable:true,value:null},defineProperty=Object.defineProperty;module.exports=function(arrayLike){var mapFn=arguments[1],thisArg=arguments[2],Context,i,j,arr,length,code,iterator,result,getIterator,value;arrayLike=Object(validValue(arrayLike));if(isValue(mapFn))callable(mapFn);if(!this||this===Array||!isFunction(this)){if(!mapFn){if(isArguments(arrayLike)){length=arrayLike.length;if(length!==1)return Array.apply(null,arrayLike);arr=new Array(1);arr[0]=arrayLike[0];return arr}if(isArray(arrayLike)){arr=new Array(length=arrayLike.length);for(i=0;i<length;++i){arr[i]=arrayLike[i]}return arr}}arr=[]}else{Context=this}if(!isArray(arrayLike)){if((getIterator=arrayLike[iteratorSymbol])!==undefined){iterator=callable(getIterator).call(arrayLike);if(Context)arr=new Context;result=iterator.next();i=0;while(!result.done){value=mapFn?call.call(mapFn,thisArg,result.value,i):result.value;if(Context){desc.value=value;defineProperty(arr,i,desc)}else{arr[i]=value}result=iterator.next();++i}length=i}else if(isString(arrayLike)){length=arrayLike.length;if(Context)arr=new Context;for(i=0,j=0;i<length;++i){value=arrayLike[i];if(i+1<length){code=value.charCodeAt(0);if(code>=55296&&code<=56319)value+=arrayLike[++i]}value=mapFn?call.call(mapFn,thisArg,value,j):value;if(Context){desc.value=value;defineProperty(arr,j,desc)}else{arr[j]=value}++j}length=j}}if(length===undefined){length=toPosInt(arrayLike.length);if(Context)arr=new Context(length);for(i=0;i<length;++i){value=mapFn?call.call(mapFn,thisArg,arrayLike[i],i):arrayLike[i];if(Context){desc.value=value;defineProperty(arr,i,desc)}else{arr[i]=value}}}if(Context){desc.value=null;arr.length=length}return arr}},{"../../function/is-arguments":58,"../../function/is-function":59,"../../number/to-pos-integer":68,"../../object/is-value":77,"../../object/valid-callable":87,"../../object/valid-value":88,"../../string/is-string":92,"es6-symbol":106}],58:[function(require,module,exports){"use strict";var objToString=Object.prototype.toString,id=objToString.call(function(){return arguments}());module.exports=function(value){return objToString.call(value)===id}},{}],59:[function(require,module,exports){"use strict";var objToString=Object.prototype.toString,isFunctionStringTag=RegExp.prototype.test.bind(/^[object [A-Za-z0-9]*Function]$/);module.exports=function(value){return typeof value==="function"&&isFunctionStringTag(objToString.call(value))}},{}],60:[function(require,module,exports){"use strict";module.exports=function(){}},{}],61:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?Math.sign:require("./shim")},{"./is-implemented":62,"./shim":63}],62:[function(require,module,exports){"use strict";module.exports=function(){var sign=Math.sign;if(typeof sign!=="function")return false;return sign(10)===1&&sign(-20)===-1}},{}],63:[function(require,module,exports){"use strict";module.exports=function(value){value=Number(value);if(isNaN(value)||value===0)return value;return value>0?1:-1}},{}],64:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?Number.isNaN:require("./shim")},{"./is-implemented":65,"./shim":66}],65:[function(require,module,exports){"use strict";module.exports=function(){var numberIsNaN=Number.isNaN;if(typeof numberIsNaN!=="function")return false;return!numberIsNaN({})&&numberIsNaN(NaN)&&!numberIsNaN(34)}},{}],66:[function(require,module,exports){"use strict";module.exports=function(value){return value!==value}},{}],67:[function(require,module,exports){"use strict";var sign=require("../math/sign"),abs=Math.abs,floor=Math.floor;module.exports=function(value){if(isNaN(value))return 0;value=Number(value);if(value===0||!isFinite(value))return value;return sign(value)*floor(abs(value))}},{"../math/sign":61}],68:[function(require,module,exports){"use strict";var toInteger=require("./to-integer"),max=Math.max;module.exports=function(value){return max(0,toInteger(value))}},{"./to-integer":67}],69:[function(require,module,exports){"use strict";var callable=require("./valid-callable"),value=require("./valid-value"),bind=Function.prototype.bind,call=Function.prototype.call,keys=Object.keys,objPropertyIsEnumerable=Object.prototype.propertyIsEnumerable;module.exports=function(method,defVal){return function(obj,cb){var list,thisArg=arguments[2],compareFn=arguments[3];obj=Object(value(obj));callable(cb);list=keys(obj);if(compareFn){list.sort(typeof compareFn==="function"?bind.call(compareFn,obj):undefined)}if(typeof method!=="function")method=list[method];return call.call(method,list,(function(key,index){if(!objPropertyIsEnumerable.call(obj,key))return defVal;return call.call(cb,thisArg,obj[key],key,obj,index)}))}}},{"./valid-callable":87,"./valid-value":88}],70:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?Object.assign:require("./shim")},{"./is-implemented":71,"./shim":72}],71:[function(require,module,exports){"use strict";module.exports=function(){var assign=Object.assign,obj;if(typeof assign!=="function")return false;obj={foo:"raz"};assign(obj,{bar:"dwa"},{trzy:"trzy"});return obj.foo+obj.bar+obj.trzy==="razdwatrzy"}},{}],72:[function(require,module,exports){"use strict";var keys=require("../keys"),value=require("../valid-value"),max=Math.max;module.exports=function(dest,src){var error,i,length=max(arguments.length,2),assign;dest=Object(value(dest));assign=function assign(key){try{dest[key]=src[key]}catch(e){if(!error)error=e}};for(i=1;i<length;++i){src=arguments[i];keys(src).forEach(assign)}if(error!==undefined)throw error;return dest}},{"../keys":78,"../valid-value":88}],73:[function(require,module,exports){"use strict";var aFrom=require("../array/from"),assign=require("./assign"),value=require("./valid-value");module.exports=function(obj){var copy=Object(value(obj)),propertyNames=arguments[1],options=Object(arguments[2]);if(copy!==obj&&!propertyNames)return copy;var result={};if(propertyNames){aFrom(propertyNames,(function(propertyName){if(options.ensure||propertyName in obj)result[propertyName]=obj[propertyName]}))}else{assign(result,obj)}return result}},{"../array/from":55,"./assign":70,"./valid-value":88}],74:[function(require,module,exports){"use strict";var create=Object.create,shim;if(!require("./set-prototype-of/is-implemented")()){shim=require("./set-prototype-of/shim")}module.exports=function(){var nullObject,polyProps,desc;if(!shim)return create;if(shim.level!==1)return create;nullObject={};polyProps={};desc={configurable:false,enumerable:false,writable:true,value:undefined};Object.getOwnPropertyNames(Object.prototype).forEach((function(name){if(name==="__proto__"){polyProps[name]={configurable:true,enumerable:false,writable:true,value:undefined};return}polyProps[name]=desc}));Object.defineProperties(nullObject,polyProps);Object.defineProperty(shim,"nullPolyfill",{configurable:false,enumerable:false,writable:false,value:nullObject});return function(prototype,props){return create(prototype===null?nullObject:prototype,props)}}()},{"./set-prototype-of/is-implemented":85,"./set-prototype-of/shim":86}],75:[function(require,module,exports){"use strict";module.exports=require("./_iterate")("forEach")},{"./_iterate":69}],76:[function(require,module,exports){"use strict";function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}var isValue=require("./is-value");var map={function:true,object:true};module.exports=function(value){return isValue(value)&&map[_typeof(value)]||false}},{"./is-value":77}],77:[function(require,module,exports){"use strict";var _undefined=require("../function/noop")();module.exports=function(val){return val!==_undefined&&val!==null}},{"../function/noop":60}],78:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?Object.keys:require("./shim")},{"./is-implemented":79,"./shim":80}],79:[function(require,module,exports){"use strict";module.exports=function(){try{Object.keys("primitive");return true}catch(e){return false}}},{}],80:[function(require,module,exports){"use strict";var isValue=require("../is-value");var keys=Object.keys;module.exports=function(object){return keys(isValue(object)?Object(object):object)}},{"../is-value":77}],81:[function(require,module,exports){"use strict";var callable=require("./valid-callable"),forEach=require("./for-each"),call=Function.prototype.call;module.exports=function(obj,cb){var result={},thisArg=arguments[2];callable(cb);forEach(obj,(function(value,key,targetObj,index){result[key]=call.call(cb,thisArg,value,key,targetObj,index)}));return result}},{"./for-each":75,"./valid-callable":87}],82:[function(require,module,exports){"use strict";var isValue=require("./is-value");var forEach=Array.prototype.forEach,create=Object.create;var process=function process(src,obj){var key;for(key in src){obj[key]=src[key]}};module.exports=function(opts1){var result=create(null);forEach.call(arguments,(function(options){if(!isValue(options))return;process(Object(options),result)}));return result}},{"./is-value":77}],83:[function(require,module,exports){"use strict";var forEach=Array.prototype.forEach,create=Object.create;module.exports=function(arg){var set=create(null);forEach.call(arguments,(function(name){set[name]=true}));return set}},{}],84:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?Object.setPrototypeOf:require("./shim")},{"./is-implemented":85,"./shim":86}],85:[function(require,module,exports){"use strict";var create=Object.create,getPrototypeOf=Object.getPrototypeOf,plainObject={};module.exports=function(){var setPrototypeOf=Object.setPrototypeOf,customCreate=arguments[0]||create;if(typeof setPrototypeOf!=="function")return false;return getPrototypeOf(setPrototypeOf(customCreate(null),plainObject))===plainObject}},{}],86:[function(require,module,exports){"use strict";var isObject=require("../is-object"),value=require("../valid-value"),objIsPrototypeOf=Object.prototype.isPrototypeOf,defineProperty=Object.defineProperty,nullDesc={configurable:true,enumerable:false,writable:true,value:undefined},validate;validate=function validate(obj,prototype){value(obj);if(prototype===null||isObject(prototype))return obj;throw new TypeError("Prototype must be null or an object")};module.exports=function(status){var fn,set;if(!status)return null;if(status.level===2){if(status.set){set=status.set;fn=function fn(obj,prototype){set.call(validate(obj,prototype),prototype);return obj}}else{fn=function fn(obj,prototype){validate(obj,prototype).__proto__=prototype;return obj}}}else{fn=function self(obj,prototype){var isNullBase;validate(obj,prototype);isNullBase=objIsPrototypeOf.call(self.nullPolyfill,obj);if(isNullBase)delete self.nullPolyfill.__proto__;if(prototype===null)prototype=self.nullPolyfill;obj.__proto__=prototype;if(isNullBase)defineProperty(self.nullPolyfill,"__proto__",nullDesc);return obj}}return Object.defineProperty(fn,"level",{configurable:false,enumerable:false,writable:false,value:status.level})}(function(){var tmpObj1=Object.create(null),tmpObj2={},set,desc=Object.getOwnPropertyDescriptor(Object.prototype,"__proto__");if(desc){try{set=desc.set;set.call(tmpObj1,tmpObj2)}catch(ignore){}if(Object.getPrototypeOf(tmpObj1)===tmpObj2)return{set:set,level:2}}tmpObj1.__proto__=tmpObj2;if(Object.getPrototypeOf(tmpObj1)===tmpObj2)return{level:2};tmpObj1={};tmpObj1.__proto__=tmpObj2;if(Object.getPrototypeOf(tmpObj1)===tmpObj2)return{level:1};return false}());require("../create")},{"../create":74,"../is-object":76,"../valid-value":88}],87:[function(require,module,exports){"use strict";module.exports=function(fn){if(typeof fn!=="function")throw new TypeError(fn+" is not a function");return fn}},{}],88:[function(require,module,exports){"use strict";var isValue=require("./is-value");module.exports=function(value){if(!isValue(value))throw new TypeError("Cannot use null or undefined");return value}},{"./is-value":77}],89:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?String.prototype.contains:require("./shim")},{"./is-implemented":90,"./shim":91}],90:[function(require,module,exports){"use strict";var str="razdwatrzy";module.exports=function(){if(typeof str.contains!=="function")return false;return str.contains("dwa")===true&&str.contains("foo")===false}},{}],91:[function(require,module,exports){"use strict";var indexOf=String.prototype.indexOf;module.exports=function(searchString){return indexOf.call(this,searchString,arguments[1])>-1}},{}],92:[function(require,module,exports){"use strict";function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}var objToString=Object.prototype.toString,id=objToString.call("");module.exports=function(value){return typeof value==="string"||value&&_typeof(value)==="object"&&(value instanceof String||objToString.call(value)===id)||false}},{}],93:[function(require,module,exports){"use strict";var setPrototypeOf=require("es5-ext/object/set-prototype-of"),contains=require("es5-ext/string/#/contains"),d=require("d"),_Symbol=require("es6-symbol"),Iterator=require("./");var defineProperty=Object.defineProperty,ArrayIterator;ArrayIterator=module.exports=function(arr,kind){if(!(this instanceof ArrayIterator))throw new TypeError("Constructor requires 'new'");Iterator.call(this,arr);if(!kind)kind="value";else if(contains.call(kind,"key+value"))kind="key+value";else if(contains.call(kind,"key"))kind="key";else kind="value";defineProperty(this,"__kind__",d("",kind))};if(setPrototypeOf)setPrototypeOf(ArrayIterator,Iterator);delete ArrayIterator.prototype.constructor;ArrayIterator.prototype=Object.create(Iterator.prototype,{_resolve:d((function(i){if(this.__kind__==="value")return this.__list__[i];if(this.__kind__==="key+value")return[i,this.__list__[i]];return i}))});defineProperty(ArrayIterator.prototype,_Symbol.toStringTag,d("c","Array Iterator"))},{"./":96,d:39,"es5-ext/object/set-prototype-of":84,"es5-ext/string/#/contains":89,"es6-symbol":106}],94:[function(require,module,exports){"use strict";var isArguments=require("es5-ext/function/is-arguments"),callable=require("es5-ext/object/valid-callable"),isString=require("es5-ext/string/is-string"),get=require("./get");var isArray=Array.isArray,call=Function.prototype.call,some=Array.prototype.some;module.exports=function(iterable,cb){var mode,thisArg=arguments[2],result,doBreak,broken,i,length,_char,code;if(isArray(iterable)||isArguments(iterable))mode="array";else if(isString(iterable))mode="string";else iterable=get(iterable);callable(cb);doBreak=function doBreak(){broken=true};if(mode==="array"){some.call(iterable,(function(value){call.call(cb,thisArg,value,doBreak);return broken}));return}if(mode==="string"){length=iterable.length;for(i=0;i<length;++i){_char=iterable[i];if(i+1<length){code=_char.charCodeAt(0);if(code>=55296&&code<=56319)_char+=iterable[++i]}call.call(cb,thisArg,_char,doBreak);if(broken)break}return}result=iterable.next();while(!result.done){call.call(cb,thisArg,result.value,doBreak);if(broken)return;result=iterable.next()}}},{"./get":95,"es5-ext/function/is-arguments":58,"es5-ext/object/valid-callable":87,"es5-ext/string/is-string":92}],95:[function(require,module,exports){"use strict";var isArguments=require("es5-ext/function/is-arguments"),isString=require("es5-ext/string/is-string"),ArrayIterator=require("./array"),StringIterator=require("./string"),iterable=require("./valid-iterable"),iteratorSymbol=require("es6-symbol").iterator;module.exports=function(obj){if(typeof iterable(obj)[iteratorSymbol]==="function")return obj[iteratorSymbol]();if(isArguments(obj))return new ArrayIterator(obj);if(isString(obj))return new StringIterator(obj);return new ArrayIterator(obj)}},{"./array":93,"./string":98,"./valid-iterable":99,"es5-ext/function/is-arguments":58,"es5-ext/string/is-string":92,"es6-symbol":106}],96:[function(require,module,exports){"use strict";var clear=require("es5-ext/array/#/clear"),assign=require("es5-ext/object/assign"),callable=require("es5-ext/object/valid-callable"),value=require("es5-ext/object/valid-value"),d=require("d"),autoBind=require("d/auto-bind"),_Symbol=require("es6-symbol");var defineProperty=Object.defineProperty,defineProperties=Object.defineProperties,_Iterator;module.exports=_Iterator=function Iterator(list,context){if(!(this instanceof _Iterator))throw new TypeError("Constructor requires 'new'");defineProperties(this,{__list__:d("w",value(list)),__context__:d("w",context),__nextIndex__:d("w",0)});if(!context)return;callable(context.on);context.on("_add",this._onAdd);context.on("_delete",this._onDelete);context.on("_clear",this._onClear)};delete _Iterator.prototype.constructor;defineProperties(_Iterator.prototype,assign({_next:d((function(){var i;if(!this.__list__)return undefined;if(this.__redo__){i=this.__redo__.shift();if(i!==undefined)return i}if(this.__nextIndex__<this.__list__.length)return this.__nextIndex__++;this._unBind();return undefined})),next:d((function(){return this._createResult(this._next())})),_createResult:d((function(i){if(i===undefined)return{done:true,value:undefined};return{done:false,value:this._resolve(i)}})),_resolve:d((function(i){return this.__list__[i]})),_unBind:d((function(){this.__list__=null;delete this.__redo__;if(!this.__context__)return;this.__context__.off("_add",this._onAdd);this.__context__.off("_delete",this._onDelete);this.__context__.off("_clear",this._onClear);this.__context__=null})),toString:d((function(){return"[object "+(this[_Symbol.toStringTag]||"Object")+"]"}))},autoBind({_onAdd:d((function(index){if(index>=this.__nextIndex__)return;++this.__nextIndex__;if(!this.__redo__){defineProperty(this,"__redo__",d("c",[index]));return}this.__redo__.forEach((function(redo,i){if(redo>=index)this.__redo__[i]=++redo}),this);this.__redo__.push(index)})),_onDelete:d((function(index){var i;if(index>=this.__nextIndex__)return;--this.__nextIndex__;if(!this.__redo__)return;i=this.__redo__.indexOf(index);if(i!==-1)this.__redo__.splice(i,1);this.__redo__.forEach((function(redo,j){if(redo>index)this.__redo__[j]=--redo}),this)})),_onClear:d((function(){if(this.__redo__)clear.call(this.__redo__);this.__nextIndex__=0}))})));defineProperty(_Iterator.prototype,_Symbol.iterator,d((function(){return this})))},{d:39,"d/auto-bind":38,"es5-ext/array/#/clear":53,"es5-ext/object/assign":70,"es5-ext/object/valid-callable":87,"es5-ext/object/valid-value":88,"es6-symbol":106}],97:[function(require,module,exports){"use strict";var isArguments=require("es5-ext/function/is-arguments"),isValue=require("es5-ext/object/is-value"),isString=require("es5-ext/string/is-string");var iteratorSymbol=require("es6-symbol").iterator,isArray=Array.isArray;module.exports=function(value){if(!isValue(value))return false;if(isArray(value))return true;if(isString(value))return true;if(isArguments(value))return true;return typeof value[iteratorSymbol]==="function"}},{"es5-ext/function/is-arguments":58,"es5-ext/object/is-value":77,"es5-ext/string/is-string":92,"es6-symbol":106}],98:[function(require,module,exports){"use strict";var setPrototypeOf=require("es5-ext/object/set-prototype-of"),d=require("d"),_Symbol=require("es6-symbol"),Iterator=require("./");var defineProperty=Object.defineProperty,StringIterator;StringIterator=module.exports=function(str){if(!(this instanceof StringIterator))throw new TypeError("Constructor requires 'new'");str=String(str);Iterator.call(this,str);defineProperty(this,"__length__",d("",str.length))};if(setPrototypeOf)setPrototypeOf(StringIterator,Iterator);delete StringIterator.prototype.constructor;StringIterator.prototype=Object.create(Iterator.prototype,{_next:d((function(){if(!this.__list__)return undefined;if(this.__nextIndex__<this.__length__)return this.__nextIndex__++;this._unBind();return undefined})),_resolve:d((function(i){var _char=this.__list__[i],code;if(this.__nextIndex__===this.__length__)return _char;code=_char.charCodeAt(0);if(code>=55296&&code<=56319)return _char+this.__list__[this.__nextIndex__++];return _char}))});defineProperty(StringIterator.prototype,_Symbol.toStringTag,d("c","String Iterator"))},{"./":96,d:39,"es5-ext/object/set-prototype-of":84,"es6-symbol":106}],99:[function(require,module,exports){"use strict";var isIterable=require("./is-iterable");module.exports=function(value){if(!isIterable(value))throw new TypeError(value+" is not iterable");return value}},{"./is-iterable":97}],100:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?Map:require("./polyfill")},{"./is-implemented":101,"./polyfill":105}],101:[function(require,module,exports){"use strict";module.exports=function(){var map,iterator,result;if(typeof Map!=="function")return false;try{map=new Map([["raz","one"],["dwa","two"],["trzy","three"]])}catch(e){return false}if(String(map)!=="[object Map]")return false;if(map.size!==3)return false;if(typeof map.clear!=="function")return false;if(typeof map["delete"]!=="function")return false;if(typeof map.entries!=="function")return false;if(typeof map.forEach!=="function")return false;if(typeof map.get!=="function")return false;if(typeof map.has!=="function")return false;if(typeof map.keys!=="function")return false;if(typeof map.set!=="function")return false;if(typeof map.values!=="function")return false;iterator=map.entries();result=iterator.next();if(result.done!==false)return false;if(!result.value)return false;if(result.value[0]!=="raz")return false;if(result.value[1]!=="one")return false;return true}},{}],102:[function(require,module,exports){"use strict";module.exports=function(){if(typeof Map==="undefined")return false;return Object.prototype.toString.call(new Map)==="[object Map]"}()},{}],103:[function(require,module,exports){"use strict";module.exports=require("es5-ext/object/primitive-set")("key","value","key+value")},{"es5-ext/object/primitive-set":83}],104:[function(require,module,exports){"use strict";var setPrototypeOf=require("es5-ext/object/set-prototype-of"),d=require("d"),Iterator=require("es6-iterator"),toStringTagSymbol=require("es6-symbol").toStringTag,kinds=require("./iterator-kinds"),defineProperties=Object.defineProperties,unBind=Iterator.prototype._unBind,MapIterator;MapIterator=module.exports=function(map,kind){if(!(this instanceof MapIterator))return new MapIterator(map,kind);Iterator.call(this,map.__mapKeysData__,map);if(!kind||!kinds[kind])kind="key+value";defineProperties(this,{__kind__:d("",kind),__values__:d("w",map.__mapValuesData__)})};if(setPrototypeOf)setPrototypeOf(MapIterator,Iterator);MapIterator.prototype=Object.create(Iterator.prototype,{constructor:d(MapIterator),_resolve:d((function(i){if(this.__kind__==="value")return this.__values__[i];if(this.__kind__==="key")return this.__list__[i];return[this.__list__[i],this.__values__[i]]})),_unBind:d((function(){this.__values__=null;unBind.call(this)})),toString:d((function(){return"[object Map Iterator]"}))});Object.defineProperty(MapIterator.prototype,toStringTagSymbol,d("c","Map Iterator"))},{"./iterator-kinds":103,d:39,"es5-ext/object/set-prototype-of":84,"es6-iterator":96,"es6-symbol":106}],105:[function(require,module,exports){"use strict";var clear=require("es5-ext/array/#/clear"),eIndexOf=require("es5-ext/array/#/e-index-of"),setPrototypeOf=require("es5-ext/object/set-prototype-of"),callable=require("es5-ext/object/valid-callable"),validValue=require("es5-ext/object/valid-value"),d=require("d"),ee=require("event-emitter"),_Symbol=require("es6-symbol"),iterator=require("es6-iterator/valid-iterable"),forOf=require("es6-iterator/for-of"),Iterator=require("./lib/iterator"),isNative=require("./is-native-implemented"),call=Function.prototype.call,defineProperties=Object.defineProperties,getPrototypeOf=Object.getPrototypeOf,_MapPoly;module.exports=_MapPoly=function MapPoly(){var iterable=arguments[0],keys,values,self;if(!(this instanceof _MapPoly))throw new TypeError("Constructor requires 'new'");if(isNative&&setPrototypeOf&&Map!==_MapPoly){self=setPrototypeOf(new Map,getPrototypeOf(this))}else{self=this}if(iterable!=null)iterator(iterable);defineProperties(self,{__mapKeysData__:d("c",keys=[]),__mapValuesData__:d("c",values=[])});if(!iterable)return self;forOf(iterable,(function(value){var key=validValue(value)[0];value=value[1];if(eIndexOf.call(keys,key)!==-1)return;keys.push(key);values.push(value)}),self);return self};if(isNative){if(setPrototypeOf)setPrototypeOf(_MapPoly,Map);_MapPoly.prototype=Object.create(Map.prototype,{constructor:d(_MapPoly)})}ee(defineProperties(_MapPoly.prototype,{clear:d((function(){if(!this.__mapKeysData__.length)return;clear.call(this.__mapKeysData__);clear.call(this.__mapValuesData__);this.emit("_clear")})),delete:d((function(key){var index=eIndexOf.call(this.__mapKeysData__,key);if(index===-1)return false;this.__mapKeysData__.splice(index,1);this.__mapValuesData__.splice(index,1);this.emit("_delete",index,key);return true})),entries:d((function(){return new Iterator(this,"key+value")})),forEach:d((function(cb){var thisArg=arguments[1],iterator,result;callable(cb);iterator=this.entries();result=iterator._next();while(result!==undefined){call.call(cb,thisArg,this.__mapValuesData__[result],this.__mapKeysData__[result],this);result=iterator._next()}})),get:d((function(key){var index=eIndexOf.call(this.__mapKeysData__,key);if(index===-1)return;return this.__mapValuesData__[index]})),has:d((function(key){return eIndexOf.call(this.__mapKeysData__,key)!==-1})),keys:d((function(){return new Iterator(this,"key")})),set:d((function(key,value){var index=eIndexOf.call(this.__mapKeysData__,key),emit;if(index===-1){index=this.__mapKeysData__.push(key)-1;emit=true}this.__mapValuesData__[index]=value;if(emit)this.emit("_add",index,key);return this})),size:d.gs((function(){return this.__mapKeysData__.length})),values:d((function(){return new Iterator(this,"value")})),toString:d((function(){return"[object Map]"}))}));Object.defineProperty(_MapPoly.prototype,_Symbol.iterator,d((function(){return this.entries()})));Object.defineProperty(_MapPoly.prototype,_Symbol.toStringTag,d("c","Map"))},{"./is-native-implemented":102,"./lib/iterator":104,d:39,"es5-ext/array/#/clear":53,"es5-ext/array/#/e-index-of":54,"es5-ext/object/set-prototype-of":84,"es5-ext/object/valid-callable":87,"es5-ext/object/valid-value":88,"es6-iterator/for-of":94,"es6-iterator/valid-iterable":99,"es6-symbol":106,"event-emitter":114}],106:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?require("ext/global-this").Symbol:require("./polyfill")},{"./is-implemented":107,"./polyfill":112,"ext/global-this":116}],107:[function(require,module,exports){"use strict";function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}var global=require("ext/global-this"),validTypes={object:true,symbol:true};module.exports=function(){var _Symbol=global.Symbol;var symbol;if(typeof _Symbol!=="function")return false;symbol=_Symbol("test symbol");try{String(symbol)}catch(e){return false}if(!validTypes[_typeof(_Symbol.iterator)])return false;if(!validTypes[_typeof(_Symbol.toPrimitive)])return false;if(!validTypes[_typeof(_Symbol.toStringTag)])return false;return true}},{"ext/global-this":116}],108:[function(require,module,exports){"use strict";function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}module.exports=function(value){if(!value)return false;if(_typeof(value)==="symbol")return true;if(!value.constructor)return false;if(value.constructor.name!=="Symbol")return false;return value[value.constructor.toStringTag]==="Symbol"}},{}],109:[function(require,module,exports){"use strict";var d=require("d");var create=Object.create,defineProperty=Object.defineProperty,objPrototype=Object.prototype;var created=create(null);module.exports=function(desc){var postfix=0,name,ie11BugWorkaround;while(created[desc+(postfix||"")]){++postfix}desc+=postfix||"";created[desc]=true;name="@@"+desc;defineProperty(objPrototype,name,d.gs(null,(function(value){if(ie11BugWorkaround)return;ie11BugWorkaround=true;defineProperty(this,name,d(value));ie11BugWorkaround=false})));return name}},{d:39}],110:[function(require,module,exports){"use strict";var d=require("d"),NativeSymbol=require("ext/global-this").Symbol;module.exports=function(SymbolPolyfill){return Object.defineProperties(SymbolPolyfill,{hasInstance:d("",NativeSymbol&&NativeSymbol.hasInstance||SymbolPolyfill("hasInstance")),isConcatSpreadable:d("",NativeSymbol&&NativeSymbol.isConcatSpreadable||SymbolPolyfill("isConcatSpreadable")),iterator:d("",NativeSymbol&&NativeSymbol.iterator||SymbolPolyfill("iterator")),match:d("",NativeSymbol&&NativeSymbol.match||SymbolPolyfill("match")),replace:d("",NativeSymbol&&NativeSymbol.replace||SymbolPolyfill("replace")),search:d("",NativeSymbol&&NativeSymbol.search||SymbolPolyfill("search")),species:d("",NativeSymbol&&NativeSymbol.species||SymbolPolyfill("species")),split:d("",NativeSymbol&&NativeSymbol.split||SymbolPolyfill("split")),toPrimitive:d("",NativeSymbol&&NativeSymbol.toPrimitive||SymbolPolyfill("toPrimitive")),toStringTag:d("",NativeSymbol&&NativeSymbol.toStringTag||SymbolPolyfill("toStringTag")),unscopables:d("",NativeSymbol&&NativeSymbol.unscopables||SymbolPolyfill("unscopables"))})}},{d:39,"ext/global-this":116}],111:[function(require,module,exports){"use strict";var d=require("d"),validateSymbol=require("../../../validate-symbol");var registry=Object.create(null);module.exports=function(SymbolPolyfill){return Object.defineProperties(SymbolPolyfill,{for:d((function(key){if(registry[key])return registry[key];return registry[key]=SymbolPolyfill(String(key))})),keyFor:d((function(symbol){var key;validateSymbol(symbol);for(key in registry){if(registry[key]===symbol)return key}return undefined}))})}},{"../../../validate-symbol":113,d:39}],112:[function(require,module,exports){"use strict";function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}var d=require("d"),validateSymbol=require("./validate-symbol"),NativeSymbol=require("ext/global-this").Symbol,generateName=require("./lib/private/generate-name"),setupStandardSymbols=require("./lib/private/setup/standard-symbols"),setupSymbolRegistry=require("./lib/private/setup/symbol-registry");var create=Object.create,defineProperties=Object.defineProperties,defineProperty=Object.defineProperty;var SymbolPolyfill,HiddenSymbol,isNativeSafe;if(typeof NativeSymbol==="function"){try{String(NativeSymbol());isNativeSafe=true}catch(ignore){}}else{NativeSymbol=null}HiddenSymbol=function _Symbol(description){if(this instanceof HiddenSymbol)throw new TypeError("Symbol is not a constructor");return SymbolPolyfill(description)};module.exports=SymbolPolyfill=function _Symbol2(description){var symbol;if(this instanceof _Symbol2)throw new TypeError("Symbol is not a constructor");if(isNativeSafe)return NativeSymbol(description);symbol=create(HiddenSymbol.prototype);description=description===undefined?"":String(description);return defineProperties(symbol,{__description__:d("",description),__name__:d("",generateName(description))})};setupStandardSymbols(SymbolPolyfill);setupSymbolRegistry(SymbolPolyfill);defineProperties(HiddenSymbol.prototype,{constructor:d(SymbolPolyfill),toString:d("",(function(){return this.__name__}))});defineProperties(SymbolPolyfill.prototype,{toString:d((function(){return"Symbol ("+validateSymbol(this).__description__+")"})),valueOf:d((function(){return validateSymbol(this)}))});defineProperty(SymbolPolyfill.prototype,SymbolPolyfill.toPrimitive,d("",(function(){var symbol=validateSymbol(this);if(_typeof(symbol)==="symbol")return symbol;return symbol.toString()})));defineProperty(SymbolPolyfill.prototype,SymbolPolyfill.toStringTag,d("c","Symbol"));defineProperty(HiddenSymbol.prototype,SymbolPolyfill.toStringTag,d("c",SymbolPolyfill.prototype[SymbolPolyfill.toStringTag]));defineProperty(HiddenSymbol.prototype,SymbolPolyfill.toPrimitive,d("c",SymbolPolyfill.prototype[SymbolPolyfill.toPrimitive]))},{"./lib/private/generate-name":109,"./lib/private/setup/standard-symbols":110,"./lib/private/setup/symbol-registry":111,"./validate-symbol":113,d:39,"ext/global-this":116}],113:[function(require,module,exports){"use strict";var isSymbol=require("./is-symbol");module.exports=function(value){if(!isSymbol(value))throw new TypeError(value+" is not a symbol");return value}},{"./is-symbol":108}],114:[function(require,module,exports){"use strict";function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}var d=require("d"),callable=require("es5-ext/object/valid-callable"),apply=Function.prototype.apply,call=Function.prototype.call,create=Object.create,defineProperty=Object.defineProperty,defineProperties=Object.defineProperties,hasOwnProperty=Object.prototype.hasOwnProperty,descriptor={configurable:true,enumerable:false,writable:true},on,_once2,off,emit,methods,descriptors,base;on=function on(type,listener){var data;callable(listener);if(!hasOwnProperty.call(this,"__ee__")){data=descriptor.value=create(null);defineProperty(this,"__ee__",descriptor);descriptor.value=null}else{data=this.__ee__}if(!data[type])data[type]=listener;else if(_typeof(data[type])==="object")data[type].push(listener);else data[type]=[data[type],listener];return this};_once2=function once(type,listener){var _once,self;callable(listener);self=this;on.call(this,type,_once=function once(){off.call(self,type,_once);apply.call(listener,this,arguments)});_once.__eeOnceListener__=listener;return this};off=function off(type,listener){var data,listeners,candidate,i;callable(listener);if(!hasOwnProperty.call(this,"__ee__"))return this;data=this.__ee__;if(!data[type])return this;listeners=data[type];if(_typeof(listeners)==="object"){for(i=0;candidate=listeners[i];++i){if(candidate===listener||candidate.__eeOnceListener__===listener){if(listeners.length===2)data[type]=listeners[i?0:1];else listeners.splice(i,1)}}}else{if(listeners===listener||listeners.__eeOnceListener__===listener){delete data[type]}}return this};emit=function emit(type){var i,l,listener,listeners,args;if(!hasOwnProperty.call(this,"__ee__"))return;listeners=this.__ee__[type];if(!listeners)return;if(_typeof(listeners)==="object"){l=arguments.length;args=new Array(l-1);for(i=1;i<l;++i){args[i-1]=arguments[i]}listeners=listeners.slice();for(i=0;listener=listeners[i];++i){apply.call(listener,this,args)}}else{switch(arguments.length){case 1:call.call(listeners,this);break;case 2:call.call(listeners,this,arguments[1]);break;case 3:call.call(listeners,this,arguments[1],arguments[2]);break;default:l=arguments.length;args=new Array(l-1);for(i=1;i<l;++i){args[i-1]=arguments[i]}apply.call(listeners,this,args)}}};methods={on:on,once:_once2,off:off,emit:emit};descriptors={on:d(on),once:d(_once2),off:d(off),emit:d(emit)};base=defineProperties({},descriptors);module.exports=exports=function exports(o){return o==null?create(base):defineProperties(Object(o),descriptors)};exports.methods=methods},{d:39,"es5-ext/object/valid-callable":87}],115:[function(require,module,exports){"use strict";function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}var naiveFallback=function naiveFallback(){if((typeof self==="undefined"?"undefined":_typeof(self))==="object"&&self)return self;if((typeof window==="undefined"?"undefined":_typeof(window))==="object"&&window)return window;throw new Error("Unable to resolve global `this`")};module.exports=function(){if(this)return this;try{Object.defineProperty(Object.prototype,"__global__",{get:function get(){return this},configurable:true})}catch(error){return naiveFallback()}try{if(!__global__)return naiveFallback();return __global__}finally{delete Object.prototype.__global__}}()},{}],116:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?globalThis:require("./implementation")},{"./implementation":115,"./is-implemented":117}],117:[function(require,module,exports){"use strict";function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}module.exports=function(){if((typeof globalThis==="undefined"?"undefined":_typeof(globalThis))!=="object")return false;if(!globalThis)return false;return globalThis.Array===Array}},{}],118:[function(require,module,exports){"use strict";function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}module.exports=(typeof self==="undefined"?"undefined":_typeof(self))=="object"?self.FormData:window.FormData},{}],119:[function(require,module,exports){"use strict";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}},{}],120:[function(require,module,exports){"use strict";if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){if(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){if(superCtor){ctor.super_=superCtor;var TempCtor=function TempCtor(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}}},{}],121:[function(require,module,exports){"use strict";
|
|
34
34
|
/*!
|
|
35
35
|
* Determine if an object is a Buffer
|
|
36
36
|
*
|
|
37
37
|
* @author Feross Aboukhadijeh <https://feross.org>
|
|
38
38
|
* @license MIT
|
|
39
|
-
*/
|
|
40
|
-
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))}},{}],150:[function(require,module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return toString.call(arr)=="[object Array]"}},{}],151:[function(require,module,exports){"use strict";module.exports=sizeof;function sizeof(object){var objects=[object];var processed=[];var size=0;for(var index=0;index<objects.length;++index){var _object=objects[index];switch(typeof _object){case"boolean":size+=4;break;case"number":size+=8;break;case"string":size+=2*_object.length;break;case"object":if(_object===null){size+=4;break}var keySizeFactor=Array.isArray(_object)?0:1;for(var key in _object){size+=keySizeFactor*2*key.length;if(processed.indexOf(_object[key])===-1){objects.push(_object[key]);if(typeof _object[key]==="object"){processed.push(_object[key])}}}break}}return size}},{}],152:[function(require,module,exports){(function(root,definition){"use strict";if(typeof define==="function"&&define.amd){define(definition)}else if(typeof module==="object"&&module.exports){module.exports=definition()}else{root.log=definition()}})(this,(function(){"use strict";var noop=function(){};var undefinedType="undefined";var isIE=typeof window!==undefinedType&&/Trident\/|MSIE /.test(window.navigator.userAgent);var logMethods=["trace","debug","info","warn","error"];function bindMethod(obj,methodName){var method=obj[methodName];if(typeof method.bind==="function"){return method.bind(obj)}else{try{return Function.prototype.bind.call(method,obj)}catch(e){return function(){return Function.prototype.apply.apply(method,[obj,arguments])}}}}function traceForIE(){if(console.log){if(console.log.apply){console.log.apply(console,arguments)}else{Function.prototype.apply.apply(console.log,[console,arguments])}}if(console.trace)console.trace()}function realMethod(methodName){if(methodName==="debug"){methodName="log"}if(typeof console===undefinedType){return false}else if(methodName==="trace"&&isIE){return traceForIE}else if(console[methodName]!==undefined){return bindMethod(console,methodName)}else if(console.log!==undefined){return bindMethod(console,"log")}else{return noop}}function replaceLoggingMethods(level,loggerName){for(var i=0;i<logMethods.length;i++){var methodName=logMethods[i];this[methodName]=i<level?noop:this.methodFactory(methodName,level,loggerName)}this.log=this.debug}function enableLoggingWhenConsoleArrives(methodName,level,loggerName){return function(){if(typeof console!==undefinedType){replaceLoggingMethods.call(this,level,loggerName);this[methodName].apply(this,arguments)}}}function defaultMethodFactory(methodName,level,loggerName){return realMethod(methodName)||enableLoggingWhenConsoleArrives.apply(this,arguments)}function Logger(name,defaultLevel,factory){var self=this;var currentLevel;var storageKey="loglevel";if(name){storageKey+=":"+name}function persistLevelIfPossible(levelNum){var levelName=(logMethods[levelNum]||"silent").toUpperCase();if(typeof window===undefinedType)return;try{window.localStorage[storageKey]=levelName;return}catch(ignore){}try{window.document.cookie=encodeURIComponent(storageKey)+"="+levelName+";"}catch(ignore){}}function getPersistedLevel(){var storedLevel;if(typeof window===undefinedType)return;try{storedLevel=window.localStorage[storageKey]}catch(ignore){}if(typeof storedLevel===undefinedType){try{var cookie=window.document.cookie;var location=cookie.indexOf(encodeURIComponent(storageKey)+"=");if(location!==-1){storedLevel=/^([^;]+)/.exec(cookie.slice(location))[1]}}catch(ignore){}}if(self.levels[storedLevel]===undefined){storedLevel=undefined}return storedLevel}self.name=name;self.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5};self.methodFactory=factory||defaultMethodFactory;self.getLevel=function(){return currentLevel};self.setLevel=function(level,persist){if(typeof level==="string"&&self.levels[level.toUpperCase()]!==undefined){level=self.levels[level.toUpperCase()]}if(typeof level==="number"&&level>=0&&level<=self.levels.SILENT){currentLevel=level;if(persist!==false){persistLevelIfPossible(level)}replaceLoggingMethods.call(self,level,name);if(typeof console===undefinedType&&level<self.levels.SILENT){return"No console available for logging"}}else{throw"log.setLevel() called with invalid level: "+level}};self.setDefaultLevel=function(level){if(!getPersistedLevel()){self.setLevel(level,false)}};self.enableAll=function(persist){self.setLevel(self.levels.TRACE,persist)};self.disableAll=function(persist){self.setLevel(self.levels.SILENT,persist)};var initialLevel=getPersistedLevel();if(initialLevel==null){initialLevel=defaultLevel==null?"WARN":defaultLevel}self.setLevel(initialLevel,false)}var defaultLogger=new Logger;var _loggersByName={};defaultLogger.getLogger=function getLogger(name){if(typeof name!=="string"||name===""){throw new TypeError("You must supply a name when creating a logger.")}var logger=_loggersByName[name];if(!logger){logger=_loggersByName[name]=new Logger(name,defaultLogger.getLevel(),defaultLogger.methodFactory)}return logger};var _log=typeof window!==undefinedType?window.log:undefined;defaultLogger.noConflict=function(){if(typeof window!==undefinedType&&window.log===defaultLogger){window.log=_log}return defaultLogger};defaultLogger.getLoggers=function getLoggers(){return _loggersByName};return defaultLogger}))},{}],153:[function(require,module,exports){"use strict";var Buffer=require("safe-buffer").Buffer;var protocol=module.exports;protocol.types={0:"reserved",1:"connect",2:"connack",3:"publish",4:"puback",5:"pubrec",6:"pubrel",7:"pubcomp",8:"subscribe",9:"suback",10:"unsubscribe",11:"unsuback",12:"pingreq",13:"pingresp",14:"disconnect",15:"auth"};protocol.codes={};for(var k in protocol.types){var v=protocol.types[k];protocol.codes[v]=k}protocol.CMD_SHIFT=4;protocol.CMD_MASK=240;protocol.DUP_MASK=8;protocol.QOS_MASK=3;protocol.QOS_SHIFT=1;protocol.RETAIN_MASK=1;protocol.LENGTH_MASK=127;protocol.LENGTH_FIN_MASK=128;protocol.SESSIONPRESENT_MASK=1;protocol.SESSIONPRESENT_HEADER=Buffer.from([protocol.SESSIONPRESENT_MASK]);protocol.CONNACK_HEADER=Buffer.from([protocol.codes["connack"]<<protocol.CMD_SHIFT]);protocol.USERNAME_MASK=128;protocol.PASSWORD_MASK=64;protocol.WILL_RETAIN_MASK=32;protocol.WILL_QOS_MASK=24;protocol.WILL_QOS_SHIFT=3;protocol.WILL_FLAG_MASK=4;protocol.CLEAN_SESSION_MASK=2;protocol.CONNECT_HEADER=Buffer.from([protocol.codes["connect"]<<protocol.CMD_SHIFT]);protocol.properties={sessionExpiryInterval:17,willDelayInterval:24,receiveMaximum:33,maximumPacketSize:39,topicAliasMaximum:34,requestResponseInformation:25,requestProblemInformation:23,userProperties:38,authenticationMethod:21,authenticationData:22,payloadFormatIndicator:1,messageExpiryInterval:2,contentType:3,responseTopic:8,correlationData:9,maximumQoS:36,retainAvailable:37,assignedClientIdentifier:18,reasonString:31,wildcardSubscriptionAvailable:40,subscriptionIdentifiersAvailable:41,sharedSubscriptionAvailable:42,serverKeepAlive:19,responseInformation:26,serverReference:28,topicAlias:35,subscriptionIdentifier:11};protocol.propertiesCodes={};for(var prop in protocol.properties){var id=protocol.properties[prop];protocol.propertiesCodes[id]=prop}protocol.propertiesTypes={sessionExpiryInterval:"int32",willDelayInterval:"int32",receiveMaximum:"int16",maximumPacketSize:"int32",topicAliasMaximum:"int16",requestResponseInformation:"byte",requestProblemInformation:"byte",userProperties:"pair",authenticationMethod:"string",authenticationData:"binary",payloadFormatIndicator:"byte",messageExpiryInterval:"int32",contentType:"string",responseTopic:"string",correlationData:"binary",maximumQoS:"int8",retainAvailable:"byte",assignedClientIdentifier:"string",reasonString:"string",wildcardSubscriptionAvailable:"byte",subscriptionIdentifiersAvailable:"byte",sharedSubscriptionAvailable:"byte",serverKeepAlive:"int16",responseInformation:"string",serverReference:"string",topicAlias:"int16",subscriptionIdentifier:"var"};function genHeader(type){return[0,1,2].map((function(qos){return[0,1].map((function(dup){return[0,1].map((function(retain){var buf=Buffer.alloc(1);buf.writeUInt8(protocol.codes[type]<<protocol.CMD_SHIFT|(dup?protocol.DUP_MASK:0)|qos<<protocol.QOS_SHIFT|retain,0,true);return buf}))}))}))}protocol.PUBLISH_HEADER=genHeader("publish");protocol.SUBSCRIBE_HEADER=genHeader("subscribe");protocol.SUBSCRIBE_OPTIONS_QOS_MASK=3;protocol.SUBSCRIBE_OPTIONS_NL_MASK=1;protocol.SUBSCRIBE_OPTIONS_NL_SHIFT=2;protocol.SUBSCRIBE_OPTIONS_RAP_MASK=1;protocol.SUBSCRIBE_OPTIONS_RAP_SHIFT=3;protocol.SUBSCRIBE_OPTIONS_RH_MASK=3;protocol.SUBSCRIBE_OPTIONS_RH_SHIFT=4;protocol.SUBSCRIBE_OPTIONS_RH=[0,16,32];protocol.SUBSCRIBE_OPTIONS_NL=4;protocol.SUBSCRIBE_OPTIONS_RAP=8;protocol.SUBSCRIBE_OPTIONS_QOS=[0,1,2];protocol.UNSUBSCRIBE_HEADER=genHeader("unsubscribe");protocol.ACKS={unsuback:genHeader("unsuback"),puback:genHeader("puback"),pubcomp:genHeader("pubcomp"),pubrel:genHeader("pubrel"),pubrec:genHeader("pubrec")};protocol.SUBACK_HEADER=Buffer.from([protocol.codes["suback"]<<protocol.CMD_SHIFT]);protocol.VERSION3=Buffer.from([3]);protocol.VERSION4=Buffer.from([4]);protocol.VERSION5=Buffer.from([5]);protocol.QOS=[0,1,2].map((function(qos){return Buffer.from([qos])}));protocol.EMPTY={pingreq:Buffer.from([protocol.codes["pingreq"]<<4,0]),pingresp:Buffer.from([protocol.codes["pingresp"]<<4,0]),disconnect:Buffer.from([protocol.codes["disconnect"]<<4,0])}},{"safe-buffer":189}],154:[function(require,module,exports){"use strict";var Buffer=require("safe-buffer").Buffer;var writeToStream=require("./writeToStream");var EE=require("events").EventEmitter;var inherits=require("inherits");function generate(packet,opts){var stream=new Accumulator;writeToStream(packet,stream,opts);return stream.concat()}function Accumulator(){this._array=new Array(20);this._i=0}inherits(Accumulator,EE);Accumulator.prototype.write=function(chunk){this._array[this._i++]=chunk;return true};Accumulator.prototype.concat=function(){var length=0;var lengths=new Array(this._array.length);var list=this._array;var pos=0;var i;var result;for(i=0;i<list.length&&list[i]!==undefined;i++){if(typeof list[i]!=="string")lengths[i]=list[i].length;else lengths[i]=Buffer.byteLength(list[i]);length+=lengths[i]}result=Buffer.allocUnsafe(length);for(i=0;i<list.length&&list[i]!==undefined;i++){if(typeof list[i]!=="string"){list[i].copy(result,pos);pos+=lengths[i]}else{result.write(list[i],pos);pos+=lengths[i]}}return result};module.exports=generate},{"./writeToStream":159,events:73,inherits:148,"safe-buffer":189}],155:[function(require,module,exports){"use strict";exports.parser=require("./parser");exports.generate=require("./generate");exports.writeToStream=require("./writeToStream")},{"./generate":154,"./parser":158,"./writeToStream":159}],156:[function(require,module,exports){"use strict";var Buffer=require("safe-buffer").Buffer;var max=65536;var cache={};function generateBuffer(i){var buffer=Buffer.allocUnsafe(2);buffer.writeUInt8(i>>8,0);buffer.writeUInt8(i&255,0+1);return buffer}function generateCache(){for(var i=0;i<max;i++){cache[i]=generateBuffer(i)}}function calcVariableByteIntLength(length){if(length>=0&&length<128)return 1;else if(length>=128&&length<16384)return 2;else if(length>=16384&&length<2097152)return 3;else if(length>=2097152&&length<268435456)return 4;else return 0}function genBufVariableByteInt(num){var digit=0;var pos=0;var length=calcVariableByteIntLength(num);var buffer=Buffer.allocUnsafe(length);do{digit=num%128|0;num=num/128|0;if(num>0)digit=digit|128;buffer.writeUInt8(digit,pos++)}while(num>0);return{data:buffer,length:length}}function generate4ByteBuffer(num){var buffer=Buffer.allocUnsafe(4);buffer.writeUInt32BE(num,0);return buffer}module.exports={cache:cache,generateCache:generateCache,generateNumber:generateBuffer,genBufVariableByteInt:genBufVariableByteInt,generate4ByteBuffer:generate4ByteBuffer}},{"safe-buffer":189}],157:[function(require,module,exports){function Packet(){this.cmd=null;this.retain=false;this.qos=0;this.dup=false;this.length=-1;this.topic=null;this.payload=null}module.exports=Packet},{}],158:[function(require,module,exports){"use strict";var bl=require("bl");var inherits=require("inherits");var EE=require("events").EventEmitter;var Packet=require("./packet");var constants=require("./constants");function Parser(opt){if(!(this instanceof Parser))return new Parser(opt);this.settings=opt||{};this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"];this._resetState()}inherits(Parser,EE);Parser.prototype._resetState=function(){this.packet=new Packet;this.error=null;this._list=bl();this._stateCounter=0};Parser.prototype.parse=function(buf){if(this.error)this._resetState();this._list.append(buf);while((this.packet.length!==-1||this._list.length>0)&&this[this._states[this._stateCounter]]()&&!this.error){this._stateCounter++;if(this._stateCounter>=this._states.length)this._stateCounter=0}return this._list.length};Parser.prototype._parseHeader=function(){var zero=this._list.readUInt8(0);this.packet.cmd=constants.types[zero>>constants.CMD_SHIFT];this.packet.retain=(zero&constants.RETAIN_MASK)!==0;this.packet.qos=zero>>constants.QOS_SHIFT&constants.QOS_MASK;this.packet.dup=(zero&constants.DUP_MASK)!==0;this._list.consume(1);return true};Parser.prototype._parseLength=function(){var result=this._parseVarByteNum(true);if(result){this.packet.length=result.value;this._list.consume(result.bytes)}return!!result};Parser.prototype._parsePayload=function(){var result=false;if(this.packet.length===0||this._list.length>=this.packet.length){this._pos=0;switch(this.packet.cmd){case"connect":this._parseConnect();break;case"connack":this._parseConnack();break;case"publish":this._parsePublish();break;case"puback":case"pubrec":case"pubrel":case"pubcomp":this._parseConfirmation();break;case"subscribe":this._parseSubscribe();break;case"suback":this._parseSuback();break;case"unsubscribe":this._parseUnsubscribe();break;case"unsuback":this._parseUnsuback();break;case"pingreq":case"pingresp":break;case"disconnect":this._parseDisconnect();break;case"auth":this._parseAuth();break;default:this._emitError(new Error("Not supported"))}result=true}return result};Parser.prototype._parseConnect=function(){var protocolId;var clientId;var topic;var payload;var password;var username;var flags={};var packet=this.packet;protocolId=this._parseString();if(protocolId===null)return this._emitError(new Error("Cannot parse protocolId"));if(protocolId!=="MQTT"&&protocolId!=="MQIsdp"){return this._emitError(new Error("Invalid protocolId"))}packet.protocolId=protocolId;if(this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));packet.protocolVersion=this._list.readUInt8(this._pos);if(packet.protocolVersion!==3&&packet.protocolVersion!==4&&packet.protocolVersion!==5){return this._emitError(new Error("Invalid protocol version"))}this._pos++;if(this._pos>=this._list.length){return this._emitError(new Error("Packet too short"))}flags.username=this._list.readUInt8(this._pos)&constants.USERNAME_MASK;flags.password=this._list.readUInt8(this._pos)&constants.PASSWORD_MASK;flags.will=this._list.readUInt8(this._pos)&constants.WILL_FLAG_MASK;if(flags.will){packet.will={};packet.will.retain=(this._list.readUInt8(this._pos)&constants.WILL_RETAIN_MASK)!==0;packet.will.qos=(this._list.readUInt8(this._pos)&constants.WILL_QOS_MASK)>>constants.WILL_QOS_SHIFT}packet.clean=(this._list.readUInt8(this._pos)&constants.CLEAN_SESSION_MASK)!==0;this._pos++;packet.keepalive=this._parseNum();if(packet.keepalive===-1)return this._emitError(new Error("Packet too short"));if(packet.protocolVersion===5){var properties=this._parseProperties();if(Object.getOwnPropertyNames(properties).length){packet.properties=properties}}clientId=this._parseString();if(clientId===null)return this._emitError(new Error("Packet too short"));packet.clientId=clientId;if(flags.will){if(packet.protocolVersion===5){var willProperties=this._parseProperties();if(Object.getOwnPropertyNames(willProperties).length){packet.will.properties=willProperties}}topic=this._parseString();if(topic===null)return this._emitError(new Error("Cannot parse will topic"));packet.will.topic=topic;payload=this._parseBuffer();if(payload===null)return this._emitError(new Error("Cannot parse will payload"));packet.will.payload=payload}if(flags.username){username=this._parseString();if(username===null)return this._emitError(new Error("Cannot parse username"));packet.username=username}if(flags.password){password=this._parseBuffer();if(password===null)return this._emitError(new Error("Cannot parse password"));packet.password=password}this.settings=packet;return packet};Parser.prototype._parseConnack=function(){var packet=this.packet;if(this._list.length<2)return null;packet.sessionPresent=!!(this._list.readUInt8(this._pos++)&constants.SESSIONPRESENT_MASK);if(this.settings.protocolVersion===5){packet.reasonCode=this._list.readUInt8(this._pos++)}else{packet.returnCode=this._list.readUInt8(this._pos++)}if(packet.returnCode===-1||packet.reasonCode===-1)return this._emitError(new Error("Cannot parse return code"));if(this.settings.protocolVersion===5){var properties=this._parseProperties();if(Object.getOwnPropertyNames(properties).length){packet.properties=properties}}};Parser.prototype._parsePublish=function(){var packet=this.packet;packet.topic=this._parseString();if(packet.topic===null)return this._emitError(new Error("Cannot parse topic"));if(packet.qos>0)if(!this._parseMessageId()){return}if(this.settings.protocolVersion===5){var properties=this._parseProperties();if(Object.getOwnPropertyNames(properties).length){packet.properties=properties}}packet.payload=this._list.slice(this._pos,packet.length)};Parser.prototype._parseSubscribe=function(){var packet=this.packet;var topic;var options;var qos;var rh;var rap;var nl;var subscription;if(packet.qos!==1){return this._emitError(new Error("Wrong subscribe header"))}packet.subscriptions=[];if(!this._parseMessageId()){return}if(this.settings.protocolVersion===5){var properties=this._parseProperties();if(Object.getOwnPropertyNames(properties).length){packet.properties=properties}}while(this._pos<packet.length){topic=this._parseString();if(topic===null)return this._emitError(new Error("Cannot parse topic"));if(this._pos>=packet.length)return this._emitError(new Error("Malformed Subscribe Payload"));options=this._parseByte();qos=options&constants.SUBSCRIBE_OPTIONS_QOS_MASK;nl=(options>>constants.SUBSCRIBE_OPTIONS_NL_SHIFT&constants.SUBSCRIBE_OPTIONS_NL_MASK)!==0;rap=(options>>constants.SUBSCRIBE_OPTIONS_RAP_SHIFT&constants.SUBSCRIBE_OPTIONS_RAP_MASK)!==0;rh=options>>constants.SUBSCRIBE_OPTIONS_RH_SHIFT&constants.SUBSCRIBE_OPTIONS_RH_MASK;subscription={topic:topic,qos:qos};if(this.settings.protocolVersion===5){subscription.nl=nl;subscription.rap=rap;subscription.rh=rh}packet.subscriptions.push(subscription)}};Parser.prototype._parseSuback=function(){var packet=this.packet;this.packet.granted=[];if(!this._parseMessageId()){return}if(this.settings.protocolVersion===5){var properties=this._parseProperties();if(Object.getOwnPropertyNames(properties).length){packet.properties=properties}}while(this._pos<this.packet.length){this.packet.granted.push(this._list.readUInt8(this._pos++))}};Parser.prototype._parseUnsubscribe=function(){var packet=this.packet;packet.unsubscriptions=[];if(!this._parseMessageId()){return}if(this.settings.protocolVersion===5){var properties=this._parseProperties();if(Object.getOwnPropertyNames(properties).length){packet.properties=properties}}while(this._pos<packet.length){var topic;topic=this._parseString();if(topic===null)return this._emitError(new Error("Cannot parse topic"));packet.unsubscriptions.push(topic)}};Parser.prototype._parseUnsuback=function(){var packet=this.packet;if(!this._parseMessageId())return this._emitError(new Error("Cannot parse messageId"));if(this.settings.protocolVersion===5){var properties=this._parseProperties();if(Object.getOwnPropertyNames(properties).length){packet.properties=properties}packet.granted=[];while(this._pos<this.packet.length){this.packet.granted.push(this._list.readUInt8(this._pos++))}}};Parser.prototype._parseConfirmation=function(){var packet=this.packet;this._parseMessageId();if(this.settings.protocolVersion===5){if(packet.length>2){packet.reasonCode=this._parseByte();var properties=this._parseProperties();if(Object.getOwnPropertyNames(properties).length){packet.properties=properties}}}return true};Parser.prototype._parseDisconnect=function(){var packet=this.packet;if(this.settings.protocolVersion===5){packet.reasonCode=this._parseByte();var properties=this._parseProperties();if(Object.getOwnPropertyNames(properties).length){packet.properties=properties}}return true};Parser.prototype._parseAuth=function(){var packet=this.packet;if(this.settings.protocolVersion!==5){return this._emitError(new Error("Not supported auth packet for this version MQTT"))}packet.reasonCode=this._parseByte();var properties=this._parseProperties();if(Object.getOwnPropertyNames(properties).length){packet.properties=properties}return true};Parser.prototype._parseMessageId=function(){var packet=this.packet;packet.messageId=this._parseNum();if(packet.messageId===null){this._emitError(new Error("Cannot parse messageId"));return false}return true};Parser.prototype._parseString=function(maybeBuffer){var length=this._parseNum();var result;var end=length+this._pos;if(length===-1||end>this._list.length||end>this.packet.length)return null;result=this._list.toString("utf8",this._pos,end);this._pos+=length;return result};Parser.prototype._parseStringPair=function(){return{name:this._parseString(),value:this._parseString()}};Parser.prototype._parseBuffer=function(){var length=this._parseNum();var result;var end=length+this._pos;if(length===-1||end>this._list.length||end>this.packet.length)return null;result=this._list.slice(this._pos,end);this._pos+=length;return result};Parser.prototype._parseNum=function(){if(this._list.length-this._pos<2)return-1;var result=this._list.readUInt16BE(this._pos);this._pos+=2;return result};Parser.prototype._parse4ByteNum=function(){if(this._list.length-this._pos<4)return-1;var result=this._list.readUInt32BE(this._pos);this._pos+=4;return result};Parser.prototype._parseVarByteNum=function(fullInfoFlag){var bytes=0;var mul=1;var length=0;var result=true;var current;var padding=this._pos?this._pos:0;while(bytes<5){current=this._list.readUInt8(padding+bytes++);length+=mul*(current&constants.LENGTH_MASK);mul*=128;if((current&constants.LENGTH_FIN_MASK)===0)break;if(this._list.length<=bytes){result=false;break}}if(padding){this._pos+=bytes}result=result?fullInfoFlag?{bytes:bytes,value:length}:length:false;return result};Parser.prototype._parseByte=function(){var result=this._list.readUInt8(this._pos);this._pos++;return result};Parser.prototype._parseByType=function(type){switch(type){case"byte":{return this._parseByte()!==0}case"int8":{return this._parseByte()}case"int16":{return this._parseNum()}case"int32":{return this._parse4ByteNum()}case"var":{return this._parseVarByteNum()}case"string":{return this._parseString()}case"pair":{return this._parseStringPair()}case"binary":{return this._parseBuffer()}}};Parser.prototype._parseProperties=function(){var length=this._parseVarByteNum();var start=this._pos;var end=start+length;var result={};while(this._pos<end){var type=this._parseByte();var name=constants.propertiesCodes[type];if(!name){this._emitError(new Error("Unknown property"));return false}if(name==="userProperties"){if(!result[name]){result[name]={}}var currentUserProperty=this._parseByType(constants.propertiesTypes[name]);if(result[name][currentUserProperty.name]){if(Array.isArray(result[name][currentUserProperty.name])){result[name][currentUserProperty.name].push(currentUserProperty.value)}else{var currentValue=result[name][currentUserProperty.name];result[name][currentUserProperty.name]=[currentValue];result[name][currentUserProperty.name].push(currentUserProperty.value)}}else{result[name][currentUserProperty.name]=currentUserProperty.value}continue}if(result[name]){if(Array.isArray(result[name])){result[name].push(this._parseByType(constants.propertiesTypes[name]))}else{result[name]=[result[name]];result[name].push(this._parseByType(constants.propertiesTypes[name]))}}else{result[name]=this._parseByType(constants.propertiesTypes[name])}}return result};Parser.prototype._newPacket=function(){if(this.packet){this._list.consume(this.packet.length);this.emit("packet",this.packet)}this.packet=new Packet;this._pos=0;return true};Parser.prototype._emitError=function(err){this.error=err;this.emit("error",err)};module.exports=Parser},{"./constants":153,"./packet":157,bl:69,events:73,inherits:148}],159:[function(require,module,exports){"use strict";var protocol=require("./constants");var Buffer=require("safe-buffer").Buffer;var empty=Buffer.allocUnsafe(0);var zeroBuf=Buffer.from([0]);var numbers=require("./numbers");var nextTick=require("process-nextick-args").nextTick;var numCache=numbers.cache;var generateNumber=numbers.generateNumber;var generateCache=numbers.generateCache;var genBufVariableByteInt=numbers.genBufVariableByteInt;var generate4ByteBuffer=numbers.generate4ByteBuffer;var writeNumber=writeNumberCached;var toGenerate=true;function generate(packet,stream,opts){if(stream.cork){stream.cork();nextTick(uncork,stream)}if(toGenerate){toGenerate=false;generateCache()}switch(packet.cmd){case"connect":return connect(packet,stream,opts);case"connack":return connack(packet,stream,opts);case"publish":return publish(packet,stream,opts);case"puback":case"pubrec":case"pubrel":case"pubcomp":return confirmation(packet,stream,opts);case"subscribe":return subscribe(packet,stream,opts);case"suback":return suback(packet,stream,opts);case"unsubscribe":return unsubscribe(packet,stream,opts);case"unsuback":return unsuback(packet,stream,opts);case"pingreq":case"pingresp":return emptyPacket(packet,stream,opts);case"disconnect":return disconnect(packet,stream,opts);case"auth":return auth(packet,stream,opts);default:stream.emit("error",new Error("Unknown command"));return false}}Object.defineProperty(generate,"cacheNumbers",{get:function(){return writeNumber===writeNumberCached},set:function(value){if(value){if(!numCache||Object.keys(numCache).length===0)toGenerate=true;writeNumber=writeNumberCached}else{toGenerate=false;writeNumber=writeNumberGenerated}}});function uncork(stream){stream.uncork()}function connect(packet,stream,opts){var settings=packet||{};var protocolId=settings.protocolId||"MQTT";var protocolVersion=settings.protocolVersion||4;var will=settings.will;var clean=settings.clean;var keepalive=settings.keepalive||0;var clientId=settings.clientId||"";var username=settings.username;var password=settings.password;var properties=settings.properties;if(clean===undefined)clean=true;var length=0;if(!protocolId||typeof protocolId!=="string"&&!Buffer.isBuffer(protocolId)){stream.emit("error",new Error("Invalid protocolId"));return false}else length+=protocolId.length+2;if(protocolVersion!==3&&protocolVersion!==4&&protocolVersion!==5){stream.emit("error",new Error("Invalid protocol version"));return false}else length+=1;if((typeof clientId==="string"||Buffer.isBuffer(clientId))&&(clientId||protocolVersion===4)&&(clientId||clean)){length+=clientId.length+2}else{if(protocolVersion<4){stream.emit("error",new Error("clientId must be supplied before 3.1.1"));return false}if(clean*1===0){stream.emit("error",new Error("clientId must be given if cleanSession set to 0"));return false}}if(typeof keepalive!=="number"||keepalive<0||keepalive>65535||keepalive%1!==0){stream.emit("error",new Error("Invalid keepalive"));return false}else length+=2;length+=1;if(protocolVersion===5){var propertiesData=getProperties(stream,properties);length+=propertiesData.length}if(will){if(typeof will!=="object"){stream.emit("error",new Error("Invalid will"));return false}if(!will.topic||typeof will.topic!=="string"){stream.emit("error",new Error("Invalid will topic"));return false}else{length+=Buffer.byteLength(will.topic)+2}length+=2;if(will.payload){if(will.payload.length>=0){if(typeof will.payload==="string"){length+=Buffer.byteLength(will.payload)}else{length+=will.payload.length}}else{stream.emit("error",new Error("Invalid will payload"));return false}}var willProperties={};if(protocolVersion===5){willProperties=getProperties(stream,will.properties);length+=willProperties.length}}var providedUsername=false;if(username!=null){if(isStringOrBuffer(username)){providedUsername=true;length+=Buffer.byteLength(username)+2}else{stream.emit("error",new Error("Invalid username"));return false}}if(password!=null){if(!providedUsername){stream.emit("error",new Error("Username is required to use password"));return false}if(isStringOrBuffer(password)){length+=byteLength(password)+2}else{stream.emit("error",new Error("Invalid password"));return false}}stream.write(protocol.CONNECT_HEADER);writeVarByteInt(stream,length);writeStringOrBuffer(stream,protocolId);stream.write(protocolVersion===4?protocol.VERSION4:protocolVersion===5?protocol.VERSION5:protocol.VERSION3);var flags=0;flags|=username!=null?protocol.USERNAME_MASK:0;flags|=password!=null?protocol.PASSWORD_MASK:0;flags|=will&&will.retain?protocol.WILL_RETAIN_MASK:0;flags|=will&&will.qos?will.qos<<protocol.WILL_QOS_SHIFT:0;flags|=will?protocol.WILL_FLAG_MASK:0;flags|=clean?protocol.CLEAN_SESSION_MASK:0;stream.write(Buffer.from([flags]));writeNumber(stream,keepalive);if(protocolVersion===5){propertiesData.write()}writeStringOrBuffer(stream,clientId);if(will){if(protocolVersion===5){willProperties.write()}writeString(stream,will.topic);writeStringOrBuffer(stream,will.payload)}if(username!=null){writeStringOrBuffer(stream,username)}if(password!=null){writeStringOrBuffer(stream,password)}return true}function connack(packet,stream,opts){var version=opts?opts.protocolVersion:4;var settings=packet||{};var rc=version===5?settings.reasonCode:settings.returnCode;var properties=settings.properties;var length=2;if(typeof rc!=="number"){stream.emit("error",new Error("Invalid return code"));return false}var propertiesData=null;if(version===5){propertiesData=getProperties(stream,properties);length+=propertiesData.length}stream.write(protocol.CONNACK_HEADER);writeVarByteInt(stream,length);stream.write(settings.sessionPresent?protocol.SESSIONPRESENT_HEADER:zeroBuf);stream.write(Buffer.from([rc]));if(propertiesData!=null){propertiesData.write()}return true}function publish(packet,stream,opts){var version=opts?opts.protocolVersion:4;var settings=packet||{};var qos=settings.qos||0;var retain=settings.retain?protocol.RETAIN_MASK:0;var topic=settings.topic;var payload=settings.payload||empty;var id=settings.messageId;var properties=settings.properties;var length=0;if(typeof topic==="string")length+=Buffer.byteLength(topic)+2;else if(Buffer.isBuffer(topic))length+=topic.length+2;else{stream.emit("error",new Error("Invalid topic"));return false}if(!Buffer.isBuffer(payload))length+=Buffer.byteLength(payload);else length+=payload.length;if(qos&&typeof id!=="number"){stream.emit("error",new Error("Invalid messageId"));return false}else if(qos)length+=2;var propertiesData=null;if(version===5){propertiesData=getProperties(stream,properties);length+=propertiesData.length}stream.write(protocol.PUBLISH_HEADER[qos][settings.dup?1:0][retain?1:0]);writeVarByteInt(stream,length);writeNumber(stream,byteLength(topic));stream.write(topic);if(qos>0)writeNumber(stream,id);if(propertiesData!=null){propertiesData.write()}return stream.write(payload)}function confirmation(packet,stream,opts){var version=opts?opts.protocolVersion:4;var settings=packet||{};var type=settings.cmd||"puback";var id=settings.messageId;var dup=settings.dup&&type==="pubrel"?protocol.DUP_MASK:0;var qos=0;var reasonCode=settings.reasonCode;var properties=settings.properties;var length=version===5?3:2;if(type==="pubrel")qos=1;if(typeof id!=="number"){stream.emit("error",new Error("Invalid messageId"));return false}var propertiesData=null;if(version===5){propertiesData=getPropertiesByMaximumPacketSize(stream,properties,opts,length);if(!propertiesData){return false}length+=propertiesData.length}stream.write(protocol.ACKS[type][qos][dup][0]);writeVarByteInt(stream,length);writeNumber(stream,id);if(version===5){stream.write(Buffer.from([reasonCode]))}if(propertiesData!==null){propertiesData.write()}return true}function subscribe(packet,stream,opts){var version=opts?opts.protocolVersion:4;var settings=packet||{};var dup=settings.dup?protocol.DUP_MASK:0;var id=settings.messageId;var subs=settings.subscriptions;var properties=settings.properties;var length=0;if(typeof id!=="number"){stream.emit("error",new Error("Invalid messageId"));return false}else length+=2;var propertiesData=null;if(version===5){propertiesData=getProperties(stream,properties);length+=propertiesData.length}if(typeof subs==="object"&&subs.length){for(var i=0;i<subs.length;i+=1){var itopic=subs[i].topic;var iqos=subs[i].qos;if(typeof itopic!=="string"){stream.emit("error",new Error("Invalid subscriptions - invalid topic"));return false}if(typeof iqos!=="number"){stream.emit("error",new Error("Invalid subscriptions - invalid qos"));return false}if(version===5){var nl=subs[i].nl||false;if(typeof nl!=="boolean"){stream.emit("error",new Error("Invalid subscriptions - invalid No Local"));return false}var rap=subs[i].rap||false;if(typeof rap!=="boolean"){stream.emit("error",new Error("Invalid subscriptions - invalid Retain as Published"));return false}var rh=subs[i].rh||0;if(typeof rh!=="number"||rh>2){stream.emit("error",new Error("Invalid subscriptions - invalid Retain Handling"));return false}}length+=Buffer.byteLength(itopic)+2+1}}else{stream.emit("error",new Error("Invalid subscriptions"));return false}stream.write(protocol.SUBSCRIBE_HEADER[1][dup?1:0][0]);writeVarByteInt(stream,length);writeNumber(stream,id);if(propertiesData!==null){propertiesData.write()}var result=true;for(var j=0;j<subs.length;j++){var sub=subs[j];var jtopic=sub.topic;var jqos=sub.qos;var jnl=+sub.nl;var jrap=+sub.rap;var jrh=sub.rh;var joptions;writeString(stream,jtopic);joptions=protocol.SUBSCRIBE_OPTIONS_QOS[jqos];if(version===5){joptions|=jnl?protocol.SUBSCRIBE_OPTIONS_NL:0;joptions|=jrap?protocol.SUBSCRIBE_OPTIONS_RAP:0;joptions|=jrh?protocol.SUBSCRIBE_OPTIONS_RH[jrh]:0}result=stream.write(Buffer.from([joptions]))}return result}function suback(packet,stream,opts){var version=opts?opts.protocolVersion:4;var settings=packet||{};var id=settings.messageId;var granted=settings.granted;var properties=settings.properties;var length=0;if(typeof id!=="number"){stream.emit("error",new Error("Invalid messageId"));return false}else length+=2;if(typeof granted==="object"&&granted.length){for(var i=0;i<granted.length;i+=1){if(typeof granted[i]!=="number"){stream.emit("error",new Error("Invalid qos vector"));return false}length+=1}}else{stream.emit("error",new Error("Invalid qos vector"));return false}var propertiesData=null;if(version===5){propertiesData=getPropertiesByMaximumPacketSize(stream,properties,opts,length);if(!propertiesData){return false}length+=propertiesData.length}stream.write(protocol.SUBACK_HEADER);writeVarByteInt(stream,length);writeNumber(stream,id);if(propertiesData!==null){propertiesData.write()}return stream.write(Buffer.from(granted))}function unsubscribe(packet,stream,opts){var version=opts?opts.protocolVersion:4;var settings=packet||{};var id=settings.messageId;var dup=settings.dup?protocol.DUP_MASK:0;var unsubs=settings.unsubscriptions;var properties=settings.properties;var length=0;if(typeof id!=="number"){stream.emit("error",new Error("Invalid messageId"));return false}else{length+=2}if(typeof unsubs==="object"&&unsubs.length){for(var i=0;i<unsubs.length;i+=1){if(typeof unsubs[i]!=="string"){stream.emit("error",new Error("Invalid unsubscriptions"));return false}length+=Buffer.byteLength(unsubs[i])+2}}else{stream.emit("error",new Error("Invalid unsubscriptions"));return false}var propertiesData=null;if(version===5){propertiesData=getProperties(stream,properties);length+=propertiesData.length}stream.write(protocol.UNSUBSCRIBE_HEADER[1][dup?1:0][0]);writeVarByteInt(stream,length);writeNumber(stream,id);if(propertiesData!==null){propertiesData.write()}var result=true;for(var j=0;j<unsubs.length;j++){result=writeString(stream,unsubs[j])}return result}function unsuback(packet,stream,opts){var version=opts?opts.protocolVersion:4;var settings=packet||{};var id=settings.messageId;var dup=settings.dup?protocol.DUP_MASK:0;var granted=settings.granted;var properties=settings.properties;var type=settings.cmd;var qos=0;var length=2;if(typeof id!=="number"){stream.emit("error",new Error("Invalid messageId"));return false}if(version===5){if(typeof granted==="object"&&granted.length){for(var i=0;i<granted.length;i+=1){if(typeof granted[i]!=="number"){stream.emit("error",new Error("Invalid qos vector"));return false}length+=1}}else{stream.emit("error",new Error("Invalid qos vector"));return false}}var propertiesData=null;if(version===5){propertiesData=getPropertiesByMaximumPacketSize(stream,properties,opts,length);if(!propertiesData){return false}length+=propertiesData.length}stream.write(protocol.ACKS[type][qos][dup][0]);writeVarByteInt(stream,length);writeNumber(stream,id);if(propertiesData!==null){propertiesData.write()}if(version===5){stream.write(Buffer.from(granted))}return true}function emptyPacket(packet,stream,opts){return stream.write(protocol.EMPTY[packet.cmd])}function disconnect(packet,stream,opts){var version=opts?opts.protocolVersion:4;var settings=packet||{};var reasonCode=settings.reasonCode;var properties=settings.properties;var length=version===5?1:0;var propertiesData=null;if(version===5){propertiesData=getPropertiesByMaximumPacketSize(stream,properties,opts,length);if(!propertiesData){return false}length+=propertiesData.length}stream.write(Buffer.from([protocol.codes["disconnect"]<<4]));writeVarByteInt(stream,length);if(version===5){stream.write(Buffer.from([reasonCode]))}if(propertiesData!==null){propertiesData.write()}return true}function auth(packet,stream,opts){var version=opts?opts.protocolVersion:4;var settings=packet||{};var reasonCode=settings.reasonCode;var properties=settings.properties;var length=version===5?1:0;if(version!==5)stream.emit("error",new Error("Invalid mqtt version for auth packet"));var propertiesData=getPropertiesByMaximumPacketSize(stream,properties,opts,length);if(!propertiesData){return false}length+=propertiesData.length;stream.write(Buffer.from([protocol.codes["auth"]<<4]));writeVarByteInt(stream,length);stream.write(Buffer.from([reasonCode]));if(propertiesData!==null){propertiesData.write()}return true}var varByteIntCache={};function writeVarByteInt(stream,num){var buffer=varByteIntCache[num];if(!buffer){buffer=genBufVariableByteInt(num).data;if(num<16384)varByteIntCache[num]=buffer}stream.write(buffer)}function writeString(stream,string){var strlen=Buffer.byteLength(string);writeNumber(stream,strlen);return stream.write(string,"utf8")}function writeStringPair(stream,name,value){writeString(stream,name);writeString(stream,value)}function writeNumberCached(stream,number){return stream.write(numCache[number])}function writeNumberGenerated(stream,number){return stream.write(generateNumber(number))}function write4ByteNumber(stream,number){return stream.write(generate4ByteBuffer(number))}function writeStringOrBuffer(stream,toWrite){if(typeof toWrite==="string"){writeString(stream,toWrite)}else if(toWrite){writeNumber(stream,toWrite.length);stream.write(toWrite)}else writeNumber(stream,0)}function getProperties(stream,properties){if(typeof properties!=="object"||properties.length!=null){return{length:1,write:function(){writeProperties(stream,{},0)}}}var propertiesLength=0;function getLengthProperty(name,value){var type=protocol.propertiesTypes[name];var length=0;switch(type){case"byte":{if(typeof value!=="boolean"){stream.emit("error",new Error("Invalid "+name));return false}length+=1+1;break}case"int8":{if(typeof value!=="number"){stream.emit("error",new Error("Invalid "+name));return false}length+=1+1;break}case"binary":{if(value&&value===null){stream.emit("error",new Error("Invalid "+name));return false}length+=1+Buffer.byteLength(value)+2;break}case"int16":{if(typeof value!=="number"){stream.emit("error",new Error("Invalid "+name));return false}length+=1+2;break}case"int32":{if(typeof value!=="number"){stream.emit("error",new Error("Invalid "+name));return false}length+=1+4;break}case"var":{if(typeof value!=="number"){stream.emit("error",new Error("Invalid "+name));return false}length+=1+genBufVariableByteInt(value).length;break}case"string":{if(typeof value!=="string"){stream.emit("error",new Error("Invalid "+name));return false}length+=1+2+Buffer.byteLength(value.toString());break}case"pair":{if(typeof value!=="object"){stream.emit("error",new Error("Invalid "+name));return false}length+=Object.getOwnPropertyNames(value).reduce((function(result,name){var currentValue=value[name];if(Array.isArray(currentValue)){result+=currentValue.reduce((function(currentLength,value){currentLength+=1+2+Buffer.byteLength(name.toString())+2+Buffer.byteLength(value.toString());return currentLength}),0)}else{result+=1+2+Buffer.byteLength(name.toString())+2+Buffer.byteLength(value[name].toString())}return result}),0);break}default:{stream.emit("error",new Error("Invalid property "+name));return false}}return length}if(properties){for(var propName in properties){var propLength=0;var propValue=properties[propName];if(Array.isArray(propValue)){for(var valueIndex=0;valueIndex<propValue.length;valueIndex++){propLength+=getLengthProperty(propName,propValue[valueIndex])}}else{propLength=getLengthProperty(propName,propValue)}if(!propLength)return false;propertiesLength+=propLength}}var propertiesLengthLength=genBufVariableByteInt(propertiesLength).length;return{length:propertiesLengthLength+propertiesLength,write:function(){writeProperties(stream,properties,propertiesLength)}}}function getPropertiesByMaximumPacketSize(stream,properties,opts,length){var mayEmptyProps=["reasonString","userProperties"];var maximumPacketSize=opts&&opts.properties&&opts.properties.maximumPacketSize?opts.properties.maximumPacketSize:0;var propertiesData=getProperties(stream,properties);if(maximumPacketSize){while(length+propertiesData.length>maximumPacketSize){var currentMayEmptyProp=mayEmptyProps.shift();if(currentMayEmptyProp&&properties[currentMayEmptyProp]){delete properties[currentMayEmptyProp];propertiesData=getProperties(stream,properties)}else{return false}}}return propertiesData}function writeProperty(stream,propName,value){var type=protocol.propertiesTypes[propName];switch(type){case"byte":{stream.write(Buffer.from([protocol.properties[propName]]));stream.write(Buffer.from([+value]));break}case"int8":{stream.write(Buffer.from([protocol.properties[propName]]));stream.write(Buffer.from([value]));break}case"binary":{stream.write(Buffer.from([protocol.properties[propName]]));writeStringOrBuffer(stream,value);break}case"int16":{stream.write(Buffer.from([protocol.properties[propName]]));writeNumber(stream,value);break}case"int32":{stream.write(Buffer.from([protocol.properties[propName]]));write4ByteNumber(stream,value);break}case"var":{stream.write(Buffer.from([protocol.properties[propName]]));writeVarByteInt(stream,value);break}case"string":{stream.write(Buffer.from([protocol.properties[propName]]));writeString(stream,value);break}case"pair":{Object.getOwnPropertyNames(value).forEach((function(name){var currentValue=value[name];if(Array.isArray(currentValue)){currentValue.forEach((function(value){stream.write(Buffer.from([protocol.properties[propName]]));writeStringPair(stream,name.toString(),value.toString())}))}else{stream.write(Buffer.from([protocol.properties[propName]]));writeStringPair(stream,name.toString(),currentValue.toString())}}));break}default:{stream.emit("error",new Error("Invalid property "+propName+" value: "+value));return false}}}function writeProperties(stream,properties,propertiesLength){writeVarByteInt(stream,propertiesLength);for(var propName in properties){if(properties.hasOwnProperty(propName)&&properties[propName]!==null){var value=properties[propName];if(Array.isArray(value)){for(var valueIndex=0;valueIndex<value.length;valueIndex++){writeProperty(stream,propName,value[valueIndex])}}else{writeProperty(stream,propName,value)}}}}function byteLength(bufOrString){if(!bufOrString)return 0;else if(bufOrString instanceof Buffer)return bufOrString.length;else return Buffer.byteLength(bufOrString)}function isStringOrBuffer(field){return typeof field==="string"||field instanceof Buffer}module.exports=generate},{"./constants":153,"./numbers":156,"process-nextick-args":170,"safe-buffer":189}],160:[function(require,module,exports){(function(process,global){"use strict";var events=require("events");var Store=require("./store");var mqttPacket=require("mqtt-packet");var Writable=require("readable-stream").Writable;var inherits=require("inherits");var reInterval=require("reinterval");var validations=require("./validations");var xtend=require("xtend");var setImmediate=global.setImmediate||function(callback){process.nextTick(callback)};var defaultConnectOptions={keepalive:60,reschedulePings:true,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:1e3,connectTimeout:30*1e3,clean:true,resubscribe:true};var errors={0:"",1:"Unacceptable protocol version",2:"Identifier rejected",3:"Server unavailable",4:"Bad username or password",5:"Not authorized",16:"No matching subscribers",17:"No subscription existed",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",132:"Unsupported Protocol Version",133:"Client Identifier not valid",134:"Bad User Name or Password",135:"Not authorized",136:"Server unavailable",137:"Server busy",138:"Banned",139:"Server shutting down",140:"Bad authentication method",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",145:"Packet identifier in use",146:"Packet Identifier not found",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};function defaultId(){return"mqttjs_"+Math.random().toString(16).substr(2,8)}function sendPacket(client,packet,cb){client.emit("packetsend",packet);var result=mqttPacket.writeToStream(packet,client.stream,client.options);if(!result&&cb){client.stream.once("drain",cb)}else if(cb){cb()}}function flush(queue){if(queue){Object.keys(queue).forEach((function(messageId){if(typeof queue[messageId].cb==="function"){queue[messageId].cb(new Error("Connection closed"));delete queue[messageId]}}))}}function flushVolatile(queue){if(queue){Object.keys(queue).forEach((function(messageId){if(queue[messageId].volatile&&typeof queue[messageId].cb==="function"){queue[messageId].cb(new Error("Connection closed"));delete queue[messageId]}}))}}function storeAndSend(client,packet,cb,cbStorePut){client.outgoingStore.put(packet,(function storedPacket(err){if(err){return cb&&cb(err)}cbStorePut();sendPacket(client,packet,cb)}))}function nop(){}function MqttClient(streamBuilder,options){var k;var that=this;if(!(this instanceof MqttClient)){return new MqttClient(streamBuilder,options)}this.options=options||{};for(k in defaultConnectOptions){if(typeof this.options[k]==="undefined"){this.options[k]=defaultConnectOptions[k]}else{this.options[k]=options[k]}}this.options.clientId=typeof options.clientId==="string"?options.clientId:defaultId();this.options.customHandleAcks=options.protocolVersion===5&&options.customHandleAcks?options.customHandleAcks:function(){arguments[3](0)};this.streamBuilder=streamBuilder;this.outgoingStore=options.outgoingStore||new Store;this.incomingStore=options.incomingStore||new Store;this.queueQoSZero=options.queueQoSZero===undefined?true:options.queueQoSZero;this._resubscribeTopics={};this.messageIdToTopic={};this.pingTimer=null;this.connected=false;this.disconnecting=false;this.queue=[];this.connackTimer=null;this.reconnectTimer=null;this._storeProcessing=false;this._packetIdsDuringStoreProcessing={};this.nextId=Math.max(1,Math.floor(Math.random()*65535));this.outgoing={};this._firstConnection=true;this.on("close",(function(){this.connected=false;clearTimeout(this.connackTimer)}));this.on("connect",(function(){var queue=this.queue;function deliver(){var entry=queue.shift();var packet=null;if(!entry){return}packet=entry.packet;that._sendPacket(packet,(function(err){if(entry.cb){entry.cb(err)}deliver()}))}deliver()}));this.on("close",(function(){if(that.pingTimer!==null){that.pingTimer.clear();that.pingTimer=null}}));this.on("close",this._setupReconnect);events.EventEmitter.call(this);this._setupStream()}inherits(MqttClient,events.EventEmitter);MqttClient.prototype._setupStream=function(){var connectPacket;var that=this;var writable=new Writable;var parser=mqttPacket.parser(this.options);var completeParse=null;var packets=[];this._clearReconnect();this.stream=this.streamBuilder(this);parser.on("packet",(function(packet){packets.push(packet)}));function nextTickWork(){if(packets.length){process.nextTick(work)}else{var done=completeParse;completeParse=null;done()}}function work(){var packet=packets.shift();if(packet){that._handlePacket(packet,nextTickWork)}else{var done=completeParse;completeParse=null;if(done)done()}}writable._write=function(buf,enc,done){completeParse=done;parser.parse(buf);work()};this.stream.pipe(writable);this.stream.on("error",nop);this.stream.on("close",(function(){flushVolatile(that.outgoing);that.emit("close")}));connectPacket=Object.create(this.options);connectPacket.cmd="connect";sendPacket(this,connectPacket);parser.on("error",this.emit.bind(this,"error"));if(this.options.properties){if(!this.options.properties.authenticationMethod&&this.options.properties.authenticationData){this.emit("error",new Error("Packet has no Authentication Method"));return this}if(this.options.properties.authenticationMethod&&this.options.authPacket&&typeof this.options.authPacket==="object"){var authPacket=xtend({cmd:"auth",reasonCode:0},this.options.authPacket);sendPacket(this,authPacket)}}this.stream.setMaxListeners(1e3);clearTimeout(this.connackTimer);this.connackTimer=setTimeout((function(){that._cleanUp(true)}),this.options.connectTimeout)};MqttClient.prototype._handlePacket=function(packet,done){var options=this.options;if(options.protocolVersion===5&&options.properties&&options.properties.maximumPacketSize&&options.properties.maximumPacketSize<packet.length){this.emit("error",new Error("exceeding packets size "+packet.cmd));this.end({reasonCode:149,properties:{reasonString:"Maximum packet size was exceeded"}});return this}this.emit("packetreceive",packet);switch(packet.cmd){case"publish":this._handlePublish(packet,done);break;case"puback":case"pubrec":case"pubcomp":case"suback":case"unsuback":this._handleAck(packet);done();break;case"pubrel":this._handlePubrel(packet,done);break;case"connack":this._handleConnack(packet);done();break;case"pingresp":this._handlePingresp(packet);done();break;case"disconnect":this._handleDisconnect(packet);done();break;default:break}};MqttClient.prototype._checkDisconnecting=function(callback){if(this.disconnecting){if(callback){callback(new Error("client disconnecting"))}else{this.emit("error",new Error("client disconnecting"))}}return this.disconnecting};MqttClient.prototype.publish=function(topic,message,opts,callback){var packet;var options=this.options;if(typeof opts==="function"){callback=opts;opts=null}var defaultOpts={qos:0,retain:false,dup:false};opts=xtend(defaultOpts,opts);if(this._checkDisconnecting(callback)){return this}packet={cmd:"publish",topic:topic,payload:message,qos:opts.qos,retain:opts.retain,messageId:this._nextId(),dup:opts.dup};if(options.protocolVersion===5){packet.properties=opts.properties;if(!options.properties&&packet.properties&&packet.properties.topicAlias||opts.properties&&options.properties&&(opts.properties.topicAlias&&options.properties.topicAliasMaximum&&opts.properties.topicAlias>options.properties.topicAliasMaximum||!options.properties.topicAliasMaximum&&opts.properties.topicAlias)){delete packet.properties.topicAlias}}switch(opts.qos){case 1:case 2:this.outgoing[packet.messageId]={volatile:false,cb:callback||nop};if(this._storeProcessing){this._packetIdsDuringStoreProcessing[packet.messageId]=false;this._storePacket(packet,undefined,opts.cbStorePut)}else{this._sendPacket(packet,undefined,opts.cbStorePut)}break;default:if(this._storeProcessing){this._storePacket(packet,callback,opts.cbStorePut)}else{this._sendPacket(packet,callback,opts.cbStorePut)}break}return this};MqttClient.prototype.subscribe=function(){var packet;var args=new Array(arguments.length);for(var i=0;i<arguments.length;i++){args[i]=arguments[i]}var subs=[];var obj=args.shift();var resubscribe=obj.resubscribe;var callback=args.pop()||nop;var opts=args.pop();var invalidTopic;var that=this;var version=this.options.protocolVersion;delete obj.resubscribe;if(typeof obj==="string"){obj=[obj]}if(typeof callback!=="function"){opts=callback;callback=nop}invalidTopic=validations.validateTopics(obj);if(invalidTopic!==null){setImmediate(callback,new Error("Invalid topic "+invalidTopic));return this}if(this._checkDisconnecting(callback)){return this}var defaultOpts={qos:0};if(version===5){defaultOpts.nl=false;defaultOpts.rap=false;defaultOpts.rh=0}opts=xtend(defaultOpts,opts);if(Array.isArray(obj)){obj.forEach((function(topic){if(!that._resubscribeTopics.hasOwnProperty(topic)||that._resubscribeTopics[topic].qos<opts.qos||resubscribe){var currentOpts={topic:topic,qos:opts.qos};if(version===5){currentOpts.nl=opts.nl;currentOpts.rap=opts.rap;currentOpts.rh=opts.rh;currentOpts.properties=opts.properties}subs.push(currentOpts)}}))}else{Object.keys(obj).forEach((function(k){if(!that._resubscribeTopics.hasOwnProperty(k)||that._resubscribeTopics[k].qos<obj[k].qos||resubscribe){var currentOpts={topic:k,qos:obj[k].qos};if(version===5){currentOpts.nl=obj[k].nl;currentOpts.rap=obj[k].rap;currentOpts.rh=obj[k].rh;currentOpts.properties=opts.properties}subs.push(currentOpts)}}))}packet={cmd:"subscribe",subscriptions:subs,qos:1,retain:false,dup:false,messageId:this._nextId()};if(opts.properties){packet.properties=opts.properties}if(!subs.length){callback(null,[]);return}if(this.options.resubscribe){var topics=[];subs.forEach((function(sub){if(that.options.reconnectPeriod>0){var topic={qos:sub.qos};if(version===5){topic.nl=sub.nl||false;topic.rap=sub.rap||false;topic.rh=sub.rh||0;topic.properties=sub.properties}that._resubscribeTopics[sub.topic]=topic;topics.push(sub.topic)}}));that.messageIdToTopic[packet.messageId]=topics}this.outgoing[packet.messageId]={volatile:true,cb:function(err,packet){if(!err){var granted=packet.granted;for(var i=0;i<granted.length;i+=1){subs[i].qos=granted[i]}}callback(err,subs)}};this._sendPacket(packet);return this};MqttClient.prototype.unsubscribe=function(){var packet={cmd:"unsubscribe",qos:1,messageId:this._nextId()};var that=this;var args=new Array(arguments.length);for(var i=0;i<arguments.length;i++){args[i]=arguments[i]}var topic=args.shift();var callback=args.pop()||nop;var opts=args.pop();if(typeof topic==="string"){topic=[topic]}if(typeof callback!=="function"){opts=callback;callback=nop}if(this._checkDisconnecting(callback)){return this}if(typeof topic==="string"){packet.unsubscriptions=[topic]}else if(typeof topic==="object"&&topic.length){packet.unsubscriptions=topic}if(this.options.resubscribe){packet.unsubscriptions.forEach((function(topic){delete that._resubscribeTopics[topic]}))}if(typeof opts==="object"&&opts.properties){packet.properties=opts.properties}this.outgoing[packet.messageId]={volatile:true,cb:callback};this._sendPacket(packet);return this};MqttClient.prototype.end=function(){var that=this;var force=arguments[0];var opts=arguments[1];var cb=arguments[2];if(force==null||typeof force!=="boolean"){cb=opts||nop;opts=force;force=false;if(typeof opts!=="object"){cb=opts;opts=null;if(typeof cb!=="function"){cb=nop}}}if(typeof opts!=="object"){cb=opts;opts=null}cb=cb||nop;function closeStores(){that.disconnected=true;that.incomingStore.close((function(){that.outgoingStore.close((function(){if(cb){cb.apply(null,arguments)}that.emit("end")}))}));if(that._deferredReconnect){that._deferredReconnect()}}function finish(){that._cleanUp(force,setImmediate.bind(null,closeStores),opts)}if(this.disconnecting){return this}this._clearReconnect();this.disconnecting=true;if(!force&&Object.keys(this.outgoing).length>0){this.once("outgoingEmpty",setTimeout.bind(null,finish,10))}else{finish()}return this};MqttClient.prototype.removeOutgoingMessage=function(mid){var cb=this.outgoing[mid]?this.outgoing[mid].cb:null;delete this.outgoing[mid];this.outgoingStore.del({messageId:mid},(function(){cb(new Error("Message removed"))}));return this};MqttClient.prototype.reconnect=function(opts){var that=this;var f=function(){if(opts){that.options.incomingStore=opts.incomingStore;that.options.outgoingStore=opts.outgoingStore}else{that.options.incomingStore=null;that.options.outgoingStore=null}that.incomingStore=that.options.incomingStore||new Store;that.outgoingStore=that.options.outgoingStore||new Store;that.disconnecting=false;that.disconnected=false;that._deferredReconnect=null;that._reconnect()};if(this.disconnecting&&!this.disconnected){this._deferredReconnect=f}else{f()}return this};MqttClient.prototype._reconnect=function(){this.emit("reconnect");this._setupStream()};MqttClient.prototype._setupReconnect=function(){var that=this;if(!that.disconnecting&&!that.reconnectTimer&&that.options.reconnectPeriod>0){if(!this.reconnecting){this.emit("offline");this.reconnecting=true}that.reconnectTimer=setInterval((function(){that._reconnect()}),that.options.reconnectPeriod)}};MqttClient.prototype._clearReconnect=function(){if(this.reconnectTimer){clearInterval(this.reconnectTimer);this.reconnectTimer=null}};MqttClient.prototype._cleanUp=function(forced,done){var opts=arguments[2];if(done){this.stream.on("close",done)}if(forced){if(this.options.reconnectPeriod===0&&this.options.clean){flush(this.outgoing)}this.stream.destroy()}else{var packet=xtend({cmd:"disconnect"},opts);this._sendPacket(packet,setImmediate.bind(null,this.stream.end.bind(this.stream)))}if(!this.disconnecting){this._clearReconnect();this._setupReconnect()}if(this.pingTimer!==null){this.pingTimer.clear();this.pingTimer=null}if(done&&!this.connected){this.stream.removeListener("close",done);done()}};MqttClient.prototype._sendPacket=function(packet,cb,cbStorePut){cbStorePut=cbStorePut||nop;if(!this.connected){this._storePacket(packet,cb,cbStorePut);return}this._shiftPingInterval();switch(packet.cmd){case"publish":break;case"pubrel":storeAndSend(this,packet,cb,cbStorePut);return;default:sendPacket(this,packet,cb);return}switch(packet.qos){case 2:case 1:storeAndSend(this,packet,cb,cbStorePut);break;case 0:default:sendPacket(this,packet,cb);break}};MqttClient.prototype._storePacket=function(packet,cb,cbStorePut){cbStorePut=cbStorePut||nop;if((packet.qos||0)===0&&this.queueQoSZero||packet.cmd!=="publish"){this.queue.push({packet:packet,cb:cb})}else if(packet.qos>0){cb=this.outgoing[packet.messageId]?this.outgoing[packet.messageId].cb:null;this.outgoingStore.put(packet,(function(err){if(err){return cb&&cb(err)}cbStorePut()}))}else if(cb){cb(new Error("No connection to broker"))}};MqttClient.prototype._setupPingTimer=function(){var that=this;if(!this.pingTimer&&this.options.keepalive){this.pingResp=true;this.pingTimer=reInterval((function(){that._checkPing()}),this.options.keepalive*1e3)}};MqttClient.prototype._shiftPingInterval=function(){if(this.pingTimer&&this.options.keepalive&&this.options.reschedulePings){this.pingTimer.reschedule(this.options.keepalive*1e3)}};MqttClient.prototype._checkPing=function(){if(this.pingResp){this.pingResp=false;this._sendPacket({cmd:"pingreq"})}else{this._cleanUp(true)}};MqttClient.prototype._handlePingresp=function(){this.pingResp=true};MqttClient.prototype._handleConnack=function(packet){var options=this.options;var version=options.protocolVersion;var rc=version===5?packet.reasonCode:packet.returnCode;clearTimeout(this.connackTimer);if(packet.properties){if(packet.properties.topicAliasMaximum){if(!options.properties){options.properties={}}options.properties.topicAliasMaximum=packet.properties.topicAliasMaximum}if(packet.properties.serverKeepAlive&&options.keepalive){options.keepalive=packet.properties.serverKeepAlive;this._shiftPingInterval()}if(packet.properties.maximumPacketSize){if(!options.properties){options.properties={}}options.properties.maximumPacketSize=packet.properties.maximumPacketSize}}if(rc===0){this.reconnecting=false;this._onConnect(packet)}else if(rc>0){var err=new Error("Connection refused: "+errors[rc]);err.code=rc;this.emit("error",err)}};MqttClient.prototype._handlePublish=function(packet,done){done=typeof done!=="undefined"?done:nop;var topic=packet.topic.toString();var message=packet.payload;var qos=packet.qos;var mid=packet.messageId;var that=this;var options=this.options;var validReasonCodes=[0,16,128,131,135,144,145,151,153];switch(qos){case 2:{options.customHandleAcks(topic,message,packet,(function(error,code){if(!(error instanceof Error)){code=error;error=null}if(error){return that.emit("error",error)}if(validReasonCodes.indexOf(code)===-1){return that.emit("error",new Error("Wrong reason code for pubrec"))}if(code){that._sendPacket({cmd:"pubrec",messageId:mid,reasonCode:code},done)}else{that.incomingStore.put(packet,(function(){that._sendPacket({cmd:"pubrec",messageId:mid},done)}))}}));break}case 1:{options.customHandleAcks(topic,message,packet,(function(error,code){if(!(error instanceof Error)){code=error;error=null}if(error){return that.emit("error",error)}if(validReasonCodes.indexOf(code)===-1){return that.emit("error",new Error("Wrong reason code for puback"))}if(!code){that.emit("message",topic,message,packet)}that.handleMessage(packet,(function(err){if(err){return done&&done(err)}that._sendPacket({cmd:"puback",messageId:mid,reasonCode:code},done)}))}));break}case 0:this.emit("message",topic,message,packet);this.handleMessage(packet,done);break;default:break}};MqttClient.prototype.handleMessage=function(packet,callback){callback()};MqttClient.prototype._handleAck=function(packet){var mid=packet.messageId;var type=packet.cmd;var response=null;var cb=this.outgoing[mid]?this.outgoing[mid].cb:null;var that=this;var err;if(!cb){return}switch(type){case"pubcomp":case"puback":var pubackRC=packet.reasonCode;if(pubackRC&&pubackRC>0&&pubackRC!==16){err=new Error("Publish error: "+errors[pubackRC]);err.code=pubackRC;cb(err,packet)}delete this.outgoing[mid];this.outgoingStore.del(packet,cb);break;case"pubrec":response={cmd:"pubrel",qos:2,messageId:mid};var pubrecRC=packet.reasonCode;if(pubrecRC&&pubrecRC>0&&pubrecRC!==16){err=new Error("Publish error: "+errors[pubrecRC]);err.code=pubrecRC;cb(err,packet)}else{this._sendPacket(response)}break;case"suback":delete this.outgoing[mid];for(var grantedI=0;grantedI<packet.granted.length;grantedI++){if((packet.granted[grantedI]&128)!==0){var topics=this.messageIdToTopic[mid];if(topics){topics.forEach((function(topic){delete that._resubscribeTopics[topic]}))}}}cb(null,packet);break;case"unsuback":delete this.outgoing[mid];cb(null);break;default:that.emit("error",new Error("unrecognized packet type"))}if(this.disconnecting&&Object.keys(this.outgoing).length===0){this.emit("outgoingEmpty")}};MqttClient.prototype._handlePubrel=function(packet,callback){callback=typeof callback!=="undefined"?callback:nop;var mid=packet.messageId;var that=this;var comp={cmd:"pubcomp",messageId:mid};that.incomingStore.get(packet,(function(err,pub){if(!err){that.emit("message",pub.topic,pub.payload,pub);that.handleMessage(pub,(function(err){if(err){return callback(err)}that.incomingStore.del(pub,nop);that._sendPacket(comp,callback)}))}else{that._sendPacket(comp,callback)}}))};MqttClient.prototype._handleDisconnect=function(packet){this.emit("disconnect",packet)};MqttClient.prototype._nextId=function(){var id=this.nextId++;if(this.nextId===65536){this.nextId=1}return id};MqttClient.prototype.getLastMessageId=function(){return this.nextId===1?65535:this.nextId-1};MqttClient.prototype._resubscribe=function(connack){var _resubscribeTopicsKeys=Object.keys(this._resubscribeTopics);if(!this._firstConnection&&(this.options.clean||this.options.protocolVersion===5&&!connack.sessionPresent)&&_resubscribeTopicsKeys.length>0){if(this.options.resubscribe){if(this.options.protocolVersion===5){for(var topicI=0;topicI<_resubscribeTopicsKeys.length;topicI++){var resubscribeTopic={};resubscribeTopic[_resubscribeTopicsKeys[topicI]]=this._resubscribeTopics[_resubscribeTopicsKeys[topicI]];resubscribeTopic.resubscribe=true;this.subscribe(resubscribeTopic,{properties:resubscribeTopic[_resubscribeTopicsKeys[topicI]].properties})}}else{this._resubscribeTopics.resubscribe=true;this.subscribe(this._resubscribeTopics)}}else{this._resubscribeTopics={}}}this._firstConnection=false};MqttClient.prototype._onConnect=function(packet){if(this.disconnected){this.emit("connect",packet);return}var that=this;this._setupPingTimer();this._resubscribe(packet);this.connected=true;function startStreamProcess(){var outStore=that.outgoingStore.createStream();function clearStoreProcessing(){that._storeProcessing=false;that._packetIdsDuringStoreProcessing={}}that.once("close",remove);outStore.on("error",(function(err){clearStoreProcessing();that.removeListener("close",remove);that.emit("error",err)}));function remove(){outStore.destroy();outStore=null;clearStoreProcessing()}function storeDeliver(){if(!outStore){return}that._storeProcessing=true;var packet=outStore.read(1);var cb;if(!packet){outStore.once("readable",storeDeliver);return}if(that._packetIdsDuringStoreProcessing[packet.messageId]){storeDeliver();return}if(!that.disconnecting&&!that.reconnectTimer){cb=that.outgoing[packet.messageId]?that.outgoing[packet.messageId].cb:null;that.outgoing[packet.messageId]={volatile:false,cb:function(err,status){if(cb){cb(err,status)}storeDeliver()}};that._packetIdsDuringStoreProcessing[packet.messageId]=true;that._sendPacket(packet)}else if(outStore.destroy){outStore.destroy()}}outStore.on("end",(function(){var allProcessed=true;for(var id in that._packetIdsDuringStoreProcessing){if(!that._packetIdsDuringStoreProcessing[id]){allProcessed=false;break}}if(allProcessed){clearStoreProcessing();that.removeListener("close",remove);that.emit("connect",packet)}else{startStreamProcess()}}));storeDeliver()}startStreamProcess()};module.exports=MqttClient}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./store":167,"./validations":168,_process:171,events:73,inherits:148,"mqtt-packet":155,"readable-stream":187,reinterval:188,xtend:216}],161:[function(require,module,exports){(function(Buffer){"use strict";var Transform=require("readable-stream").Transform;var duplexify=require("duplexify");var base64=require("base64-js");var my;var proxy;var stream;var isInitialized=false;function buildProxy(){var proxy=new Transform;proxy._write=function(chunk,encoding,next){my.sendSocketMessage({data:chunk.buffer,success:function(){next()},fail:function(){next(new Error)}})};proxy._flush=function socketEnd(done){my.closeSocket({success:function(){done()}})};return proxy}function setDefaultOpts(opts){if(!opts.hostname){opts.hostname="localhost"}if(!opts.path){opts.path="/"}if(!opts.wsOptions){opts.wsOptions={}}}function buildUrl(opts,client){var protocol=opts.protocol==="alis"?"wss":"ws";var url=protocol+"://"+opts.hostname+opts.path;if(opts.port&&opts.port!==80&&opts.port!==443){url=protocol+"://"+opts.hostname+":"+opts.port+opts.path}if(typeof opts.transformWsUrl==="function"){url=opts.transformWsUrl(url,opts,client)}return url}function bindEventHandler(){if(isInitialized)return;isInitialized=true;my.onSocketOpen((function(){stream.setReadable(proxy);stream.setWritable(proxy);stream.emit("connect")}));my.onSocketMessage((function(res){if(typeof res.data==="string"){var array=base64.toByteArray(res.data);var buffer=Buffer.from(array);proxy.push(buffer)}else{var reader=new FileReader;reader.addEventListener("load",(function(){var data=reader.result;if(data instanceof ArrayBuffer)data=Buffer.from(data);else data=Buffer.from(data,"utf8");proxy.push(data)}));reader.readAsArrayBuffer(res.data)}}));my.onSocketClose((function(){stream.end();stream.destroy()}));my.onSocketError((function(res){stream.destroy(res)}))}function buildStream(client,opts){opts.hostname=opts.hostname||opts.host;if(!opts.hostname){throw new Error("Could not determine host. Specify host manually.")}var websocketSubProtocol=opts.protocolId==="MQIsdp"&&opts.protocolVersion===3?"mqttv3.1":"mqtt";setDefaultOpts(opts);var url=buildUrl(opts,client);my=opts.my;my.connectSocket({url:url,protocols:websocketSubProtocol});proxy=buildProxy();stream=duplexify.obj();bindEventHandler();return stream}module.exports=buildStream}).call(this,require("buffer").Buffer)},{"base64-js":68,buffer:75,duplexify:79,"readable-stream":187}],162:[function(require,module,exports){(function(process){"use strict";var MqttClient=require("../client");var Store=require("../store");var url=require("url");var xtend=require("xtend");var protocols={};if(process.title!=="browser"){protocols.mqtt=require("./tcp");protocols.tcp=require("./tcp");protocols.ssl=require("./tls");protocols.tls=require("./tls");protocols.mqtts=require("./tls")}else{protocols.wx=require("./wx");protocols.wxs=require("./wx");protocols.ali=require("./ali");protocols.alis=require("./ali")}protocols.ws=require("./ws");protocols.wss=require("./ws");function parseAuthOptions(opts){var matches;if(opts.auth){matches=opts.auth.match(/^(.+):(.+)$/);if(matches){opts.username=matches[1];opts.password=matches[2]}else{opts.username=opts.auth}}}function connect(brokerUrl,opts){if(typeof brokerUrl==="object"&&!opts){opts=brokerUrl;brokerUrl=null}opts=opts||{};if(brokerUrl){var parsed=url.parse(brokerUrl,true);if(parsed.port!=null){parsed.port=Number(parsed.port)}opts=xtend(parsed,opts);if(opts.protocol===null){throw new Error("Missing protocol")}opts.protocol=opts.protocol.replace(/:$/,"")}parseAuthOptions(opts);if(opts.query&&typeof opts.query.clientId==="string"){opts.clientId=opts.query.clientId}if(opts.cert&&opts.key){if(opts.protocol){if(["mqtts","wss","wxs","alis"].indexOf(opts.protocol)===-1){switch(opts.protocol){case"mqtt":opts.protocol="mqtts";break;case"ws":opts.protocol="wss";break;case"wx":opts.protocol="wxs";break;case"ali":opts.protocol="alis";break;default:throw new Error('Unknown protocol for secure connection: "'+opts.protocol+'"!')}}}else{throw new Error("Missing secure protocol key")}}if(!protocols[opts.protocol]){var isSecure=["mqtts","wss"].indexOf(opts.protocol)!==-1;opts.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((function(key,index){if(isSecure&&index%2===0){return false}return typeof protocols[key]==="function"}))[0]}if(opts.clean===false&&!opts.clientId){throw new Error("Missing clientId for unclean clients")}if(opts.protocol){opts.defaultProtocol=opts.protocol}function wrapper(client){if(opts.servers){if(!client._reconnectCount||client._reconnectCount===opts.servers.length){client._reconnectCount=0}opts.host=opts.servers[client._reconnectCount].host;opts.port=opts.servers[client._reconnectCount].port;opts.protocol=!opts.servers[client._reconnectCount].protocol?opts.defaultProtocol:opts.servers[client._reconnectCount].protocol;opts.hostname=opts.host;client._reconnectCount++}return protocols[opts.protocol](client,opts)}return new MqttClient(wrapper,opts)}module.exports=connect;module.exports.connect=connect;module.exports.MqttClient=MqttClient;module.exports.Store=Store}).call(this,require("_process"))},{"../client":160,"../store":167,"./ali":161,"./tcp":163,"./tls":164,"./ws":165,"./wx":166,_process:171,url:204,xtend:216}],163:[function(require,module,exports){"use strict";var net=require("net");function buildBuilder(client,opts){var port,host;opts.port=opts.port||1883;opts.hostname=opts.hostname||opts.host||"localhost";port=opts.port;host=opts.hostname;return net.createConnection(port,host)}module.exports=buildBuilder},{net:71}],164:[function(require,module,exports){"use strict";var tls=require("tls");function buildBuilder(mqttClient,opts){var connection;opts.port=opts.port||8883;opts.host=opts.hostname||opts.host||"localhost";opts.rejectUnauthorized=opts.rejectUnauthorized!==false;delete opts.path;connection=tls.connect(opts);connection.on("secureConnect",(function(){if(opts.rejectUnauthorized&&!connection.authorized){connection.emit("error",new Error("TLS not authorized"))}else{connection.removeListener("error",handleTLSerrors)}}));function handleTLSerrors(err){if(opts.rejectUnauthorized){mqttClient.emit("error",err)}connection.end()}connection.on("error",handleTLSerrors);return connection}module.exports=buildBuilder},{tls:71}],165:[function(require,module,exports){(function(process){"use strict";var websocket=require("websocket-stream");var urlModule=require("url");var WSS_OPTIONS=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];var IS_BROWSER=process.title==="browser";function buildUrl(opts,client){var url=opts.protocol+"://"+opts.hostname+":"+opts.port+opts.path;if(typeof opts.transformWsUrl==="function"){url=opts.transformWsUrl(url,opts,client)}return url}function setDefaultOpts(opts){if(!opts.hostname){opts.hostname="localhost"}if(!opts.port){if(opts.protocol==="wss"){opts.port=443}else{opts.port=80}}if(!opts.path){opts.path="/"}if(!opts.wsOptions){opts.wsOptions={}}if(!IS_BROWSER&&opts.protocol==="wss"){WSS_OPTIONS.forEach((function(prop){if(opts.hasOwnProperty(prop)&&!opts.wsOptions.hasOwnProperty(prop)){opts.wsOptions[prop]=opts[prop]}}))}}function createWebSocket(client,opts){var websocketSubProtocol=opts.protocolId==="MQIsdp"&&opts.protocolVersion===3?"mqttv3.1":"mqtt";setDefaultOpts(opts);var url=buildUrl(opts,client);return websocket(url,[websocketSubProtocol],opts.wsOptions)}function buildBuilder(client,opts){return createWebSocket(client,opts)}function buildBuilderBrowser(client,opts){if(!opts.hostname){opts.hostname=opts.host}if(!opts.hostname){if(typeof document==="undefined"){throw new Error("Could not determine host. Specify host manually.")}var parsed=urlModule.parse(document.URL);opts.hostname=parsed.hostname;if(!opts.port){opts.port=parsed.port}}return createWebSocket(client,opts)}if(IS_BROWSER){module.exports=buildBuilderBrowser}else{module.exports=buildBuilder}}).call(this,require("_process"))},{_process:171,url:204,"websocket-stream":213}],166:[function(require,module,exports){(function(process,Buffer){"use strict";var Transform=require("readable-stream").Transform;var duplexify=require("duplexify");var socketTask;var proxy;var stream;function buildProxy(){var proxy=new Transform;proxy._write=function(chunk,encoding,next){socketTask.send({data:chunk.buffer,success:function(){next()},fail:function(errMsg){next(new Error(errMsg))}})};proxy._flush=function socketEnd(done){socketTask.close({success:function(){done()}})};return proxy}function setDefaultOpts(opts){if(!opts.hostname){opts.hostname="localhost"}if(!opts.path){opts.path="/"}if(!opts.wsOptions){opts.wsOptions={}}}function buildUrl(opts,client){var protocol=opts.protocol==="wxs"?"wss":"ws";var url=protocol+"://"+opts.hostname+opts.path;if(opts.port&&opts.port!==80&&opts.port!==443){url=protocol+"://"+opts.hostname+":"+opts.port+opts.path}if(typeof opts.transformWsUrl==="function"){url=opts.transformWsUrl(url,opts,client)}return url}function bindEventHandler(){socketTask.onOpen((function(){stream.setReadable(proxy);stream.setWritable(proxy);stream.emit("connect")}));socketTask.onMessage((function(res){var data=res.data;if(data instanceof ArrayBuffer)data=Buffer.from(data);else data=Buffer.from(data,"utf8");proxy.push(data)}));socketTask.onClose((function(){stream.end();stream.destroy()}));socketTask.onError((function(res){stream.destroy(new Error(res.errMsg))}))}function buildStream(client,opts){opts.hostname=opts.hostname||opts.host;if(!opts.hostname){throw new Error("Could not determine host. Specify host manually.")}var websocketSubProtocol=opts.protocolId==="MQIsdp"&&opts.protocolVersion===3?"mqttv3.1":"mqtt";setDefaultOpts(opts);var url=buildUrl(opts,client);socketTask=wx.connectSocket({url:url,protocols:websocketSubProtocol});proxy=buildProxy();stream=duplexify.obj();stream._destroy=function(err,cb){socketTask.close({success:function(){cb&&cb(err)}})};var destroyRef=stream.destroy;stream.destroy=function(){stream.destroy=destroyRef;var self=this;process.nextTick((function(){socketTask.close({fail:function(){self._destroy(new Error)}})}))}.bind(stream);bindEventHandler();return stream}module.exports=buildStream}).call(this,require("_process"),require("buffer").Buffer)},{_process:171,buffer:75,duplexify:79,"readable-stream":187}],167:[function(require,module,exports){(function(process){"use strict";var xtend=require("xtend");var Readable=require("readable-stream").Readable;var streamsOpts={objectMode:true};var defaultStoreOptions={clean:true};var Map=require("es6-map");function Store(options){if(!(this instanceof Store)){return new Store(options)}this.options=options||{};this.options=xtend(defaultStoreOptions,options);this._inflights=new Map}Store.prototype.put=function(packet,cb){this._inflights.set(packet.messageId,packet);if(cb){cb()}return this};Store.prototype.createStream=function(){var stream=new Readable(streamsOpts);var destroyed=false;var values=[];var i=0;this._inflights.forEach((function(value,key){values.push(value)}));stream._read=function(){if(!destroyed&&i<values.length){this.push(values[i++])}else{this.push(null)}};stream.destroy=function(){if(destroyed){return}var self=this;destroyed=true;process.nextTick((function(){self.emit("close")}))};return stream};Store.prototype.del=function(packet,cb){packet=this._inflights.get(packet.messageId);if(packet){this._inflights.delete(packet.messageId);cb(null,packet)}else if(cb){cb(new Error("missing packet"))}return this};Store.prototype.get=function(packet,cb){packet=this._inflights.get(packet.messageId);if(packet){cb(null,packet)}else if(cb){cb(new Error("missing packet"))}return this};Store.prototype.close=function(cb){if(this.options.clean){this._inflights=null}if(cb){cb()}};module.exports=Store}).call(this,require("_process"))},{_process:171,"es6-map":128,"readable-stream":187,xtend:216}],168:[function(require,module,exports){"use strict";function validateTopic(topic){var parts=topic.split("/");for(var i=0;i<parts.length;i++){if(parts[i]==="+"){continue}if(parts[i]==="#"){return i===parts.length-1}if(parts[i].indexOf("+")!==-1||parts[i].indexOf("#")!==-1){return false}}return true}function validateTopics(topics){if(topics.length===0){return"empty_topic_list"}for(var i=0;i<topics.length;i++){if(!validateTopic(topics[i])){return topics[i]}}return null}module.exports={validateTopics:validateTopics}},{}],169:[function(require,module,exports){var wrappy=require("wrappy");module.exports=wrappy(once);module.exports.strict=wrappy(onceStrict);once.proto=once((function(){Object.defineProperty(Function.prototype,"once",{value:function(){return once(this)},configurable:true});Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return onceStrict(this)},configurable:true})}));function once(fn){var f=function(){if(f.called)return f.value;f.called=true;return f.value=fn.apply(this,arguments)};f.called=false;return f}function onceStrict(fn){var f=function(){if(f.called)throw new Error(f.onceError);f.called=true;return f.value=fn.apply(this,arguments)};var name=fn.name||"Function wrapped with `once`";f.onceError=name+" shouldn't be called more than once";f.called=false;return f}},{wrappy:215}],170:[function(require,module,exports){(function(process){"use strict";if(typeof process==="undefined"||!process.version||process.version.indexOf("v0.")===0||process.version.indexOf("v1.")===0&&process.version.indexOf("v1.8.")!==0){module.exports={nextTick:nextTick}}else{module.exports=process}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:171}],171:[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}},{}],172:[function(require,module,exports){(function(global){(function(root){var freeExports=typeof exports=="object"&&exports&&!exports.nodeType&&exports;var freeModule=typeof module=="object"&&module&&!module.nodeType&&module;var freeGlobal=typeof global=="object"&&global;if(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal||freeGlobal.self===freeGlobal){root=freeGlobal}var punycode,maxInt=2147483647,base=36,tMin=1,tMax=26,skew=38,damp=700,initialBias=72,initialN=128,delimiter="-",regexPunycode=/^xn--/,regexNonASCII=/[^\x20-\x7E]/,regexSeparators=/[\x2E\u3002\uFF0E\uFF61]/g,errors={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},baseMinusTMin=base-tMin,floor=Math.floor,stringFromCharCode=String.fromCharCode,key;function error(type){throw new RangeError(errors[type])}function map(array,fn){var length=array.length;var result=[];while(length--){result[length]=fn(array[length])}return result}function mapDomain(string,fn){var parts=string.split("@");var result="";if(parts.length>1){result=parts[0]+"@";string=parts[1]}string=string.replace(regexSeparators,".");var labels=string.split(".");var encoded=map(labels,fn).join(".");return result+encoded}function ucs2decode(string){var output=[],counter=0,length=string.length,value,extra;while(counter<length){value=string.charCodeAt(counter++);if(value>=55296&&value<=56319&&counter<length){extra=string.charCodeAt(counter++);if((extra&64512)==56320){output.push(((value&1023)<<10)+(extra&1023)+65536)}else{output.push(value);counter--}}else{output.push(value)}}return output}function ucs2encode(array){return map(array,(function(value){var output="";if(value>65535){value-=65536;output+=stringFromCharCode(value>>>10&1023|55296);value=56320|value&1023}output+=stringFromCharCode(value);return output})).join("")}function basicToDigit(codePoint){if(codePoint-48<10){return codePoint-22}if(codePoint-65<26){return codePoint-65}if(codePoint-97<26){return codePoint-97}return base}function digitToBasic(digit,flag){return digit+22+75*(digit<26)-((flag!=0)<<5)}function adapt(delta,numPoints,firstTime){var k=0;delta=firstTime?floor(delta/damp):delta>>1;delta+=floor(delta/numPoints);for(;delta>baseMinusTMin*tMax>>1;k+=base){delta=floor(delta/baseMinusTMin)}return floor(k+(baseMinusTMin+1)*delta/(delta+skew))}function decode(input){var output=[],inputLength=input.length,out,i=0,n=initialN,bias=initialBias,basic,j,index,oldi,w,k,digit,t,baseMinusT;basic=input.lastIndexOf(delimiter);if(basic<0){basic=0}for(j=0;j<basic;++j){if(input.charCodeAt(j)>=128){error("not-basic")}output.push(input.charCodeAt(j))}for(index=basic>0?basic+1:0;index<inputLength;){for(oldi=i,w=1,k=base;;k+=base){if(index>=inputLength){error("invalid-input")}digit=basicToDigit(input.charCodeAt(index++));if(digit>=base||digit>floor((maxInt-i)/w)){error("overflow")}i+=digit*w;t=k<=bias?tMin:k>=bias+tMax?tMax:k-bias;if(digit<t){break}baseMinusT=base-t;if(w>floor(maxInt/baseMinusT)){error("overflow")}w*=baseMinusT}out=output.length+1;bias=adapt(i-oldi,out,oldi==0);if(floor(i/out)>maxInt-n){error("overflow")}n+=floor(i/out);i%=out;output.splice(i++,0,n)}return ucs2encode(output)}function encode(input){var n,delta,handledCPCount,basicLength,bias,j,m,q,k,t,currentValue,output=[],inputLength,handledCPCountPlusOne,baseMinusT,qMinusT;input=ucs2decode(input);inputLength=input.length;n=initialN;delta=0;bias=initialBias;for(j=0;j<inputLength;++j){currentValue=input[j];if(currentValue<128){output.push(stringFromCharCode(currentValue))}}handledCPCount=basicLength=output.length;if(basicLength){output.push(delimiter)}while(handledCPCount<inputLength){for(m=maxInt,j=0;j<inputLength;++j){currentValue=input[j];if(currentValue>=n&¤tValue<m){m=currentValue}}handledCPCountPlusOne=handledCPCount+1;if(m-n>floor((maxInt-delta)/handledCPCountPlusOne)){error("overflow")}delta+=(m-n)*handledCPCountPlusOne;n=m;for(j=0;j<inputLength;++j){currentValue=input[j];if(currentValue<n&&++delta>maxInt){error("overflow")}if(currentValue==n){for(q=delta,k=base;;k+=base){t=k<=bias?tMin:k>=bias+tMax?tMax:k-bias;if(q<t){break}qMinusT=q-t;baseMinusT=base-t;output.push(stringFromCharCode(digitToBasic(t+qMinusT%baseMinusT,0)));q=floor(qMinusT/baseMinusT)}output.push(stringFromCharCode(digitToBasic(q,0)));bias=adapt(delta,handledCPCountPlusOne,handledCPCount==basicLength);delta=0;++handledCPCount}}++delta;++n}return output.join("")}function toUnicode(input){return mapDomain(input,(function(string){return regexPunycode.test(string)?decode(string.slice(4).toLowerCase()):string}))}function toASCII(input){return mapDomain(input,(function(string){return regexNonASCII.test(string)?"xn--"+encode(string):string}))}punycode={version:"1.4.1",ucs2:{decode:ucs2decode,encode:ucs2encode},decode:decode,encode:encode,toASCII:toASCII,toUnicode:toUnicode};if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){define("punycode",(function(){return punycode}))}else if(freeExports&&freeModule){if(module.exports==freeExports){freeModule.exports=punycode}else{for(key in punycode){punycode.hasOwnProperty(key)&&(freeExports[key]=punycode[key])}}}else{root.punycode=punycode}})(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],173:[function(require,module,exports){"use strict";function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}module.exports=function(qs,sep,eq,options){sep=sep||"&";eq=eq||"=";var obj={};if(typeof qs!=="string"||qs.length===0){return obj}var regexp=/\+/g;qs=qs.split(sep);var maxKeys=1e3;if(options&&typeof options.maxKeys==="number"){maxKeys=options.maxKeys}var len=qs.length;if(maxKeys>0&&len>maxKeys){len=maxKeys}for(var i=0;i<len;++i){var x=qs[i].replace(regexp,"%20"),idx=x.indexOf(eq),kstr,vstr,k,v;if(idx>=0){kstr=x.substr(0,idx);vstr=x.substr(idx+1)}else{kstr=x;vstr=""}k=decodeURIComponent(kstr);v=decodeURIComponent(vstr);if(!hasOwnProperty(obj,k)){obj[k]=v}else if(isArray(obj[k])){obj[k].push(v)}else{obj[k]=[obj[k],v]}}return obj};var isArray=Array.isArray||function(xs){return Object.prototype.toString.call(xs)==="[object Array]"}},{}],174:[function(require,module,exports){"use strict";var stringifyPrimitive=function(v){switch(typeof v){case"string":return v;case"boolean":return v?"true":"false";case"number":return isFinite(v)?v:"";default:return""}};module.exports=function(obj,sep,eq,name){sep=sep||"&";eq=eq||"=";if(obj===null){obj=undefined}if(typeof obj==="object"){return map(objectKeys(obj),(function(k){var ks=encodeURIComponent(stringifyPrimitive(k))+eq;if(isArray(obj[k])){return map(obj[k],(function(v){return ks+encodeURIComponent(stringifyPrimitive(v))})).join(sep)}else{return ks+encodeURIComponent(stringifyPrimitive(obj[k]))}})).join(sep)}if(!name)return"";return encodeURIComponent(stringifyPrimitive(name))+eq+encodeURIComponent(stringifyPrimitive(obj))};var isArray=Array.isArray||function(xs){return Object.prototype.toString.call(xs)==="[object Array]"};function map(xs,f){if(xs.map)return xs.map(f);var res=[];for(var i=0;i<xs.length;i++){res.push(f(xs[i],i))}return res}var objectKeys=Object.keys||function(obj){var res=[];for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))res.push(key)}return res}},{}],175:[function(require,module,exports){"use strict";exports.decode=exports.parse=require("./decode");exports.encode=exports.stringify=require("./encode")},{"./decode":173,"./encode":174}],176:[function(require,module,exports){module.exports=require("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":177}],177:[function(require,module,exports){"use strict";var pna=require("process-nextick-args");var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj){keys.push(key)}return keys};module.exports=Duplex;var util=Object.create(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)}Object.defineProperty(Duplex.prototype,"writableHighWaterMark",{enumerable:false,get:function(){return this._writableState.highWaterMark}});function onend(){if(this.allowHalfOpen||this._writableState.ended)return;pna.nextTick(onEndNT,this)}function onEndNT(self){self.end()}Object.defineProperty(Duplex.prototype,"destroyed",{get:function(){if(this._readableState===undefined||this._writableState===undefined){return false}return this._readableState.destroyed&&this._writableState.destroyed},set:function(value){if(this._readableState===undefined||this._writableState===undefined){return}this._readableState.destroyed=value;this._writableState.destroyed=value}});Duplex.prototype._destroy=function(err,cb){this.push(null);this.end();pna.nextTick(cb,err)}},{"./_stream_readable":179,"./_stream_writable":181,"core-util-is":76,inherits:148,"process-nextick-args":170}],178:[function(require,module,exports){"use strict";module.exports=PassThrough;var Transform=require("./_stream_transform");var util=Object.create(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":180,"core-util-is":76,inherits:148}],179:[function(require,module,exports){(function(process,global){"use strict";var pna=require("process-nextick-args");module.exports=Readable;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("safe-buffer").Buffer;var OurUint8Array=global.Uint8Array||function(){};function _uint8ArrayToBuffer(chunk){return Buffer.from(chunk)}function _isUint8Array(obj){return Buffer.isBuffer(obj)||obj instanceof OurUint8Array}var util=Object.create(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 destroyImpl=require("./internal/streams/destroy");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);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||{};var isDuplex=stream instanceof Duplex;this.objectMode=!!options.objectMode;if(isDuplex)this.objectMode=this.objectMode||!!options.readableObjectMode;var hwm=options.highWaterMark;var readableHwm=options.readableHighWaterMark;var defaultHwm=this.objectMode?16:16*1024;if(hwm||hwm===0)this.highWaterMark=hwm;else if(isDuplex&&(readableHwm||readableHwm===0))this.highWaterMark=readableHwm;else this.highWaterMark=defaultHwm;this.highWaterMark=Math.floor(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.destroyed=false;this.defaultEncoding=options.defaultEncoding||"utf8";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){if(typeof options.read==="function")this._read=options.read;if(typeof options.destroy==="function")this._destroy=options.destroy}Stream.call(this)}Object.defineProperty(Readable.prototype,"destroyed",{get:function(){if(this._readableState===undefined){return false}return this._readableState.destroyed},set:function(value){if(!this._readableState){return}this._readableState.destroyed=value}});Readable.prototype.destroy=destroyImpl.destroy;Readable.prototype._undestroy=destroyImpl.undestroy;Readable.prototype._destroy=function(err,cb){this.push(null);cb(err)};Readable.prototype.push=function(chunk,encoding){var state=this._readableState;var skipChunkCheck;if(!state.objectMode){if(typeof chunk==="string"){encoding=encoding||state.defaultEncoding;if(encoding!==state.encoding){chunk=Buffer.from(chunk,encoding);encoding=""}skipChunkCheck=true}}else{skipChunkCheck=true}return readableAddChunk(this,chunk,encoding,false,skipChunkCheck)};Readable.prototype.unshift=function(chunk){return readableAddChunk(this,chunk,null,true,false)};function readableAddChunk(stream,chunk,encoding,addToFront,skipChunkCheck){var state=stream._readableState;if(chunk===null){state.reading=false;onEofChunk(stream,state)}else{var er;if(!skipChunkCheck)er=chunkInvalid(state,chunk);if(er){stream.emit("error",er)}else if(state.objectMode||chunk&&chunk.length>0){if(typeof chunk!=="string"&&!state.objectMode&&Object.getPrototypeOf(chunk)!==Buffer.prototype){chunk=_uint8ArrayToBuffer(chunk)}if(addToFront){if(state.endEmitted)stream.emit("error",new Error("stream.unshift() after end event"));else addChunk(stream,state,chunk,true)}else if(state.ended){stream.emit("error",new Error("stream.push() after EOF"))}else{state.reading=false;if(state.decoder&&!encoding){chunk=state.decoder.write(chunk);if(state.objectMode||chunk.length!==0)addChunk(stream,state,chunk,false);else maybeReadMore(stream,state)}else{addChunk(stream,state,chunk,false)}}}else if(!addToFront){state.reading=false}}return needMoreData(state)}function addChunk(stream,state,chunk,addToFront){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)}function chunkInvalid(state,chunk){var er;if(!_isUint8Array(chunk)&&typeof chunk!=="string"&&chunk!==undefined&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}return er}function needMoreData(state){return!state.ended&&(state.needReadable||state.length<state.highWaterMark||state.length===0)}Readable.prototype.isPaused=function(){return this._readableState.flowing===false};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 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)pna.nextTick(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;pna.nextTick(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:unpipe;if(state.endEmitted)pna.nextTick(endFn);else src.once("end",endFn);dest.on("unpipe",onunpipe);function onunpipe(readable,unpipeInfo){debug("onunpipe");if(readable===src){if(unpipeInfo&&unpipeInfo.hasUnpiped===false){unpipeInfo.hasUnpiped=true;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",unpipe);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;var unpipeInfo={hasUnpiped:false};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,unpipeInfo);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,unpipeInfo)}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,unpipeInfo);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){pna.nextTick(nReadingNextTick,this)}else if(state.length){emitReadable(this)}}}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;pna.nextTick(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 _this=this;var state=this._readableState;var paused=false;stream.on("end",(function(){debug("wrapped end");if(state.decoder&&!state.ended){var chunk=state.decoder.end();if(chunk&&chunk.length)_this.push(chunk)}_this.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=_this.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],this.emit.bind(this,kProxyEvents[n]))}this._read=function(n){debug("wrapped _read",n);if(paused){paused=false;stream.resume()}};return this};Object.defineProperty(Readable.prototype,"readableHighWaterMark",{enumerable:false,get:function(){return this._readableState.highWaterMark}});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=Buffer.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;pna.nextTick(endReadableNT,state,stream)}}function endReadableNT(state,stream){if(!state.endEmitted&&state.length===0){state.endEmitted=true;stream.readable=false;stream.emit("end")}}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"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./_stream_duplex":177,"./internal/streams/BufferList":182,"./internal/streams/destroy":183,"./internal/streams/stream":184,_process:171,"core-util-is":76,events:73,inherits:148,isarray:150,"process-nextick-args":170,"safe-buffer":185,"string_decoder/":186,util:71}],180:[function(require,module,exports){"use strict";module.exports=Transform;var Duplex=require("./_stream_duplex");var util=Object.create(require("core-util-is"));util.inherits=require("inherits");util.inherits(Transform,Duplex);function afterTransform(er,data){var ts=this._transformState;ts.transforming=false;var cb=ts.writecb;if(!cb){return this.emit("error",new Error("write callback called multiple times"))}ts.writechunk=null;ts.writecb=null;if(data!=null)this.push(data);cb(er);var rs=this._readableState;rs.reading=false;if(rs.needReadable||rs.length<rs.highWaterMark){this._read(rs.highWaterMark)}}function Transform(options){if(!(this instanceof Transform))return new Transform(options);Duplex.call(this,options);this._transformState={afterTransform:afterTransform.bind(this),needTransform:false,transforming:false,writecb:null,writechunk:null,writeencoding:null};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.on("prefinish",prefinish)}function prefinish(){var _this=this;if(typeof this._flush==="function"){this._flush((function(er,data){done(_this,er,data)}))}else{done(this,null,null)}}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}};Transform.prototype._destroy=function(err,cb){var _this2=this;Duplex.prototype._destroy.call(this,err,(function(err2){cb(err2);_this2.emit("close")}))};function done(stream,er,data){if(er)return stream.emit("error",er);if(data!=null)stream.push(data);if(stream._writableState.length)throw new Error("Calling transform done when ws.length != 0");if(stream._transformState.transforming)throw new Error("Calling transform done when still transforming");return stream.push(null)}},{"./_stream_duplex":177,"core-util-is":76,inherits:148}],181:[function(require,module,exports){(function(process,global,setImmediate){"use strict";var pna=require("process-nextick-args");module.exports=Writable;function WriteReq(chunk,encoding,cb){this.chunk=chunk;this.encoding=encoding;this.callback=cb;this.next=null}function CorkedRequest(state){var _this=this;this.next=null;this.entry=null;this.finish=function(){onCorkedFinish(_this,state)}}var asyncWrite=!process.browser&&["v0.10","v0.9."].indexOf(process.version.slice(0,5))>-1?setImmediate:pna.nextTick;var Duplex;Writable.WritableState=WritableState;var util=Object.create(require("core-util-is"));util.inherits=require("inherits");var internalUtil={deprecate:require("util-deprecate")};var Stream=require("./internal/streams/stream");var Buffer=require("safe-buffer").Buffer;var OurUint8Array=global.Uint8Array||function(){};function _uint8ArrayToBuffer(chunk){return Buffer.from(chunk)}function _isUint8Array(obj){return Buffer.isBuffer(obj)||obj instanceof OurUint8Array}var destroyImpl=require("./internal/streams/destroy");util.inherits(Writable,Stream);function nop(){}function WritableState(options,stream){Duplex=Duplex||require("./_stream_duplex");options=options||{};var isDuplex=stream instanceof Duplex;this.objectMode=!!options.objectMode;if(isDuplex)this.objectMode=this.objectMode||!!options.writableObjectMode;var hwm=options.highWaterMark;var writableHwm=options.writableHighWaterMark;var defaultHwm=this.objectMode?16:16*1024;if(hwm||hwm===0)this.highWaterMark=hwm;else if(isDuplex&&(writableHwm||writableHwm===0))this.highWaterMark=writableHwm;else this.highWaterMark=defaultHwm;this.highWaterMark=Math.floor(this.highWaterMark);this.finalCalled=false;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;this.destroyed=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.","DEP0003")})}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;if(this!==Writable)return false;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;if(typeof options.destroy==="function")this._destroy=options.destroy;if(typeof options.final==="function")this._final=options.final}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);pna.nextTick(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);pna.nextTick(cb,er);valid=false}return valid}Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState;var ret=false;var isBuf=!state.objectMode&&_isUint8Array(chunk);if(isBuf&&!Buffer.isBuffer(chunk)){chunk=_uint8ArrayToBuffer(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=Buffer.from(chunk,encoding)}return chunk}Object.defineProperty(Writable.prototype,"writableHighWaterMark",{enumerable:false,get:function(){return this._writableState.highWaterMark}});function writeOrBuffer(stream,state,isBuf,chunk,encoding,cb){if(!isBuf){var newChunk=decodeChunk(state,chunk,encoding);if(chunk!==newChunk){isBuf=true;encoding="buffer";chunk=newChunk}}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={chunk:chunk,encoding:encoding,isBuf:isBuf,callback:cb,next:null};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){pna.nextTick(cb,er);pna.nextTick(finishMaybe,stream,state);stream._writableState.errorEmitted=true;stream.emit("error",er)}else{cb(er);stream._writableState.errorEmitted=true;stream.emit("error",er);finishMaybe(stream,state)}}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;var allBuffers=true;while(entry){buffer[count]=entry;if(!entry.isBuf)allBuffers=false;entry=entry.next;count+=1}buffer.allBuffers=allBuffers;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)}state.bufferedRequestCount=0}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;state.bufferedRequestCount--;if(state.writing){break}}if(entry===null)state.lastBufferedRequest=null}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 callFinal(stream,state){stream._final((function(err){state.pendingcb--;if(err){stream.emit("error",err)}state.prefinished=true;stream.emit("prefinish");finishMaybe(stream,state)}))}function prefinish(stream,state){if(!state.prefinished&&!state.finalCalled){if(typeof stream._final==="function"){state.pendingcb++;state.finalCalled=true;pna.nextTick(callFinal,stream,state)}else{state.prefinished=true;stream.emit("prefinish")}}}function finishMaybe(stream,state){var need=needFinish(state);if(need){prefinish(stream,state);if(state.pendingcb===0){state.finished=true;stream.emit("finish")}}return need}function endWritable(stream,state,cb){state.ending=true;finishMaybe(stream,state);if(cb){if(state.finished)pna.nextTick(cb);else stream.once("finish",cb)}state.ended=true;stream.writable=false}function onCorkedFinish(corkReq,state,err){var entry=corkReq.entry;corkReq.entry=null;while(entry){var cb=entry.callback;state.pendingcb--;cb(err);entry=entry.next}if(state.corkedRequestsFree){state.corkedRequestsFree.next=corkReq}else{state.corkedRequestsFree=corkReq}}Object.defineProperty(Writable.prototype,"destroyed",{get:function(){if(this._writableState===undefined){return false}return this._writableState.destroyed},set:function(value){if(!this._writableState){return}this._writableState.destroyed=value}});Writable.prototype.destroy=destroyImpl.destroy;Writable.prototype._undestroy=destroyImpl.undestroy;Writable.prototype._destroy=function(err,cb){this.end();cb(err)}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},require("timers").setImmediate)},{"./_stream_duplex":177,"./internal/streams/destroy":183,"./internal/streams/stream":184,_process:171,"core-util-is":76,inherits:148,"process-nextick-args":170,"safe-buffer":185,timers:191,"util-deprecate":206}],182:[function(require,module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var Buffer=require("safe-buffer").Buffer;var util=require("util");function copyBuffer(src,target,offset){src.copy(target,offset)}module.exports=function(){function BufferList(){_classCallCheck(this,BufferList);this.head=null;this.tail=null;this.length=0}BufferList.prototype.push=function push(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 unshift(v){var entry={data:v,next:this.head};if(this.length===0)this.tail=entry;this.head=entry;++this.length};BufferList.prototype.shift=function shift(){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 clear(){this.head=this.tail=null;this.length=0};BufferList.prototype.join=function join(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 concat(n){if(this.length===0)return Buffer.alloc(0);if(this.length===1)return this.head.data;var ret=Buffer.allocUnsafe(n>>>0);var p=this.head;var i=0;while(p){copyBuffer(p.data,ret,i);i+=p.data.length;p=p.next}return ret};return BufferList}();if(util&&util.inspect&&util.inspect.custom){module.exports.prototype[util.inspect.custom]=function(){var obj=util.inspect({length:this.length});return this.constructor.name+" "+obj}}},{"safe-buffer":185,util:71}],183:[function(require,module,exports){"use strict";var pna=require("process-nextick-args");function destroy(err,cb){var _this=this;var readableDestroyed=this._readableState&&this._readableState.destroyed;var writableDestroyed=this._writableState&&this._writableState.destroyed;if(readableDestroyed||writableDestroyed){if(cb){cb(err)}else if(err&&(!this._writableState||!this._writableState.errorEmitted)){pna.nextTick(emitErrorNT,this,err)}return this}if(this._readableState){this._readableState.destroyed=true}if(this._writableState){this._writableState.destroyed=true}this._destroy(err||null,(function(err){if(!cb&&err){pna.nextTick(emitErrorNT,_this,err);if(_this._writableState){_this._writableState.errorEmitted=true}}else if(cb){cb(err)}}));return this}function undestroy(){if(this._readableState){this._readableState.destroyed=false;this._readableState.reading=false;this._readableState.ended=false;this._readableState.endEmitted=false}if(this._writableState){this._writableState.destroyed=false;this._writableState.ended=false;this._writableState.ending=false;this._writableState.finished=false;this._writableState.errorEmitted=false}}function emitErrorNT(self,err){self.emit("error",err)}module.exports={destroy:destroy,undestroy:undestroy}},{"process-nextick-args":170}],184:[function(require,module,exports){module.exports=require("events").EventEmitter},{events:73}],185:[function(require,module,exports){var buffer=require("buffer");var Buffer=buffer.Buffer;function copyProps(src,dst){for(var key in src){dst[key]=src[key]}}if(Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow){module.exports=buffer}else{copyProps(buffer,exports);exports.Buffer=SafeBuffer}function SafeBuffer(arg,encodingOrOffset,length){return Buffer(arg,encodingOrOffset,length)}copyProps(Buffer,SafeBuffer);SafeBuffer.from=function(arg,encodingOrOffset,length){if(typeof arg==="number"){throw new TypeError("Argument must not be a number")}return Buffer(arg,encodingOrOffset,length)};SafeBuffer.alloc=function(size,fill,encoding){if(typeof size!=="number"){throw new TypeError("Argument must be a number")}var buf=Buffer(size);if(fill!==undefined){if(typeof encoding==="string"){buf.fill(fill,encoding)}else{buf.fill(fill)}}else{buf.fill(0)}return buf};SafeBuffer.allocUnsafe=function(size){if(typeof size!=="number"){throw new TypeError("Argument must be a number")}return Buffer(size)};SafeBuffer.allocUnsafeSlow=function(size){if(typeof size!=="number"){throw new TypeError("Argument must be a number")}return buffer.SlowBuffer(size)}},{buffer:75}],186:[function(require,module,exports){"use strict";var Buffer=require("safe-buffer").Buffer;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=Buffer.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 byte>>6===2?-1:-2}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||nb===-2)return 0;nb=utf8CheckByte(buf[j]);if(nb>=0){if(nb>0)self.lastNeed=nb-2;return nb}if(--j<i||nb===-2)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"�"}if(self.lastNeed>1&&buf.length>1){if((buf[1]&192)!==128){self.lastNeed=1;return"�"}if(self.lastNeed>2&&buf.length>2){if((buf[2]&192)!==128){self.lastNeed=2;return"�"}}}}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+"�";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):""}},{"safe-buffer":185}],187:[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":177,"./lib/_stream_passthrough.js":178,"./lib/_stream_readable.js":179,"./lib/_stream_transform.js":180,"./lib/_stream_writable.js":181}],188:[function(require,module,exports){"use strict";function ReInterval(callback,interval,args){var self=this;this._callback=callback;this._args=args;this._interval=setInterval(callback,interval,this._args);this.reschedule=function(interval){if(!interval)interval=self._interval;if(self._interval)clearInterval(self._interval);self._interval=setInterval(self._callback,interval,self._args)};this.clear=function(){if(self._interval){clearInterval(self._interval);self._interval=undefined}};this.destroy=function(){if(self._interval){clearInterval(self._interval)}self._callback=undefined;self._interval=undefined;self._args=undefined}}function reInterval(){if(typeof arguments[0]!=="function")throw new Error("callback needed");if(typeof arguments[1]!=="number")throw new Error("interval needed");var args;if(arguments.length>0){args=new Array(arguments.length-2);for(var i=0;i<args.length;i++){args[i]=arguments[i+2]}}return new ReInterval(arguments[0],arguments[1],args)}module.exports=reInterval},{}],189:[function(require,module,exports){var buffer=require("buffer");var Buffer=buffer.Buffer;function copyProps(src,dst){for(var key in src){dst[key]=src[key]}}if(Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow){module.exports=buffer}else{copyProps(buffer,exports);exports.Buffer=SafeBuffer}function SafeBuffer(arg,encodingOrOffset,length){return Buffer(arg,encodingOrOffset,length)}SafeBuffer.prototype=Object.create(Buffer.prototype);copyProps(Buffer,SafeBuffer);SafeBuffer.from=function(arg,encodingOrOffset,length){if(typeof arg==="number"){throw new TypeError("Argument must not be a number")}return Buffer(arg,encodingOrOffset,length)};SafeBuffer.alloc=function(size,fill,encoding){if(typeof size!=="number"){throw new TypeError("Argument must be a number")}var buf=Buffer(size);if(fill!==undefined){if(typeof encoding==="string"){buf.fill(fill,encoding)}else{buf.fill(fill)}}else{buf.fill(0)}return buf};SafeBuffer.allocUnsafe=function(size){if(typeof size!=="number"){throw new TypeError("Argument must be a number")}return Buffer(size)};SafeBuffer.allocUnsafeSlow=function(size){if(typeof size!=="number"){throw new TypeError("Argument must be a number")}return buffer.SlowBuffer(size)}},{buffer:75}],190:[function(require,module,exports){module.exports=shift;function shift(stream){var rs=stream._readableState;if(!rs)return null;return rs.objectMode||typeof stream._duplexState==="number"?stream.read():stream.read(getStateLength(rs))}function getStateLength(state){if(state.buffer.length){if(state.buffer.head){return state.buffer.head.data.length}return state.buffer[0].length}return state.length}},{}],191:[function(require,module,exports){(function(setImmediate,clearImmediate){var nextTick=require("process/browser.js").nextTick;var apply=Function.prototype.apply;var slice=Array.prototype.slice;var immediateIds={};var nextImmediateId=0;exports.setTimeout=function(){return new Timeout(apply.call(setTimeout,window,arguments),clearTimeout)};exports.setInterval=function(){return new Timeout(apply.call(setInterval,window,arguments),clearInterval)};exports.clearTimeout=exports.clearInterval=function(timeout){timeout.close()};function Timeout(id,clearFn){this._id=id;this._clearFn=clearFn}Timeout.prototype.unref=Timeout.prototype.ref=function(){};Timeout.prototype.close=function(){this._clearFn.call(window,this._id)};exports.enroll=function(item,msecs){clearTimeout(item._idleTimeoutId);item._idleTimeout=msecs};exports.unenroll=function(item){clearTimeout(item._idleTimeoutId);item._idleTimeout=-1};exports._unrefActive=exports.active=function(item){clearTimeout(item._idleTimeoutId);var msecs=item._idleTimeout;if(msecs>=0){item._idleTimeoutId=setTimeout((function onTimeout(){if(item._onTimeout)item._onTimeout()}),msecs)}};exports.setImmediate=typeof setImmediate==="function"?setImmediate:function(fn){var id=nextImmediateId++;var args=arguments.length<2?false:slice.call(arguments,1);immediateIds[id]=true;nextTick((function onNextTick(){if(immediateIds[id]){if(args){fn.apply(null,args)}else{fn.call(null)}exports.clearImmediate(id)}}));return id};exports.clearImmediate=typeof clearImmediate==="function"?clearImmediate:function(id){delete immediateIds[id]}}).call(this,require("timers").setImmediate,require("timers").clearImmediate)},{"process/browser.js":171,timers:191}],192:[function(require,module,exports){"use strict";const sizeof=require("js-sizeof");const TinyCache=function(){this._cache={};this._timeouts={};this._hits=0;this._misses=0;this._size=0;return this};TinyCache.prototype={get size(){return this._size},get memsize(){return sizeof(this._cache)},get hits(){return this._hits},get misses(){return this._misses},put:function(key,value,time){if(this._timeouts[key]){clearTimeout(this._timeouts[key]);delete this._timeouts[key]}this._cache[key]=value;if(!isNaN(time)){this._timeouts[key]=setTimeout(this.del.bind(this,key),time)}++this._size},get:function(key){if(typeof key==="undefined"){return this._cache}if(!(key in this._cache)){++this._misses;return null}++this._hits;return this._cache[key]},del:function(key){clearTimeout(this._timeouts[key]);delete this._timeouts[key];if(!(key in this._cache)){return false}delete this._cache[key];--this._size;return true},clear:function(){for(let key in this._timeouts){clearTimeout(this._timeouts[key])}this._cache={};this._timeouts={};this._size=0}};TinyCache.shared=new TinyCache;if(typeof module!=="undefined"&&module.exports){module.exports=TinyCache}else if(typeof define==="function"&&define.amd){define([],(function(){return TinyCache}))}else{window.TinyCache=TinyCache}},{"js-sizeof":151}],193:[function(require,module,exports){"use strict";var isPrototype=require("../prototype/is");module.exports=function(value){if(typeof value!=="function")return false;if(!hasOwnProperty.call(value,"length"))return false;try{if(typeof value.length!=="number")return false;if(typeof value.call!=="function")return false;if(typeof value.apply!=="function")return false}catch(error){return false}return!isPrototype(value)}},{"../prototype/is":200}],194:[function(require,module,exports){"use strict";var isValue=require("../value/is"),isObject=require("../object/is"),stringCoerce=require("../string/coerce"),toShortString=require("./to-short-string");var resolveMessage=function(message,value){return message.replace("%v",toShortString(value))};module.exports=function(value,defaultMessage,inputOptions){if(!isObject(inputOptions))throw new TypeError(resolveMessage(defaultMessage,value));if(!isValue(value)){if("default"in inputOptions)return inputOptions["default"];if(inputOptions.isOptional)return null}var errorMessage=stringCoerce(inputOptions.errorMessage);if(!isValue(errorMessage))errorMessage=defaultMessage;throw new TypeError(resolveMessage(errorMessage,value))}},{"../object/is":197,"../string/coerce":201,"../value/is":203,"./to-short-string":196}],195:[function(require,module,exports){"use strict";module.exports=function(value){try{return value.toString()}catch(error){try{return String(value)}catch(error2){return null}}}},{}],196:[function(require,module,exports){"use strict";var safeToString=require("./safe-to-string");var reNewLine=/[\n\r\u2028\u2029]/g;module.exports=function(value){var string=safeToString(value);if(string===null)return"<Non-coercible to string value>";if(string.length>100)string=string.slice(0,99)+"…";string=string.replace(reNewLine,(function(char){switch(char){case"\n":return"\\n";case"\r":return"\\r";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:throw new Error("Unexpected character")}}));return string}},{"./safe-to-string":195}],197:[function(require,module,exports){"use strict";var isValue=require("../value/is");var possibleTypes={object:true,function:true,undefined:true};module.exports=function(value){if(!isValue(value))return false;return hasOwnProperty.call(possibleTypes,typeof value)}},{"../value/is":203}],198:[function(require,module,exports){"use strict";var resolveException=require("../lib/resolve-exception"),is=require("./is");module.exports=function(value){if(is(value))return value;return resolveException(value,"%v is not a plain function",arguments[1])}},{"../lib/resolve-exception":194,"./is":199}],199:[function(require,module,exports){"use strict";var isFunction=require("../function/is");var classRe=/^\s*class[\s{/}]/,functionToString=Function.prototype.toString;module.exports=function(value){if(!isFunction(value))return false;if(classRe.test(functionToString.call(value)))return false;return true}},{"../function/is":193}],200:[function(require,module,exports){"use strict";var isObject=require("../object/is");module.exports=function(value){if(!isObject(value))return false;try{if(!value.constructor)return false;return value.constructor.prototype===value}catch(error){return false}}},{"../object/is":197}],201:[function(require,module,exports){"use strict";var isValue=require("../value/is"),isObject=require("../object/is");var objectToString=Object.prototype.toString;module.exports=function(value){if(!isValue(value))return null;if(isObject(value)){var valueToString=value.toString;if(typeof valueToString!=="function")return null;if(valueToString===objectToString)return null}try{return""+value}catch(error){return null}}},{"../object/is":197,"../value/is":203}],202:[function(require,module,exports){"use strict";var resolveException=require("../lib/resolve-exception"),is=require("./is");module.exports=function(value){if(is(value))return value;return resolveException(value,"Cannot use %v",arguments[1])}},{"../lib/resolve-exception":194,"./is":203}],203:[function(require,module,exports){"use strict";var _undefined=void 0;module.exports=function(value){return value!==_undefined&&value!==null}},{}],204:[function(require,module,exports){"use strict";var punycode=require("punycode");var util=require("./util");exports.parse=urlParse;exports.resolve=urlResolve;exports.resolveObject=urlResolveObject;exports.format=urlFormat;exports.Url=Url;function Url(){this.protocol=null;this.slashes=null;this.auth=null;this.host=null;this.port=null;this.hostname=null;this.hash=null;this.search=null;this.query=null;this.pathname=null;this.path=null;this.href=null}var protocolPattern=/^([a-z0-9.+-]+:)/i,portPattern=/:[0-9]*$/,simplePathPattern=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,delims=["<",">",'"',"`"," ","\r","\n","\t"],unwise=["{","}","|","\\","^","`"].concat(delims),autoEscape=["'"].concat(unwise),nonHostChars=["%","/","?",";","#"].concat(autoEscape),hostEndingChars=["/","?","#"],hostnameMaxLen=255,hostnamePartPattern=/^[+a-z0-9A-Z_-]{0,63}$/,hostnamePartStart=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,unsafeProtocol={javascript:true,"javascript:":true},hostlessProtocol={javascript:true,"javascript:":true},slashedProtocol={http:true,https:true,ftp:true,gopher:true,file:true,"http:":true,"https:":true,"ftp:":true,"gopher:":true,"file:":true},querystring=require("querystring");function urlParse(url,parseQueryString,slashesDenoteHost){if(url&&util.isObject(url)&&url instanceof Url)return url;var u=new Url;u.parse(url,parseQueryString,slashesDenoteHost);return u}Url.prototype.parse=function(url,parseQueryString,slashesDenoteHost){if(!util.isString(url)){throw new TypeError("Parameter 'url' must be a string, not "+typeof url)}var queryIndex=url.indexOf("?"),splitter=queryIndex!==-1&&queryIndex<url.indexOf("#")?"?":"#",uSplit=url.split(splitter),slashRegex=/\\/g;uSplit[0]=uSplit[0].replace(slashRegex,"/");url=uSplit.join(splitter);var rest=url;rest=rest.trim();if(!slashesDenoteHost&&url.split("#").length===1){var simplePath=simplePathPattern.exec(rest);if(simplePath){this.path=rest;this.href=rest;this.pathname=simplePath[1];if(simplePath[2]){this.search=simplePath[2];if(parseQueryString){this.query=querystring.parse(this.search.substr(1))}else{this.query=this.search.substr(1)}}else if(parseQueryString){this.search="";this.query={}}return this}}var proto=protocolPattern.exec(rest);if(proto){proto=proto[0];var lowerProto=proto.toLowerCase();this.protocol=lowerProto;rest=rest.substr(proto.length)}if(slashesDenoteHost||proto||rest.match(/^\/\/[^@\/]+@[^@\/]+/)){var slashes=rest.substr(0,2)==="//";if(slashes&&!(proto&&hostlessProtocol[proto])){rest=rest.substr(2);this.slashes=true}}if(!hostlessProtocol[proto]&&(slashes||proto&&!slashedProtocol[proto])){var hostEnd=-1;for(var i=0;i<hostEndingChars.length;i++){var hec=rest.indexOf(hostEndingChars[i]);if(hec!==-1&&(hostEnd===-1||hec<hostEnd))hostEnd=hec}var auth,atSign;if(hostEnd===-1){atSign=rest.lastIndexOf("@")}else{atSign=rest.lastIndexOf("@",hostEnd)}if(atSign!==-1){auth=rest.slice(0,atSign);rest=rest.slice(atSign+1);this.auth=decodeURIComponent(auth)}hostEnd=-1;for(var i=0;i<nonHostChars.length;i++){var hec=rest.indexOf(nonHostChars[i]);if(hec!==-1&&(hostEnd===-1||hec<hostEnd))hostEnd=hec}if(hostEnd===-1)hostEnd=rest.length;this.host=rest.slice(0,hostEnd);rest=rest.slice(hostEnd);this.parseHost();this.hostname=this.hostname||"";var ipv6Hostname=this.hostname[0]==="["&&this.hostname[this.hostname.length-1]==="]";if(!ipv6Hostname){var hostparts=this.hostname.split(/\./);for(var i=0,l=hostparts.length;i<l;i++){var part=hostparts[i];if(!part)continue;if(!part.match(hostnamePartPattern)){var newpart="";for(var j=0,k=part.length;j<k;j++){if(part.charCodeAt(j)>127){newpart+="x"}else{newpart+=part[j]}}if(!newpart.match(hostnamePartPattern)){var validParts=hostparts.slice(0,i);var notHost=hostparts.slice(i+1);var bit=part.match(hostnamePartStart);if(bit){validParts.push(bit[1]);notHost.unshift(bit[2])}if(notHost.length){rest="/"+notHost.join(".")+rest}this.hostname=validParts.join(".");break}}}}if(this.hostname.length>hostnameMaxLen){this.hostname=""}else{this.hostname=this.hostname.toLowerCase()}if(!ipv6Hostname){this.hostname=punycode.toASCII(this.hostname)}var p=this.port?":"+this.port:"";var h=this.hostname||"";this.host=h+p;this.href+=this.host;if(ipv6Hostname){this.hostname=this.hostname.substr(1,this.hostname.length-2);if(rest[0]!=="/"){rest="/"+rest}}}if(!unsafeProtocol[lowerProto]){for(var i=0,l=autoEscape.length;i<l;i++){var ae=autoEscape[i];if(rest.indexOf(ae)===-1)continue;var esc=encodeURIComponent(ae);if(esc===ae){esc=escape(ae)}rest=rest.split(ae).join(esc)}}var hash=rest.indexOf("#");if(hash!==-1){this.hash=rest.substr(hash);rest=rest.slice(0,hash)}var qm=rest.indexOf("?");if(qm!==-1){this.search=rest.substr(qm);this.query=rest.substr(qm+1);if(parseQueryString){this.query=querystring.parse(this.query)}rest=rest.slice(0,qm)}else if(parseQueryString){this.search="";this.query={}}if(rest)this.pathname=rest;if(slashedProtocol[lowerProto]&&this.hostname&&!this.pathname){this.pathname="/"}if(this.pathname||this.search){var p=this.pathname||"";var s=this.search||"";this.path=p+s}this.href=this.format();return this};function urlFormat(obj){if(util.isString(obj))obj=urlParse(obj);if(!(obj instanceof Url))return Url.prototype.format.call(obj);return obj.format()}Url.prototype.format=function(){var auth=this.auth||"";if(auth){auth=encodeURIComponent(auth);auth=auth.replace(/%3A/i,":");auth+="@"}var protocol=this.protocol||"",pathname=this.pathname||"",hash=this.hash||"",host=false,query="";if(this.host){host=auth+this.host}else if(this.hostname){host=auth+(this.hostname.indexOf(":")===-1?this.hostname:"["+this.hostname+"]");if(this.port){host+=":"+this.port}}if(this.query&&util.isObject(this.query)&&Object.keys(this.query).length){query=querystring.stringify(this.query)}var search=this.search||query&&"?"+query||"";if(protocol&&protocol.substr(-1)!==":")protocol+=":";if(this.slashes||(!protocol||slashedProtocol[protocol])&&host!==false){host="//"+(host||"");if(pathname&&pathname.charAt(0)!=="/")pathname="/"+pathname}else if(!host){host=""}if(hash&&hash.charAt(0)!=="#")hash="#"+hash;if(search&&search.charAt(0)!=="?")search="?"+search;pathname=pathname.replace(/[?#]/g,(function(match){return encodeURIComponent(match)}));search=search.replace("#","%23");return protocol+host+pathname+search+hash};function urlResolve(source,relative){return urlParse(source,false,true).resolve(relative)}Url.prototype.resolve=function(relative){return this.resolveObject(urlParse(relative,false,true)).format()};function urlResolveObject(source,relative){if(!source)return relative;return urlParse(source,false,true).resolveObject(relative)}Url.prototype.resolveObject=function(relative){if(util.isString(relative)){var rel=new Url;rel.parse(relative,false,true);relative=rel}var result=new Url;var tkeys=Object.keys(this);for(var tk=0;tk<tkeys.length;tk++){var tkey=tkeys[tk];result[tkey]=this[tkey]}result.hash=relative.hash;if(relative.href===""){result.href=result.format();return result}if(relative.slashes&&!relative.protocol){var rkeys=Object.keys(relative);for(var rk=0;rk<rkeys.length;rk++){var rkey=rkeys[rk];if(rkey!=="protocol")result[rkey]=relative[rkey]}if(slashedProtocol[result.protocol]&&result.hostname&&!result.pathname){result.path=result.pathname="/"}result.href=result.format();return result}if(relative.protocol&&relative.protocol!==result.protocol){if(!slashedProtocol[relative.protocol]){var keys=Object.keys(relative);for(var v=0;v<keys.length;v++){var k=keys[v];result[k]=relative[k]}result.href=result.format();return result}result.protocol=relative.protocol;if(!relative.host&&!hostlessProtocol[relative.protocol]){var relPath=(relative.pathname||"").split("/");while(relPath.length&&!(relative.host=relPath.shift()));if(!relative.host)relative.host="";if(!relative.hostname)relative.hostname="";if(relPath[0]!=="")relPath.unshift("");if(relPath.length<2)relPath.unshift("");result.pathname=relPath.join("/")}else{result.pathname=relative.pathname}result.search=relative.search;result.query=relative.query;result.host=relative.host||"";result.auth=relative.auth;result.hostname=relative.hostname||relative.host;result.port=relative.port;if(result.pathname||result.search){var p=result.pathname||"";var s=result.search||"";result.path=p+s}result.slashes=result.slashes||relative.slashes;result.href=result.format();return result}var isSourceAbs=result.pathname&&result.pathname.charAt(0)==="/",isRelAbs=relative.host||relative.pathname&&relative.pathname.charAt(0)==="/",mustEndAbs=isRelAbs||isSourceAbs||result.host&&relative.pathname,removeAllDots=mustEndAbs,srcPath=result.pathname&&result.pathname.split("/")||[],relPath=relative.pathname&&relative.pathname.split("/")||[],psychotic=result.protocol&&!slashedProtocol[result.protocol];if(psychotic){result.hostname="";result.port=null;if(result.host){if(srcPath[0]==="")srcPath[0]=result.host;else srcPath.unshift(result.host)}result.host="";if(relative.protocol){relative.hostname=null;relative.port=null;if(relative.host){if(relPath[0]==="")relPath[0]=relative.host;else relPath.unshift(relative.host)}relative.host=null}mustEndAbs=mustEndAbs&&(relPath[0]===""||srcPath[0]==="")}if(isRelAbs){result.host=relative.host||relative.host===""?relative.host:result.host;result.hostname=relative.hostname||relative.hostname===""?relative.hostname:result.hostname;result.search=relative.search;result.query=relative.query;srcPath=relPath}else if(relPath.length){if(!srcPath)srcPath=[];srcPath.pop();srcPath=srcPath.concat(relPath);result.search=relative.search;result.query=relative.query}else if(!util.isNullOrUndefined(relative.search)){if(psychotic){result.hostname=result.host=srcPath.shift();var authInHost=result.host&&result.host.indexOf("@")>0?result.host.split("@"):false;if(authInHost){result.auth=authInHost.shift();result.host=result.hostname=authInHost.shift()}}result.search=relative.search;result.query=relative.query;if(!util.isNull(result.pathname)||!util.isNull(result.search)){result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")}result.href=result.format();return result}if(!srcPath.length){result.pathname=null;if(result.search){result.path="/"+result.search}else{result.path=null}result.href=result.format();return result}var last=srcPath.slice(-1)[0];var hasTrailingSlash=(result.host||relative.host||srcPath.length>1)&&(last==="."||last==="..")||last==="";var up=0;for(var i=srcPath.length;i>=0;i--){last=srcPath[i];if(last==="."){srcPath.splice(i,1)}else if(last===".."){srcPath.splice(i,1);up++}else if(up){srcPath.splice(i,1);up--}}if(!mustEndAbs&&!removeAllDots){for(;up--;up){srcPath.unshift("..")}}if(mustEndAbs&&srcPath[0]!==""&&(!srcPath[0]||srcPath[0].charAt(0)!=="/")){srcPath.unshift("")}if(hasTrailingSlash&&srcPath.join("/").substr(-1)!=="/"){srcPath.push("")}var isAbsolute=srcPath[0]===""||srcPath[0]&&srcPath[0].charAt(0)==="/";if(psychotic){result.hostname=result.host=isAbsolute?"":srcPath.length?srcPath.shift():"";var authInHost=result.host&&result.host.indexOf("@")>0?result.host.split("@"):false;if(authInHost){result.auth=authInHost.shift();result.host=result.hostname=authInHost.shift()}}mustEndAbs=mustEndAbs||result.host&&srcPath.length;if(mustEndAbs&&!isAbsolute){srcPath.unshift("")}if(!srcPath.length){result.pathname=null;result.path=null}else{result.pathname=srcPath.join("/")}if(!util.isNull(result.pathname)||!util.isNull(result.search)){result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")}result.auth=relative.auth||result.auth;result.slashes=result.slashes||relative.slashes;result.href=result.format();return result};Url.prototype.parseHost=function(){var host=this.host;var port=portPattern.exec(host);if(port){port=port[0];if(port!==":"){this.port=port.substr(1)}host=host.substr(0,host.length-port.length)}if(host)this.hostname=host}},{"./util":205,punycode:172,querystring:175}],205:[function(require,module,exports){"use strict";module.exports={isString:function(arg){return typeof arg==="string"},isObject:function(arg){return typeof arg==="object"&&arg!==null},isNull:function(arg){return arg===null},isNullOrUndefined:function(arg){return arg==null}}},{}],206:[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:{})},{}],207:[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}}},{}],208:[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"}},{}],209:[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":208,_process:171,inherits:207}],210:[function(require,module,exports){var byteToHex=[];for(var i=0;i<256;++i){byteToHex[i]=(i+256).toString(16).substr(1)}function bytesToUuid(buf,offset){var i=offset||0;var bth=byteToHex;return[bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],"-",bth[buf[i++]],bth[buf[i++]],"-",bth[buf[i++]],bth[buf[i++]],"-",bth[buf[i++]],bth[buf[i++]],"-",bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]]].join("")}module.exports=bytesToUuid},{}],211:[function(require,module,exports){var getRandomValues=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof window.msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto);if(getRandomValues){var rnds8=new Uint8Array(16);module.exports=function whatwgRNG(){getRandomValues(rnds8);return rnds8}}else{var rnds=new Array(16);module.exports=function mathRNG(){for(var i=0,r;i<16;i++){if((i&3)===0)r=Math.random()*4294967296;rnds[i]=r>>>((i&3)<<3)&255}return rnds}}},{}],212:[function(require,module,exports){var rng=require("./lib/rng");var bytesToUuid=require("./lib/bytesToUuid");function v4(options,buf,offset){var i=buf&&offset||0;if(typeof options=="string"){buf=options==="binary"?new Array(16):null;options=null}options=options||{};var rnds=options.random||(options.rng||rng)();rnds[6]=rnds[6]&15|64;rnds[8]=rnds[8]&63|128;if(buf){for(var ii=0;ii<16;++ii){buf[i+ii]=rnds[ii]}}return buf||bytesToUuid(rnds)}module.exports=v4},{"./lib/bytesToUuid":210,"./lib/rng":211}],213:[function(require,module,exports){(function(process,global){"use strict";var Transform=require("readable-stream").Transform;var duplexify=require("duplexify");var WS=require("ws");var Buffer=require("safe-buffer").Buffer;module.exports=WebSocketStream;function buildProxy(options,socketWrite,socketEnd){var proxy=new Transform({objectMode:options.objectMode});proxy._write=socketWrite;proxy._flush=socketEnd;return proxy}function WebSocketStream(target,protocols,options){var stream,socket;var isBrowser=process.title==="browser";var isNative=!!global.WebSocket;var socketWrite=isBrowser?socketWriteBrowser:socketWriteNode;if(protocols&&!Array.isArray(protocols)&&"object"===typeof protocols){options=protocols;protocols=null;if(typeof options.protocol==="string"||Array.isArray(options.protocol)){protocols=options.protocol}}if(!options)options={};if(options.objectMode===undefined){options.objectMode=!(options.binary===true||options.binary===undefined)}var proxy=buildProxy(options,socketWrite,socketEnd);if(!options.objectMode){proxy._writev=writev}var bufferSize=options.browserBufferSize||1024*512;var bufferTimeout=options.browserBufferTimeout||1e3;if(typeof target==="object"){socket=target}else{if(isNative&&isBrowser){socket=new WS(target,protocols)}else{socket=new WS(target,protocols,options)}socket.binaryType="arraybuffer"}if(socket.readyState===socket.OPEN){stream=proxy}else{stream=stream=duplexify(undefined,undefined,options);if(!options.objectMode){stream._writev=writev}socket.onopen=onopen}stream.socket=socket;socket.onclose=onclose;socket.onerror=onerror;socket.onmessage=onmessage;proxy.on("close",destroy);var coerceToBuffer=!options.objectMode;function socketWriteNode(chunk,enc,next){if(socket.readyState!==socket.OPEN){next();return}if(coerceToBuffer&&typeof chunk==="string"){chunk=Buffer.from(chunk,"utf8")}socket.send(chunk,next)}function socketWriteBrowser(chunk,enc,next){if(socket.bufferedAmount>bufferSize){setTimeout(socketWriteBrowser,bufferTimeout,chunk,enc,next);return}if(coerceToBuffer&&typeof chunk==="string"){chunk=Buffer.from(chunk,"utf8")}try{socket.send(chunk)}catch(err){return next(err)}next()}function socketEnd(done){socket.close();done()}function onopen(){stream.setReadable(proxy);stream.setWritable(proxy);stream.emit("connect")}function onclose(){stream.end();stream.destroy()}function onerror(err){stream.destroy(err)}function onmessage(event){var data=event.data;if(data instanceof ArrayBuffer)data=Buffer.from(data);else data=Buffer.from(data,"utf8");proxy.push(data)}function destroy(){socket.close()}function writev(chunks,cb){var buffers=new Array(chunks.length);for(var i=0;i<chunks.length;i++){if(typeof chunks[i].chunk==="string"){buffers[i]=Buffer.from(chunks[i],"utf8")}else{buffers[i]=chunks[i].chunk}}this._write(Buffer.concat(buffers),"binary",cb)}return stream}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{_process:171,duplexify:79,"readable-stream":187,"safe-buffer":189,ws:214}],214:[function(require,module,exports){var ws=null;if(typeof WebSocket!=="undefined"){ws=WebSocket}else if(typeof MozWebSocket!=="undefined"){ws=MozWebSocket}else if(typeof window!=="undefined"){ws=window.WebSocket||window.MozWebSocket}module.exports=ws},{}],215:[function(require,module,exports){module.exports=wrappy;function wrappy(fn,cb){if(fn&&cb)return wrappy(fn)(cb);if(typeof fn!=="function")throw new TypeError("need wrapper function");Object.keys(fn).forEach((function(k){wrapper[k]=fn[k]}));return wrapper;function wrapper(){var args=new Array(arguments.length);for(var i=0;i<args.length;i++){args[i]=arguments[i]}var ret=fn.apply(this,args);var cb=args[args.length-1];if(typeof ret==="function"&&ret!==cb){Object.keys(cb).forEach((function(k){ret[k]=cb[k]}))}return ret}}},{}],216:[function(require,module,exports){module.exports=extend;var hasOwnProperty=Object.prototype.hasOwnProperty;function extend(){var target={};for(var i=0;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(hasOwnProperty.call(source,key)){target[key]=source[key]}}}return target}},{}],217:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _Alias=_interopRequireDefault(require("./schema/Alias"));var _Map=_interopRequireDefault(require("./schema/Map"));var _Merge=_interopRequireDefault(require("./schema/Merge"));var _Scalar=_interopRequireDefault(require("./schema/Scalar"));var _Seq=_interopRequireDefault(require("./schema/Seq"));var Anchors=function(){(0,_createClass2.default)(Anchors,null,[{key:"validAnchorNode",value:function validAnchorNode(node){return node instanceof _Scalar.default||node instanceof _Seq.default||node instanceof _Map.default}}]);function Anchors(prefix){(0,_classCallCheck2.default)(this,Anchors);(0,_defineProperty2.default)(this,"map",{});this.prefix=prefix}(0,_createClass2.default)(Anchors,[{key:"createAlias",value:function createAlias(node,name){this.setAnchor(node,name);return new _Alias.default(node)}},{key:"createMergePair",value:function createMergePair(){var _this=this;var merge=new _Merge.default;for(var _len=arguments.length,sources=new Array(_len),_key=0;_key<_len;_key++){sources[_key]=arguments[_key]}merge.value.items=sources.map((function(s){if(s instanceof _Alias.default){if(s.source instanceof _Map.default)return s}else if(s instanceof _Map.default){return _this.createAlias(s)}throw new Error("Merge sources must be Map nodes or their Aliases")}));return merge}},{key:"getName",value:function getName(node){var map=this.map;return Object.keys(map).find((function(a){return map[a]===node}))}},{key:"getNode",value:function getNode(name){return this.map[name]}},{key:"newName",value:function newName(prefix){if(!prefix)prefix=this.prefix;var names=Object.keys(this.map);for(var i=1;true;++i){var name="".concat(prefix).concat(i);if(!names.includes(name))return name}}},{key:"resolveNodes",value:function resolveNodes(){var map=this.map,_cstAliases=this._cstAliases;Object.keys(map).forEach((function(a){map[a]=map[a].resolved}));_cstAliases.forEach((function(a){a.source=a.source.resolved}));delete this._cstAliases}},{key:"setAnchor",value:function setAnchor(node,name){if(node!=null&&!Anchors.validAnchorNode(node)){throw new Error("Anchors may only be set for Scalar, Seq and Map nodes")}if(name&&/[\x00-\x19\s,[\]{}]/.test(name)){throw new Error("Anchor names must not contain whitespace or control characters")}var map=this.map;var prev=node&&Object.keys(map).find((function(a){return map[a]===node}));if(prev){if(!name){return prev}else if(prev!==name){delete map[prev];map[name]=node}}else{if(!name){if(!node)return null;name=this.newName()}map[name]=node}return name}}]);return Anchors}();exports.default=Anchors},{"./schema/Alias":242,"./schema/Map":244,"./schema/Merge":245,"./schema/Scalar":248,"./schema/Seq":249,"@babel/runtime/helpers/classCallCheck":21,"@babel/runtime/helpers/createClass":23,"@babel/runtime/helpers/defineProperty":24,"@babel/runtime/helpers/interopRequireDefault":28}],218:[function(require,module,exports){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard");var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _slicedToArray2=_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _addComment=_interopRequireDefault(require("./addComment"));var _Anchors=_interopRequireDefault(require("./Anchors"));var _constants=require("./constants");var _errors=require("./errors");var _listTagNames=_interopRequireDefault(require("./listTagNames"));var _schema=_interopRequireDefault(require("./schema"));var _Alias=_interopRequireDefault(require("./schema/Alias"));var _Collection=_interopRequireWildcard(require("./schema/Collection"));var _Node=_interopRequireDefault(require("./schema/Node"));var _Scalar=_interopRequireDefault(require("./schema/Scalar"));var _toJSON2=_interopRequireDefault(require("./toJSON"));var isCollectionItem=function isCollectionItem(node){return node&&[_constants.Type.MAP_KEY,_constants.Type.MAP_VALUE,_constants.Type.SEQ_ITEM].includes(node.type)};var Document=function(){function Document(options){(0,_classCallCheck2.default)(this,Document);this.anchors=new _Anchors.default(options.anchorPrefix);this.commentBefore=null;this.comment=null;this.contents=null;this.directivesEndMarker=null;this.errors=[];this.options=options;this.schema=null;this.tagPrefixes=[];this.version=null;this.warnings=[]}(0,_createClass2.default)(Document,[{key:"assertCollectionContents",value:function assertCollectionContents(){if(this.contents instanceof _Collection.default)return true;throw new Error("Expected a YAML collection as document contents")}},{key:"add",value:function add(value){this.assertCollectionContents();return this.contents.add(value)}},{key:"addIn",value:function addIn(path,value){this.assertCollectionContents();this.contents.addIn(path,value)}},{key:"delete",value:function _delete(key){this.assertCollectionContents();return this.contents.delete(key)}},{key:"deleteIn",value:function deleteIn(path){if((0,_Collection.isEmptyPath)(path)){if(this.contents==null)return false;this.contents=null;return true}this.assertCollectionContents();return this.contents.deleteIn(path)}},{key:"getDefaults",value:function getDefaults(){return Document.defaults[this.version]||Document.defaults[this.options.version]||{}}},{key:"get",value:function get(key,keepScalar){return this.contents instanceof _Collection.default?this.contents.get(key,keepScalar):undefined}},{key:"getIn",value:function getIn(path,keepScalar){if((0,_Collection.isEmptyPath)(path))return!keepScalar&&this.contents instanceof _Scalar.default?this.contents.value:this.contents;return this.contents instanceof _Collection.default?this.contents.getIn(path,keepScalar):undefined}},{key:"has",value:function has(key){return this.contents instanceof _Collection.default?this.contents.has(key):false}},{key:"hasIn",value:function hasIn(path){if((0,_Collection.isEmptyPath)(path))return this.contents!==undefined;return this.contents instanceof _Collection.default?this.contents.hasIn(path):false}},{key:"set",value:function set(key,value){this.assertCollectionContents();this.contents.set(key,value)}},{key:"setIn",value:function setIn(path,value){if((0,_Collection.isEmptyPath)(path))this.contents=value;else{this.assertCollectionContents();this.contents.setIn(path,value)}}},{key:"setSchema",value:function setSchema(id,customTags){if(!id&&!customTags&&this.schema)return;if(typeof id==="number")id=id.toFixed(1);if(id==="1.0"||id==="1.1"||id==="1.2"){if(this.version)this.version=id;else this.options.version=id;delete this.options.schema}else if(id&&typeof id==="string"){this.options.schema=id}if(Array.isArray(customTags))this.options.customTags=customTags;var opt=Object.assign({},this.getDefaults(),this.options);this.schema=new _schema.default(opt)}},{key:"parse",value:function parse(node,prevDoc){if(this.options.keepCstNodes)this.cstNode=node;if(this.options.keepNodeTypes)this.type="DOCUMENT";var _node$directives=node.directives,directives=_node$directives===void 0?[]:_node$directives,_node$contents=node.contents,contents=_node$contents===void 0?[]:_node$contents,directivesEndMarker=node.directivesEndMarker,error=node.error,valueRange=node.valueRange;if(error){if(!error.source)error.source=this;this.errors.push(error)}this.parseDirectives(directives,prevDoc);if(directivesEndMarker)this.directivesEndMarker=true;this.range=valueRange?[valueRange.start,valueRange.end]:null;this.setSchema();this.anchors._cstAliases=[];this.parseContents(contents);this.anchors.resolveNodes();if(this.options.prettyErrors){var _iteratorNormalCompletion=true;var _didIteratorError=false;var _iteratorError=undefined;try{for(var _iterator=this.errors[Symbol.iterator](),_step;!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=true){var _error=_step.value;if(_error instanceof _errors.YAMLError)_error.makePretty()}}catch(err){_didIteratorError=true;_iteratorError=err}finally{try{if(!_iteratorNormalCompletion&&_iterator.return!=null){_iterator.return()}}finally{if(_didIteratorError){throw _iteratorError}}}var _iteratorNormalCompletion2=true;var _didIteratorError2=false;var _iteratorError2=undefined;try{for(var _iterator2=this.warnings[Symbol.iterator](),_step2;!(_iteratorNormalCompletion2=(_step2=_iterator2.next()).done);_iteratorNormalCompletion2=true){var warn=_step2.value;if(warn instanceof _errors.YAMLError)warn.makePretty()}}catch(err){_didIteratorError2=true;_iteratorError2=err}finally{try{if(!_iteratorNormalCompletion2&&_iterator2.return!=null){_iterator2.return()}}finally{if(_didIteratorError2){throw _iteratorError2}}}}return this}},{key:"parseDirectives",value:function parseDirectives(directives,prevDoc){var _this=this;var directiveComments=[];var hasDirectives=false;directives.forEach((function(directive){var comment=directive.comment,name=directive.name;switch(name){case"TAG":_this.resolveTagDirective(directive);hasDirectives=true;break;case"YAML":case"YAML:1.0":_this.resolveYamlDirective(directive);hasDirectives=true;break;default:if(name){var msg="YAML only supports %TAG and %YAML directives, and not %".concat(name);_this.warnings.push(new _errors.YAMLWarning(directive,msg))}}if(comment)directiveComments.push(comment)}));if(prevDoc&&!hasDirectives&&"1.1"===(this.version||prevDoc.version||this.options.version)){var copyTagPrefix=function copyTagPrefix(_ref){var handle=_ref.handle,prefix=_ref.prefix;return{handle:handle,prefix:prefix}};this.tagPrefixes=prevDoc.tagPrefixes.map(copyTagPrefix);this.version=prevDoc.version}this.commentBefore=directiveComments.join("\n")||null}},{key:"parseContents",value:function parseContents(contents){var _this2=this;var comments={before:[],after:[]};var contentNodes=[];var spaceBefore=false;contents.forEach((function(node){if(node.valueRange){if(contentNodes.length===1){var msg="Document is not valid YAML (bad indentation?)";_this2.errors.push(new _errors.YAMLSyntaxError(node,msg))}var res=_this2.resolveNode(node);if(spaceBefore){res.spaceBefore=true;spaceBefore=false}contentNodes.push(res)}else if(node.comment!==null){var cc=contentNodes.length===0?comments.before:comments.after;cc.push(node.comment)}else if(node.type===_constants.Type.BLANK_LINE){spaceBefore=true;if(contentNodes.length===0&&comments.before.length>0&&!_this2.commentBefore){_this2.commentBefore=comments.before.join("\n");comments.before=[]}}}));switch(contentNodes.length){case 0:this.contents=null;comments.after=comments.before;break;case 1:this.contents=contentNodes[0];if(this.contents){var cb=comments.before.join("\n")||null;if(cb){var cbNode=this.contents instanceof _Collection.default&&this.contents.items[0]?this.contents.items[0]:this.contents;cbNode.commentBefore=cbNode.commentBefore?"".concat(cb,"\n").concat(cbNode.commentBefore):cb}}else{comments.after=comments.before.concat(comments.after)}break;default:this.contents=contentNodes;if(this.contents[0]){this.contents[0].commentBefore=comments.before.join("\n")||null}else{comments.after=comments.before.concat(comments.after)}}this.comment=comments.after.join("\n")||null}},{key:"resolveTagDirective",value:function resolveTagDirective(directive){var _directive$parameters=(0,_slicedToArray2.default)(directive.parameters,2),handle=_directive$parameters[0],prefix=_directive$parameters[1];if(handle&&prefix){if(this.tagPrefixes.every((function(p){return p.handle!==handle}))){this.tagPrefixes.push({handle:handle,prefix:prefix})}else{var msg="The %TAG directive must only be given at most once per handle in the same document.";this.errors.push(new _errors.YAMLSemanticError(directive,msg))}}else{var _msg="Insufficient parameters given for %TAG directive";this.errors.push(new _errors.YAMLSemanticError(directive,_msg))}}},{key:"resolveYamlDirective",value:function resolveYamlDirective(directive){var _directive$parameters2=(0,_slicedToArray2.default)(directive.parameters,1),version=_directive$parameters2[0];if(directive.name==="YAML:1.0")version="1.0";if(this.version){var msg="The %YAML directive must only be given at most once per document.";this.errors.push(new _errors.YAMLSemanticError(directive,msg))}if(!version){var _msg2="Insufficient parameters given for %YAML directive";this.errors.push(new _errors.YAMLSemanticError(directive,_msg2))}else{if(!Document.defaults[version]){var v0=this.version||this.options.version;var _msg3="Document will be parsed as YAML ".concat(v0," rather than YAML ").concat(version);this.warnings.push(new _errors.YAMLWarning(directive,_msg3))}this.version=version}}},{key:"resolveTagName",value:function resolveTagName(node){var tag=node.tag,type=node.type;var nonSpecific=false;if(tag){var handle=tag.handle,suffix=tag.suffix,verbatim=tag.verbatim;if(verbatim){if(verbatim!=="!"&&verbatim!=="!!")return verbatim;var msg="Verbatim tags aren't resolved, so ".concat(verbatim," is invalid.");this.errors.push(new _errors.YAMLSemanticError(node,msg))}else if(handle==="!"&&!suffix){nonSpecific=true}else{var prefix=this.tagPrefixes.find((function(p){return p.handle===handle}));if(!prefix){var dtp=this.getDefaults().tagPrefixes;if(dtp)prefix=dtp.find((function(p){return p.handle===handle}))}if(prefix){if(suffix){if(handle==="!"&&(this.version||this.options.version)==="1.0"){if(suffix[0]==="^")return suffix;if(/[:/]/.test(suffix)){var vocab=suffix.match(/^([a-z0-9-]+)\/(.*)/i);return vocab?"tag:".concat(vocab[1],".yaml.org,2002:").concat(vocab[2]):"tag:".concat(suffix)}}return prefix.prefix+decodeURIComponent(suffix)}this.errors.push(new _errors.YAMLSemanticError(node,"The ".concat(handle," tag has no suffix.")))}else{var _msg4="The ".concat(handle," tag handle is non-default and was not declared.");this.errors.push(new _errors.YAMLSemanticError(node,_msg4))}}}switch(type){case _constants.Type.BLOCK_FOLDED:case _constants.Type.BLOCK_LITERAL:case _constants.Type.QUOTE_DOUBLE:case _constants.Type.QUOTE_SINGLE:return _schema.default.defaultTags.STR;case _constants.Type.FLOW_MAP:case _constants.Type.MAP:return _schema.default.defaultTags.MAP;case _constants.Type.FLOW_SEQ:case _constants.Type.SEQ:return _schema.default.defaultTags.SEQ;case _constants.Type.PLAIN:return nonSpecific?_schema.default.defaultTags.STR:null;default:return null}}},{key:"resolveNode",value:function resolveNode(node){if(!node)return null;var anchors=this.anchors,errors=this.errors,schema=this.schema;var hasAnchor=false;var hasTag=false;var comments={before:[],after:[]};var props=isCollectionItem(node.context.parent)?node.context.parent.props.concat(node.props):node.props;var _iteratorNormalCompletion3=true;var _didIteratorError3=false;var _iteratorError3=undefined;try{for(var _iterator3=props[Symbol.iterator](),_step3;!(_iteratorNormalCompletion3=(_step3=_iterator3.next()).done);_iteratorNormalCompletion3=true){var _step3$value=_step3.value,start=_step3$value.start,end=_step3$value.end;switch(node.context.src[start]){case _constants.Char.COMMENT:{if(!node.commentHasRequiredWhitespace(start)){var _msg7="Comments must be separated from other tokens by white space characters";errors.push(new _errors.YAMLSemanticError(node,_msg7))}var c=node.context.src.slice(start+1,end);var header=node.header,valueRange=node.valueRange;if(valueRange&&(start>valueRange.start||header&&start>header.start)){comments.after.push(c)}else{comments.before.push(c)}}break;case _constants.Char.ANCHOR:if(hasAnchor){var _msg8="A node can have at most one anchor";errors.push(new _errors.YAMLSemanticError(node,_msg8))}hasAnchor=true;break;case _constants.Char.TAG:if(hasTag){var _msg9="A node can have at most one tag";errors.push(new _errors.YAMLSemanticError(node,_msg9))}hasTag=true;break}}}catch(err){_didIteratorError3=true;_iteratorError3=err}finally{try{if(!_iteratorNormalCompletion3&&_iterator3.return!=null){_iterator3.return()}}finally{if(_didIteratorError3){throw _iteratorError3}}}if(hasAnchor){var name=node.anchor;var prev=anchors.getNode(name);if(prev)anchors.map[anchors.newName(name)]=prev;anchors.map[name]=node}var res;if(node.type===_constants.Type.ALIAS){if(hasAnchor||hasTag){var msg="An alias node must not specify any properties";errors.push(new _errors.YAMLSemanticError(node,msg))}var _name=node.rawValue;var src=anchors.getNode(_name);if(!src){var _msg5="Aliased anchor not found: ".concat(_name);errors.push(new _errors.YAMLReferenceError(node,_msg5));return null}res=new _Alias.default(src);anchors._cstAliases.push(res)}else{var tagName=this.resolveTagName(node);if(tagName){res=schema.resolveNodeWithFallback(this,node,tagName)}else{if(node.type!==_constants.Type.PLAIN){var _msg6="Failed to resolve ".concat(node.type," node here");errors.push(new _errors.YAMLSyntaxError(node,_msg6));return null}try{res=schema.resolveScalar(node.strValue||"")}catch(error){if(!error.source)error.source=node;errors.push(error);return null}}}if(res){res.range=[node.range.start,node.range.end];if(this.options.keepCstNodes)res.cstNode=node;if(this.options.keepNodeTypes)res.type=node.type;var cb=comments.before.join("\n");if(cb){res.commentBefore=res.commentBefore?"".concat(res.commentBefore,"\n").concat(cb):cb}var ca=comments.after.join("\n");if(ca)res.comment=res.comment?"".concat(res.comment,"\n").concat(ca):ca}return node.resolved=res}},{key:"listNonDefaultTags",value:function listNonDefaultTags(){return(0,_listTagNames.default)(this.contents).filter((function(t){return t.indexOf(_schema.default.defaultPrefix)!==0}))}},{key:"setTagPrefix",value:function setTagPrefix(handle,prefix){if(handle[0]!=="!"||handle[handle.length-1]!=="!")throw new Error("Handle must start and end with !");if(prefix){var prev=this.tagPrefixes.find((function(p){return p.handle===handle}));if(prev)prev.prefix=prefix;else this.tagPrefixes.push({handle:handle,prefix:prefix})}else{this.tagPrefixes=this.tagPrefixes.filter((function(p){return p.handle!==handle}))}}},{key:"stringifyTag",value:function stringifyTag(tag){if((this.version||this.options.version)==="1.0"){var priv=tag.match(/^tag:private\.yaml\.org,2002:([^:/]+)$/);if(priv)return"!"+priv[1];var vocab=tag.match(/^tag:([a-zA-Z0-9-]+)\.yaml\.org,2002:(.*)/);return vocab?"!".concat(vocab[1],"/").concat(vocab[2]):"!".concat(tag.replace(/^tag:/,""))}else{var p=this.tagPrefixes.find((function(p){return tag.indexOf(p.prefix)===0}));if(!p){var dtp=this.getDefaults().tagPrefixes;p=dtp&&dtp.find((function(p){return tag.indexOf(p.prefix)===0}))}if(!p)return tag[0]==="!"?tag:"!<".concat(tag,">");var suffix=tag.substr(p.prefix.length).replace(/[!,[\]{}]/g,(function(ch){return{"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"}[ch]}));return p.handle+suffix}}},{key:"toJSON",value:function toJSON(arg){var _this3=this;var _this$options=this.options,keepBlobsInJSON=_this$options.keepBlobsInJSON,mapAsMap=_this$options.mapAsMap,maxAliasCount=_this$options.maxAliasCount;var keep=keepBlobsInJSON&&(typeof arg!=="string"||!(this.contents instanceof _Scalar.default));var ctx={doc:this,keep:keep,mapAsMap:keep&&!!mapAsMap,maxAliasCount:maxAliasCount};var anchorNames=Object.keys(this.anchors.map);if(anchorNames.length>0)ctx.anchors=anchorNames.map((function(name){return{alias:[],aliasCount:0,count:1,node:_this3.anchors.map[name]}}));return(0,_toJSON2.default)(this.contents,arg,ctx)}},{key:"toString",value:function toString(){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");this.setSchema();var lines=[];var hasDirectives=false;if(this.version){var vd="%YAML 1.2";if(this.schema.name==="yaml-1.1"){if(this.version==="1.0")vd="%YAML:1.0";else if(this.version==="1.1")vd="%YAML 1.1"}lines.push(vd);hasDirectives=true}var tagNames=this.listNonDefaultTags();this.tagPrefixes.forEach((function(_ref2){var handle=_ref2.handle,prefix=_ref2.prefix;if(tagNames.some((function(t){return t.indexOf(prefix)===0}))){lines.push("%TAG ".concat(handle," ").concat(prefix));hasDirectives=true}}));if(hasDirectives||this.directivesEndMarker)lines.push("---");if(this.commentBefore){if(hasDirectives||!this.directivesEndMarker)lines.unshift("");lines.unshift(this.commentBefore.replace(/^/gm,"#"))}var ctx={anchors:{},doc:this,indent:""};var chompKeep=false;var contentComment=null;if(this.contents){if(this.contents instanceof _Node.default){if(this.contents.spaceBefore&&(hasDirectives||this.directivesEndMarker))lines.push("");if(this.contents.commentBefore)lines.push(this.contents.commentBefore.replace(/^/gm,"#"));ctx.forceBlockIndent=!!this.comment;contentComment=this.contents.comment}var onChompKeep=contentComment?null:function(){return chompKeep=true};var body=this.schema.stringify(this.contents,ctx,(function(){return contentComment=null}),onChompKeep);lines.push((0,_addComment.default)(body,"",contentComment))}else if(this.contents!==undefined){lines.push(this.schema.stringify(this.contents,ctx))}if(this.comment){if((!chompKeep||contentComment)&&lines[lines.length-1]!=="")lines.push("");lines.push(this.comment.replace(/^/gm,"#"))}return lines.join("\n")+"\n"}}]);return Document}();exports.default=Document;(0,_defineProperty2.default)(Document,"defaults",{"1.0":{schema:"yaml-1.1",merge:true,tagPrefixes:[{handle:"!",prefix:_schema.default.defaultPrefix},{handle:"!!",prefix:"tag:private.yaml.org,2002:"}]},1.1:{schema:"yaml-1.1",merge:true,tagPrefixes:[{handle:"!",prefix:"!"},{handle:"!!",prefix:_schema.default.defaultPrefix}]},1.2:{schema:"core",merge:false,tagPrefixes:[{handle:"!",prefix:"!"},{handle:"!!",prefix:_schema.default.defaultPrefix}]}})},{"./Anchors":217,"./addComment":219,"./constants":220,"./errors":238,"./listTagNames":241,"./schema":250,"./schema/Alias":242,"./schema/Collection":243,"./schema/Node":246,"./schema/Scalar":248,"./toJSON":269,"@babel/runtime/helpers/classCallCheck":21,"@babel/runtime/helpers/createClass":23,"@babel/runtime/helpers/defineProperty":24,"@babel/runtime/helpers/interopRequireDefault":28,"@babel/runtime/helpers/interopRequireWildcard":29,"@babel/runtime/helpers/slicedToArray":36}],219:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.addCommentBefore=addCommentBefore;exports.default=addComment;function addCommentBefore(str,indent,comment){if(!comment)return str;var cc=comment.replace(/[\s\S]^/gm,"$&".concat(indent,"#"));return"#".concat(cc,"\n").concat(indent).concat(str)}function addComment(str,indent,comment){return!comment?str:comment.indexOf("\n")===-1?"".concat(str," #").concat(comment):"".concat(str,"\n")+comment.replace(/^/gm,"".concat(indent||"","#"))}},{}],220:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Type=exports.Char=void 0;var Char={ANCHOR:"&",COMMENT:"#",TAG:"!",DIRECTIVES_END:"-",DOCUMENT_END:"."};exports.Char=Char;var Type={ALIAS:"ALIAS",BLANK_LINE:"BLANK_LINE",BLOCK_FOLDED:"BLOCK_FOLDED",BLOCK_LITERAL:"BLOCK_LITERAL",COMMENT:"COMMENT",DIRECTIVE:"DIRECTIVE",DOCUMENT:"DOCUMENT",FLOW_MAP:"FLOW_MAP",FLOW_SEQ:"FLOW_SEQ",MAP:"MAP",MAP_KEY:"MAP_KEY",MAP_VALUE:"MAP_VALUE",PLAIN:"PLAIN",QUOTE_DOUBLE:"QUOTE_DOUBLE",QUOTE_SINGLE:"QUOTE_SINGLE",SEQ:"SEQ",SEQ_ITEM:"SEQ_ITEM"};exports.Type=Type},{}],221:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));var _getPrototypeOf2=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));var _inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits"));var _Node2=_interopRequireDefault(require("./Node"));var _Range=_interopRequireDefault(require("./Range"));var Alias=function(_Node){(0,_inherits2.default)(Alias,_Node);function Alias(){(0,_classCallCheck2.default)(this,Alias);return(0,_possibleConstructorReturn2.default)(this,(0,_getPrototypeOf2.default)(Alias).apply(this,arguments))}(0,_createClass2.default)(Alias,[{key:"parse",value:function parse(context,start){this.context=context;var src=context.src;var offset=_Node2.default.endOfIdentifier(src,start+1);this.valueRange=new _Range.default(start+1,offset);offset=_Node2.default.endOfWhiteSpace(src,offset);offset=this.parseComment(offset);return offset}}]);return Alias}(_Node2.default);exports.default=Alias},{"./Node":230,"./Range":235,"@babel/runtime/helpers/classCallCheck":21,"@babel/runtime/helpers/createClass":23,"@babel/runtime/helpers/getPrototypeOf":26,"@babel/runtime/helpers/inherits":27,"@babel/runtime/helpers/interopRequireDefault":28,"@babel/runtime/helpers/possibleConstructorReturn":34}],222:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));var _getPrototypeOf2=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));var _inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits"));var _constants=require("../constants");var _Node2=_interopRequireDefault(require("./Node"));var _Range=_interopRequireDefault(require("./Range"));var BlankLine=function(_Node){(0,_inherits2.default)(BlankLine,_Node);function BlankLine(){(0,_classCallCheck2.default)(this,BlankLine);return(0,_possibleConstructorReturn2.default)(this,(0,_getPrototypeOf2.default)(BlankLine).call(this,_constants.Type.BLANK_LINE))}(0,_createClass2.default)(BlankLine,[{key:"parse",value:function parse(context,start){this.context=context;var src=context.src;var offset=start+1;while(_Node2.default.atBlank(src,offset)){var lineEnd=_Node2.default.endOfWhiteSpace(src,offset);if(lineEnd==="\n")offset=lineEnd+1;else break}this.range=new _Range.default(start,offset);return offset}},{key:"includesTrailingLines",get:function get(){return true}}]);return BlankLine}(_Node2.default);exports.default=BlankLine},{"../constants":220,"./Node":230,"./Range":235,"@babel/runtime/helpers/classCallCheck":21,"@babel/runtime/helpers/createClass":23,"@babel/runtime/helpers/getPrototypeOf":26,"@babel/runtime/helpers/inherits":27,"@babel/runtime/helpers/interopRequireDefault":28,"@babel/runtime/helpers/possibleConstructorReturn":34}],223:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=exports.Chomp=void 0;var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));var _getPrototypeOf2=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));var _get2=_interopRequireDefault(require("@babel/runtime/helpers/get"));var _inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits"));var _constants=require("../constants");var _Node2=_interopRequireDefault(require("./Node"));var _Range=_interopRequireDefault(require("./Range"));var Chomp={CLIP:"CLIP",KEEP:"KEEP",STRIP:"STRIP"};exports.Chomp=Chomp;var BlockValue=function(_Node){(0,_inherits2.default)(BlockValue,_Node);function BlockValue(type,props){var _this;(0,_classCallCheck2.default)(this,BlockValue);_this=(0,_possibleConstructorReturn2.default)(this,(0,_getPrototypeOf2.default)(BlockValue).call(this,type,props));_this.blockIndent=null;_this.chomping=Chomp.CLIP;_this.header=null;return _this}(0,_createClass2.default)(BlockValue,[{key:"parseBlockHeader",value:function parseBlockHeader(start){var src=this.context.src;var offset=start+1;var bi="";while(true){var ch=src[offset];switch(ch){case"-":this.chomping=Chomp.STRIP;break;case"+":this.chomping=Chomp.KEEP;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":bi+=ch;break;default:this.blockIndent=Number(bi)||null;this.header=new _Range.default(start,offset);return offset}offset+=1}}},{key:"parseBlockValue",value:function parseBlockValue(start){var _this$context=this.context,indent=_this$context.indent,src=_this$context.src;var offset=start;var valueEnd=start;var bi=this.blockIndent?indent+this.blockIndent-1:indent;var minBlockIndent=1;for(var ch=src[offset];ch==="\n";ch=src[offset]){offset+=1;if(_Node2.default.atDocumentBoundary(src,offset))break;var end=_Node2.default.endOfBlockIndent(src,bi,offset);if(end===null)break;if(!this.blockIndent){var lineIndent=end-(offset+indent);if(src[end]!=="\n"){if(lineIndent<minBlockIndent){offset-=1;break}this.blockIndent=lineIndent;bi=indent+this.blockIndent-1}else if(lineIndent>minBlockIndent){minBlockIndent=lineIndent}}if(src[end]==="\n"){offset=end}else{offset=valueEnd=_Node2.default.endOfLine(src,end)}}if(this.chomping!==Chomp.KEEP){offset=src[valueEnd]?valueEnd+1:valueEnd}this.valueRange=new _Range.default(start+1,offset);return offset}},{key:"parse",value:function parse(context,start){this.context=context;var src=context.src;var offset=this.parseBlockHeader(start);offset=_Node2.default.endOfWhiteSpace(src,offset);offset=this.parseComment(offset);offset=this.parseBlockValue(offset);return offset}},{key:"setOrigRanges",value:function setOrigRanges(cr,offset){offset=(0,_get2.default)((0,_getPrototypeOf2.default)(BlockValue.prototype),"setOrigRanges",this).call(this,cr,offset);return this.header?this.header.setOrigRange(cr,offset):offset}},{key:"includesTrailingLines",get:function get(){return this.chomping===Chomp.KEEP}},{key:"strValue",get:function get(){if(!this.valueRange||!this.context)return null;var _this$valueRange=this.valueRange,start=_this$valueRange.start,end=_this$valueRange.end;var _this$context2=this.context,indent=_this$context2.indent,src=_this$context2.src;if(this.valueRange.isEmpty())return"";var lastNewLine=null;var ch=src[end-1];while(ch==="\n"||ch==="\t"||ch===" "){end-=1;if(end<=start){if(this.chomping===Chomp.KEEP)break;else return""}if(ch==="\n")lastNewLine=end;ch=src[end-1]}var keepStart=end+1;if(lastNewLine){if(this.chomping===Chomp.KEEP){keepStart=lastNewLine;end=this.valueRange.end}else{end=lastNewLine}}var bi=indent+this.blockIndent;var folded=this.type===_constants.Type.BLOCK_FOLDED;var atStart=true;var str="";var sep="";var prevMoreIndented=false;for(var i=start;i<end;++i){for(var j=0;j<bi;++j){if(src[i]!==" ")break;i+=1}var _ch=src[i];if(_ch==="\n"){if(sep==="\n")str+="\n";else sep="\n"}else{var lineEnd=_Node2.default.endOfLine(src,i);var line=src.slice(i,lineEnd);i=lineEnd;if(folded&&(_ch===" "||_ch==="\t")&&i<keepStart){if(sep===" ")sep="\n";else if(!prevMoreIndented&&!atStart&&sep==="\n")sep="\n\n";str+=sep+line;sep=lineEnd<end&&src[lineEnd]||"";prevMoreIndented=true}else{str+=sep+line;sep=folded&&i<keepStart?" ":"\n";prevMoreIndented=false}if(atStart&&line!=="")atStart=false}}return this.chomping===Chomp.STRIP?str:str+"\n"}}]);return BlockValue}(_Node2.default);exports.default=BlockValue},{"../constants":220,"./Node":230,"./Range":235,"@babel/runtime/helpers/classCallCheck":21,"@babel/runtime/helpers/createClass":23,"@babel/runtime/helpers/get":25,"@babel/runtime/helpers/getPrototypeOf":26,"@babel/runtime/helpers/inherits":27,"@babel/runtime/helpers/interopRequireDefault":28,"@babel/runtime/helpers/possibleConstructorReturn":34}],224:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.grabCollectionEndComments=grabCollectionEndComments;exports.default=void 0;var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));var _getPrototypeOf2=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));var _get2=_interopRequireDefault(require("@babel/runtime/helpers/get"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits"));var _constants=require("../constants");var _BlankLine=_interopRequireDefault(require("./BlankLine"));var _CollectionItem=_interopRequireDefault(require("./CollectionItem"));var _Comment=_interopRequireDefault(require("./Comment"));var _Node2=_interopRequireDefault(require("./Node"));var _Range=_interopRequireDefault(require("./Range"));function grabCollectionEndComments(node){var cnode=node;while(cnode instanceof _CollectionItem.default){cnode=cnode.node}if(!(cnode instanceof Collection))return null;var len=cnode.items.length;var ci=-1;for(var i=len-1;i>=0;--i){var n=cnode.items[i];if(n.type===_constants.Type.COMMENT){var _n$context=n.context,indent=_n$context.indent,lineStart=_n$context.lineStart;if(indent>0&&n.range.start>=lineStart+indent)break;ci=i}else if(n.type===_constants.Type.BLANK_LINE)ci=i;else break}if(ci===-1)return null;var ca=cnode.items.splice(ci,len-ci);var prevEnd=ca[0].range.start;while(true){cnode.range.end=prevEnd;if(cnode.valueRange&&cnode.valueRange.end>prevEnd)cnode.valueRange.end=prevEnd;if(cnode===node)break;cnode=cnode.context.parent}return ca}var Collection=function(_Node){(0,_inherits2.default)(Collection,_Node);(0,_createClass2.default)(Collection,null,[{key:"nextContentHasIndent",value:function nextContentHasIndent(src,offset,indent){var lineStart=_Node2.default.endOfLine(src,offset)+1;offset=_Node2.default.endOfWhiteSpace(src,lineStart);var ch=src[offset];if(!ch)return false;if(offset>=lineStart+indent)return true;if(ch!=="#"&&ch!=="\n")return false;return Collection.nextContentHasIndent(src,offset,indent)}}]);function Collection(firstItem){var _this;(0,_classCallCheck2.default)(this,Collection);_this=(0,_possibleConstructorReturn2.default)(this,(0,_getPrototypeOf2.default)(Collection).call(this,firstItem.type===_constants.Type.SEQ_ITEM?_constants.Type.SEQ:_constants.Type.MAP));for(var i=firstItem.props.length-1;i>=0;--i){if(firstItem.props[i].start<firstItem.context.lineStart){_this.props=firstItem.props.slice(0,i+1);firstItem.props=firstItem.props.slice(i+1);var itemRange=firstItem.props[0]||firstItem.valueRange;firstItem.range.start=itemRange.start;break}}_this.items=[firstItem];var ec=grabCollectionEndComments(firstItem);if(ec)Array.prototype.push.apply(_this.items,ec);return _this}(0,_createClass2.default)(Collection,[{key:"parse",value:function parse(context,start){this.context=context;var parseNode=context.parseNode,src=context.src;var lineStart=_Node2.default.startOfLine(src,start);var firstItem=this.items[0];firstItem.context.parent=this;this.valueRange=_Range.default.copy(firstItem.valueRange);var indent=firstItem.range.start-firstItem.context.lineStart;var offset=start;offset=_Node2.default.normalizeOffset(src,offset);var ch=src[offset];var atLineStart=_Node2.default.endOfWhiteSpace(src,lineStart)===offset;var prevIncludesTrailingLines=false;while(ch){while(ch==="\n"||ch==="#"){if(atLineStart&&ch==="\n"&&!prevIncludesTrailingLines){var blankLine=new _BlankLine.default;offset=blankLine.parse({src:src},offset);this.valueRange.end=offset;if(offset>=src.length){ch=null;break}this.items.push(blankLine);offset-=1}else if(ch==="#"){if(offset<lineStart+indent&&!Collection.nextContentHasIndent(src,offset,indent)){return offset}var comment=new _Comment.default;offset=comment.parse({indent:indent,lineStart:lineStart,src:src},offset);this.items.push(comment);this.valueRange.end=offset;if(offset>=src.length){ch=null;break}}lineStart=offset+1;offset=_Node2.default.endOfIndent(src,lineStart);if(_Node2.default.atBlank(src,offset)){var wsEnd=_Node2.default.endOfWhiteSpace(src,offset);var next=src[wsEnd];if(!next||next==="\n"||next==="#"){offset=wsEnd}}ch=src[offset];atLineStart=true}if(!ch){break}if(offset!==lineStart+indent&&(atLineStart||ch!==":")){if(lineStart>start)offset=lineStart;break}if(firstItem.type===_constants.Type.SEQ_ITEM!==(ch==="-")){var typeswitch=true;if(ch==="-"){var _next=src[offset+1];typeswitch=!_next||_next==="\n"||_next==="\t"||_next===" "}if(typeswitch){if(lineStart>start)offset=lineStart;break}}var node=parseNode({atLineStart:atLineStart,inCollection:true,indent:indent,lineStart:lineStart,parent:this},offset);if(!node)return offset;this.items.push(node);this.valueRange.end=node.valueRange.end;offset=_Node2.default.normalizeOffset(src,node.range.end);ch=src[offset];atLineStart=false;prevIncludesTrailingLines=node.includesTrailingLines;if(ch){var ls=offset-1;var prev=src[ls];while(prev===" "||prev==="\t"){prev=src[--ls]}if(prev==="\n"){lineStart=ls+1;atLineStart=true}}var ec=grabCollectionEndComments(node);if(ec)Array.prototype.push.apply(this.items,ec)}return offset}},{key:"setOrigRanges",value:function setOrigRanges(cr,offset){offset=(0,_get2.default)((0,_getPrototypeOf2.default)(Collection.prototype),"setOrigRanges",this).call(this,cr,offset);this.items.forEach((function(node){offset=node.setOrigRanges(cr,offset)}));return offset}},{key:"toString",value:function toString(){var src=this.context.src,items=this.items,range=this.range,value=this.value;if(value!=null)return value;var str=src.slice(range.start,items[0].range.start)+String(items[0]);for(var i=1;i<items.length;++i){var item=items[i];var _item$context=item.context,atLineStart=_item$context.atLineStart,indent=_item$context.indent;if(atLineStart)for(var _i=0;_i<indent;++_i){str+=" "}str+=String(item)}return _Node2.default.addStringTerminator(src,range.end,str)}},{key:"includesTrailingLines",get:function get(){return this.items.length>0}}]);return Collection}(_Node2.default);exports.default=Collection},{"../constants":220,"./BlankLine":222,"./CollectionItem":225,"./Comment":226,"./Node":230,"./Range":235,"@babel/runtime/helpers/classCallCheck":21,"@babel/runtime/helpers/createClass":23,"@babel/runtime/helpers/get":25,"@babel/runtime/helpers/getPrototypeOf":26,"@babel/runtime/helpers/inherits":27,"@babel/runtime/helpers/interopRequireDefault":28,"@babel/runtime/helpers/possibleConstructorReturn":34}],225:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));var _getPrototypeOf2=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));var _get2=_interopRequireDefault(require("@babel/runtime/helpers/get"));var _inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits"));var _constants=require("../constants");var _errors=require("../errors");var _BlankLine=_interopRequireDefault(require("./BlankLine"));var _Node2=_interopRequireDefault(require("./Node"));var _Range=_interopRequireDefault(require("./Range"));var CollectionItem=function(_Node){(0,_inherits2.default)(CollectionItem,_Node);function CollectionItem(type,props){var _this;(0,_classCallCheck2.default)(this,CollectionItem);_this=(0,_possibleConstructorReturn2.default)(this,(0,_getPrototypeOf2.default)(CollectionItem).call(this,type,props));_this.node=null;return _this}(0,_createClass2.default)(CollectionItem,[{key:"parse",value:function parse(context,start){this.context=context;var parseNode=context.parseNode,src=context.src;var atLineStart=context.atLineStart,lineStart=context.lineStart;if(!atLineStart&&this.type===_constants.Type.SEQ_ITEM)this.error=new _errors.YAMLSemanticError(this,"Sequence items must not have preceding content on the same line");var indent=atLineStart?start-lineStart:context.indent;var offset=_Node2.default.endOfWhiteSpace(src,start+1);var ch=src[offset];var inlineComment=ch==="#";var comments=[];var blankLine=null;while(ch==="\n"||ch==="#"){if(ch==="#"){var _end=_Node2.default.endOfLine(src,offset+1);comments.push(new _Range.default(offset,_end));offset=_end}else{atLineStart=true;lineStart=offset+1;var wsEnd=_Node2.default.endOfWhiteSpace(src,lineStart);if(src[wsEnd]==="\n"&&comments.length===0){blankLine=new _BlankLine.default;lineStart=blankLine.parse({src:src},lineStart)}offset=_Node2.default.endOfIndent(src,lineStart)}ch=src[offset]}if(_Node2.default.nextNodeIsIndented(ch,offset-(lineStart+indent),this.type!==_constants.Type.SEQ_ITEM)){this.node=parseNode({atLineStart:atLineStart,inCollection:false,indent:indent,lineStart:lineStart,parent:this},offset)}else if(ch&&lineStart>start+1){offset=lineStart-1}if(this.node){if(blankLine){var items=context.parent.items||context.parent.contents;if(items)items.push(blankLine)}if(comments.length)Array.prototype.push.apply(this.props,comments);offset=this.node.range.end}else{if(inlineComment){var c=comments[0];this.props.push(c);offset=c.end}else{offset=_Node2.default.endOfLine(src,start+1)}}var end=this.node?this.node.valueRange.end:offset;this.valueRange=new _Range.default(start,end);return offset}},{key:"setOrigRanges",value:function setOrigRanges(cr,offset){offset=(0,_get2.default)((0,_getPrototypeOf2.default)(CollectionItem.prototype),"setOrigRanges",this).call(this,cr,offset);return this.node?this.node.setOrigRanges(cr,offset):offset}},{key:"toString",value:function toString(){var src=this.context.src,node=this.node,range=this.range,value=this.value;if(value!=null)return value;var str=node?src.slice(range.start,node.range.start)+String(node):src.slice(range.start,range.end);return _Node2.default.addStringTerminator(src,range.end,str)}},{key:"includesTrailingLines",get:function get(){return!!this.node&&this.node.includesTrailingLines}}]);return CollectionItem}(_Node2.default);exports.default=CollectionItem},{"../constants":220,"../errors":238,"./BlankLine":222,"./Node":230,"./Range":235,"@babel/runtime/helpers/classCallCheck":21,"@babel/runtime/helpers/createClass":23,"@babel/runtime/helpers/get":25,"@babel/runtime/helpers/getPrototypeOf":26,"@babel/runtime/helpers/inherits":27,"@babel/runtime/helpers/interopRequireDefault":28,"@babel/runtime/helpers/possibleConstructorReturn":34}],226:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));var _getPrototypeOf2=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));var _inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits"));var _constants=require("../constants");var _Node2=_interopRequireDefault(require("./Node"));var _Range=_interopRequireDefault(require("./Range"));var Comment=function(_Node){(0,_inherits2.default)(Comment,_Node);function Comment(){(0,_classCallCheck2.default)(this,Comment);return(0,_possibleConstructorReturn2.default)(this,(0,_getPrototypeOf2.default)(Comment).call(this,_constants.Type.COMMENT))}(0,_createClass2.default)(Comment,[{key:"parse",value:function parse(context,start){this.context=context;var offset=this.parseComment(start);this.range=new _Range.default(start,offset);return offset}}]);return Comment}(_Node2.default);exports.default=Comment},{"../constants":220,"./Node":230,"./Range":235,"@babel/runtime/helpers/classCallCheck":21,"@babel/runtime/helpers/createClass":23,"@babel/runtime/helpers/getPrototypeOf":26,"@babel/runtime/helpers/inherits":27,"@babel/runtime/helpers/interopRequireDefault":28,"@babel/runtime/helpers/possibleConstructorReturn":34}],227:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));var _getPrototypeOf2=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits"));var _constants=require("../constants");var _Node2=_interopRequireDefault(require("./Node"));var _Range=_interopRequireDefault(require("./Range"));var Directive=function(_Node){(0,_inherits2.default)(Directive,_Node);(0,_createClass2.default)(Directive,null,[{key:"endOfDirective",value:function endOfDirective(src,offset){var ch=src[offset];while(ch&&ch!=="\n"&&ch!=="#"){ch=src[offset+=1]}ch=src[offset-1];while(ch===" "||ch==="\t"){offset-=1;ch=src[offset-1]}return offset}}]);function Directive(){var _this;(0,_classCallCheck2.default)(this,Directive);_this=(0,_possibleConstructorReturn2.default)(this,(0,_getPrototypeOf2.default)(Directive).call(this,_constants.Type.DIRECTIVE));_this.name=null;return _this}(0,_createClass2.default)(Directive,[{key:"parseName",value:function parseName(start){var src=this.context.src;var offset=start;var ch=src[offset];while(ch&&ch!=="\n"&&ch!=="\t"&&ch!==" "){ch=src[offset+=1]}this.name=src.slice(start,offset);return offset}},{key:"parseParameters",value:function parseParameters(start){var src=this.context.src;var offset=start;var ch=src[offset];while(ch&&ch!=="\n"&&ch!=="#"){ch=src[offset+=1]}this.valueRange=new _Range.default(start,offset);return offset}},{key:"parse",value:function parse(context,start){this.context=context;var offset=this.parseName(start+1);offset=this.parseParameters(offset);offset=this.parseComment(offset);this.range=new _Range.default(start,offset);return offset}},{key:"parameters",get:function get(){var raw=this.rawValue;return raw?raw.trim().split(/[ \t]+/):[]}}]);return Directive}(_Node2.default);exports.default=Directive},{"../constants":220,"./Node":230,"./Range":235,"@babel/runtime/helpers/classCallCheck":21,"@babel/runtime/helpers/createClass":23,"@babel/runtime/helpers/getPrototypeOf":26,"@babel/runtime/helpers/inherits":27,"@babel/runtime/helpers/interopRequireDefault":28,"@babel/runtime/helpers/possibleConstructorReturn":34}],228:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));var _getPrototypeOf2=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));var _get2=_interopRequireDefault(require("@babel/runtime/helpers/get"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits"));var _constants=require("../constants");var _errors=require("../errors");var _BlankLine=_interopRequireDefault(require("./BlankLine"));var _Collection=require("./Collection");var _Comment=_interopRequireDefault(require("./Comment"));var _Directive=_interopRequireDefault(require("./Directive"));var _Node2=_interopRequireDefault(require("./Node"));var _Range=_interopRequireDefault(require("./Range"));var Document=function(_Node){(0,_inherits2.default)(Document,_Node);(0,_createClass2.default)(Document,null,[{key:"startCommentOrEndBlankLine",value:function startCommentOrEndBlankLine(src,start){var offset=_Node2.default.endOfWhiteSpace(src,start);var ch=src[offset];return ch==="#"||ch==="\n"?offset:start}}]);function Document(){var _this;(0,_classCallCheck2.default)(this,Document);_this=(0,_possibleConstructorReturn2.default)(this,(0,_getPrototypeOf2.default)(Document).call(this,_constants.Type.DOCUMENT));_this.directives=null;_this.contents=null;_this.directivesEndMarker=null;_this.documentEndMarker=null;return _this}(0,_createClass2.default)(Document,[{key:"parseDirectives",value:function parseDirectives(start){var src=this.context.src;this.directives=[];var atLineStart=true;var hasDirectives=false;var offset=start;while(!_Node2.default.atDocumentBoundary(src,offset,_constants.Char.DIRECTIVES_END)){offset=Document.startCommentOrEndBlankLine(src,offset);switch(src[offset]){case"\n":if(atLineStart){var blankLine=new _BlankLine.default;offset=blankLine.parse({src:src},offset);if(offset<src.length){this.directives.push(blankLine)}}else{offset+=1;atLineStart=true}break;case"#":{var comment=new _Comment.default;offset=comment.parse({src:src},offset);this.directives.push(comment);atLineStart=false}break;case"%":{var directive=new _Directive.default;offset=directive.parse({parent:this,src:src},offset);this.directives.push(directive);hasDirectives=true;atLineStart=false}break;default:if(hasDirectives){this.error=new _errors.YAMLSemanticError(this,"Missing directives-end indicator line")}else if(this.directives.length>0){this.contents=this.directives;this.directives=[]}return offset}}if(src[offset]){this.directivesEndMarker=new _Range.default(offset,offset+3);return offset+3}if(hasDirectives){this.error=new _errors.YAMLSemanticError(this,"Missing directives-end indicator line")}else if(this.directives.length>0){this.contents=this.directives;this.directives=[]}return offset}},{key:"parseContents",value:function parseContents(start){var _this$context=this.context,parseNode=_this$context.parseNode,src=_this$context.src;if(!this.contents)this.contents=[];var lineStart=start;while(src[lineStart-1]==="-"){lineStart-=1}var offset=_Node2.default.endOfWhiteSpace(src,start);var atLineStart=lineStart===start;this.valueRange=new _Range.default(offset);while(!_Node2.default.atDocumentBoundary(src,offset,_constants.Char.DOCUMENT_END)){switch(src[offset]){case"\n":if(atLineStart){var blankLine=new _BlankLine.default;offset=blankLine.parse({src:src},offset);if(offset<src.length){this.contents.push(blankLine)}}else{offset+=1;atLineStart=true}lineStart=offset;break;case"#":{var comment=new _Comment.default;offset=comment.parse({src:src},offset);this.contents.push(comment);atLineStart=false}break;default:{var iEnd=_Node2.default.endOfIndent(src,offset);var context={atLineStart:atLineStart,indent:-1,inFlow:false,inCollection:false,lineStart:lineStart,parent:this};var node=parseNode(context,iEnd);if(!node)return this.valueRange.end=iEnd;this.contents.push(node);offset=node.range.end;atLineStart=false;var ec=(0,_Collection.grabCollectionEndComments)(node);if(ec)Array.prototype.push.apply(this.contents,ec)}}offset=Document.startCommentOrEndBlankLine(src,offset)}this.valueRange.end=offset;if(src[offset]){this.documentEndMarker=new _Range.default(offset,offset+3);offset+=3;if(src[offset]){offset=_Node2.default.endOfWhiteSpace(src,offset);if(src[offset]==="#"){var _comment=new _Comment.default;offset=_comment.parse({src:src},offset);this.contents.push(_comment)}switch(src[offset]){case"\n":offset+=1;break;case undefined:break;default:this.error=new _errors.YAMLSyntaxError(this,"Document end marker line cannot have a non-comment suffix")}}}return offset}},{key:"parse",value:function parse(context,start){context.root=this;this.context=context;var src=context.src;var offset=src.charCodeAt(start)===65279?start+1:start;offset=this.parseDirectives(offset);offset=this.parseContents(offset);return offset}},{key:"setOrigRanges",value:function setOrigRanges(cr,offset){offset=(0,_get2.default)((0,_getPrototypeOf2.default)(Document.prototype),"setOrigRanges",this).call(this,cr,offset);this.directives.forEach((function(node){offset=node.setOrigRanges(cr,offset)}));if(this.directivesEndMarker)offset=this.directivesEndMarker.setOrigRange(cr,offset);this.contents.forEach((function(node){offset=node.setOrigRanges(cr,offset)}));if(this.documentEndMarker)offset=this.documentEndMarker.setOrigRange(cr,offset);return offset}},{key:"toString",value:function toString(){var contents=this.contents,directives=this.directives,value=this.value;if(value!=null)return value;var str=directives.join("");if(contents.length>0){if(directives.length>0||contents[0].type===_constants.Type.COMMENT)str+="---\n";str+=contents.join("")}if(str[str.length-1]!=="\n")str+="\n";return str}}]);return Document}(_Node2.default);exports.default=Document},{"../constants":220,"../errors":238,"./BlankLine":222,"./Collection":224,"./Comment":226,"./Directive":227,"./Node":230,"./Range":235,"@babel/runtime/helpers/classCallCheck":21,"@babel/runtime/helpers/createClass":23,"@babel/runtime/helpers/get":25,"@babel/runtime/helpers/getPrototypeOf":26,"@babel/runtime/helpers/inherits":27,"@babel/runtime/helpers/interopRequireDefault":28,"@babel/runtime/helpers/possibleConstructorReturn":34}],229:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));var _getPrototypeOf2=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));var _get2=_interopRequireDefault(require("@babel/runtime/helpers/get"));var _inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits"));var _constants=require("../constants");var _errors=require("../errors");var _BlankLine=_interopRequireDefault(require("./BlankLine"));var _Comment=_interopRequireDefault(require("./Comment"));var _Node2=_interopRequireDefault(require("./Node"));var _Range=_interopRequireDefault(require("./Range"));var FlowCollection=function(_Node){(0,_inherits2.default)(FlowCollection,_Node);function FlowCollection(type,props){var _this;(0,_classCallCheck2.default)(this,FlowCollection);_this=(0,_possibleConstructorReturn2.default)(this,(0,_getPrototypeOf2.default)(FlowCollection).call(this,type,props));_this.items=null;return _this}(0,_createClass2.default)(FlowCollection,[{key:"prevNodeIsJsonLike",value:function prevNodeIsJsonLike(){var idx=arguments.length>0&&arguments[0]!==undefined?arguments[0]:this.items.length;var node=this.items[idx-1];return!!node&&(node.jsonLike||node.type===_constants.Type.COMMENT&&this.nodeIsJsonLike(idx-1))}},{key:"parse",value:function parse(context,start){this.context=context;var parseNode=context.parseNode,src=context.src;var indent=context.indent,lineStart=context.lineStart;var char=src[start];this.items=[{char:char,offset:start}];var offset=_Node2.default.endOfWhiteSpace(src,start+1);char=src[offset];while(char&&char!=="]"&&char!=="}"){switch(char){case"\n":{lineStart=offset+1;var wsEnd=_Node2.default.endOfWhiteSpace(src,lineStart);if(src[wsEnd]==="\n"){var blankLine=new _BlankLine.default;lineStart=blankLine.parse({src:src},lineStart);this.items.push(blankLine)}offset=_Node2.default.endOfIndent(src,lineStart);if(offset<=lineStart+indent){char=src[offset];if(offset<lineStart+indent||char!=="]"&&char!=="}"){var msg="Insufficient indentation in flow collection";this.error=new _errors.YAMLSemanticError(this,msg)}}}break;case",":{this.items.push({char:char,offset:offset});offset+=1}break;case"#":{var comment=new _Comment.default;offset=comment.parse({src:src},offset);this.items.push(comment)}break;case"?":case":":{var next=src[offset+1];if(next==="\n"||next==="\t"||next===" "||next===","||char===":"&&this.prevNodeIsJsonLike()){this.items.push({char:char,offset:offset});offset+=1;break}}default:{var node=parseNode({atLineStart:false,inCollection:false,inFlow:true,indent:-1,lineStart:lineStart,parent:this},offset);if(!node){this.valueRange=new _Range.default(start,offset);return offset}this.items.push(node);offset=_Node2.default.normalizeOffset(src,node.range.end)}}offset=_Node2.default.endOfWhiteSpace(src,offset);char=src[offset]}this.valueRange=new _Range.default(start,offset+1);if(char){this.items.push({char:char,offset:offset});offset=_Node2.default.endOfWhiteSpace(src,offset+1);offset=this.parseComment(offset)}return offset}},{key:"setOrigRanges",value:function setOrigRanges(cr,offset){offset=(0,_get2.default)((0,_getPrototypeOf2.default)(FlowCollection.prototype),"setOrigRanges",this).call(this,cr,offset);this.items.forEach((function(node){if(node instanceof _Node2.default){offset=node.setOrigRanges(cr,offset)}else if(cr.length===0){node.origOffset=node.offset}else{var i=offset;while(i<cr.length){if(cr[i]>node.offset)break;else++i}node.origOffset=node.offset+i;offset=i}}));return offset}},{key:"toString",value:function toString(){var src=this.context.src,items=this.items,range=this.range,value=this.value;if(value!=null)return value;var nodes=items.filter((function(item){return item instanceof _Node2.default}));var str="";var prevEnd=range.start;nodes.forEach((function(node){var prefix=src.slice(prevEnd,node.range.start);prevEnd=node.range.end;str+=prefix+String(node);if(str[str.length-1]==="\n"&&src[prevEnd-1]!=="\n"&&src[prevEnd]==="\n"){prevEnd+=1}}));str+=src.slice(prevEnd,range.end);return _Node2.default.addStringTerminator(src,range.end,str)}}]);return FlowCollection}(_Node2.default);exports.default=FlowCollection},{"../constants":220,"../errors":238,"./BlankLine":222,"./Comment":226,"./Node":230,"./Range":235,"@babel/runtime/helpers/classCallCheck":21,"@babel/runtime/helpers/createClass":23,"@babel/runtime/helpers/get":25,"@babel/runtime/helpers/getPrototypeOf":26,"@babel/runtime/helpers/inherits":27,"@babel/runtime/helpers/interopRequireDefault":28,"@babel/runtime/helpers/possibleConstructorReturn":34}],230:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _slicedToArray2=_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _constants=require("../constants");var _sourceUtils=require("./source-utils");var _Range=_interopRequireDefault(require("./Range"));var Node=function(){(0,_createClass2.default)(Node,null,[{key:"addStringTerminator",value:function addStringTerminator(src,offset,str){if(str[str.length-1]==="\n")return str;var next=Node.endOfWhiteSpace(src,offset);return next>=src.length||src[next]==="\n"?str+"\n":str}},{key:"atDocumentBoundary",value:function atDocumentBoundary(src,offset,sep){var ch0=src[offset];if(!ch0)return true;var prev=src[offset-1];if(prev&&prev!=="\n")return false;if(sep){if(ch0!==sep)return false}else{if(ch0!==_constants.Char.DIRECTIVES_END&&ch0!==_constants.Char.DOCUMENT_END)return false}var ch1=src[offset+1];var ch2=src[offset+2];if(ch1!==ch0||ch2!==ch0)return false;var ch3=src[offset+3];return!ch3||ch3==="\n"||ch3==="\t"||ch3===" "}},{key:"endOfIdentifier",value:function endOfIdentifier(src,offset){var ch=src[offset];var isVerbatim=ch==="<";var notOk=isVerbatim?["\n","\t"," ",">"]:["\n","\t"," ","[","]","{","}",","];while(ch&¬Ok.indexOf(ch)===-1){ch=src[offset+=1]}if(isVerbatim&&ch===">")offset+=1;return offset}},{key:"endOfIndent",value:function endOfIndent(src,offset){var ch=src[offset];while(ch===" "){ch=src[offset+=1]}return offset}},{key:"endOfLine",value:function endOfLine(src,offset){var ch=src[offset];while(ch&&ch!=="\n"){ch=src[offset+=1]}return offset}},{key:"endOfWhiteSpace",value:function endOfWhiteSpace(src,offset){var ch=src[offset];while(ch==="\t"||ch===" "){ch=src[offset+=1]}return offset}},{key:"startOfLine",value:function startOfLine(src,offset){var ch=src[offset-1];if(ch==="\n")return offset;while(ch&&ch!=="\n"){ch=src[offset-=1]}return offset+1}},{key:"endOfBlockIndent",value:function endOfBlockIndent(src,indent,lineStart){var inEnd=Node.endOfIndent(src,lineStart);if(inEnd>lineStart+indent){return inEnd}else{var wsEnd=Node.endOfWhiteSpace(src,inEnd);var ch=src[wsEnd];if(!ch||ch==="\n")return wsEnd}return null}},{key:"atBlank",value:function atBlank(src,offset,endAsBlank){var ch=src[offset];return ch==="\n"||ch==="\t"||ch===" "||endAsBlank&&!ch}},{key:"atCollectionItem",value:function atCollectionItem(src,offset){var ch=src[offset];return(ch==="?"||ch===":"||ch==="-")&&Node.atBlank(src,offset+1,true)}},{key:"nextNodeIsIndented",value:function nextNodeIsIndented(ch,indentDiff,indicatorAsIndent){if(!ch||indentDiff<0)return false;if(indentDiff>0)return true;return indicatorAsIndent&&ch==="-"}},{key:"normalizeOffset",value:function normalizeOffset(src,offset){var ch=src[offset];return!ch?offset:ch!=="\n"&&src[offset-1]==="\n"?offset-1:Node.endOfWhiteSpace(src,offset)}},{key:"foldNewline",value:function foldNewline(src,offset,indent){var inCount=0;var error=false;var fold="";var ch=src[offset+1];while(ch===" "||ch==="\t"||ch==="\n"){switch(ch){case"\n":inCount=0;offset+=1;fold+="\n";break;case"\t":if(inCount<=indent)error=true;offset=Node.endOfWhiteSpace(src,offset+2)-1;break;case" ":inCount+=1;offset+=1;break}ch=src[offset+1]}if(!fold)fold=" ";if(ch&&inCount<=indent)error=true;return{fold:fold,offset:offset,error:error}}}]);function Node(type,props,context){(0,_classCallCheck2.default)(this,Node);Object.defineProperty(this,"context",{value:context||null,writable:true});this.error=null;this.range=null;this.valueRange=null;this.props=props||[];this.type=type;this.value=null}(0,_createClass2.default)(Node,[{key:"getPropValue",value:function getPropValue(idx,key,skipKey){if(!this.context)return null;var src=this.context.src;var prop=this.props[idx];return prop&&src[prop.start]===key?src.slice(prop.start+(skipKey?1:0),prop.end):null}},{key:"commentHasRequiredWhitespace",value:function commentHasRequiredWhitespace(start){var src=this.context.src;if(this.header&&start===this.header.end)return false;if(!this.valueRange)return false;var end=this.valueRange.end;return start!==end||Node.atBlank(src,end-1)}},{key:"parseComment",value:function parseComment(start){var src=this.context.src;if(src[start]===_constants.Char.COMMENT){var end=Node.endOfLine(src,start+1);var commentRange=new _Range.default(start,end);this.props.push(commentRange);return end}return start}},{key:"setOrigRanges",value:function setOrigRanges(cr,offset){if(this.range)offset=this.range.setOrigRange(cr,offset);if(this.valueRange)this.valueRange.setOrigRange(cr,offset);this.props.forEach((function(prop){return prop.setOrigRange(cr,offset)}));return offset}},{key:"toString",value:function toString(){var src=this.context.src,range=this.range,value=this.value;if(value!=null)return value;var str=src.slice(range.start,range.end);return Node.addStringTerminator(src,range.end,str)}},{key:"anchor",get:function get(){for(var i=0;i<this.props.length;++i){var anchor=this.getPropValue(i,_constants.Char.ANCHOR,true);if(anchor!=null)return anchor}return null}},{key:"comment",get:function get(){var comments=[];for(var i=0;i<this.props.length;++i){var comment=this.getPropValue(i,_constants.Char.COMMENT,true);if(comment!=null)comments.push(comment)}return comments.length>0?comments.join("\n"):null}},{key:"hasComment",get:function get(){if(this.context){var src=this.context.src;for(var i=0;i<this.props.length;++i){if(src[this.props[i].start]===_constants.Char.COMMENT)return true}}return false}},{key:"hasProps",get:function get(){if(this.context){var src=this.context.src;for(var i=0;i<this.props.length;++i){if(src[this.props[i].start]!==_constants.Char.COMMENT)return true}}return false}},{key:"includesTrailingLines",get:function get(){return false}},{key:"jsonLike",get:function get(){var jsonLikeTypes=[_constants.Type.FLOW_MAP,_constants.Type.FLOW_SEQ,_constants.Type.QUOTE_DOUBLE,_constants.Type.QUOTE_SINGLE];return jsonLikeTypes.indexOf(this.type)!==-1}},{key:"rangeAsLinePos",get:function get(){if(!this.range||!this.context)return undefined;var start=(0,_sourceUtils.getLinePos)(this.range.start,this.context.root);if(!start)return undefined;var end=(0,_sourceUtils.getLinePos)(this.range.end,this.context.root);return{start:start,end:end}}},{key:"rawValue",get:function get(){if(!this.valueRange||!this.context)return null;var _this$valueRange=this.valueRange,start=_this$valueRange.start,end=_this$valueRange.end;return this.context.src.slice(start,end)}},{key:"tag",get:function get(){for(var i=0;i<this.props.length;++i){var tag=this.getPropValue(i,_constants.Char.TAG,false);if(tag!=null){if(tag[1]==="<"){return{verbatim:tag.slice(2,-1)}}else{var _tag$match=tag.match(/^(.*!)([^!]*)$/),_tag$match2=(0,_slicedToArray2.default)(_tag$match,3),_=_tag$match2[0],handle=_tag$match2[1],suffix=_tag$match2[2];return{handle:handle,suffix:suffix}}}}return null}},{key:"valueRangeContainsNewline",get:function get(){if(!this.valueRange||!this.context)return false;var _this$valueRange2=this.valueRange,start=_this$valueRange2.start,end=_this$valueRange2.end;var src=this.context.src;for(var i=start;i<end;++i){if(src[i]==="\n")return true}return false}}]);return Node}();exports.default=Node},{"../constants":220,"./Range":235,"./source-utils":237,"@babel/runtime/helpers/classCallCheck":21,"@babel/runtime/helpers/createClass":23,"@babel/runtime/helpers/interopRequireDefault":28,"@babel/runtime/helpers/slicedToArray":36}],231:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _constants=require("../constants");var _errors=require("../errors");var _Alias=_interopRequireDefault(require("./Alias"));var _BlockValue=_interopRequireDefault(require("./BlockValue"));var _Collection=_interopRequireDefault(require("./Collection"));var _CollectionItem=_interopRequireDefault(require("./CollectionItem"));var _FlowCollection=_interopRequireDefault(require("./FlowCollection"));var _Node=_interopRequireDefault(require("./Node"));var _PlainValue=_interopRequireDefault(require("./PlainValue"));var _QuoteDouble=_interopRequireDefault(require("./QuoteDouble"));var _QuoteSingle=_interopRequireDefault(require("./QuoteSingle"));var _Range=_interopRequireDefault(require("./Range"));var ParseContext=function(){(0,_createClass2.default)(ParseContext,null,[{key:"parseType",value:function parseType(src,offset,inFlow){switch(src[offset]){case"*":return _constants.Type.ALIAS;case">":return _constants.Type.BLOCK_FOLDED;case"|":return _constants.Type.BLOCK_LITERAL;case"{":return _constants.Type.FLOW_MAP;case"[":return _constants.Type.FLOW_SEQ;case"?":return!inFlow&&_Node.default.atBlank(src,offset+1,true)?_constants.Type.MAP_KEY:_constants.Type.PLAIN;case":":return!inFlow&&_Node.default.atBlank(src,offset+1,true)?_constants.Type.MAP_VALUE:_constants.Type.PLAIN;case"-":return!inFlow&&_Node.default.atBlank(src,offset+1,true)?_constants.Type.SEQ_ITEM:_constants.Type.PLAIN;case'"':return _constants.Type.QUOTE_DOUBLE;case"'":return _constants.Type.QUOTE_SINGLE;default:return _constants.Type.PLAIN}}}]);function ParseContext(){var _this=this;var orig=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var _ref=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},atLineStart=_ref.atLineStart,inCollection=_ref.inCollection,inFlow=_ref.inFlow,indent=_ref.indent,lineStart=_ref.lineStart,parent=_ref.parent;(0,_classCallCheck2.default)(this,ParseContext);(0,_defineProperty2.default)(this,"parseNode",(function(overlay,start){if(_Node.default.atDocumentBoundary(_this.src,start))return null;var context=new ParseContext(_this,overlay);var _context$parseProps=context.parseProps(start),props=_context$parseProps.props,type=_context$parseProps.type,valueStart=_context$parseProps.valueStart;var node;switch(type){case _constants.Type.ALIAS:node=new _Alias.default(type,props);break;case _constants.Type.BLOCK_FOLDED:case _constants.Type.BLOCK_LITERAL:node=new _BlockValue.default(type,props);break;case _constants.Type.FLOW_MAP:case _constants.Type.FLOW_SEQ:node=new _FlowCollection.default(type,props);break;case _constants.Type.MAP_KEY:case _constants.Type.MAP_VALUE:case _constants.Type.SEQ_ITEM:node=new _CollectionItem.default(type,props);break;case _constants.Type.COMMENT:case _constants.Type.PLAIN:node=new _PlainValue.default(type,props);break;case _constants.Type.QUOTE_DOUBLE:node=new _QuoteDouble.default(type,props);break;case _constants.Type.QUOTE_SINGLE:node=new _QuoteSingle.default(type,props);break;default:node.error=new _errors.YAMLSyntaxError(node,"Unknown node type: ".concat(JSON.stringify(type)));node.range=new _Range.default(start,start+1);return node}var offset=node.parse(context,valueStart);node.range=new _Range.default(start,offset);if(offset<=start){node.error=new Error("Node#parse consumed no characters");node.error.parseEnd=offset;node.error.source=node;node.range.end=start+1}if(context.nodeStartsCollection(node)){if(!node.error&&!context.atLineStart&&context.parent.type===_constants.Type.DOCUMENT){node.error=new _errors.YAMLSyntaxError(node,"Block collection must not have preceding content here (e.g. directives-end indicator)")}var collection=new _Collection.default(node);offset=collection.parse(new ParseContext(context),offset);collection.range=new _Range.default(start,offset);return collection}return node}));this.atLineStart=atLineStart!=null?atLineStart:orig.atLineStart||false;this.inCollection=inCollection!=null?inCollection:orig.inCollection||false;this.inFlow=inFlow!=null?inFlow:orig.inFlow||false;this.indent=indent!=null?indent:orig.indent;this.lineStart=lineStart!=null?lineStart:orig.lineStart;this.parent=parent!=null?parent:orig.parent||{};this.root=orig.root;this.src=orig.src}(0,_createClass2.default)(ParseContext,[{key:"nodeStartsCollection",value:function nodeStartsCollection(node){var inCollection=this.inCollection,inFlow=this.inFlow,src=this.src;if(inCollection||inFlow)return false;if(node instanceof _CollectionItem.default)return true;var offset=node.range.end;if(src[offset]==="\n"||src[offset-1]==="\n")return false;offset=_Node.default.endOfWhiteSpace(src,offset);return src[offset]===":"}},{key:"parseProps",value:function parseProps(offset){var inFlow=this.inFlow,parent=this.parent,src=this.src;var props=[];var lineHasProps=false;offset=_Node.default.endOfWhiteSpace(src,offset);var ch=src[offset];while(ch===_constants.Char.ANCHOR||ch===_constants.Char.COMMENT||ch===_constants.Char.TAG||ch==="\n"){if(ch==="\n"){var lineStart=offset+1;var inEnd=_Node.default.endOfIndent(src,lineStart);var indentDiff=inEnd-(lineStart+this.indent);var noIndicatorAsIndent=parent.type===_constants.Type.SEQ_ITEM&&parent.context.atLineStart;if(!_Node.default.nextNodeIsIndented(src[inEnd],indentDiff,!noIndicatorAsIndent))break;this.atLineStart=true;this.lineStart=lineStart;lineHasProps=false;offset=inEnd}else if(ch===_constants.Char.COMMENT){var end=_Node.default.endOfLine(src,offset+1);props.push(new _Range.default(offset,end));offset=end}else{var _end=_Node.default.endOfIdentifier(src,offset+1);if(ch===_constants.Char.TAG&&src[_end]===","&&/^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+,\d\d\d\d(-\d\d){0,2}\/\S/.test(src.slice(offset+1,_end+13))){_end=_Node.default.endOfIdentifier(src,_end+5)}props.push(new _Range.default(offset,_end));lineHasProps=true;offset=_Node.default.endOfWhiteSpace(src,_end)}ch=src[offset]}if(lineHasProps&&ch===":"&&_Node.default.atBlank(src,offset+1,true))offset-=1;var type=ParseContext.parseType(src,offset,inFlow);return{props:props,type:type,valueStart:offset}}},{key:"pretty",get:function get(){var obj={start:"".concat(this.lineStart," + ").concat(this.indent),in:[],parent:this.parent.type};if(!this.atLineStart)obj.start+=" + N";if(this.inCollection)obj.in.push("collection");if(this.inFlow)obj.in.push("flow");return obj}}]);return ParseContext}();exports.default=ParseContext},{"../constants":220,"../errors":238,"./Alias":221,"./BlockValue":223,"./Collection":224,"./CollectionItem":225,"./FlowCollection":229,"./Node":230,"./PlainValue":232,"./QuoteDouble":233,"./QuoteSingle":234,"./Range":235,"@babel/runtime/helpers/classCallCheck":21,"@babel/runtime/helpers/createClass":23,"@babel/runtime/helpers/defineProperty":24,"@babel/runtime/helpers/interopRequireDefault":28}],232:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));var _getPrototypeOf2=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));var _inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits"));var _Node2=_interopRequireDefault(require("./Node"));var _Range=_interopRequireDefault(require("./Range"));var PlainValue=function(_Node){(0,_inherits2.default)(PlainValue,_Node);function PlainValue(){(0,_classCallCheck2.default)(this,PlainValue);return(0,_possibleConstructorReturn2.default)(this,(0,_getPrototypeOf2.default)(PlainValue).apply(this,arguments))}(0,_createClass2.default)(PlainValue,[{key:"parseBlockValue",value:function parseBlockValue(start){var _this$context=this.context,indent=_this$context.indent,inFlow=_this$context.inFlow,src=_this$context.src;var offset=start;var valueEnd=start;for(var ch=src[offset];ch==="\n";ch=src[offset]){if(_Node2.default.atDocumentBoundary(src,offset+1))break;var end=_Node2.default.endOfBlockIndent(src,indent,offset+1);if(end===null||src[end]==="#")break;if(src[end]==="\n"){offset=end}else{valueEnd=PlainValue.endOfLine(src,end,inFlow);offset=valueEnd}}if(this.valueRange.isEmpty())this.valueRange.start=start;this.valueRange.end=valueEnd;return valueEnd}},{key:"parse",value:function parse(context,start){this.context=context;var inFlow=context.inFlow,src=context.src;var offset=start;var ch=src[offset];if(ch&&ch!=="#"&&ch!=="\n"){offset=PlainValue.endOfLine(src,start,inFlow)}this.valueRange=new _Range.default(start,offset);offset=_Node2.default.endOfWhiteSpace(src,offset);offset=this.parseComment(offset);if(!this.hasComment||this.valueRange.isEmpty()){offset=this.parseBlockValue(offset)}return offset}},{key:"strValue",get:function get(){if(!this.valueRange||!this.context)return null;var _this$valueRange=this.valueRange,start=_this$valueRange.start,end=_this$valueRange.end;var src=this.context.src;var ch=src[end-1];while(start<end&&(ch==="\n"||ch==="\t"||ch===" ")){ch=src[--end-1]}ch=src[start];while(start<end&&(ch==="\n"||ch==="\t"||ch===" ")){ch=src[++start]}var str="";for(var i=start;i<end;++i){var _ch=src[i];if(_ch==="\n"){var _Node$foldNewline=_Node2.default.foldNewline(src,i,-1),fold=_Node$foldNewline.fold,offset=_Node$foldNewline.offset;str+=fold;i=offset}else if(_ch===" "||_ch==="\t"){var wsStart=i;var next=src[i+1];while(i<end&&(next===" "||next==="\t")){i+=1;next=src[i+1]}if(next!=="\n")str+=i>wsStart?src.slice(wsStart,i+1):_ch}else{str+=_ch}}return str}}],[{key:"endOfLine",value:function endOfLine(src,start,inFlow){var ch=src[start];var offset=start;while(ch&&ch!=="\n"){if(inFlow&&(ch==="["||ch==="]"||ch==="{"||ch==="}"||ch===","))break;var next=src[offset+1];if(ch===":"&&(!next||next==="\n"||next==="\t"||next===" "||inFlow&&next===","))break;if((ch===" "||ch==="\t")&&next==="#")break;offset+=1;ch=next}return offset}}]);return PlainValue}(_Node2.default);exports.default=PlainValue},{"./Node":230,"./Range":235,"@babel/runtime/helpers/classCallCheck":21,"@babel/runtime/helpers/createClass":23,"@babel/runtime/helpers/getPrototypeOf":26,"@babel/runtime/helpers/inherits":27,"@babel/runtime/helpers/interopRequireDefault":28,"@babel/runtime/helpers/possibleConstructorReturn":34}],233:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));var _getPrototypeOf2=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));var _inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits"));var _errors=require("../errors");var _Node2=_interopRequireDefault(require("./Node"));var _Range=_interopRequireDefault(require("./Range"));var QuoteDouble=function(_Node){(0,_inherits2.default)(QuoteDouble,_Node);function QuoteDouble(){(0,_classCallCheck2.default)(this,QuoteDouble);return(0,_possibleConstructorReturn2.default)(this,(0,_getPrototypeOf2.default)(QuoteDouble).apply(this,arguments))}(0,_createClass2.default)(QuoteDouble,[{key:"parseCharCode",value:function parseCharCode(offset,length,errors){var src=this.context.src;var cc=src.substr(offset,length);var ok=cc.length===length&&/^[0-9a-fA-F]+$/.test(cc);var code=ok?parseInt(cc,16):NaN;if(isNaN(code)){errors.push(new _errors.YAMLSyntaxError(this,"Invalid escape sequence ".concat(src.substr(offset-2,length+2))));return src.substr(offset-2,length+2)}return String.fromCodePoint(code)}},{key:"parse",value:function parse(context,start){this.context=context;var src=context.src;var offset=QuoteDouble.endOfQuote(src,start+1);this.valueRange=new _Range.default(start,offset);offset=_Node2.default.endOfWhiteSpace(src,offset);offset=this.parseComment(offset);return offset}},{key:"strValue",get:function get(){if(!this.valueRange||!this.context)return null;var errors=[];var _this$valueRange=this.valueRange,start=_this$valueRange.start,end=_this$valueRange.end;var _this$context=this.context,indent=_this$context.indent,src=_this$context.src;if(src[end-1]!=='"')errors.push(new _errors.YAMLSyntaxError(this,'Missing closing "quote'));var str="";for(var i=start+1;i<end-1;++i){var ch=src[i];if(ch==="\n"){if(_Node2.default.atDocumentBoundary(src,i+1))errors.push(new _errors.YAMLSemanticError(this,"Document boundary indicators are not allowed within string values"));var _Node$foldNewline=_Node2.default.foldNewline(src,i,indent),fold=_Node$foldNewline.fold,offset=_Node$foldNewline.offset,error=_Node$foldNewline.error;str+=fold;i=offset;if(error)errors.push(new _errors.YAMLSemanticError(this,"Multi-line double-quoted string needs to be sufficiently indented"))}else if(ch==="\\"){i+=1;switch(src[i]){case"0":str+="\0";break;case"a":str+="";break;case"b":str+="\b";break;case"e":str+="";break;case"f":str+="\f";break;case"n":str+="\n";break;case"r":str+="\r";break;case"t":str+="\t";break;case"v":str+="\v";break;case"N":str+="
";break;case"_":str+=" ";break;case"L":str+="\u2028";break;case"P":str+="\u2029";break;case" ":str+=" ";break;case'"':str+='"';break;case"/":str+="/";break;case"\\":str+="\\";break;case"\t":str+="\t";break;case"x":str+=this.parseCharCode(i+1,2,errors);i+=2;break;case"u":str+=this.parseCharCode(i+1,4,errors);i+=4;break;case"U":str+=this.parseCharCode(i+1,8,errors);i+=8;break;case"\n":while(src[i+1]===" "||src[i+1]==="\t"){i+=1}break;default:errors.push(new _errors.YAMLSyntaxError(this,"Invalid escape sequence ".concat(src.substr(i-1,2))));str+="\\"+src[i]}}else if(ch===" "||ch==="\t"){var wsStart=i;var next=src[i+1];while(next===" "||next==="\t"){i+=1;next=src[i+1]}if(next!=="\n")str+=i>wsStart?src.slice(wsStart,i+1):ch}else{str+=ch}}return errors.length>0?{errors:errors,str:str}:str}}],[{key:"endOfQuote",value:function endOfQuote(src,offset){var ch=src[offset];while(ch&&ch!=='"'){offset+=ch==="\\"?2:1;ch=src[offset]}return offset+1}}]);return QuoteDouble}(_Node2.default);exports.default=QuoteDouble},{"../errors":238,"./Node":230,"./Range":235,"@babel/runtime/helpers/classCallCheck":21,"@babel/runtime/helpers/createClass":23,"@babel/runtime/helpers/getPrototypeOf":26,"@babel/runtime/helpers/inherits":27,"@babel/runtime/helpers/interopRequireDefault":28,"@babel/runtime/helpers/possibleConstructorReturn":34}],234:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));var _getPrototypeOf2=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));var _inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits"));var _errors=require("../errors");var _Node2=_interopRequireDefault(require("./Node"));var _Range=_interopRequireDefault(require("./Range"));var QuoteSingle=function(_Node){(0,_inherits2.default)(QuoteSingle,_Node);function QuoteSingle(){(0,_classCallCheck2.default)(this,QuoteSingle);return(0,_possibleConstructorReturn2.default)(this,(0,_getPrototypeOf2.default)(QuoteSingle).apply(this,arguments))}(0,_createClass2.default)(QuoteSingle,[{key:"parse",value:function parse(context,start){this.context=context;var src=context.src;var offset=QuoteSingle.endOfQuote(src,start+1);this.valueRange=new _Range.default(start,offset);offset=_Node2.default.endOfWhiteSpace(src,offset);offset=this.parseComment(offset);return offset}},{key:"strValue",get:function get(){if(!this.valueRange||!this.context)return null;var errors=[];var _this$valueRange=this.valueRange,start=_this$valueRange.start,end=_this$valueRange.end;var _this$context=this.context,indent=_this$context.indent,src=_this$context.src;if(src[end-1]!=="'")errors.push(new _errors.YAMLSyntaxError(this,"Missing closing 'quote"));var str="";for(var i=start+1;i<end-1;++i){var ch=src[i];if(ch==="\n"){if(_Node2.default.atDocumentBoundary(src,i+1))errors.push(new _errors.YAMLSemanticError(this,"Document boundary indicators are not allowed within string values"));var _Node$foldNewline=_Node2.default.foldNewline(src,i,indent),fold=_Node$foldNewline.fold,offset=_Node$foldNewline.offset,error=_Node$foldNewline.error;str+=fold;i=offset;if(error)errors.push(new _errors.YAMLSemanticError(this,"Multi-line single-quoted string needs to be sufficiently indented"))}else if(ch==="'"){str+=ch;i+=1;if(src[i]!=="'")errors.push(new _errors.YAMLSyntaxError(this,"Unescaped single quote? This should not happen."))}else if(ch===" "||ch==="\t"){var wsStart=i;var next=src[i+1];while(next===" "||next==="\t"){i+=1;next=src[i+1]}if(next!=="\n")str+=i>wsStart?src.slice(wsStart,i+1):ch}else{str+=ch}}return errors.length>0?{errors:errors,str:str}:str}}],[{key:"endOfQuote",value:function endOfQuote(src,offset){var ch=src[offset];while(ch){if(ch==="'"){if(src[offset+1]!=="'")break;ch=src[offset+=2]}else{ch=src[offset+=1]}}return offset+1}}]);return QuoteSingle}(_Node2.default);exports.default=QuoteSingle},{"../errors":238,"./Node":230,"./Range":235,"@babel/runtime/helpers/classCallCheck":21,"@babel/runtime/helpers/createClass":23,"@babel/runtime/helpers/getPrototypeOf":26,"@babel/runtime/helpers/inherits":27,"@babel/runtime/helpers/interopRequireDefault":28,"@babel/runtime/helpers/possibleConstructorReturn":34}],235:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var Range=function(){(0,_createClass2.default)(Range,null,[{key:"copy",value:function copy(orig){return new Range(orig.start,orig.end)}}]);function Range(start,end){(0,_classCallCheck2.default)(this,Range);this.start=start;this.end=end||start}(0,_createClass2.default)(Range,[{key:"isEmpty",value:function isEmpty(){return typeof this.start!=="number"||!this.end||this.end<=this.start}},{key:"setOrigRange",value:function setOrigRange(cr,offset){var start=this.start,end=this.end;if(cr.length===0||end<=cr[0]){this.origStart=start;this.origEnd=end;return offset}var i=offset;while(i<cr.length){if(cr[i]>start)break;else++i}this.origStart=start+i;var nextOffset=i;while(i<cr.length){if(cr[i]>=end)break;else++i}this.origEnd=end+i;return nextOffset}}]);return Range}();exports.default=Range},{"@babel/runtime/helpers/classCallCheck":21,"@babel/runtime/helpers/createClass":23,"@babel/runtime/helpers/interopRequireDefault":28}],236:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=parse;var _Document=_interopRequireDefault(require("./Document"));var _ParseContext=_interopRequireDefault(require("./ParseContext"));function parse(src){var cr=[];if(src.indexOf("\r")!==-1){src=src.replace(/\r\n?/g,(function(match,offset){if(match.length>1)cr.push(offset);return"\n"}))}var documents=[];var offset=0;do{var doc=new _Document.default;var context=new _ParseContext.default({src:src});offset=doc.parse(context,offset);documents.push(doc)}while(offset<src.length);documents.setOrigRanges=function(){if(cr.length===0)return false;for(var i=1;i<cr.length;++i){cr[i]-=i}var crOffset=0;for(var _i=0;_i<documents.length;++_i){crOffset=documents[_i].setOrigRanges(cr,crOffset)}cr.splice(0,cr.length);return true};documents.toString=function(){return documents.join("...\n")};return documents}},{"./Document":228,"./ParseContext":231,"@babel/runtime/helpers/interopRequireDefault":28}],237:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.getLinePos=getLinePos;exports.getLine=getLine;exports.getPrettyContext=getPrettyContext;function findLineStarts(src){var ls=[0];var offset=src.indexOf("\n");while(offset!==-1){offset+=1;ls.push(offset);offset=src.indexOf("\n",offset)}return ls}function getSrcInfo(cst){var lineStarts,src;if(typeof cst==="string"){lineStarts=findLineStarts(cst);src=cst}else{if(Array.isArray(cst))cst=cst[0];if(cst&&cst.context){if(!cst.lineStarts)cst.lineStarts=findLineStarts(cst.context.src);lineStarts=cst.lineStarts;src=cst.context.src}}return{lineStarts:lineStarts,src:src}}function getLinePos(offset,cst){if(typeof offset!=="number"||offset<0)return null;var _getSrcInfo=getSrcInfo(cst),lineStarts=_getSrcInfo.lineStarts,src=_getSrcInfo.src;if(!lineStarts||!src||offset>src.length)return null;for(var i=0;i<lineStarts.length;++i){var start=lineStarts[i];if(offset<start){return{line:i,col:offset-lineStarts[i-1]+1}}if(offset===start)return{line:i+1,col:1}}var line=lineStarts.length;return{line:line,col:offset-lineStarts[line-1]+1}}function getLine(line,cst){var _getSrcInfo2=getSrcInfo(cst),lineStarts=_getSrcInfo2.lineStarts,src=_getSrcInfo2.src;if(!lineStarts||!(line>=1)||line>lineStarts.length)return null;var start=lineStarts[line-1];var end=lineStarts[line];while(end&&end>start&&src[end-1]==="\n"){--end}return src.slice(start,end)}function getPrettyContext(_ref,cst){var start=_ref.start,end=_ref.end;var maxWidth=arguments.length>2&&arguments[2]!==undefined?arguments[2]:80;var src=getLine(start.line,cst);if(!src)return null;var col=start.col;if(src.length>maxWidth){if(col<=maxWidth-10){src=src.substr(0,maxWidth-1)+"…"}else{var halfWidth=Math.round(maxWidth/2);if(src.length>col+halfWidth)src=src.substr(0,col+halfWidth-1)+"…";col-=src.length-maxWidth;src="…"+src.substr(1-maxWidth)}}var errLen=1;var errEnd="";if(end){if(end.line===start.line&&col+(end.col-start.col)<=maxWidth+1){errLen=end.col-start.col}else{errLen=Math.min(src.length+1,maxWidth)-col;errEnd="…"}}var offset=col>1?" ".repeat(col-1):"";var err="^".repeat(errLen);return"".concat(src,"\n").concat(offset).concat(err).concat(errEnd)}},{}],238:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.YAMLWarning=exports.YAMLSyntaxError=exports.YAMLSemanticError=exports.YAMLReferenceError=exports.YAMLError=void 0;var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));var _getPrototypeOf2=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));var _inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits"));var _wrapNativeSuper2=_interopRequireDefault(require("@babel/runtime/helpers/wrapNativeSuper"));var _Node=_interopRequireDefault(require("./cst/Node"));var _sourceUtils=require("./cst/source-utils");var _Range=_interopRequireDefault(require("./cst/Range"));var YAMLError=function(_Error){(0,_inherits2.default)(YAMLError,_Error);function YAMLError(name,source,message){var _this;(0,_classCallCheck2.default)(this,YAMLError);if(!message||!(source instanceof _Node.default))throw new Error("Invalid arguments for new ".concat(name));_this=(0,_possibleConstructorReturn2.default)(this,(0,_getPrototypeOf2.default)(YAMLError).call(this));_this.name=name;_this.message=message;_this.source=source;return _this}(0,_createClass2.default)(YAMLError,[{key:"makePretty",value:function makePretty(){if(!this.source)return;this.nodeType=this.source.type;var cst=this.source.context&&this.source.context.root;if(typeof this.offset==="number"){this.range=new _Range.default(this.offset,this.offset+1);var start=cst&&(0,_sourceUtils.getLinePos)(this.offset,cst);if(start){var end={line:start.line,col:start.col+1};this.linePos={start:start,end:end}}delete this.offset}else{this.range=this.source.range;this.linePos=this.source.rangeAsLinePos}if(this.linePos){var _this$linePos$start=this.linePos.start,line=_this$linePos$start.line,col=_this$linePos$start.col;this.message+=" at line ".concat(line,", column ").concat(col);var ctx=cst&&(0,_sourceUtils.getPrettyContext)(this.linePos,cst);if(ctx)this.message+=":\n\n".concat(ctx,"\n")}delete this.source}}]);return YAMLError}((0,_wrapNativeSuper2.default)(Error));exports.YAMLError=YAMLError;var YAMLReferenceError=function(_YAMLError){(0,_inherits2.default)(YAMLReferenceError,_YAMLError);function YAMLReferenceError(source,message){(0,_classCallCheck2.default)(this,YAMLReferenceError);return(0,_possibleConstructorReturn2.default)(this,(0,_getPrototypeOf2.default)(YAMLReferenceError).call(this,"YAMLReferenceError",source,message))}return YAMLReferenceError}(YAMLError);exports.YAMLReferenceError=YAMLReferenceError;var YAMLSemanticError=function(_YAMLError2){(0,_inherits2.default)(YAMLSemanticError,_YAMLError2);function YAMLSemanticError(source,message){(0,_classCallCheck2.default)(this,YAMLSemanticError);return(0,_possibleConstructorReturn2.default)(this,(0,_getPrototypeOf2.default)(YAMLSemanticError).call(this,"YAMLSemanticError",source,message))}return YAMLSemanticError}(YAMLError);exports.YAMLSemanticError=YAMLSemanticError;var YAMLSyntaxError=function(_YAMLError3){(0,_inherits2.default)(YAMLSyntaxError,_YAMLError3);function YAMLSyntaxError(source,message){(0,_classCallCheck2.default)(this,YAMLSyntaxError);return(0,_possibleConstructorReturn2.default)(this,(0,_getPrototypeOf2.default)(YAMLSyntaxError).call(this,"YAMLSyntaxError",source,message))}return YAMLSyntaxError}(YAMLError);exports.YAMLSyntaxError=YAMLSyntaxError;var YAMLWarning=function(_YAMLError4){(0,_inherits2.default)(YAMLWarning,_YAMLError4);function YAMLWarning(source,message){(0,_classCallCheck2.default)(this,YAMLWarning);return(0,_possibleConstructorReturn2.default)(this,(0,_getPrototypeOf2.default)(YAMLWarning).call(this,"YAMLWarning",source,message))}return YAMLWarning}(YAMLError);exports.YAMLWarning=YAMLWarning},{"./cst/Node":230,"./cst/Range":235,"./cst/source-utils":237,"@babel/runtime/helpers/classCallCheck":21,"@babel/runtime/helpers/createClass":23,"@babel/runtime/helpers/getPrototypeOf":26,"@babel/runtime/helpers/inherits":27,"@babel/runtime/helpers/interopRequireDefault":28,"@babel/runtime/helpers/possibleConstructorReturn":34,"@babel/runtime/helpers/wrapNativeSuper":40}],239:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=foldFlowLines;exports.FOLD_QUOTED=exports.FOLD_BLOCK=exports.FOLD_FLOW=void 0;var FOLD_FLOW="flow";exports.FOLD_FLOW=FOLD_FLOW;var FOLD_BLOCK="block";exports.FOLD_BLOCK=FOLD_BLOCK;var FOLD_QUOTED="quoted";exports.FOLD_QUOTED=FOLD_QUOTED;var consumeMoreIndentedLines=function consumeMoreIndentedLines(text,i){var ch=text[i+1];while(ch===" "||ch==="\t"){do{ch=text[i+=1]}while(ch&&ch!=="\n");ch=text[i+1]}return i};function foldFlowLines(text,indent,mode,_ref){var indentAtStart=_ref.indentAtStart,_ref$lineWidth=_ref.lineWidth,lineWidth=_ref$lineWidth===void 0?80:_ref$lineWidth,_ref$minContentWidth=_ref.minContentWidth,minContentWidth=_ref$minContentWidth===void 0?20:_ref$minContentWidth,onFold=_ref.onFold,onOverflow=_ref.onOverflow;if(!lineWidth||lineWidth<0)return text;var endStep=Math.max(1+minContentWidth,1+lineWidth-indent.length);if(text.length<=endStep)return text;var folds=[];var escapedFolds={};var end=lineWidth-(typeof indentAtStart==="number"?indentAtStart:indent.length);var split=undefined;var prev=undefined;var overflow=false;var i=-1;if(mode===FOLD_BLOCK){i=consumeMoreIndentedLines(text,i);if(i!==-1)end=i+endStep}for(var ch;ch=text[i+=1];){if(mode===FOLD_QUOTED&&ch==="\\"){switch(text[i+1]){case"x":i+=3;break;case"u":i+=5;break;case"U":i+=9;break;default:i+=1}}if(ch==="\n"){if(mode===FOLD_BLOCK)i=consumeMoreIndentedLines(text,i);end=i+endStep;split=undefined}else{if(ch===" "&&prev&&prev!==" "&&prev!=="\n"&&prev!=="\t"){var next=text[i+1];if(next&&next!==" "&&next!=="\n"&&next!=="\t")split=i}if(i>=end){if(split){folds.push(split);end=split+endStep;split=undefined}else if(mode===FOLD_QUOTED){while(prev===" "||prev==="\t"){prev=ch;ch=text[i+=1];overflow=true}folds.push(i-2);escapedFolds[i-2]=true;end=i-2+endStep;split=undefined}else{overflow=true}}}prev=ch}if(overflow&&onOverflow)onOverflow();if(folds.length===0)return text;if(onFold)onFold();var res=text.slice(0,folds[0]);for(var _i=0;_i<folds.length;++_i){var fold=folds[_i];var _end=folds[_i+1]||text.length;if(mode===FOLD_QUOTED&&escapedFolds[fold])res+="".concat(text[fold],"\\");res+="\n".concat(indent).concat(text.slice(fold+1,_end))}return res}},{}],240:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));var _getPrototypeOf2=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));var _inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits"));var _parse=_interopRequireDefault(require("./cst/parse"));var _Document=_interopRequireDefault(require("./Document"));var _errors=require("./errors");var _schema=_interopRequireDefault(require("./schema"));var _warnings=require("./warnings");var defaultOptions={anchorPrefix:"a",customTags:null,keepCstNodes:false,keepNodeTypes:true,keepBlobsInJSON:true,mapAsMap:false,maxAliasCount:100,prettyErrors:false,simpleKeys:false,version:"1.2"};function createNode(value){var wrapScalars=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;var tag=arguments.length>2?arguments[2]:undefined;if(tag===undefined&&typeof wrapScalars==="string"){tag=wrapScalars;wrapScalars=true}var options=Object.assign({},_Document.default.defaults[defaultOptions.version],defaultOptions);var schema=new _schema.default(options);return schema.createNode(value,wrapScalars,tag)}var Document=function(_YAMLDocument){(0,_inherits2.default)(Document,_YAMLDocument);function Document(options){(0,_classCallCheck2.default)(this,Document);return(0,_possibleConstructorReturn2.default)(this,(0,_getPrototypeOf2.default)(Document).call(this,Object.assign({},defaultOptions,options)))}return Document}(_Document.default);function parseAllDocuments(src,options){var stream=[];var prev;var _iteratorNormalCompletion=true;var _didIteratorError=false;var _iteratorError=undefined;try{for(var _iterator=(0,_parse.default)(src)[Symbol.iterator](),_step;!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=true){var cstDoc=_step.value;var doc=new Document(options);doc.parse(cstDoc,prev);stream.push(doc);prev=doc}}catch(err){_didIteratorError=true;_iteratorError=err}finally{try{if(!_iteratorNormalCompletion&&_iterator.return!=null){_iterator.return()}}finally{if(_didIteratorError){throw _iteratorError}}}return stream}function parseDocument(src,options){var cst=(0,_parse.default)(src);var doc=new Document(options).parse(cst[0]);if(cst.length>1){var errMsg="Source contains multiple documents; please use YAML.parseAllDocuments()";doc.errors.unshift(new _errors.YAMLSemanticError(cst[1],errMsg))}return doc}function parse(src,options){var doc=parseDocument(src,options);doc.warnings.forEach((function(warning){return(0,_warnings.warn)(warning)}));if(doc.errors.length>0)throw doc.errors[0];return doc.toJSON()}function stringify(value,options){var doc=new Document(options);doc.contents=value;return String(doc)}var _default={createNode:createNode,defaultOptions:defaultOptions,Document:Document,parse:parse,parseAllDocuments:parseAllDocuments,parseCST:_parse.default,parseDocument:parseDocument,stringify:stringify};exports.default=_default},{"./Document":218,"./cst/parse":236,"./errors":238,"./schema":250,"./warnings":270,"@babel/runtime/helpers/classCallCheck":21,"@babel/runtime/helpers/getPrototypeOf":26,"@babel/runtime/helpers/inherits":27,"@babel/runtime/helpers/interopRequireDefault":28,"@babel/runtime/helpers/possibleConstructorReturn":34}],241:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _typeof2=_interopRequireDefault(require("@babel/runtime/helpers/typeof"));var _Collection=_interopRequireDefault(require("./schema/Collection"));var _Pair=_interopRequireDefault(require("./schema/Pair"));var _Scalar=_interopRequireDefault(require("./schema/Scalar"));var visit=function visit(node,tags){if(node&&(0,_typeof2.default)(node)==="object"){var tag=node.tag;if(node instanceof _Collection.default){if(tag)tags[tag]=true;node.items.forEach((function(n){return visit(n,tags)}))}else if(node instanceof _Pair.default){visit(node.key,tags);visit(node.value,tags)}else if(node instanceof _Scalar.default){if(tag)tags[tag]=true}}return tags};var _default=function _default(node){return Object.keys(visit(node,{}))};exports.default=_default},{"./schema/Collection":243,"./schema/Pair":247,"./schema/Scalar":248,"@babel/runtime/helpers/interopRequireDefault":28,"@babel/runtime/helpers/typeof":39}],242:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));var _getPrototypeOf2=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits"));var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _constants=require("../constants");var _errors=require("../errors");var _toJSON2=_interopRequireDefault(require("../toJSON"));var _Collection=_interopRequireDefault(require("./Collection"));var _Node2=_interopRequireDefault(require("./Node"));var _Pair=_interopRequireDefault(require("./Pair"));var getAliasCount=function getAliasCount(node,anchors){if(node instanceof Alias){var anchor=anchors.find((function(a){return a.node===node.source}));return anchor.count*anchor.aliasCount}else if(node instanceof _Collection.default){var count=0;var _iteratorNormalCompletion=true;var _didIteratorError=false;var _iteratorError=undefined;try{for(var _iterator=node.items[Symbol.iterator](),_step;!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=true){var item=_step.value;var c=getAliasCount(item,anchors);if(c>count)count=c}}catch(err){_didIteratorError=true;_iteratorError=err}finally{try{if(!_iteratorNormalCompletion&&_iterator.return!=null){_iterator.return()}}finally{if(_didIteratorError){throw _iteratorError}}}return count}else if(node instanceof _Pair.default){var kc=getAliasCount(node.key,anchors);var vc=getAliasCount(node.value,anchors);return Math.max(kc,vc)}return 1};var Alias=function(_Node){(0,_inherits2.default)(Alias,_Node);(0,_createClass2.default)(Alias,null,[{key:"stringify",value:function stringify(_ref,_ref2){var range=_ref.range,source=_ref.source;var anchors=_ref2.anchors,doc=_ref2.doc,implicitKey=_ref2.implicitKey,inStringifyKey=_ref2.inStringifyKey;var anchor=Object.keys(anchors).find((function(a){return anchors[a]===source}));if(!anchor&&inStringifyKey)anchor=doc.anchors.getName(source)||doc.anchors.newName();if(anchor)return"*".concat(anchor).concat(implicitKey?" ":"");var msg=doc.anchors.getName(source)?"Alias node must be after source node":"Source node not found for alias node";throw new Error("".concat(msg," [").concat(range,"]"))}}]);function Alias(source){var _this;(0,_classCallCheck2.default)(this,Alias);_this=(0,_possibleConstructorReturn2.default)(this,(0,_getPrototypeOf2.default)(Alias).call(this));_this.source=source;_this.type=_constants.Type.ALIAS;return _this}(0,_createClass2.default)(Alias,[{key:"toJSON",value:function toJSON(arg,ctx){var _this2=this;if(!ctx)return(0,_toJSON2.default)(this.source,arg,ctx);var anchors=ctx.anchors,maxAliasCount=ctx.maxAliasCount;var anchor=anchors.find((function(a){return a.node===_this2.source}));if(!anchor||anchor.res===undefined){var msg="This should not happen: Alias anchor was not resolved?";if(this.cstNode)throw new _errors.YAMLReferenceError(this.cstNode,msg);else throw new ReferenceError(msg)}if(maxAliasCount>=0){anchor.count+=1;if(anchor.aliasCount===0)anchor.aliasCount=getAliasCount(this.source,anchors);if(anchor.count*anchor.aliasCount>maxAliasCount){var _msg="Excessive alias count indicates a resource exhaustion attack";if(this.cstNode)throw new _errors.YAMLReferenceError(this.cstNode,_msg);else throw new ReferenceError(_msg)}}return anchor.res}},{key:"toString",value:function toString(ctx){return Alias.stringify(this,ctx)}},{key:"tag",set:function set(t){throw new Error("Alias nodes cannot have tags")}}]);return Alias}(_Node2.default);exports.default=Alias;(0,_defineProperty2.default)(Alias,"default",true)},{"../constants":220,"../errors":238,"../toJSON":269,"./Collection":243,"./Node":246,"./Pair":247,"@babel/runtime/helpers/classCallCheck":21,"@babel/runtime/helpers/createClass":23,"@babel/runtime/helpers/defineProperty":24,"@babel/runtime/helpers/getPrototypeOf":26,"@babel/runtime/helpers/inherits":27,"@babel/runtime/helpers/interopRequireDefault":28,"@babel/runtime/helpers/possibleConstructorReturn":34}],243:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=exports.isEmptyPath=void 0;var _toArray2=_interopRequireDefault(require("@babel/runtime/helpers/toArray"));var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));var _getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));var _assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));var _inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits"));var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _typeof2=_interopRequireDefault(require("@babel/runtime/helpers/typeof"));var _addComment=_interopRequireDefault(require("../addComment"));var _Node2=_interopRequireDefault(require("./Node"));var _Pair=_interopRequireDefault(require("./Pair"));var _Scalar=_interopRequireDefault(require("./Scalar"));var isEmptyPath=function isEmptyPath(path){return path==null||(0,_typeof2.default)(path)==="object"&&path[Symbol.iterator]().next().done};exports.isEmptyPath=isEmptyPath;var Collection=function(_Node){(0,_inherits2.default)(Collection,_Node);function Collection(){var _getPrototypeOf2;var _this;(0,_classCallCheck2.default)(this,Collection);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key]}_this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(Collection)).call.apply(_getPrototypeOf2,[this].concat(args)));(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"items",[]);return _this}(0,_createClass2.default)(Collection,[{key:"addIn",value:function addIn(path,value){if(isEmptyPath(path))this.add(value);else{var _path=(0,_toArray2.default)(path),key=_path[0],rest=_path.slice(1);var node=this.get(key,true);if(node instanceof Collection)node.addIn(rest,value);else throw new Error("Expected YAML collection at ".concat(key,". Remaining path: ").concat(rest))}}},{key:"deleteIn",value:function deleteIn(_ref){var _ref2=(0,_toArray2.default)(_ref),key=_ref2[0],rest=_ref2.slice(1);if(rest.length===0)return this.delete(key);var node=this.get(key,true);if(node instanceof Collection)return node.deleteIn(rest);else throw new Error("Expected YAML collection at ".concat(key,". Remaining path: ").concat(rest))}},{key:"getIn",value:function getIn(_ref3,keepScalar){var _ref4=(0,_toArray2.default)(_ref3),key=_ref4[0],rest=_ref4.slice(1);var node=this.get(key,true);if(rest.length===0)return!keepScalar&&node instanceof _Scalar.default?node.value:node;else return node instanceof Collection?node.getIn(rest,keepScalar):undefined}},{key:"hasAllNullValues",value:function hasAllNullValues(){return this.items.every((function(node){if(!(node instanceof _Pair.default))return false;var n=node.value;return n==null||n instanceof _Scalar.default&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag}))}},{key:"hasIn",value:function hasIn(_ref5){var _ref6=(0,_toArray2.default)(_ref5),key=_ref6[0],rest=_ref6.slice(1);if(rest.length===0)return this.has(key);var node=this.get(key,true);return node instanceof Collection?node.hasIn(rest):false}},{key:"setIn",value:function setIn(_ref7,value){var _ref8=(0,_toArray2.default)(_ref7),key=_ref8[0],rest=_ref8.slice(1);if(rest.length===0){this.set(key,value)}else{var node=this.get(key,true);if(node instanceof Collection)node.setIn(rest,value);else throw new Error("Expected YAML collection at ".concat(key,". Remaining path: ").concat(rest))}}},{key:"toJSON",value:function toJSON(){return null}},{key:"toString",value:function toString(ctx,_ref9,onComment,onChompKeep){var _this2=this;var blockItem=_ref9.blockItem,flowChars=_ref9.flowChars,isMap=_ref9.isMap,itemIndent=_ref9.itemIndent;var _ctx=ctx,doc=_ctx.doc,indent=_ctx.indent;var inFlow=this.type&&this.type.substr(0,4)==="FLOW"||ctx.inFlow;if(inFlow)itemIndent+=" ";var allNullValues=isMap&&this.hasAllNullValues();ctx=Object.assign({},ctx,{allNullValues:allNullValues,indent:itemIndent,inFlow:inFlow,type:null});var chompKeep=false;var hasItemWithNewLine=false;var nodes=this.items.reduce((function(nodes,item,i){var comment;if(item){if(!chompKeep&&item.spaceBefore)nodes.push({type:"comment",str:""});if(item.commentBefore)item.commentBefore.match(/^.*$/gm).forEach((function(line){nodes.push({type:"comment",str:"#".concat(line)})}));if(item.comment)comment=item.comment;if(inFlow&&(!chompKeep&&item.spaceBefore||item.commentBefore||item.comment||item.key&&(item.key.commentBefore||item.key.comment)||item.value&&(item.value.commentBefore||item.value.comment)))hasItemWithNewLine=true}chompKeep=false;var str=doc.schema.stringify(item,ctx,(function(){return comment=null}),(function(){return chompKeep=true}));if(inFlow&&!hasItemWithNewLine&&str.includes("\n"))hasItemWithNewLine=true;if(inFlow&&i<_this2.items.length-1)str+=",";str=(0,_addComment.default)(str,itemIndent,comment);if(chompKeep&&(comment||inFlow))chompKeep=false;nodes.push({type:"item",str:str});return nodes}),[]);var str;if(nodes.length===0){str=flowChars.start+flowChars.end}else if(inFlow){var start=flowChars.start,end=flowChars.end;var strings=nodes.map((function(n){return n.str}));if(hasItemWithNewLine||strings.reduce((function(sum,str){return sum+str.length+2}),2)>Collection.maxFlowStringSingleLineLength){str=start;var _iteratorNormalCompletion=true;var _didIteratorError=false;var _iteratorError=undefined;try{for(var _iterator=strings[Symbol.iterator](),_step;!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=true){var s=_step.value;str+=s?"\n ".concat(indent).concat(s):"\n"}}catch(err){_didIteratorError=true;_iteratorError=err}finally{try{if(!_iteratorNormalCompletion&&_iterator.return!=null){_iterator.return()}}finally{if(_didIteratorError){throw _iteratorError}}}str+="\n".concat(indent).concat(end)}else{str="".concat(start," ").concat(strings.join(" ")," ").concat(end)}}else{var _strings=nodes.map(blockItem);str=_strings.shift();var _iteratorNormalCompletion2=true;var _didIteratorError2=false;var _iteratorError2=undefined;try{for(var _iterator2=_strings[Symbol.iterator](),_step2;!(_iteratorNormalCompletion2=(_step2=_iterator2.next()).done);_iteratorNormalCompletion2=true){var _s=_step2.value;str+=_s?"\n".concat(indent).concat(_s):"\n"}}catch(err){_didIteratorError2=true;_iteratorError2=err}finally{try{if(!_iteratorNormalCompletion2&&_iterator2.return!=null){_iterator2.return()}}finally{if(_didIteratorError2){throw _iteratorError2}}}}if(this.comment){str+="\n"+this.comment.replace(/^/gm,"".concat(indent,"#"));if(onComment)onComment()}else if(chompKeep&&onChompKeep)onChompKeep();return str}}]);return Collection}(_Node2.default);exports.default=Collection;(0,_defineProperty2.default)(Collection,"maxFlowStringSingleLineLength",60)},{"../addComment":219,"./Node":246,"./Pair":247,"./Scalar":248,"@babel/runtime/helpers/assertThisInitialized":20,"@babel/runtime/helpers/classCallCheck":21,"@babel/runtime/helpers/createClass":23,"@babel/runtime/helpers/defineProperty":24,"@babel/runtime/helpers/getPrototypeOf":26,"@babel/runtime/helpers/inherits":27,"@babel/runtime/helpers/interopRequireDefault":28,"@babel/runtime/helpers/possibleConstructorReturn":34,"@babel/runtime/helpers/toArray":38,"@babel/runtime/helpers/typeof":39}],244:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.findPair=findPair;exports.default=void 0;var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));var _getPrototypeOf2=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));var _get2=_interopRequireDefault(require("@babel/runtime/helpers/get"));var _inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits"));var _Collection2=_interopRequireDefault(require("./Collection"));var _Pair=_interopRequireDefault(require("./Pair"));var _Scalar=_interopRequireDefault(require("./Scalar"));function findPair(items,key){var k=key instanceof _Scalar.default?key.value:key;var _iteratorNormalCompletion=true;var _didIteratorError=false;var _iteratorError=undefined;try{for(var _iterator=items[Symbol.iterator](),_step;!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=true){var it=_step.value;if(it instanceof _Pair.default){if(it.key===key||it.key===k)return it;if(it.key&&it.key.value===k)return it}}}catch(err){_didIteratorError=true;_iteratorError=err}finally{try{if(!_iteratorNormalCompletion&&_iterator.return!=null){_iterator.return()}}finally{if(_didIteratorError){throw _iteratorError}}}return undefined}var YAMLMap=function(_Collection){(0,_inherits2.default)(YAMLMap,_Collection);function YAMLMap(){(0,_classCallCheck2.default)(this,YAMLMap);return(0,_possibleConstructorReturn2.default)(this,(0,_getPrototypeOf2.default)(YAMLMap).apply(this,arguments))}(0,_createClass2.default)(YAMLMap,[{key:"add",value:function add(pair){if(!pair)pair=new _Pair.default(pair);else if(!(pair instanceof _Pair.default))pair=new _Pair.default(pair.key||pair,pair.value);var prev=findPair(this.items,pair.key);if(prev)throw new Error("Key ".concat(pair.key," already set"));this.items.push(pair)}},{key:"delete",value:function _delete(key){var it=findPair(this.items,key);if(!it)return false;var del=this.items.splice(this.items.indexOf(it),1);return del.length>0}},{key:"get",value:function get(key,keepScalar){var it=findPair(this.items,key);var node=it&&it.value;return!keepScalar&&node instanceof _Scalar.default?node.value:node}},{key:"has",value:function has(key){return!!findPair(this.items,key)}},{key:"set",value:function set(key,value){var prev=findPair(this.items,key);if(prev)prev.value=value;else this.items.push(new _Pair.default(key,value))}},{key:"toJSON",value:function toJSON(_,ctx,Type){var map=Type?new Type:ctx&&ctx.mapAsMap?new Map:{};if(ctx&&ctx.onCreate)ctx.onCreate(map);var _iteratorNormalCompletion2=true;var _didIteratorError2=false;var _iteratorError2=undefined;try{for(var _iterator2=this.items[Symbol.iterator](),_step2;!(_iteratorNormalCompletion2=(_step2=_iterator2.next()).done);_iteratorNormalCompletion2=true){var item=_step2.value;item.addToJSMap(ctx,map)}}catch(err){_didIteratorError2=true;_iteratorError2=err}finally{try{if(!_iteratorNormalCompletion2&&_iterator2.return!=null){_iterator2.return()}}finally{if(_didIteratorError2){throw _iteratorError2}}}return map}},{key:"toString",value:function toString(ctx,onComment,onChompKeep){if(!ctx)return JSON.stringify(this);var _iteratorNormalCompletion3=true;var _didIteratorError3=false;var _iteratorError3=undefined;try{for(var _iterator3=this.items[Symbol.iterator](),_step3;!(_iteratorNormalCompletion3=(_step3=_iterator3.next()).done);_iteratorNormalCompletion3=true){var item=_step3.value;if(!(item instanceof _Pair.default))throw new Error("Map items must all be pairs; found ".concat(JSON.stringify(item)," instead"))}}catch(err){_didIteratorError3=true;_iteratorError3=err}finally{try{if(!_iteratorNormalCompletion3&&_iterator3.return!=null){_iterator3.return()}}finally{if(_didIteratorError3){throw _iteratorError3}}}return(0,_get2.default)((0,_getPrototypeOf2.default)(YAMLMap.prototype),"toString",this).call(this,ctx,{blockItem:function blockItem(n){return n.str},flowChars:{start:"{",end:"}"},isMap:true,itemIndent:ctx.indent||""},onComment,onChompKeep)}}]);return YAMLMap}(_Collection2.default);exports.default=YAMLMap},{"./Collection":243,"./Pair":247,"./Scalar":248,"@babel/runtime/helpers/classCallCheck":21,"@babel/runtime/helpers/createClass":23,"@babel/runtime/helpers/get":25,"@babel/runtime/helpers/getPrototypeOf":26,"@babel/runtime/helpers/inherits":27,"@babel/runtime/helpers/interopRequireDefault":28,"@babel/runtime/helpers/possibleConstructorReturn":34}],245:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=exports.MERGE_KEY=void 0;var _slicedToArray2=_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));var _getPrototypeOf2=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));var _get2=_interopRequireDefault(require("@babel/runtime/helpers/get"));var _inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits"));var _Map=_interopRequireDefault(require("./Map"));var _Pair2=_interopRequireDefault(require("./Pair"));var _Scalar=_interopRequireDefault(require("./Scalar"));var _Seq=_interopRequireDefault(require("./Seq"));var MERGE_KEY="<<";exports.MERGE_KEY=MERGE_KEY;var Merge=function(_Pair){(0,_inherits2.default)(Merge,_Pair);function Merge(pair){var _this;(0,_classCallCheck2.default)(this,Merge);if(pair instanceof _Pair2.default){var seq=pair.value;if(!(seq instanceof _Seq.default)){seq=new _Seq.default;seq.items.push(pair.value);seq.range=pair.value.range}_this=(0,_possibleConstructorReturn2.default)(this,(0,_getPrototypeOf2.default)(Merge).call(this,pair.key,seq));_this.range=pair.range}else{_this=(0,_possibleConstructorReturn2.default)(this,(0,_getPrototypeOf2.default)(Merge).call(this,new _Scalar.default(MERGE_KEY),new _Seq.default))}_this.type="MERGE_PAIR";return(0,_possibleConstructorReturn2.default)(_this)}(0,_createClass2.default)(Merge,[{key:"addToJSMap",value:function addToJSMap(ctx,map){var _iteratorNormalCompletion=true;var _didIteratorError=false;var _iteratorError=undefined;try{for(var _iterator=this.value.items[Symbol.iterator](),_step;!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=true){var source=_step.value.source;if(!(source instanceof _Map.default))throw new Error("Merge sources must be maps");var srcMap=source.toJSON(null,ctx,Map);var _iteratorNormalCompletion2=true;var _didIteratorError2=false;var _iteratorError2=undefined;try{for(var _iterator2=srcMap[Symbol.iterator](),_step2;!(_iteratorNormalCompletion2=(_step2=_iterator2.next()).done);_iteratorNormalCompletion2=true){var _step2$value=(0,_slicedToArray2.default)(_step2.value,2),key=_step2$value[0],value=_step2$value[1];if(map instanceof Map){if(!map.has(key))map.set(key,value)}else if(map instanceof Set){map.add(key)}else{if(!Object.prototype.hasOwnProperty.call(map,key))map[key]=value}}}catch(err){_didIteratorError2=true;_iteratorError2=err}finally{try{if(!_iteratorNormalCompletion2&&_iterator2.return!=null){_iterator2.return()}}finally{if(_didIteratorError2){throw _iteratorError2}}}}}catch(err){_didIteratorError=true;_iteratorError=err}finally{try{if(!_iteratorNormalCompletion&&_iterator.return!=null){_iterator.return()}}finally{if(_didIteratorError){throw _iteratorError}}}return map}},{key:"toString",value:function toString(ctx,onComment){var seq=this.value;if(seq.items.length>1)return(0,_get2.default)((0,_getPrototypeOf2.default)(Merge.prototype),"toString",this).call(this,ctx,onComment);this.value=seq.items[0];var str=(0,_get2.default)((0,_getPrototypeOf2.default)(Merge.prototype),"toString",this).call(this,ctx,onComment);this.value=seq;return str}}]);return Merge}(_Pair2.default);exports.default=Merge},{"./Map":244,"./Pair":247,"./Scalar":248,"./Seq":249,"@babel/runtime/helpers/classCallCheck":21,"@babel/runtime/helpers/createClass":23,"@babel/runtime/helpers/get":25,"@babel/runtime/helpers/getPrototypeOf":26,"@babel/runtime/helpers/inherits":27,"@babel/runtime/helpers/interopRequireDefault":28,"@babel/runtime/helpers/possibleConstructorReturn":34,"@babel/runtime/helpers/slicedToArray":36}],246:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var Node=function Node(){(0,_classCallCheck2.default)(this,Node)};exports.default=Node},{"@babel/runtime/helpers/classCallCheck":21,"@babel/runtime/helpers/interopRequireDefault":28}],247:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));var _getPrototypeOf2=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));var _inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits"));var _typeof2=_interopRequireDefault(require("@babel/runtime/helpers/typeof"));var _addComment=_interopRequireDefault(require("../addComment"));var _constants=require("../constants");var _toJSON=_interopRequireDefault(require("../toJSON"));var _Collection=_interopRequireDefault(require("./Collection"));var _Node2=_interopRequireDefault(require("./Node"));var _Scalar=_interopRequireDefault(require("./Scalar"));var stringifyKey=function stringifyKey(key,jsKey,ctx){if(jsKey===null)return"";if((0,_typeof2.default)(jsKey)!=="object")return String(jsKey);if(key instanceof _Node2.default&&ctx&&ctx.doc)return key.toString({anchors:{},doc:ctx.doc,indent:"",inFlow:true,inStringifyKey:true});return JSON.stringify(jsKey)};var Pair=function(_Node){(0,_inherits2.default)(Pair,_Node);function Pair(key){var _this;var value=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;(0,_classCallCheck2.default)(this,Pair);_this=(0,_possibleConstructorReturn2.default)(this,(0,_getPrototypeOf2.default)(Pair).call(this));_this.key=key;_this.value=value;_this.type="PAIR";return _this}(0,_createClass2.default)(Pair,[{key:"addToJSMap",value:function addToJSMap(ctx,map){var key=(0,_toJSON.default)(this.key,"",ctx);if(map instanceof Map){var value=(0,_toJSON.default)(this.value,key,ctx);map.set(key,value)}else if(map instanceof Set){map.add(key)}else{var stringKey=stringifyKey(this.key,key,ctx);map[stringKey]=(0,_toJSON.default)(this.value,stringKey,ctx)}return map}},{key:"toJSON",value:function toJSON(_,ctx){var pair=ctx&&ctx.mapAsMap?new Map:{};return this.addToJSMap(ctx,pair)}},{key:"toString",value:function toString(ctx,onComment,onChompKeep){if(!ctx||!ctx.doc)return JSON.stringify(this);var simpleKeys=ctx.doc.options.simpleKeys;var key=this.key,value=this.value;var keyComment=key instanceof _Node2.default&&key.comment;if(simpleKeys){if(keyComment){throw new Error("With simple keys, key nodes cannot have comments")}if(key instanceof _Collection.default){var msg="With simple keys, collection cannot be used as a key value";throw new Error(msg)}}var explicitKey=!simpleKeys&&(!key||keyComment||key instanceof _Collection.default||key.type===_constants.Type.BLOCK_FOLDED||key.type===_constants.Type.BLOCK_LITERAL);var _ctx=ctx,doc=_ctx.doc,indent=_ctx.indent;ctx=Object.assign({},ctx,{implicitKey:!explicitKey,indent:indent+" "});var chompKeep=false;var str=doc.schema.stringify(key,ctx,(function(){return keyComment=null}),(function(){return chompKeep=true}));str=(0,_addComment.default)(str,ctx.indent,keyComment);if(ctx.allNullValues&&!simpleKeys){if(this.comment){str=(0,_addComment.default)(str,ctx.indent,this.comment);if(onComment)onComment()}else if(chompKeep&&!keyComment&&onChompKeep)onChompKeep();return ctx.inFlow?str:"? ".concat(str)}str=explicitKey?"? ".concat(str,"\n").concat(indent,":"):"".concat(str,":");if(this.comment){str=(0,_addComment.default)(str,ctx.indent,this.comment);if(onComment)onComment()}var vcb="";var valueComment=null;if(value instanceof _Node2.default){if(value.spaceBefore)vcb="\n";if(value.commentBefore){var cs=value.commentBefore.replace(/^/gm,"".concat(ctx.indent,"#"));vcb+="\n".concat(cs)}valueComment=value.comment}else if(value&&(0,_typeof2.default)(value)==="object"){value=doc.schema.createNode(value,true)}ctx.implicitKey=false;chompKeep=false;var valueStr=doc.schema.stringify(value,ctx,(function(){return valueComment=null}),(function(){return chompKeep=true}));var ws=" ";if(vcb||this.comment){ws="".concat(vcb,"\n").concat(ctx.indent)}else if(!explicitKey&&value instanceof _Collection.default){var flow=valueStr[0]==="["||valueStr[0]==="{";if(!flow||valueStr.includes("\n"))ws="\n".concat(ctx.indent)}if(chompKeep&&!valueComment&&onChompKeep)onChompKeep();return(0,_addComment.default)(str+ws+valueStr,ctx.indent,valueComment)}},{key:"commentBefore",get:function get(){return this.key&&this.key.commentBefore},set:function set(cb){if(this.key==null)this.key=new _Scalar.default(null);this.key.commentBefore=cb}}]);return Pair}(_Node2.default);exports.default=Pair},{"../addComment":219,"../constants":220,"../toJSON":269,"./Collection":243,"./Node":246,"./Scalar":248,"@babel/runtime/helpers/classCallCheck":21,"@babel/runtime/helpers/createClass":23,"@babel/runtime/helpers/getPrototypeOf":26,"@babel/runtime/helpers/inherits":27,"@babel/runtime/helpers/interopRequireDefault":28,"@babel/runtime/helpers/possibleConstructorReturn":34,"@babel/runtime/helpers/typeof":39}],248:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));var _getPrototypeOf2=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));var _inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits"));var _toJSON2=_interopRequireDefault(require("../toJSON"));var _Node2=_interopRequireDefault(require("./Node"));var Scalar=function(_Node){(0,_inherits2.default)(Scalar,_Node);function Scalar(value){var _this;(0,_classCallCheck2.default)(this,Scalar);_this=(0,_possibleConstructorReturn2.default)(this,(0,_getPrototypeOf2.default)(Scalar).call(this));_this.value=value;return _this}(0,_createClass2.default)(Scalar,[{key:"toJSON",value:function toJSON(arg,ctx){return ctx&&ctx.keep?this.value:(0,_toJSON2.default)(this.value,arg,ctx)}},{key:"toString",value:function toString(){return String(this.value)}}]);return Scalar}(_Node2.default);exports.default=Scalar},{"../toJSON":269,"./Node":246,"@babel/runtime/helpers/classCallCheck":21,"@babel/runtime/helpers/createClass":23,"@babel/runtime/helpers/getPrototypeOf":26,"@babel/runtime/helpers/inherits":27,"@babel/runtime/helpers/interopRequireDefault":28,"@babel/runtime/helpers/possibleConstructorReturn":34}],249:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));var _getPrototypeOf2=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));var _get2=_interopRequireDefault(require("@babel/runtime/helpers/get"));var _inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits"));var _toJSON2=_interopRequireDefault(require("../toJSON"));var _Collection2=_interopRequireDefault(require("./Collection"));var _Scalar=_interopRequireDefault(require("./Scalar"));function asItemIndex(key){var idx=key instanceof _Scalar.default?key.value:key;if(idx&&typeof idx==="string")idx=Number(idx);return Number.isInteger(idx)&&idx>=0?idx:null}var YAMLSeq=function(_Collection){(0,_inherits2.default)(YAMLSeq,_Collection);function YAMLSeq(){(0,_classCallCheck2.default)(this,YAMLSeq);return(0,_possibleConstructorReturn2.default)(this,(0,_getPrototypeOf2.default)(YAMLSeq).apply(this,arguments))}(0,_createClass2.default)(YAMLSeq,[{key:"add",value:function add(value){this.items.push(value)}},{key:"delete",value:function _delete(key){var idx=asItemIndex(key);if(typeof idx!=="number")return false;var del=this.items.splice(idx,1);return del.length>0}},{key:"get",value:function get(key,keepScalar){var idx=asItemIndex(key);if(typeof idx!=="number")return undefined;var it=this.items[idx];return!keepScalar&&it instanceof _Scalar.default?it.value:it}},{key:"has",value:function has(key){var idx=asItemIndex(key);return typeof idx==="number"&&idx<this.items.length}},{key:"set",value:function set(key,value){var idx=asItemIndex(key);if(typeof idx!=="number")throw new Error("Expected a valid index, not ".concat(key,"."));this.items[idx]=value}},{key:"toJSON",value:function toJSON(_,ctx){var seq=[];if(ctx&&ctx.onCreate)ctx.onCreate(seq);var i=0;var _iteratorNormalCompletion=true;var _didIteratorError=false;var _iteratorError=undefined;try{for(var _iterator=this.items[Symbol.iterator](),_step;!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=true){var item=_step.value;seq.push((0,_toJSON2.default)(item,String(i++),ctx))}}catch(err){_didIteratorError=true;_iteratorError=err}finally{try{if(!_iteratorNormalCompletion&&_iterator.return!=null){_iterator.return()}}finally{if(_didIteratorError){throw _iteratorError}}}return seq}},{key:"toString",value:function toString(ctx,onComment,onChompKeep){if(!ctx)return JSON.stringify(this);return(0,_get2.default)((0,_getPrototypeOf2.default)(YAMLSeq.prototype),"toString",this).call(this,ctx,{blockItem:function blockItem(n){return n.type==="comment"?n.str:"- ".concat(n.str)},flowChars:{start:"[",end:"]"},isMap:false,itemIndent:(ctx.indent||"")+" "},onComment,onChompKeep)}}]);return YAMLSeq}(_Collection2.default);exports.default=YAMLSeq},{"../toJSON":269,"./Collection":243,"./Scalar":248,"@babel/runtime/helpers/classCallCheck":21,"@babel/runtime/helpers/createClass":23,"@babel/runtime/helpers/get":25,"@babel/runtime/helpers/getPrototypeOf":26,"@babel/runtime/helpers/inherits":27,"@babel/runtime/helpers/interopRequireDefault":28,"@babel/runtime/helpers/possibleConstructorReturn":34}],250:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _typeof2=_interopRequireDefault(require("@babel/runtime/helpers/typeof"));var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _warnings=require("../warnings");var _constants=require("../constants");var _errors=require("../errors");var _stringify=require("../stringify");var _tags=require("../tags");var _string=require("../tags/failsafe/string");var _Alias=_interopRequireDefault(require("./Alias"));var _Collection=_interopRequireDefault(require("./Collection"));var _Node=_interopRequireDefault(require("./Node"));var _Pair=_interopRequireDefault(require("./Pair"));var _Scalar=_interopRequireDefault(require("./Scalar"));var isMap=function isMap(_ref){var type=_ref.type;return type===_constants.Type.FLOW_MAP||type===_constants.Type.MAP};var isSeq=function isSeq(_ref2){var type=_ref2.type;return type===_constants.Type.FLOW_SEQ||type===_constants.Type.SEQ};var Schema=function(){function Schema(_ref3){var customTags=_ref3.customTags,merge=_ref3.merge,schema=_ref3.schema,deprecatedCustomTags=_ref3.tags;(0,_classCallCheck2.default)(this,Schema);this.merge=!!merge;this.name=schema;this.tags=_tags.schemas[schema.replace(/\W/g,"")];if(!this.tags){var keys=Object.keys(_tags.schemas).map((function(key){return JSON.stringify(key)})).join(", ");throw new Error('Unknown schema "'.concat(schema,'"; use one of ').concat(keys))}if(!customTags&&deprecatedCustomTags){customTags=deprecatedCustomTags;(0,_warnings.warnOptionDeprecation)("tags","customTags")}if(Array.isArray(customTags)){var _iteratorNormalCompletion=true;var _didIteratorError=false;var _iteratorError=undefined;try{for(var _iterator=customTags[Symbol.iterator](),_step;!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=true){var tag=_step.value;this.tags=this.tags.concat(tag)}}catch(err){_didIteratorError=true;_iteratorError=err}finally{try{if(!_iteratorNormalCompletion&&_iterator.return!=null){_iterator.return()}}finally{if(_didIteratorError){throw _iteratorError}}}}else if(typeof customTags==="function"){this.tags=customTags(this.tags.slice())}for(var i=0;i<this.tags.length;++i){var _tag=this.tags[i];if(typeof _tag==="string"){var tagObj=_tags.tags[_tag];if(!tagObj){var _keys=Object.keys(_tags.tags).map((function(key){return JSON.stringify(key)})).join(", ");throw new Error('Unknown custom tag "'.concat(_tag,'"; use one of ').concat(_keys))}this.tags[i]=tagObj}}}(0,_createClass2.default)(Schema,[{key:"createNode",value:function createNode(value,wrapScalars,tag,ctx){if(value instanceof _Node.default)return value;var tagObj;if(tag){if(tag.startsWith("!!"))tag=Schema.defaultPrefix+tag.slice(2);var match=this.tags.filter((function(t){return t.tag===tag}));tagObj=match.find((function(t){return!t.format}))||match[0];if(!tagObj)throw new Error("Tag ".concat(tag," not found"))}else{tagObj=this.tags.find((function(t){return(t.identify&&t.identify(value)||t.class&&value instanceof t.class)&&!t.format}));if(!tagObj){if(typeof value.toJSON==="function")value=value.toJSON();if((0,_typeof2.default)(value)!=="object")return wrapScalars?new _Scalar.default(value):value;tagObj=value instanceof Map?_tags.tags.map:value[Symbol.iterator]?_tags.tags.seq:_tags.tags.map}}if(!ctx)ctx={wrapScalars:wrapScalars};else ctx.wrapScalars=wrapScalars;if(ctx.onTagObj){ctx.onTagObj(tagObj);delete ctx.onTagObj}var obj={};if(value&&(0,_typeof2.default)(value)==="object"&&ctx.prevObjects){var prev=ctx.prevObjects.find((function(o){return o.value===value}));if(prev){var alias=new _Alias.default(prev);ctx.aliasNodes.push(alias);return alias}obj.value=value;ctx.prevObjects.push(obj)}obj.node=tagObj.createNode?tagObj.createNode(this,value,ctx):wrapScalars?new _Scalar.default(value):value;return obj.node}},{key:"createPair",value:function createPair(key,value,ctx){var k=this.createNode(key,ctx.wrapScalars,null,ctx);var v=this.createNode(value,ctx.wrapScalars,null,ctx);return new _Pair.default(k,v)}},{key:"resolveScalar",value:function resolveScalar(str,tags){if(!tags)tags=this.tags;for(var i=0;i<tags.length;++i){var _tags$i=tags[i],format=_tags$i.format,test=_tags$i.test,resolve=_tags$i.resolve;if(test){var match=str.match(test);if(match){var res=resolve.apply(null,match);if(!(res instanceof _Scalar.default))res=new _Scalar.default(res);if(format)res.format=format;return res}}}if(this.tags.scalarFallback)str=this.tags.scalarFallback(str);return new _Scalar.default(str)}},{key:"resolveNode",value:function resolveNode(doc,node,tagName){var tags=this.tags.filter((function(_ref4){var tag=_ref4.tag;return tag===tagName}));var generic=tags.find((function(_ref5){var test=_ref5.test;return!test}));if(node.error)doc.errors.push(node.error);try{if(generic){var res=generic.resolve(doc,node);if(!(res instanceof _Collection.default))res=new _Scalar.default(res);node.resolved=res}else{var str=(0,_string.resolveString)(doc,node);if(typeof str==="string"&&tags.length>0){node.resolved=this.resolveScalar(str,tags)}}}catch(error){if(!error.source)error.source=node;doc.errors.push(error);node.resolved=null}if(!node.resolved)return null;if(tagName&&node.tag)node.resolved.tag=tagName;return node.resolved}},{key:"resolveNodeWithFallback",value:function resolveNodeWithFallback(doc,node,tagName){var res=this.resolveNode(doc,node,tagName);if(Object.prototype.hasOwnProperty.call(node,"resolved"))return res;var fallback=isMap(node)?Schema.defaultTags.MAP:isSeq(node)?Schema.defaultTags.SEQ:Schema.defaultTags.STR;if(fallback){doc.warnings.push(new _errors.YAMLWarning(node,"The tag ".concat(tagName," is unavailable, falling back to ").concat(fallback)));var _res=this.resolveNode(doc,node,fallback);_res.tag=tagName;return _res}else{doc.errors.push(new _errors.YAMLReferenceError(node,"The tag ".concat(tagName," is unavailable")))}return null}},{key:"getTagObject",value:function getTagObject(item){if(item instanceof _Alias.default)return _Alias.default;if(item.tag){var match=this.tags.filter((function(t){return t.tag===item.tag}));if(match.length>0)return match.find((function(t){return t.format===item.format}))||match[0]}var tagObj,obj;if(item instanceof _Scalar.default){obj=item.value;var _match=this.tags.filter((function(t){return t.identify&&t.identify(obj)||t.class&&obj instanceof t.class}));tagObj=_match.find((function(t){return t.format===item.format}))||_match.find((function(t){return!t.format}))}else{obj=item;tagObj=this.tags.find((function(t){return t.nodeClass&&obj instanceof t.nodeClass}))}if(!tagObj){var name=obj&&obj.constructor?obj.constructor.name:(0,_typeof2.default)(obj);throw new Error("Tag not resolved for ".concat(name," value"))}return tagObj}},{key:"stringifyProps",value:function stringifyProps(node,tagObj,_ref6){var anchors=_ref6.anchors,doc=_ref6.doc;var props=[];var anchor=doc.anchors.getName(node);if(anchor){anchors[anchor]=node;props.push("&".concat(anchor))}if(node.tag){props.push(doc.stringifyTag(node.tag))}else if(!tagObj.default){props.push(doc.stringifyTag(tagObj.tag))}return props.join(" ")}},{key:"stringify",value:function stringify(item,ctx,onComment,onChompKeep){var tagObj;if(!(item instanceof _Node.default)){var createCtx={aliasNodes:[],onTagObj:function onTagObj(o){return tagObj=o},prevObjects:[]};item=this.createNode(item,true,null,createCtx);var anchors=ctx.doc.anchors;var _iteratorNormalCompletion2=true;var _didIteratorError2=false;var _iteratorError2=undefined;try{for(var _iterator2=createCtx.aliasNodes[Symbol.iterator](),_step2;!(_iteratorNormalCompletion2=(_step2=_iterator2.next()).done);_iteratorNormalCompletion2=true){var alias=_step2.value;alias.source=alias.source.node;var name=anchors.getName(alias.source);if(!name){name=anchors.newName();anchors.map[name]=alias.source}}}catch(err){_didIteratorError2=true;_iteratorError2=err}finally{try{if(!_iteratorNormalCompletion2&&_iterator2.return!=null){_iterator2.return()}}finally{if(_didIteratorError2){throw _iteratorError2}}}}ctx.tags=this;if(item instanceof _Pair.default)return item.toString(ctx,onComment,onChompKeep);if(!tagObj)tagObj=this.getTagObject(item);var props=this.stringifyProps(item,tagObj,ctx);var str=typeof tagObj.stringify==="function"?tagObj.stringify(item,ctx,onComment,onChompKeep):item instanceof _Collection.default?item.toString(ctx,onComment,onChompKeep):(0,_stringify.stringifyString)(item,ctx,onComment,onChompKeep);return props?item instanceof _Collection.default&&str[0]!=="{"&&str[0]!=="["?"".concat(props,"\n").concat(ctx.indent).concat(str):"".concat(props," ").concat(str):str}}]);return Schema}();exports.default=Schema;(0,_defineProperty2.default)(Schema,"defaultPrefix","tag:yaml.org,2002:");(0,_defineProperty2.default)(Schema,"defaultTags",{MAP:"tag:yaml.org,2002:map",SEQ:"tag:yaml.org,2002:seq",STR:"tag:yaml.org,2002:str"})},{"../constants":220,"../errors":238,"../stringify":254,"../tags":260,"../tags/failsafe/string":259,"../warnings":270,"./Alias":242,"./Collection":243,"./Node":246,"./Pair":247,"./Scalar":248,"@babel/runtime/helpers/classCallCheck":21,"@babel/runtime/helpers/createClass":23,"@babel/runtime/helpers/defineProperty":24,"@babel/runtime/helpers/interopRequireDefault":28,"@babel/runtime/helpers/typeof":39}],251:[function(require,module,exports){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard");var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=parseMap;var _constants=require("../constants");var _PlainValue=_interopRequireDefault(require("../cst/PlainValue"));var _errors=require("../errors");var _Map=_interopRequireDefault(require("./Map"));var _Merge=_interopRequireWildcard(require("./Merge"));var _Pair=_interopRequireDefault(require("./Pair"));var _parseUtils=require("./parseUtils");var _Alias=_interopRequireDefault(require("./Alias"));var _Collection=_interopRequireDefault(require("./Collection"));function parseMap(doc,cst){if(cst.type!==_constants.Type.MAP&&cst.type!==_constants.Type.FLOW_MAP){var msg="A ".concat(cst.type," node cannot be resolved as a mapping");doc.errors.push(new _errors.YAMLSyntaxError(cst,msg));return null}var _ref=cst.type===_constants.Type.FLOW_MAP?resolveFlowMapItems(doc,cst):resolveBlockMapItems(doc,cst),comments=_ref.comments,items=_ref.items;var map=new _Map.default;map.items=items;(0,_parseUtils.resolveComments)(map,comments);var hasCollectionKey=false;for(var i=0;i<items.length;++i){var iKey=items[i].key;if(iKey instanceof _Collection.default)hasCollectionKey=true;if(doc.schema.merge&&iKey&&iKey.value===_Merge.MERGE_KEY){items[i]=new _Merge.default(items[i]);var sources=items[i].value.items;var error=null;sources.some((function(node){if(node instanceof _Alias.default){var type=node.source.type;if(type===_constants.Type.MAP||type===_constants.Type.FLOW_MAP)return false;return error="Merge nodes aliases can only point to maps"}return error="Merge nodes can only have Alias nodes as values"}));if(error)doc.errors.push(new _errors.YAMLSemanticError(cst,error))}else{for(var j=i+1;j<items.length;++j){var jKey=items[j].key;if(iKey===jKey||iKey&&jKey&&Object.prototype.hasOwnProperty.call(iKey,"value")&&iKey.value===jKey.value){var _msg='Map keys must be unique; "'.concat(iKey,'" is repeated');doc.errors.push(new _errors.YAMLSemanticError(cst,_msg));break}}}}if(hasCollectionKey&&!doc.options.mapAsMap){var warn="Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.";doc.warnings.push(new _errors.YAMLWarning(cst,warn))}cst.resolved=map;return map}var valueHasPairComment=function valueHasPairComment(_ref2){var _ref2$context=_ref2.context,lineStart=_ref2$context.lineStart,node=_ref2$context.node,src=_ref2$context.src,props=_ref2.props;if(props.length===0)return false;var start=props[0].start;if(node&&start>node.valueRange.start)return false;if(src[start]!==_constants.Char.COMMENT)return false;for(var i=lineStart;i<start;++i){if(src[i]==="\n")return false}return true};function resolvePairComment(item,pair){if(!valueHasPairComment(item))return;var comment=item.getPropValue(0,_constants.Char.COMMENT,true);var found=false;var cb=pair.value.commentBefore;if(cb&&cb.startsWith(comment)){pair.value.commentBefore=cb.substr(comment.length+1);found=true}else{var cc=pair.value.comment;if(!item.node&&cc&&cc.startsWith(comment)){pair.value.comment=cc.substr(comment.length+1);found=true}}if(found)pair.comment=comment}function resolveBlockMapItems(doc,cst){var comments=[];var items=[];var key=undefined;var keyStart=null;for(var i=0;i<cst.items.length;++i){var item=cst.items[i];switch(item.type){case _constants.Type.BLANK_LINE:comments.push({afterKey:!!key,before:items.length});break;case _constants.Type.COMMENT:comments.push({afterKey:!!key,before:items.length,comment:item.comment});break;case _constants.Type.MAP_KEY:if(key!==undefined)items.push(new _Pair.default(key));if(item.error)doc.errors.push(item.error);key=doc.resolveNode(item.node);keyStart=null;break;case _constants.Type.MAP_VALUE:{if(key===undefined)key=null;if(item.error)doc.errors.push(item.error);if(!item.context.atLineStart&&item.node&&item.node.type===_constants.Type.MAP&&!item.node.context.atLineStart){var msg="Nested mappings are not allowed in compact mappings";doc.errors.push(new _errors.YAMLSemanticError(item.node,msg))}var valueNode=item.node;if(!valueNode&&item.props.length>0){valueNode=new _PlainValue.default(_constants.Type.PLAIN,[]);valueNode.context={parent:item,src:item.context.src};var pos=item.range.start+1;valueNode.range={start:pos,end:pos};valueNode.valueRange={start:pos,end:pos};if(typeof item.range.origStart==="number"){var origPos=item.range.origStart+1;valueNode.range.origStart=valueNode.range.origEnd=origPos;valueNode.valueRange.origStart=valueNode.valueRange.origEnd=origPos}}var pair=new _Pair.default(key,doc.resolveNode(valueNode));resolvePairComment(item,pair);items.push(pair);(0,_parseUtils.checkKeyLength)(doc.errors,cst,i,key,keyStart);key=undefined;keyStart=null}break;default:if(key!==undefined)items.push(new _Pair.default(key));key=doc.resolveNode(item);keyStart=item.range.start;if(item.error)doc.errors.push(item.error);next:for(var j=i+1;;++j){var nextItem=cst.items[j];switch(nextItem&&nextItem.type){case _constants.Type.BLANK_LINE:case _constants.Type.COMMENT:continue next;case _constants.Type.MAP_VALUE:break next;default:doc.errors.push(new _errors.YAMLSemanticError(item,"Implicit map keys need to be followed by map values"));break next}}if(item.valueRangeContainsNewline){var _msg2="Implicit map keys need to be on a single line";doc.errors.push(new _errors.YAMLSemanticError(item,_msg2))}}}if(key!==undefined)items.push(new _Pair.default(key));return{comments:comments,items:items}}function resolveFlowMapItems(doc,cst){var comments=[];var items=[];var key=undefined;var keyStart=null;var explicitKey=false;var next="{";for(var i=0;i<cst.items.length;++i){(0,_parseUtils.checkKeyLength)(doc.errors,cst,i,key,keyStart);var item=cst.items[i];if(typeof item.char==="string"){var char=item.char,offset=item.offset;if(char==="?"&&key===undefined&&!explicitKey){explicitKey=true;next=":";continue}if(char===":"){if(key===undefined)key=null;if(next===":"){next=",";continue}}else{if(explicitKey){if(key===undefined&&char!==",")key=null;explicitKey=false}if(key!==undefined){items.push(new _Pair.default(key));key=undefined;keyStart=null;if(char===","){next=":";continue}}}if(char==="}"){if(i===cst.items.length-1)continue}else if(char===next){next=":";continue}var msg="Flow map contains an unexpected ".concat(char);var err=new _errors.YAMLSyntaxError(cst,msg);err.offset=offset;doc.errors.push(err)}else if(item.type===_constants.Type.BLANK_LINE){comments.push({afterKey:!!key,before:items.length})}else if(item.type===_constants.Type.COMMENT){comments.push({afterKey:!!key,before:items.length,comment:item.comment})}else if(key===undefined){if(next===",")doc.errors.push(new _errors.YAMLSemanticError(item,"Separator , missing in flow map"));key=doc.resolveNode(item);keyStart=explicitKey?null:item.range.start}else{if(next!==",")doc.errors.push(new _errors.YAMLSemanticError(item,"Indicator : missing in flow map entry"));items.push(new _Pair.default(key,doc.resolveNode(item)));key=undefined;explicitKey=false}}(0,_parseUtils.checkFlowCollectionEnd)(doc.errors,cst);if(key!==undefined)items.push(new _Pair.default(key));return{comments:comments,items:items}}},{"../constants":220,"../cst/PlainValue":232,"../errors":238,"./Alias":242,"./Collection":243,"./Map":244,"./Merge":245,"./Pair":247,"./parseUtils":253,"@babel/runtime/helpers/interopRequireDefault":28,"@babel/runtime/helpers/interopRequireWildcard":29}],252:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=parseSeq;var _constants=require("../constants");var _errors=require("../errors");var _Pair=_interopRequireDefault(require("./Pair"));var _parseUtils=require("./parseUtils");var _Seq=_interopRequireDefault(require("./Seq"));var _Collection=_interopRequireDefault(require("./Collection"));function parseSeq(doc,cst){if(cst.type!==_constants.Type.SEQ&&cst.type!==_constants.Type.FLOW_SEQ){var msg="A ".concat(cst.type," node cannot be resolved as a sequence");doc.errors.push(new _errors.YAMLSyntaxError(cst,msg));return null}var _ref=cst.type===_constants.Type.FLOW_SEQ?resolveFlowSeqItems(doc,cst):resolveBlockSeqItems(doc,cst),comments=_ref.comments,items=_ref.items;var seq=new _Seq.default;seq.items=items;(0,_parseUtils.resolveComments)(seq,comments);if(!doc.options.mapAsMap&&items.some((function(it){return it instanceof _Pair.default&&it.key instanceof _Collection.default}))){var warn="Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.";doc.warnings.push(new _errors.YAMLWarning(cst,warn))}cst.resolved=seq;return seq}function resolveBlockSeqItems(doc,cst){var comments=[];var items=[];for(var i=0;i<cst.items.length;++i){var item=cst.items[i];switch(item.type){case _constants.Type.BLANK_LINE:comments.push({before:items.length});break;case _constants.Type.COMMENT:comments.push({comment:item.comment,before:items.length});break;case _constants.Type.SEQ_ITEM:if(item.error)doc.errors.push(item.error);items.push(doc.resolveNode(item.node));if(item.hasProps){var msg="Sequence items cannot have tags or anchors before the - indicator";doc.errors.push(new _errors.YAMLSemanticError(item,msg))}break;default:if(item.error)doc.errors.push(item.error);doc.errors.push(new _errors.YAMLSyntaxError(item,"Unexpected ".concat(item.type," node in sequence")))}}return{comments:comments,items:items}}function resolveFlowSeqItems(doc,cst){var comments=[];var items=[];var explicitKey=false;var key=undefined;var keyStart=null;var next="[";for(var i=0;i<cst.items.length;++i){var item=cst.items[i];if(typeof item.char==="string"){var char=item.char,offset=item.offset;if(char!==":"&&(explicitKey||key!==undefined)){if(explicitKey&&key===undefined)key=next?items.pop():null;items.push(new _Pair.default(key));explicitKey=false;key=undefined;keyStart=null}if(char===next){next=null}else if(!next&&char==="?"){explicitKey=true}else if(next!=="["&&char===":"&&key===undefined){if(next===","){key=items.pop();if(key instanceof _Pair.default){var msg="Chaining flow sequence pairs is invalid";var err=new _errors.YAMLSemanticError(cst,msg);err.offset=offset;doc.errors.push(err)}if(!explicitKey)(0,_parseUtils.checkKeyLength)(doc.errors,cst,i,key,keyStart)}else{key=null}keyStart=null;explicitKey=false;next=null}else if(next==="["||char!=="]"||i<cst.items.length-1){var _msg="Flow sequence contains an unexpected ".concat(char);var _err=new _errors.YAMLSyntaxError(cst,_msg);_err.offset=offset;doc.errors.push(_err)}}else if(item.type===_constants.Type.BLANK_LINE){comments.push({before:items.length})}else if(item.type===_constants.Type.COMMENT){comments.push({comment:item.comment,before:items.length})}else{if(next){var _msg2="Expected a ".concat(next," in flow sequence");doc.errors.push(new _errors.YAMLSemanticError(item,_msg2))}var value=doc.resolveNode(item);if(key===undefined){items.push(value)}else{items.push(new _Pair.default(key,value));key=undefined}keyStart=item.range.start;next=","}}(0,_parseUtils.checkFlowCollectionEnd)(doc.errors,cst);if(key!==undefined)items.push(new _Pair.default(key));return{comments:comments,items:items}}},{"../constants":220,"../errors":238,"./Collection":243,"./Pair":247,"./Seq":249,"./parseUtils":253,"@babel/runtime/helpers/interopRequireDefault":28}],253:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.checkFlowCollectionEnd=checkFlowCollectionEnd;exports.checkKeyLength=checkKeyLength;exports.resolveComments=resolveComments;var _errors=require("../errors");var _constants=require("../constants");function checkFlowCollectionEnd(errors,cst){var char,name;switch(cst.type){case _constants.Type.FLOW_MAP:char="}";name="flow map";break;case _constants.Type.FLOW_SEQ:char="]";name="flow sequence";break;default:errors.push(new _errors.YAMLSemanticError(cst,"Not a flow collection!?"));return}var lastItem;for(var i=cst.items.length-1;i>=0;--i){var item=cst.items[i];if(!item||item.type!==_constants.Type.COMMENT){lastItem=item;break}}if(lastItem&&lastItem.char!==char){var msg="Expected ".concat(name," to end with ").concat(char);var err;if(typeof lastItem.offset==="number"){err=new _errors.YAMLSemanticError(cst,msg);err.offset=lastItem.offset+1}else{err=new _errors.YAMLSemanticError(lastItem,msg);if(lastItem.range&&lastItem.range.end)err.offset=lastItem.range.end-lastItem.range.start}errors.push(err)}}function checkKeyLength(errors,node,itemIdx,key,keyStart){if(!key||typeof keyStart!=="number")return;var item=node.items[itemIdx];var keyEnd=item&&item.range&&item.range.start;if(!keyEnd){for(var i=itemIdx-1;i>=0;--i){var it=node.items[i];if(it&&it.range){keyEnd=it.range.end+2*(itemIdx-i);break}}}if(keyEnd>keyStart+1024){var k=String(key).substr(0,8)+"..."+String(key).substr(-8);errors.push(new _errors.YAMLSemanticError(node,'The "'.concat(k,'" key is too long')))}}function resolveComments(collection,comments){var _iteratorNormalCompletion=true;var _didIteratorError=false;var _iteratorError=undefined;try{for(var _iterator=comments[Symbol.iterator](),_step;!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=true){var _step$value=_step.value,afterKey=_step$value.afterKey,before=_step$value.before,comment=_step$value.comment;var item=collection.items[before];if(!item){if(comment!==undefined){if(collection.comment)collection.comment+="\n"+comment;else collection.comment=comment}}else{if(afterKey&&item.value)item=item.value;if(comment===undefined){if(afterKey||!item.commentBefore)item.spaceBefore=true}else{if(item.commentBefore)item.commentBefore+="\n"+comment;else item.commentBefore=comment}}}}catch(err){_didIteratorError=true;_iteratorError=err}finally{try{if(!_iteratorNormalCompletion&&_iterator.return!=null){_iterator.return()}}finally{if(_didIteratorError){throw _iteratorError}}}}},{"../constants":220,"../errors":238}],254:[function(require,module,exports){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard");Object.defineProperty(exports,"__esModule",{value:true});exports.stringifyNumber=stringifyNumber;exports.stringifyString=stringifyString;var _addComment=require("./addComment");var _constants=require("./constants");var _foldFlowLines=_interopRequireWildcard(require("./foldFlowLines"));var _options=require("./tags/options");function stringifyNumber(_ref){var format=_ref.format,minFractionDigits=_ref.minFractionDigits,tag=_ref.tag,value=_ref.value;if(!isFinite(value))return isNaN(value)?".nan":value<0?"-.inf":".inf";var n=JSON.stringify(value);if(!format&&minFractionDigits&&(!tag||tag==="tag:yaml.org,2002:float")&&/^\d/.test(n)){var i=n.indexOf(".");if(i<0){i=n.length;n+="."}var d=minFractionDigits-(n.length-i-1);while(d-- >0){n+="0"}}return n}function lineLengthOverLimit(str,limit){var strLen=str.length;if(strLen<=limit)return false;for(var i=0,start=0;i<strLen;++i){if(str[i]==="\n"){if(i-start>limit)return true;start=i+1;if(strLen-start<=limit)return false}}return true}function doubleQuotedString(value,_ref2){var implicitKey=_ref2.implicitKey,indent=_ref2.indent;var _strOptions$doubleQuo=_options.strOptions.doubleQuoted,jsonEncoding=_strOptions$doubleQuo.jsonEncoding,minMultiLineLength=_strOptions$doubleQuo.minMultiLineLength;var json=JSON.stringify(value);if(jsonEncoding)return json;var str="";var start=0;for(var i=0,ch=json[i];ch;ch=json[++i]){if(ch===" "&&json[i+1]==="\\"&&json[i+2]==="n"){str+=json.slice(start,i)+"\\ ";i+=1;start=i;ch="\\"}if(ch==="\\")switch(json[i+1]){case"u":{str+=json.slice(start,i);var code=json.substr(i+2,4);switch(code){case"0000":str+="\\0";break;case"0007":str+="\\a";break;case"000b":str+="\\v";break;case"001b":str+="\\e";break;case"0085":str+="\\N";break;case"00a0":str+="\\_";break;case"2028":str+="\\L";break;case"2029":str+="\\P";break;default:if(code.substr(0,2)==="00")str+="\\x"+code.substr(2);else str+=json.substr(i,6)}i+=5;start=i+1}break;case"n":if(implicitKey||json[i+2]==='"'||json.length<minMultiLineLength){i+=1}else{str+=json.slice(start,i)+"\n\n";while(json[i+2]==="\\"&&json[i+3]==="n"&&json[i+4]!=='"'){str+="\n";i+=2}str+=indent;if(json[i+2]===" ")str+="\\";i+=1;start=i+1}break;default:i+=1}}str=start?str+json.slice(start):json;return implicitKey?str:(0,_foldFlowLines.default)(str,indent,_foldFlowLines.FOLD_QUOTED,_options.strOptions.fold)}function singleQuotedString(value,ctx){var indent=ctx.indent,implicitKey=ctx.implicitKey;if(implicitKey){if(/\n/.test(value))return doubleQuotedString(value,ctx)}else{if(/[ \t]\n|\n[ \t]/.test(value))return doubleQuotedString(value,ctx)}var res="'"+value.replace(/'/g,"''").replace(/\n+/g,"$&\n".concat(indent))+"'";return implicitKey?res:(0,_foldFlowLines.default)(res,indent,_foldFlowLines.FOLD_FLOW,_options.strOptions.fold)}function blockString(_ref3,ctx,onComment,onChompKeep){var comment=_ref3.comment,type=_ref3.type,value=_ref3.value;if(/\n[\t ]+$/.test(value)||/^\s*$/.test(value)){return doubleQuotedString(value,ctx)}var indent=ctx.indent||(ctx.forceBlockIndent?" ":"");var indentSize=indent?"2":"1";var literal=type===_constants.Type.BLOCK_FOLDED?false:type===_constants.Type.BLOCK_LITERAL?true:!lineLengthOverLimit(value,_options.strOptions.fold.lineWidth-indent.length);var header=literal?"|":">";if(!value)return header+"\n";var wsStart="";var wsEnd="";value=value.replace(/[\n\t ]*$/,(function(ws){var n=ws.indexOf("\n");if(n===-1){header+="-"}else if(value===ws||n!==ws.length-1){header+="+";if(onChompKeep)onChompKeep()}wsEnd=ws.replace(/\n$/,"");return""})).replace(/^[\n ]*/,(function(ws){if(ws.indexOf(" ")!==-1)header+=indentSize;var m=ws.match(/ +$/);if(m){wsStart=ws.slice(0,-m[0].length);return m[0]}else{wsStart=ws;return""}}));if(wsEnd)wsEnd=wsEnd.replace(/\n+(?!\n|$)/g,"$&".concat(indent));if(wsStart)wsStart=wsStart.replace(/\n+/g,"$&".concat(indent));if(comment){header+=" #"+comment.replace(/ ?[\r\n]+/g," ");if(onComment)onComment()}if(!value)return"".concat(header).concat(indentSize,"\n").concat(indent).concat(wsEnd);if(literal){value=value.replace(/\n+/g,"$&".concat(indent));return"".concat(header,"\n").concat(indent).concat(wsStart).concat(value).concat(wsEnd)}value=value.replace(/\n+/g,"\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,"$&".concat(indent));var body=(0,_foldFlowLines.default)("".concat(wsStart).concat(value).concat(wsEnd),indent,_foldFlowLines.FOLD_BLOCK,_options.strOptions.fold);return"".concat(header,"\n").concat(indent).concat(body)}function plainString(item,ctx,onComment,onChompKeep){var comment=item.comment,type=item.type,value=item.value;var actualString=ctx.actualString,implicitKey=ctx.implicitKey,indent=ctx.indent,inFlow=ctx.inFlow,tags=ctx.tags;if(implicitKey&&/[\n[\]{},]/.test(value)||inFlow&&/[[\]{},]/.test(value)){return doubleQuotedString(value,ctx)}if(!value||/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)){return implicitKey||inFlow||value.indexOf("\n")===-1?value.indexOf('"')!==-1&&value.indexOf("'")===-1?singleQuotedString(value,ctx):doubleQuotedString(value,ctx):blockString(item,ctx,onComment,onChompKeep)}if(!implicitKey&&!inFlow&&type!==_constants.Type.PLAIN&&value.indexOf("\n")!==-1){return blockString(item,ctx,onComment,onChompKeep)}var str=value.replace(/\n+/g,"$&\n".concat(indent));if(actualString&&typeof tags.resolveScalar(str).value!=="string"){return doubleQuotedString(value,ctx)}var body=implicitKey?str:(0,_foldFlowLines.default)(str,indent,_foldFlowLines.FOLD_FLOW,_options.strOptions.fold);if(comment&&!inFlow&&(body.indexOf("\n")!==-1||comment.indexOf("\n")!==-1)){if(onComment)onComment();return(0,_addComment.addCommentBefore)(body,indent,comment)}return body}function stringifyString(item,ctx,onComment,onChompKeep){var defaultType=_options.strOptions.defaultType;var implicitKey=ctx.implicitKey,inFlow=ctx.inFlow;var _item=item,type=_item.type,value=_item.value;if(typeof value!=="string"){value=String(value);item=Object.assign({},item,{value:value})}var _stringify=function _stringify(_type){switch(_type){case _constants.Type.BLOCK_FOLDED:case _constants.Type.BLOCK_LITERAL:return blockString(item,ctx,onComment,onChompKeep);case _constants.Type.QUOTE_DOUBLE:return doubleQuotedString(value,ctx);case _constants.Type.QUOTE_SINGLE:return singleQuotedString(value,ctx);case _constants.Type.PLAIN:return plainString(item,ctx,onComment,onChompKeep);default:return null}};if(type!==_constants.Type.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f]/.test(value)){type=_constants.Type.QUOTE_DOUBLE}else if((implicitKey||inFlow)&&(type===_constants.Type.BLOCK_FOLDED||type===_constants.Type.BLOCK_LITERAL)){type=_constants.Type.QUOTE_DOUBLE}var res=_stringify(type);if(res===null){res=_stringify(defaultType);if(res===null)throw new Error("Unsupported default string type ".concat(defaultType))}return res}},{"./addComment":219,"./constants":220,"./foldFlowLines":239,"./tags/options":262,"@babel/runtime/helpers/interopRequireWildcard":29}],255:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _Scalar=_interopRequireDefault(require("../schema/Scalar"));var _stringify=require("../stringify");var _failsafe=_interopRequireDefault(require("./failsafe"));var _options=require("./options");var _default=_failsafe.default.concat([{identify:function identify(value){return value==null},createNode:function createNode(schema,value,ctx){return ctx.wrapScalars?new _Scalar.default(null):null},default:true,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:function resolve(){return null},options:_options.nullOptions,stringify:function stringify(){return _options.nullOptions.nullStr}},{identify:function identify(value){return typeof value==="boolean"},default:true,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:function resolve(str){return str[0]==="t"||str[0]==="T"},options:_options.boolOptions,stringify:function stringify(_ref){var value=_ref.value;return value?_options.boolOptions.trueStr:_options.boolOptions.falseStr}},{identify:function identify(value){return typeof value==="number"},default:true,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o([0-7]+)$/,resolve:function resolve(str,oct){return parseInt(oct,8)},stringify:function stringify(_ref2){var value=_ref2.value;return"0o"+value.toString(8)}},{identify:function identify(value){return typeof value==="number"},default:true,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:function resolve(str){return parseInt(str,10)},stringify:_stringify.stringifyNumber},{identify:function identify(value){return typeof value==="number"},default:true,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x([0-9a-fA-F]+)$/,resolve:function resolve(str,hex){return parseInt(hex,16)},stringify:function stringify(_ref3){var value=_ref3.value;return"0x"+value.toString(16)}},{identify:function identify(value){return typeof value==="number"},default:true,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.inf|(\.nan))$/i,resolve:function resolve(str,nan){return nan?NaN:str[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY},stringify:_stringify.stringifyNumber},{identify:function identify(value){return typeof value==="number"},default:true,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:0|[1-9][0-9]*)(\.[0-9]*)?[eE][-+]?[0-9]+$/,resolve:function resolve(str){return parseFloat(str)},stringify:function stringify(_ref4){var value=_ref4.value;return Number(value).toExponential()}},{identify:function identify(value){return typeof value==="number"},default:true,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:0|[1-9][0-9]*)\.([0-9]*)$/,resolve:function resolve(str,frac){var node=new _Scalar.default(parseFloat(str));if(frac&&frac[frac.length-1]==="0")node.minFractionDigits=frac.length;return node},stringify:_stringify.stringifyNumber}]);exports.default=_default},{"../schema/Scalar":248,"../stringify":254,"./failsafe":256,"./options":262,"@babel/runtime/helpers/interopRequireDefault":28}],256:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _map=_interopRequireDefault(require("./map"));var _seq=_interopRequireDefault(require("./seq"));var _string=_interopRequireDefault(require("./string"));var _default=[_map.default,_seq.default,_string.default];exports.default=_default},{"./map":257,"./seq":258,"./string":259,"@babel/runtime/helpers/interopRequireDefault":28}],257:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _typeof2=_interopRequireDefault(require("@babel/runtime/helpers/typeof"));var _slicedToArray2=_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));var _Map=_interopRequireDefault(require("../../schema/Map"));var _parseMap=_interopRequireDefault(require("../../schema/parseMap"));function createMap(schema,obj,ctx){var map=new _Map.default;if(obj instanceof Map){var _iteratorNormalCompletion=true;var _didIteratorError=false;var _iteratorError=undefined;try{for(var _iterator=obj[Symbol.iterator](),_step;!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=true){var _step$value=(0,_slicedToArray2.default)(_step.value,2),key=_step$value[0],value=_step$value[1];map.items.push(schema.createPair(key,value,ctx))}}catch(err){_didIteratorError=true;_iteratorError=err}finally{try{if(!_iteratorNormalCompletion&&_iterator.return!=null){_iterator.return()}}finally{if(_didIteratorError){throw _iteratorError}}}}else if(obj&&(0,_typeof2.default)(obj)==="object"){for(var _i=0,_Object$keys=Object.keys(obj);_i<_Object$keys.length;_i++){var _key=_Object$keys[_i];map.items.push(schema.createPair(_key,obj[_key],ctx))}}return map}var _default={createNode:createMap,default:true,nodeClass:_Map.default,tag:"tag:yaml.org,2002:map",resolve:_parseMap.default};exports.default=_default},{"../../schema/Map":244,"../../schema/parseMap":251,"@babel/runtime/helpers/interopRequireDefault":28,"@babel/runtime/helpers/slicedToArray":36,"@babel/runtime/helpers/typeof":39}],258:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _parseSeq=_interopRequireDefault(require("../../schema/parseSeq"));var _Seq=_interopRequireDefault(require("../../schema/Seq"));function createSeq(schema,obj,ctx){var seq=new _Seq.default;if(obj&&obj[Symbol.iterator]){var _iteratorNormalCompletion=true;var _didIteratorError=false;var _iteratorError=undefined;try{for(var _iterator=obj[Symbol.iterator](),_step;!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=true){var it=_step.value;var v=schema.createNode(it,ctx.wrapScalars,null,ctx);seq.items.push(v)}}catch(err){_didIteratorError=true;_iteratorError=err}finally{try{if(!_iteratorNormalCompletion&&_iterator.return!=null){_iterator.return()}}finally{if(_didIteratorError){throw _iteratorError}}}}return seq}var _default={createNode:createSeq,default:true,nodeClass:_Seq.default,tag:"tag:yaml.org,2002:seq",resolve:_parseSeq.default};exports.default=_default},{"../../schema/Seq":249,"../../schema/parseSeq":252,"@babel/runtime/helpers/interopRequireDefault":28}],259:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=exports.resolveString=void 0;var _stringify=require("../../stringify");var _options=require("../options");var resolveString=function resolveString(doc,node){var res=node.strValue;if(!res)return"";if(typeof res==="string")return res;res.errors.forEach((function(error){if(!error.source)error.source=node;doc.errors.push(error)}));return res.str};exports.resolveString=resolveString;var _default={identify:function identify(value){return typeof value==="string"},default:true,tag:"tag:yaml.org,2002:str",resolve:resolveString,stringify:function stringify(item,ctx,onComment,onChompKeep){ctx=Object.assign({actualString:true},ctx);return(0,_stringify.stringifyString)(item,ctx,onComment,onChompKeep)},options:_options.strOptions};exports.default=_default},{"../../stringify":254,"../options":262}],260:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.tags=exports.schemas=void 0;var _core=_interopRequireDefault(require("./core"));var _failsafe=_interopRequireDefault(require("./failsafe"));var _json=_interopRequireDefault(require("./json"));var _yaml=_interopRequireDefault(require("./yaml-1.1"));var _map=_interopRequireDefault(require("./failsafe/map"));var _seq=_interopRequireDefault(require("./failsafe/seq"));var _binary=_interopRequireDefault(require("./yaml-1.1/binary"));var _omap=_interopRequireDefault(require("./yaml-1.1/omap"));var _pairs=_interopRequireDefault(require("./yaml-1.1/pairs"));var _set=_interopRequireDefault(require("./yaml-1.1/set"));var _timestamp=require("./yaml-1.1/timestamp");var schemas={core:_core.default,failsafe:_failsafe.default,json:_json.default,yaml11:_yaml.default};exports.schemas=schemas;var tags={binary:_binary.default,floatTime:_timestamp.floatTime,intTime:_timestamp.intTime,map:_map.default,omap:_omap.default,pairs:_pairs.default,seq:_seq.default,set:_set.default,timestamp:_timestamp.timestamp};exports.tags=tags},{"./core":255,"./failsafe":256,"./failsafe/map":257,"./failsafe/seq":258,"./json":261,"./yaml-1.1":264,"./yaml-1.1/binary":263,"./yaml-1.1/omap":265,"./yaml-1.1/pairs":266,"./yaml-1.1/set":267,"./yaml-1.1/timestamp":268,"@babel/runtime/helpers/interopRequireDefault":28}],261:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _map=_interopRequireDefault(require("./failsafe/map"));var _seq=_interopRequireDefault(require("./failsafe/seq"));var _Scalar=_interopRequireDefault(require("../schema/Scalar"));var _string=require("./failsafe/string");var schema=[_map.default,_seq.default,{identify:function identify(value){return typeof value==="string"},default:true,tag:"tag:yaml.org,2002:str",resolve:_string.resolveString,stringify:function stringify(value){return JSON.stringify(value)}},{identify:function identify(value){return value==null},createNode:function createNode(schema,value,ctx){return ctx.wrapScalars?new _Scalar.default(null):null},default:true,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:function resolve(){return null},stringify:function stringify(value){return JSON.stringify(value)}},{identify:function identify(value){return typeof value==="boolean"},default:true,tag:"tag:yaml.org,2002:bool",test:/^true$/,resolve:function resolve(){return true},stringify:function stringify(value){return JSON.stringify(value)}},{identify:function identify(value){return typeof value==="boolean"},default:true,tag:"tag:yaml.org,2002:bool",test:/^false$/,resolve:function resolve(){return false},stringify:function stringify(value){return JSON.stringify(value)}},{identify:function identify(value){return typeof value==="number"},default:true,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:function resolve(str){return parseInt(str,10)},stringify:function stringify(value){return JSON.stringify(value)}},{identify:function identify(value){return typeof value==="number"},default:true,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:function resolve(str){return parseFloat(str)},stringify:function stringify(value){return JSON.stringify(value)}}];schema.scalarFallback=function(str){throw new SyntaxError("Unresolved plain scalar ".concat(JSON.stringify(str)))};var _default=schema;exports.default=_default},{"../schema/Scalar":248,"./failsafe/map":257,"./failsafe/seq":258,"./failsafe/string":259,"@babel/runtime/helpers/interopRequireDefault":28}],262:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.strOptions=exports.nullOptions=exports.boolOptions=exports.binaryOptions=void 0;var _constants=require("../constants");var binaryOptions={defaultType:_constants.Type.BLOCK_LITERAL,lineWidth:76};exports.binaryOptions=binaryOptions;var boolOptions={trueStr:"true",falseStr:"false"};exports.boolOptions=boolOptions;var nullOptions={nullStr:"null"};exports.nullOptions=nullOptions;var strOptions={defaultType:_constants.Type.PLAIN,doubleQuoted:{jsonEncoding:false,minMultiLineLength:40},fold:{lineWidth:80,minContentWidth:20}};exports.strOptions=strOptions},{"../constants":220}],263:[function(require,module,exports){(function(Buffer){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _constants=require("../../constants");var _errors=require("../../errors");var _stringify=require("../../stringify");var _string=require("../failsafe/string");var _options=require("../options");var _default={identify:function identify(value){return value instanceof Uint8Array},default:false,tag:"tag:yaml.org,2002:binary",resolve:function resolve(doc,node){if(typeof Buffer==="function"){var src=(0,_string.resolveString)(doc,node);return Buffer.from(src,"base64")}else if(typeof atob==="function"){var _src=atob((0,_string.resolveString)(doc,node));var buffer=new Uint8Array(_src.length);for(var i=0;i<_src.length;++i){buffer[i]=_src.charCodeAt(i)}return buffer}else{doc.errors.push(new _errors.YAMLReferenceError(node,"This environment does not support reading binary tags; either Buffer or atob is required"));return null}},options:_options.binaryOptions,stringify:function stringify(_ref,ctx,onComment,onChompKeep){var comment=_ref.comment,type=_ref.type,value=_ref.value;var src;if(typeof Buffer==="function"){src=value instanceof Buffer?value.toString("base64"):Buffer.from(value.buffer).toString("base64")}else if(typeof btoa==="function"){var s="";for(var i=0;i<value.length;++i){s+=String.fromCharCode(value[i])}src=btoa(s)}else{throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required")}if(!type)type=_options.binaryOptions.defaultType;if(type===_constants.Type.QUOTE_DOUBLE){value=src}else{var lineWidth=_options.binaryOptions.lineWidth;var n=Math.ceil(src.length/lineWidth);var lines=new Array(n);for(var _i=0,o=0;_i<n;++_i,o+=lineWidth){lines[_i]=src.substr(o,lineWidth)}value=lines.join(type===_constants.Type.BLOCK_LITERAL?"\n":" ")}return(0,_stringify.stringifyString)({comment:comment,type:type,value:value},ctx,onComment,onChompKeep)}};exports.default=_default}).call(this,require("buffer").Buffer)},{"../../constants":220,"../../errors":238,"../../stringify":254,"../failsafe/string":259,"../options":262,buffer:75}],264:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _Scalar=_interopRequireDefault(require("../../schema/Scalar"));var _stringify=require("../../stringify");var _failsafe=_interopRequireDefault(require("../failsafe"));var _options=require("../options");var _binary=_interopRequireDefault(require("./binary"));var _omap=_interopRequireDefault(require("./omap"));var _pairs=_interopRequireDefault(require("./pairs"));var _set=_interopRequireDefault(require("./set"));var _timestamp=require("./timestamp");var _default=_failsafe.default.concat([{identify:function identify(value){return value==null},createNode:function createNode(schema,value,ctx){return ctx.wrapScalars?new _Scalar.default(null):null},default:true,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:function resolve(){return null},options:_options.nullOptions,stringify:function stringify(){return _options.nullOptions.nullStr}},{identify:function identify(value){return typeof value==="boolean"},default:true,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:function resolve(){return true},options:_options.boolOptions,stringify:function stringify(_ref){var value=_ref.value;return value?_options.boolOptions.trueStr:_options.boolOptions.falseStr}},{identify:function identify(value){return typeof value==="boolean"},default:true,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/i,resolve:function resolve(){return false},options:_options.boolOptions,stringify:function stringify(_ref2){var value=_ref2.value;return value?_options.boolOptions.trueStr:_options.boolOptions.falseStr}},{identify:function identify(value){return typeof value==="number"},default:true,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^0b([0-1_]+)$/,resolve:function resolve(str,bin){return parseInt(bin.replace(/_/g,""),2)},stringify:function stringify(_ref3){var value=_ref3.value;return"0b"+value.toString(2)}},{identify:function identify(value){return typeof value==="number"},default:true,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0([0-7_]+)$/,resolve:function resolve(str,oct){return parseInt(oct.replace(/_/g,""),8)},stringify:function stringify(_ref4){var value=_ref4.value;return(value<0?"-0":"0")+value.toString(8)}},{identify:function identify(value){return typeof value==="number"},default:true,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:function resolve(str){return parseInt(str.replace(/_/g,""),10)},stringify:_stringify.stringifyNumber},{identify:function identify(value){return typeof value==="number"},default:true,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x([0-9a-fA-F_]+)$/,resolve:function resolve(str,hex){return parseInt(hex.replace(/_/g,""),16)},stringify:function stringify(_ref5){var value=_ref5.value;return(value<0?"-0x":"0x")+value.toString(16)}},{identify:function identify(value){return typeof value==="number"},default:true,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.inf|(\.nan))$/i,resolve:function resolve(str,nan){return nan?NaN:str[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY},stringify:_stringify.stringifyNumber},{identify:function identify(value){return typeof value==="number"},default:true,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?([0-9][0-9_]*)?(\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:function resolve(str){return parseFloat(str.replace(/_/g,""))},stringify:function stringify(_ref6){var value=_ref6.value;return Number(value).toExponential()}},{identify:function identify(value){return typeof value==="number"},default:true,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.([0-9_]*)$/,resolve:function resolve(str,frac){var node=new _Scalar.default(parseFloat(str.replace(/_/g,"")));if(frac){var f=frac.replace(/_/g,"");if(f[f.length-1]==="0")node.minFractionDigits=f.length}return node},stringify:_stringify.stringifyNumber}],_binary.default,_omap.default,_pairs.default,_set.default,_timestamp.intTime,_timestamp.floatTime,_timestamp.timestamp);exports.default=_default},{"../../schema/Scalar":248,"../../stringify":254,"../failsafe":256,"../options":262,"./binary":263,"./omap":265,"./pairs":266,"./set":267,"./timestamp":268,"@babel/runtime/helpers/interopRequireDefault":28}],265:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=exports.YAMLOMap=void 0;var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));var _getPrototypeOf2=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));var _assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));var _inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits"));var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _errors=require("../../errors");var _toJSON2=_interopRequireDefault(require("../../toJSON"));var _Map=_interopRequireDefault(require("../../schema/Map"));var _Pair=_interopRequireDefault(require("../../schema/Pair"));var _Scalar=_interopRequireDefault(require("../../schema/Scalar"));var _Seq=_interopRequireDefault(require("../../schema/Seq"));var _pairs=require("./pairs");var YAMLOMap=function(_YAMLSeq){(0,_inherits2.default)(YAMLOMap,_YAMLSeq);function YAMLOMap(){var _this;(0,_classCallCheck2.default)(this,YAMLOMap);_this=(0,_possibleConstructorReturn2.default)(this,(0,_getPrototypeOf2.default)(YAMLOMap).call(this));(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"add",_Map.default.prototype.add.bind((0,_assertThisInitialized2.default)(_this)));(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"delete",_Map.default.prototype.delete.bind((0,_assertThisInitialized2.default)(_this)));(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"get",_Map.default.prototype.get.bind((0,_assertThisInitialized2.default)(_this)));(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"has",_Map.default.prototype.has.bind((0,_assertThisInitialized2.default)(_this)));(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"set",_Map.default.prototype.set.bind((0,_assertThisInitialized2.default)(_this)));_this.tag=YAMLOMap.tag;return _this}(0,_createClass2.default)(YAMLOMap,[{key:"toJSON",value:function toJSON(_,ctx){var map=new Map;if(ctx&&ctx.onCreate)ctx.onCreate(map);var _iteratorNormalCompletion=true;var _didIteratorError=false;var _iteratorError=undefined;try{for(var _iterator=this.items[Symbol.iterator](),_step;!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=true){var pair=_step.value;var key=void 0,value=void 0;if(pair instanceof _Pair.default){key=(0,_toJSON2.default)(pair.key,"",ctx);value=(0,_toJSON2.default)(pair.value,key,ctx)}else{key=(0,_toJSON2.default)(pair,"",ctx)}if(map.has(key))throw new Error("Ordered maps must not include duplicate keys");map.set(key,value)}}catch(err){_didIteratorError=true;_iteratorError=err}finally{try{if(!_iteratorNormalCompletion&&_iterator.return!=null){_iterator.return()}}finally{if(_didIteratorError){throw _iteratorError}}}return map}}]);return YAMLOMap}(_Seq.default);exports.YAMLOMap=YAMLOMap;(0,_defineProperty2.default)(YAMLOMap,"tag","tag:yaml.org,2002:omap");function parseOMap(doc,cst){var pairs=(0,_pairs.parsePairs)(doc,cst);var seenKeys=[];var _iteratorNormalCompletion2=true;var _didIteratorError2=false;var _iteratorError2=undefined;try{for(var _iterator2=pairs.items[Symbol.iterator](),_step2;!(_iteratorNormalCompletion2=(_step2=_iterator2.next()).done);_iteratorNormalCompletion2=true){var key=_step2.value.key;if(key instanceof _Scalar.default){if(seenKeys.includes(key.value)){var msg="Ordered maps must not include duplicate keys";throw new _errors.YAMLSemanticError(cst,msg)}else{seenKeys.push(key.value)}}}}catch(err){_didIteratorError2=true;_iteratorError2=err}finally{try{if(!_iteratorNormalCompletion2&&_iterator2.return!=null){_iterator2.return()}}finally{if(_didIteratorError2){throw _iteratorError2}}}return Object.assign(new YAMLOMap,pairs)}function createOMap(schema,iterable,ctx){var pairs=(0,_pairs.createPairs)(schema,iterable,ctx);var omap=new YAMLOMap;omap.items=pairs.items;return omap}var _default={identify:function identify(value){return value instanceof Map},nodeClass:YAMLOMap,default:false,tag:"tag:yaml.org,2002:omap",resolve:parseOMap,createNode:createOMap};exports.default=_default},{"../../errors":238,"../../schema/Map":244,"../../schema/Pair":247,"../../schema/Scalar":248,"../../schema/Seq":249,"../../toJSON":269,"./pairs":266,"@babel/runtime/helpers/assertThisInitialized":20,"@babel/runtime/helpers/classCallCheck":21,"@babel/runtime/helpers/createClass":23,"@babel/runtime/helpers/defineProperty":24,"@babel/runtime/helpers/getPrototypeOf":26,"@babel/runtime/helpers/inherits":27,"@babel/runtime/helpers/interopRequireDefault":28,"@babel/runtime/helpers/possibleConstructorReturn":34}],266:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.parsePairs=parsePairs;exports.createPairs=createPairs;exports.default=void 0;var _errors=require("../../errors");var _Map=_interopRequireDefault(require("../../schema/Map"));var _Pair=_interopRequireDefault(require("../../schema/Pair"));var _parseSeq=_interopRequireDefault(require("../../schema/parseSeq"));var _Seq=_interopRequireDefault(require("../../schema/Seq"));function parsePairs(doc,cst){var seq=(0,_parseSeq.default)(doc,cst);for(var i=0;i<seq.items.length;++i){var item=seq.items[i];if(item instanceof _Pair.default)continue;else if(item instanceof _Map.default){if(item.items.length>1){var msg="Each pair must have its own sequence indicator";throw new _errors.YAMLSemanticError(cst,msg)}var pair=item.items[0]||new _Pair.default;if(item.commentBefore)pair.commentBefore=pair.commentBefore?"".concat(item.commentBefore,"\n").concat(pair.commentBefore):item.commentBefore;if(item.comment)pair.comment=pair.comment?"".concat(item.comment,"\n").concat(pair.comment):item.comment;item=pair}seq.items[i]=item instanceof _Pair.default?item:new _Pair.default(item)}return seq}function createPairs(schema,iterable,ctx){var pairs=new _Seq.default;pairs.tag="tag:yaml.org,2002:pairs";var _iteratorNormalCompletion=true;var _didIteratorError=false;var _iteratorError=undefined;try{for(var _iterator=iterable[Symbol.iterator](),_step;!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=true){var it=_step.value;var key=void 0,value=void 0;if(Array.isArray(it)){if(it.length===2){key=it[0];value=it[1]}else throw new TypeError("Expected [key, value] tuple: ".concat(it))}else if(it&&it instanceof Object){var keys=Object.keys(it);if(keys.length===1){key=keys[0];value=it[key]}else throw new TypeError("Expected { key: value } tuple: ".concat(it))}else{key=it}var pair=schema.createPair(key,value,ctx);pairs.items.push(pair)}}catch(err){_didIteratorError=true;_iteratorError=err}finally{try{if(!_iteratorNormalCompletion&&_iterator.return!=null){_iterator.return()}}finally{if(_didIteratorError){throw _iteratorError}}}return pairs}var _default={default:false,tag:"tag:yaml.org,2002:pairs",resolve:parsePairs,createNode:createPairs};exports.default=_default},{"../../errors":238,"../../schema/Map":244,"../../schema/Pair":247,"../../schema/Seq":249,"../../schema/parseSeq":252,"@babel/runtime/helpers/interopRequireDefault":28}],267:[function(require,module,exports){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard");var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=exports.YAMLSet=void 0;var _typeof2=_interopRequireDefault(require("@babel/runtime/helpers/typeof"));var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));var _getPrototypeOf2=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));var _get2=_interopRequireDefault(require("@babel/runtime/helpers/get"));var _inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits"));var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _errors=require("../../errors");var _Map=_interopRequireWildcard(require("../../schema/Map"));var _Pair=_interopRequireDefault(require("../../schema/Pair"));var _parseMap=_interopRequireDefault(require("../../schema/parseMap"));var _Scalar=_interopRequireDefault(require("../../schema/Scalar"));var YAMLSet=function(_YAMLMap){(0,_inherits2.default)(YAMLSet,_YAMLMap);function YAMLSet(){var _this;(0,_classCallCheck2.default)(this,YAMLSet);_this=(0,_possibleConstructorReturn2.default)(this,(0,_getPrototypeOf2.default)(YAMLSet).call(this));_this.tag=YAMLSet.tag;return _this}(0,_createClass2.default)(YAMLSet,[{key:"add",value:function add(key){var pair=key instanceof _Pair.default?key:new _Pair.default(key);var prev=(0,_Map.findPair)(this.items,pair.key);if(!prev)this.items.push(pair)}},{key:"get",value:function get(key,keepPair){var pair=(0,_Map.findPair)(this.items,key);return!keepPair&&pair instanceof _Pair.default?pair.key instanceof _Scalar.default?pair.key.value:pair.key:pair}},{key:"set",value:function set(key,value){if(typeof value!=="boolean")throw new Error("Expected boolean value for set(key, value) in a YAML set, not ".concat((0,_typeof2.default)(value)));var prev=(0,_Map.findPair)(this.items,key);if(prev&&!value){this.items.splice(this.items.indexOf(prev),1)}else if(!prev&&value){this.items.push(new _Pair.default(key))}}},{key:"toJSON",value:function toJSON(_,ctx){return(0,_get2.default)((0,_getPrototypeOf2.default)(YAMLSet.prototype),"toJSON",this).call(this,_,ctx,Set)}},{key:"toString",value:function toString(ctx,onComment,onChompKeep){if(!ctx)return JSON.stringify(this);if(this.hasAllNullValues())return(0,_get2.default)((0,_getPrototypeOf2.default)(YAMLSet.prototype),"toString",this).call(this,ctx,onComment,onChompKeep);else throw new Error("Set items must all have null values")}}]);return YAMLSet}(_Map.default);exports.YAMLSet=YAMLSet;(0,_defineProperty2.default)(YAMLSet,"tag","tag:yaml.org,2002:set");function parseSet(doc,cst){var map=(0,_parseMap.default)(doc,cst);if(!map.hasAllNullValues())throw new _errors.YAMLSemanticError(cst,"Set items must all have null values");return Object.assign(new YAMLSet,map)}function createSet(schema,iterable,ctx){var set=new YAMLSet;var _iteratorNormalCompletion=true;var _didIteratorError=false;var _iteratorError=undefined;try{for(var _iterator=iterable[Symbol.iterator](),_step;!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=true){var value=_step.value;set.items.push(schema.createPair(value,null,ctx))}}catch(err){_didIteratorError=true;_iteratorError=err}finally{try{if(!_iteratorNormalCompletion&&_iterator.return!=null){_iterator.return()}}finally{if(_didIteratorError){throw _iteratorError}}}return set}var _default={identify:function identify(value){return value instanceof Set},nodeClass:YAMLSet,default:false,tag:"tag:yaml.org,2002:set",resolve:parseSet,createNode:createSet};exports.default=_default},{"../../errors":238,"../../schema/Map":244,"../../schema/Pair":247,"../../schema/Scalar":248,"../../schema/parseMap":251,"@babel/runtime/helpers/classCallCheck":21,"@babel/runtime/helpers/createClass":23,"@babel/runtime/helpers/defineProperty":24,"@babel/runtime/helpers/get":25,"@babel/runtime/helpers/getPrototypeOf":26,"@babel/runtime/helpers/inherits":27,"@babel/runtime/helpers/interopRequireDefault":28,"@babel/runtime/helpers/interopRequireWildcard":29,"@babel/runtime/helpers/possibleConstructorReturn":34,"@babel/runtime/helpers/typeof":39}],268:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.timestamp=exports.floatTime=exports.intTime=void 0;var _stringify=require("../../stringify");var parseSexagesimal=function parseSexagesimal(sign,parts){var n=parts.split(":").reduce((function(n,p){return n*60+Number(p)}),0);return sign==="-"?-n:n};var stringifySexagesimal=function stringifySexagesimal(_ref){var value=_ref.value;if(isNaN(value)||!isFinite(value))return(0,_stringify.stringifyNumber)(value);var sign="";if(value<0){sign="-";value=Math.abs(value)}var parts=[value%60];if(value<60){parts.unshift(0)}else{value=Math.round((value-parts[0])/60);parts.unshift(value%60);if(value>=60){value=Math.round((value-parts[0])/60);parts.unshift(value)}}return sign+parts.map((function(n){return n<10?"0"+String(n):String(n)})).join(":").replace(/000000\d*$/,"")};var intTime={identify:function identify(value){return typeof value==="number"},default:true,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+)$/,resolve:function resolve(str,sign,parts){return parseSexagesimal(sign,parts.replace(/_/g,""))},stringify:stringifySexagesimal};exports.intTime=intTime;var floatTime={identify:function identify(value){return typeof value==="number"},default:true,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*)$/,resolve:function resolve(str,sign,parts){return parseSexagesimal(sign,parts.replace(/_/g,""))},stringify:stringifySexagesimal};exports.floatTime=floatTime;var timestamp={identify:function identify(value){return value instanceof Date},default:true,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^(?:"+"([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})"+"(?:(?:t|T|[ \\t]+)"+"([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)"+"(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?"+")?"+")$"),resolve:function resolve(str,year,month,day,hour,minute,second,millisec,tz){if(millisec)millisec=(millisec+"00").substr(1,3);var date=Date.UTC(year,month-1,day,hour||0,minute||0,second||0,millisec||0);if(tz&&tz!=="Z"){var d=parseSexagesimal(tz[0],tz.slice(1));if(Math.abs(d)<30)d*=60;date-=6e4*d}return new Date(date)},stringify:function stringify(_ref2){var value=_ref2.value;return value.toISOString().replace(/((T00:00)?:00)?\.000Z$/,"")}};exports.timestamp=timestamp},{"../../stringify":254}],269:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=toJSON;function toJSON(value,arg,ctx){if(Array.isArray(value))return value.map((function(v,i){return toJSON(v,String(i),ctx)}));if(value&&typeof value.toJSON==="function"){var anchor=ctx&&ctx.anchors&&ctx.anchors.find((function(a){return a.node===value}));if(anchor)ctx.onCreate=function(res){anchor.res=res;delete ctx.onCreate};var res=value.toJSON(arg,ctx);if(anchor&&ctx.onCreate)ctx.onCreate(res);return res}return value}},{}],270:[function(require,module,exports){(function(global){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.warn=warn;exports.warnFileDeprecation=warnFileDeprecation;exports.warnOptionDeprecation=warnOptionDeprecation;function warn(warning,type){if(global&&global._YAML_SILENCE_WARNINGS)return;var _ref=global&&global.process,emitWarning=_ref.emitWarning;if(emitWarning)emitWarning(warning,type);else{console.warn(type?"".concat(type,": ").concat(warning):warning)}}function warnFileDeprecation(filename){if(global&&global._YAML_SILENCE_DEPRECATION_WARNINGS)return;var path=filename.replace(/.*yaml[/\\]/i,"").replace(/\.js$/,"").replace(/\\/g,"/");warn("The endpoint 'yaml/".concat(path,"' will be removed in a future release."),"DeprecationWarning")}var warned={};function warnOptionDeprecation(name,alternative){if(global&&global._YAML_SILENCE_DEPRECATION_WARNINGS)return;if(warned[name])return;warned[name]=true;var msg="The option '".concat(name,"' will be removed in a future release");msg+=alternative?", use '".concat(alternative,"' instead."):".";warn(msg,"DeprecationWarning")}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],271:[function(require,module,exports){module.exports=require("./dist").default},{"./dist":240}]},{},[17]);
|
|
39
|
+
*/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))}},{}],122:[function(require,module,exports){"use strict";var toString={}.toString;module.exports=Array.isArray||function(arr){return toString.call(arr)=="[object Array]"}},{}],123:[function(require,module,exports){"use strict";function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}module.exports=sizeof;function sizeof(object){var objects=[object];var processed=[];var size=0;for(var index=0;index<objects.length;++index){var _object=objects[index];switch(_typeof(_object)){case"boolean":size+=4;break;case"number":size+=8;break;case"string":size+=2*_object.length;break;case"object":if(_object===null){size+=4;break}var keySizeFactor=Array.isArray(_object)?0:1;for(var key in _object){size+=keySizeFactor*2*key.length;if(processed.indexOf(_object[key])===-1){objects.push(_object[key]);if(_typeof(_object[key])==="object"){processed.push(_object[key])}}}break}}return size}},{}],124:[function(require,module,exports){"use strict";function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}(function(root,definition){"use strict";if(typeof define==="function"&&define.amd){define(definition)}else if((typeof module==="undefined"?"undefined":_typeof(module))==="object"&&module.exports){module.exports=definition()}else{root.log=definition()}})(void 0,(function(){"use strict";var noop=function noop(){};var undefinedType="undefined";var isIE=(typeof window==="undefined"?"undefined":_typeof(window))!==undefinedType&&_typeof(window.navigator)!==undefinedType&&/Trident\/|MSIE /.test(window.navigator.userAgent);var logMethods=["trace","debug","info","warn","error"];function bindMethod(obj,methodName){var method=obj[methodName];if(typeof method.bind==="function"){return method.bind(obj)}else{try{return Function.prototype.bind.call(method,obj)}catch(e){return function(){return Function.prototype.apply.apply(method,[obj,arguments])}}}}function traceForIE(){if(console.log){if(console.log.apply){console.log.apply(console,arguments)}else{Function.prototype.apply.apply(console.log,[console,arguments])}}if(console.trace)console.trace()}function realMethod(methodName){if(methodName==="debug"){methodName="log"}if((typeof console==="undefined"?"undefined":_typeof(console))===undefinedType){return false}else if(methodName==="trace"&&isIE){return traceForIE}else if(console[methodName]!==undefined){return bindMethod(console,methodName)}else if(console.log!==undefined){return bindMethod(console,"log")}else{return noop}}function replaceLoggingMethods(level,loggerName){for(var i=0;i<logMethods.length;i++){var methodName=logMethods[i];this[methodName]=i<level?noop:this.methodFactory(methodName,level,loggerName)}this.log=this.debug}function enableLoggingWhenConsoleArrives(methodName,level,loggerName){return function(){if((typeof console==="undefined"?"undefined":_typeof(console))!==undefinedType){replaceLoggingMethods.call(this,level,loggerName);this[methodName].apply(this,arguments)}}}function defaultMethodFactory(methodName,level,loggerName){return realMethod(methodName)||enableLoggingWhenConsoleArrives.apply(this,arguments)}function Logger(name,defaultLevel,factory){var self=this;var currentLevel;var storageKey="loglevel";if(name){storageKey+=":"+name}function persistLevelIfPossible(levelNum){var levelName=(logMethods[levelNum]||"silent").toUpperCase();if((typeof window==="undefined"?"undefined":_typeof(window))===undefinedType)return;try{window.localStorage[storageKey]=levelName;return}catch(ignore){}try{window.document.cookie=encodeURIComponent(storageKey)+"="+levelName+";"}catch(ignore){}}function getPersistedLevel(){var storedLevel;if((typeof window==="undefined"?"undefined":_typeof(window))===undefinedType)return;try{storedLevel=window.localStorage[storageKey]}catch(ignore){}if(_typeof(storedLevel)===undefinedType){try{var cookie=window.document.cookie;var location=cookie.indexOf(encodeURIComponent(storageKey)+"=");if(location!==-1){storedLevel=/^([^;]+)/.exec(cookie.slice(location))[1]}}catch(ignore){}}if(self.levels[storedLevel]===undefined){storedLevel=undefined}return storedLevel}self.name=name;self.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5};self.methodFactory=factory||defaultMethodFactory;self.getLevel=function(){return currentLevel};self.setLevel=function(level,persist){if(typeof level==="string"&&self.levels[level.toUpperCase()]!==undefined){level=self.levels[level.toUpperCase()]}if(typeof level==="number"&&level>=0&&level<=self.levels.SILENT){currentLevel=level;if(persist!==false){persistLevelIfPossible(level)}replaceLoggingMethods.call(self,level,name);if((typeof console==="undefined"?"undefined":_typeof(console))===undefinedType&&level<self.levels.SILENT){return"No console available for logging"}}else{throw"log.setLevel() called with invalid level: "+level}};self.setDefaultLevel=function(level){if(!getPersistedLevel()){self.setLevel(level,false)}};self.enableAll=function(persist){self.setLevel(self.levels.TRACE,persist)};self.disableAll=function(persist){self.setLevel(self.levels.SILENT,persist)};var initialLevel=getPersistedLevel();if(initialLevel==null){initialLevel=defaultLevel==null?"WARN":defaultLevel}self.setLevel(initialLevel,false)}var defaultLogger=new Logger;var _loggersByName={};defaultLogger.getLogger=function getLogger(name){if(typeof name!=="string"||name===""){throw new TypeError("You must supply a name when creating a logger.")}var logger=_loggersByName[name];if(!logger){logger=_loggersByName[name]=new Logger(name,defaultLogger.getLevel(),defaultLogger.methodFactory)}return logger};var _log=(typeof window==="undefined"?"undefined":_typeof(window))!==undefinedType?window.log:undefined;defaultLogger.noConflict=function(){if((typeof window==="undefined"?"undefined":_typeof(window))!==undefinedType&&window.log===defaultLogger){window.log=_log}return defaultLogger};defaultLogger.getLoggers=function getLoggers(){return _loggersByName};return defaultLogger}))},{}],125:[function(require,module,exports){(function(Buffer){"use strict";var protocol=module.exports;protocol.types={0:"reserved",1:"connect",2:"connack",3:"publish",4:"puback",5:"pubrec",6:"pubrel",7:"pubcomp",8:"subscribe",9:"suback",10:"unsubscribe",11:"unsuback",12:"pingreq",13:"pingresp",14:"disconnect",15:"auth"};protocol.codes={};for(var k in protocol.types){var v=protocol.types[k];protocol.codes[v]=k}protocol.CMD_SHIFT=4;protocol.CMD_MASK=240;protocol.DUP_MASK=8;protocol.QOS_MASK=3;protocol.QOS_SHIFT=1;protocol.RETAIN_MASK=1;protocol.VARBYTEINT_MASK=127;protocol.VARBYTEINT_FIN_MASK=128;protocol.SESSIONPRESENT_MASK=1;protocol.SESSIONPRESENT_HEADER=Buffer.from([protocol.SESSIONPRESENT_MASK]);protocol.CONNACK_HEADER=Buffer.from([protocol.codes.connack<<protocol.CMD_SHIFT]);protocol.USERNAME_MASK=128;protocol.PASSWORD_MASK=64;protocol.WILL_RETAIN_MASK=32;protocol.WILL_QOS_MASK=24;protocol.WILL_QOS_SHIFT=3;protocol.WILL_FLAG_MASK=4;protocol.CLEAN_SESSION_MASK=2;protocol.CONNECT_HEADER=Buffer.from([protocol.codes.connect<<protocol.CMD_SHIFT]);protocol.properties={sessionExpiryInterval:17,willDelayInterval:24,receiveMaximum:33,maximumPacketSize:39,topicAliasMaximum:34,requestResponseInformation:25,requestProblemInformation:23,userProperties:38,authenticationMethod:21,authenticationData:22,payloadFormatIndicator:1,messageExpiryInterval:2,contentType:3,responseTopic:8,correlationData:9,maximumQoS:36,retainAvailable:37,assignedClientIdentifier:18,reasonString:31,wildcardSubscriptionAvailable:40,subscriptionIdentifiersAvailable:41,sharedSubscriptionAvailable:42,serverKeepAlive:19,responseInformation:26,serverReference:28,topicAlias:35,subscriptionIdentifier:11};protocol.propertiesCodes={};for(var prop in protocol.properties){var id=protocol.properties[prop];protocol.propertiesCodes[id]=prop}protocol.propertiesTypes={sessionExpiryInterval:"int32",willDelayInterval:"int32",receiveMaximum:"int16",maximumPacketSize:"int32",topicAliasMaximum:"int16",requestResponseInformation:"byte",requestProblemInformation:"byte",userProperties:"pair",authenticationMethod:"string",authenticationData:"binary",payloadFormatIndicator:"byte",messageExpiryInterval:"int32",contentType:"string",responseTopic:"string",correlationData:"binary",maximumQoS:"int8",retainAvailable:"byte",assignedClientIdentifier:"string",reasonString:"string",wildcardSubscriptionAvailable:"byte",subscriptionIdentifiersAvailable:"byte",sharedSubscriptionAvailable:"byte",serverKeepAlive:"int16",responseInformation:"string",serverReference:"string",topicAlias:"int16",subscriptionIdentifier:"var"};function genHeader(type){return[0,1,2].map((function(qos){return[0,1].map((function(dup){return[0,1].map((function(retain){var buf=Buffer.alloc(1);buf.writeUInt8(protocol.codes[type]<<protocol.CMD_SHIFT|(dup?protocol.DUP_MASK:0)|qos<<protocol.QOS_SHIFT|retain,0,true);return buf}))}))}))}protocol.PUBLISH_HEADER=genHeader("publish");protocol.SUBSCRIBE_HEADER=genHeader("subscribe");protocol.SUBSCRIBE_OPTIONS_QOS_MASK=3;protocol.SUBSCRIBE_OPTIONS_NL_MASK=1;protocol.SUBSCRIBE_OPTIONS_NL_SHIFT=2;protocol.SUBSCRIBE_OPTIONS_RAP_MASK=1;protocol.SUBSCRIBE_OPTIONS_RAP_SHIFT=3;protocol.SUBSCRIBE_OPTIONS_RH_MASK=3;protocol.SUBSCRIBE_OPTIONS_RH_SHIFT=4;protocol.SUBSCRIBE_OPTIONS_RH=[0,16,32];protocol.SUBSCRIBE_OPTIONS_NL=4;protocol.SUBSCRIBE_OPTIONS_RAP=8;protocol.SUBSCRIBE_OPTIONS_QOS=[0,1,2];protocol.UNSUBSCRIBE_HEADER=genHeader("unsubscribe");protocol.ACKS={unsuback:genHeader("unsuback"),puback:genHeader("puback"),pubcomp:genHeader("pubcomp"),pubrel:genHeader("pubrel"),pubrec:genHeader("pubrec")};protocol.SUBACK_HEADER=Buffer.from([protocol.codes.suback<<protocol.CMD_SHIFT]);protocol.VERSION3=Buffer.from([3]);protocol.VERSION4=Buffer.from([4]);protocol.VERSION5=Buffer.from([5]);protocol.QOS=[0,1,2].map((function(qos){return Buffer.from([qos])}));protocol.EMPTY={pingreq:Buffer.from([protocol.codes.pingreq<<4,0]),pingresp:Buffer.from([protocol.codes.pingresp<<4,0]),disconnect:Buffer.from([protocol.codes.disconnect<<4,0])}}).call(this,require("buffer").Buffer)},{buffer:33}],126:[function(require,module,exports){(function(Buffer){"use strict";function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function")}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:true,configurable:true}});if(superClass)_setPrototypeOf(subClass,superClass)}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o};return _setPrototypeOf(o,p)}function _createSuper(Derived){var hasNativeReflectConstruct=_isNativeReflectConstruct();return function _createSuperInternal(){var Super=_getPrototypeOf(Derived),result;if(hasNativeReflectConstruct){var NewTarget=_getPrototypeOf(this).constructor;result=Reflect.construct(Super,arguments,NewTarget)}else{result=Super.apply(this,arguments)}return _possibleConstructorReturn(this,result)}}function _possibleConstructorReturn(self,call){if(call&&(_typeof(call)==="object"||typeof call==="function")){return call}return _assertThisInitialized(self)}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return self}function _isNativeReflectConstruct(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{Date.prototype.toString.call(Reflect.construct(Date,[],(function(){})));return true}catch(e){return false}}function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o)};return _getPrototypeOf(o)}var writeToStream=require("./writeToStream");var EventEmitter=require("events");function generate(packet,opts){var stream=new Accumulator;writeToStream(packet,stream,opts);return stream.concat()}var Accumulator=function(_EventEmitter){_inherits(Accumulator,_EventEmitter);var _super=_createSuper(Accumulator);function Accumulator(){var _this;_classCallCheck(this,Accumulator);_this=_super.call(this);_this._array=new Array(20);_this._i=0;return _this}_createClass(Accumulator,[{key:"write",value:function write(chunk){this._array[this._i++]=chunk;return true}},{key:"concat",value:function concat(){var length=0;var lengths=new Array(this._array.length);var list=this._array;var pos=0;var i;for(i=0;i<list.length&&list[i]!==undefined;i++){if(typeof list[i]!=="string")lengths[i]=list[i].length;else lengths[i]=Buffer.byteLength(list[i]);length+=lengths[i]}var result=Buffer.allocUnsafe(length);for(i=0;i<list.length&&list[i]!==undefined;i++){if(typeof list[i]!=="string"){list[i].copy(result,pos);pos+=lengths[i]}else{result.write(list[i],pos);pos+=lengths[i]}}return result}}]);return Accumulator}(EventEmitter);module.exports=generate}).call(this,require("buffer").Buffer)},{"./writeToStream":134,buffer:33,events:34}],127:[function(require,module,exports){"use strict";exports.parser=require("./parser").parser;exports.generate=require("./generate");exports.writeToStream=require("./writeToStream")},{"./generate":126,"./parser":133,"./writeToStream":134}],128:[function(require,module,exports){(function(process){"use strict";exports.formatArgs=formatArgs;exports.save=save;exports.load=load;exports.useColors=useColors;exports.storage=localstorage();exports.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function useColors(){if(typeof window!=="undefined"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)){return true}if(typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)){return false}return typeof document!=="undefined"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window!=="undefined"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function formatArgs(args){args[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+args[0]+(this.useColors?"%c ":" ")+"+"+module.exports.humanize(this.diff);if(!this.useColors){return}var c="color: "+this.color;args.splice(1,0,c,"color: inherit");var index=0;var lastC=0;args[0].replace(/%[a-zA-Z%]/g,(function(match){if(match==="%%"){return}index++;if(match==="%c"){lastC=index}}));args.splice(lastC,0,c)}exports.log=console.debug||console.log||function(){};function save(namespaces){try{if(namespaces){exports.storage.setItem("debug",namespaces)}else{exports.storage.removeItem("debug")}}catch(error){}}function load(){var r;try{r=exports.storage.getItem("debug")}catch(error){}if(!r&&typeof process!=="undefined"&&"env"in process){r=process.env.DEBUG}return r}function localstorage(){try{return localStorage}catch(error){}}module.exports=require("./common")(exports);var formatters=module.exports.formatters;formatters.j=function(v){try{return JSON.stringify(v)}catch(error){return"[UnexpectedJSONParseError]: "+error.message}}}).call(this,require("_process"))},{"./common":129,_process:157}],129:[function(require,module,exports){"use strict";function _toConsumableArray(arr){return _arrayWithoutHoles(arr)||_iterableToArray(arr)||_unsupportedIterableToArray(arr)||_nonIterableSpread()}function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen)}function _iterableToArray(iter){if(typeof Symbol!=="undefined"&&Symbol.iterator in Object(iter))return Array.from(iter)}function _arrayWithoutHoles(arr){if(Array.isArray(arr))return _arrayLikeToArray(arr)}function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i<len;i++){arr2[i]=arr[i]}return arr2}function setup(env){createDebug.debug=createDebug;createDebug["default"]=createDebug;createDebug.coerce=coerce;createDebug.disable=disable;createDebug.enable=enable;createDebug.enabled=enabled;createDebug.humanize=require("ms");Object.keys(env).forEach((function(key){createDebug[key]=env[key]}));createDebug.instances=[];createDebug.names=[];createDebug.skips=[];createDebug.formatters={};function selectColor(namespace){var hash=0;for(var i=0;i<namespace.length;i++){hash=(hash<<5)-hash+namespace.charCodeAt(i);hash|=0}return createDebug.colors[Math.abs(hash)%createDebug.colors.length]}createDebug.selectColor=selectColor;function createDebug(namespace){var prevTime;function debug(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key]}if(!debug.enabled){return}var self=debug;var curr=Number(new Date);var ms=curr-(prevTime||curr);self.diff=ms;self.prev=prevTime;self.curr=curr;prevTime=curr;args[0]=createDebug.coerce(args[0]);if(typeof args[0]!=="string"){args.unshift("%O")}var index=0;args[0]=args[0].replace(/%([a-zA-Z%])/g,(function(match,format){if(match==="%%"){return match}index++;var formatter=createDebug.formatters[format];if(typeof formatter==="function"){var val=args[index];match=formatter.call(self,val);args.splice(index,1);index--}return match}));createDebug.formatArgs.call(self,args);var logFn=self.log||createDebug.log;logFn.apply(self,args)}debug.namespace=namespace;debug.enabled=createDebug.enabled(namespace);debug.useColors=createDebug.useColors();debug.color=createDebug.selectColor(namespace);debug.destroy=destroy;debug.extend=extend;if(typeof createDebug.init==="function"){createDebug.init(debug)}createDebug.instances.push(debug);return debug}function destroy(){var index=createDebug.instances.indexOf(this);if(index!==-1){createDebug.instances.splice(index,1);return true}return false}function extend(namespace,delimiter){var newDebug=createDebug(this.namespace+(typeof delimiter==="undefined"?":":delimiter)+namespace);newDebug.log=this.log;return newDebug}function enable(namespaces){createDebug.save(namespaces);createDebug.names=[];createDebug.skips=[];var i;var split=(typeof namespaces==="string"?namespaces:"").split(/[\s,]+/);var len=split.length;for(i=0;i<len;i++){if(!split[i]){continue}namespaces=split[i].replace(/\*/g,".*?");if(namespaces[0]==="-"){createDebug.skips.push(new RegExp("^"+namespaces.substr(1)+"$"))}else{createDebug.names.push(new RegExp("^"+namespaces+"$"))}}for(i=0;i<createDebug.instances.length;i++){var instance=createDebug.instances[i];instance.enabled=createDebug.enabled(instance.namespace)}}function disable(){var namespaces=[].concat(_toConsumableArray(createDebug.names.map(toNamespace)),_toConsumableArray(createDebug.skips.map(toNamespace).map((function(namespace){return"-"+namespace})))).join(",");createDebug.enable("");return namespaces}function enabled(name){if(name[name.length-1]==="*"){return true}var i;var len;for(i=0,len=createDebug.skips.length;i<len;i++){if(createDebug.skips[i].test(name)){return false}}for(i=0,len=createDebug.names.length;i<len;i++){if(createDebug.names[i].test(name)){return true}}return false}function toNamespace(regexp){return regexp.toString().substring(2,regexp.toString().length-2).replace(/\.\*\?$/,"*")}function coerce(val){if(val instanceof Error){return val.stack||val.message}return val}createDebug.enable(createDebug.load());return createDebug}module.exports=setup},{ms:130}],130:[function(require,module,exports){"use strict";function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}var s=1e3;var m=s*60;var h=m*60;var d=h*24;var w=d*7;var y=d*365.25;module.exports=function(val,options){options=options||{};var type=_typeof(val);if(type==="string"&&val.length>0){return parse(val)}else if(type==="number"&&isFinite(val)){return options["long"]?fmtLong(val):fmtShort(val)}throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(val))};function parse(str){str=String(str);if(str.length>100){return}var match=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str);if(!match){return}var n=parseFloat(match[1]);var type=(match[2]||"ms").toLowerCase();switch(type){case"years":case"year":case"yrs":case"yr":case"y":return n*y;case"weeks":case"week":case"w":return n*w;case"days":case"day":case"d":return n*d;case"hours":case"hour":case"hrs":case"hr":case"h":return n*h;case"minutes":case"minute":case"mins":case"min":case"m":return n*m;case"seconds":case"second":case"secs":case"sec":case"s":return n*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return undefined}}function fmtShort(ms){var msAbs=Math.abs(ms);if(msAbs>=d){return Math.round(ms/d)+"d"}if(msAbs>=h){return Math.round(ms/h)+"h"}if(msAbs>=m){return Math.round(ms/m)+"m"}if(msAbs>=s){return Math.round(ms/s)+"s"}return ms+"ms"}function fmtLong(ms){var msAbs=Math.abs(ms);if(msAbs>=d){return plural(ms,msAbs,d,"day")}if(msAbs>=h){return plural(ms,msAbs,h,"hour")}if(msAbs>=m){return plural(ms,msAbs,m,"minute")}if(msAbs>=s){return plural(ms,msAbs,s,"second")}return ms+" ms"}function plural(ms,msAbs,n,name){var isPlural=msAbs>=n*1.5;return Math.round(ms/n)+" "+name+(isPlural?"s":"")}},{}],131:[function(require,module,exports){(function(Buffer){"use strict";var max=65536;var cache={};var SubOk=Buffer.isBuffer(Buffer.from([1,2]).subarray(0,1));function generateBuffer(i){var buffer=Buffer.allocUnsafe(2);buffer.writeUInt8(i>>8,0);buffer.writeUInt8(i&255,0+1);return buffer}function generateCache(){for(var i=0;i<max;i++){cache[i]=generateBuffer(i)}}function genBufVariableByteInt(num){var maxLength=4;var digit=0;var pos=0;var buffer=Buffer.allocUnsafe(maxLength);do{digit=num%128|0;num=num/128|0;if(num>0)digit=digit|128;buffer.writeUInt8(digit,pos++)}while(num>0&&pos<maxLength);if(num>0){pos=0}return SubOk?buffer.subarray(0,pos):buffer.slice(0,pos)}function generate4ByteBuffer(num){var buffer=Buffer.allocUnsafe(4);buffer.writeUInt32BE(num,0);return buffer}module.exports={cache:cache,generateCache:generateCache,generateNumber:generateBuffer,genBufVariableByteInt:genBufVariableByteInt,generate4ByteBuffer:generate4ByteBuffer}}).call(this,require("buffer").Buffer)},{buffer:33}],132:[function(require,module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var Packet=function Packet(){_classCallCheck(this,Packet);this.cmd=null;this.retain=false;this.qos=0;this.dup=false;this.length=-1;this.topic=null;this.payload=null};module.exports=Packet},{}],133:[function(require,module,exports){"use strict";function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function")}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:true,configurable:true}});if(superClass)_setPrototypeOf(subClass,superClass)}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o};return _setPrototypeOf(o,p)}function _createSuper(Derived){var hasNativeReflectConstruct=_isNativeReflectConstruct();return function _createSuperInternal(){var Super=_getPrototypeOf(Derived),result;if(hasNativeReflectConstruct){var NewTarget=_getPrototypeOf(this).constructor;result=Reflect.construct(Super,arguments,NewTarget)}else{result=Super.apply(this,arguments)}return _possibleConstructorReturn(this,result)}}function _possibleConstructorReturn(self,call){if(call&&(_typeof(call)==="object"||typeof call==="function")){return call}return _assertThisInitialized(self)}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return self}function _isNativeReflectConstruct(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{Date.prototype.toString.call(Reflect.construct(Date,[],(function(){})));return true}catch(e){return false}}function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o)};return _getPrototypeOf(o)}var bl=require("bl");var EventEmitter=require("events");var Packet=require("./packet");var constants=require("./constants");var debug=require("debug")("mqtt-packet:parser");var Parser=function(_EventEmitter){_inherits(Parser,_EventEmitter);var _super=_createSuper(Parser);function Parser(){var _this;_classCallCheck(this,Parser);_this=_super.call(this);_this.parser=_this.constructor.parser;return _this}_createClass(Parser,[{key:"_resetState",value:function _resetState(){debug("_resetState: resetting packet, error, _list, and _stateCounter");this.packet=new Packet;this.error=null;this._list=bl();this._stateCounter=0}},{key:"parse",value:function parse(buf){if(this.error)this._resetState();this._list.append(buf);debug("parse: current state: %s",this._states[this._stateCounter]);while((this.packet.length!==-1||this._list.length>0)&&this[this._states[this._stateCounter]]()&&!this.error){this._stateCounter++;debug("parse: state complete. _stateCounter is now: %d",this._stateCounter);debug("parse: packet.length: %d, buffer list length: %d",this.packet.length,this._list.length);if(this._stateCounter>=this._states.length)this._stateCounter=0}debug("parse: exited while loop. packet: %d, buffer list length: %d",this.packet.length,this._list.length);return this._list.length}},{key:"_parseHeader",value:function _parseHeader(){var zero=this._list.readUInt8(0);this.packet.cmd=constants.types[zero>>constants.CMD_SHIFT];this.packet.retain=(zero&constants.RETAIN_MASK)!==0;this.packet.qos=zero>>constants.QOS_SHIFT&constants.QOS_MASK;this.packet.dup=(zero&constants.DUP_MASK)!==0;debug("_parseHeader: packet: %o",this.packet);this._list.consume(1);return true}},{key:"_parseLength",value:function _parseLength(){var result=this._parseVarByteNum(true);if(result){this.packet.length=result.value;this._list.consume(result.bytes)}else{this._emitError(new Error("Invalid length"))}debug("_parseLength %d",result.value);return!!result}},{key:"_parsePayload",value:function _parsePayload(){debug("_parsePayload: payload %O",this._list);var result=false;if(this.packet.length===0||this._list.length>=this.packet.length){this._pos=0;switch(this.packet.cmd){case"connect":this._parseConnect();break;case"connack":this._parseConnack();break;case"publish":this._parsePublish();break;case"puback":case"pubrec":case"pubrel":case"pubcomp":this._parseConfirmation();break;case"subscribe":this._parseSubscribe();break;case"suback":this._parseSuback();break;case"unsubscribe":this._parseUnsubscribe();break;case"unsuback":this._parseUnsuback();break;case"pingreq":case"pingresp":break;case"disconnect":this._parseDisconnect();break;case"auth":this._parseAuth();break;default:this._emitError(new Error("Not supported"))}result=true}debug("_parsePayload complete result: %s",result);return result}},{key:"_parseConnect",value:function _parseConnect(){debug("_parseConnect");var topic;var payload;var password;var username;var flags={};var packet=this.packet;var protocolId=this._parseString();if(protocolId===null)return this._emitError(new Error("Cannot parse protocolId"));if(protocolId!=="MQTT"&&protocolId!=="MQIsdp"){return this._emitError(new Error("Invalid protocolId"))}packet.protocolId=protocolId;if(this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));packet.protocolVersion=this._list.readUInt8(this._pos);if(packet.protocolVersion!==3&&packet.protocolVersion!==4&&packet.protocolVersion!==5){return this._emitError(new Error("Invalid protocol version"))}this._pos++;if(this._pos>=this._list.length){return this._emitError(new Error("Packet too short"))}flags.username=this._list.readUInt8(this._pos)&constants.USERNAME_MASK;flags.password=this._list.readUInt8(this._pos)&constants.PASSWORD_MASK;flags.will=this._list.readUInt8(this._pos)&constants.WILL_FLAG_MASK;if(flags.will){packet.will={};packet.will.retain=(this._list.readUInt8(this._pos)&constants.WILL_RETAIN_MASK)!==0;packet.will.qos=(this._list.readUInt8(this._pos)&constants.WILL_QOS_MASK)>>constants.WILL_QOS_SHIFT}packet.clean=(this._list.readUInt8(this._pos)&constants.CLEAN_SESSION_MASK)!==0;this._pos++;packet.keepalive=this._parseNum();if(packet.keepalive===-1)return this._emitError(new Error("Packet too short"));if(packet.protocolVersion===5){var properties=this._parseProperties();if(Object.getOwnPropertyNames(properties).length){packet.properties=properties}}var clientId=this._parseString();if(clientId===null)return this._emitError(new Error("Packet too short"));packet.clientId=clientId;debug("_parseConnect: packet.clientId: %s",packet.clientId);if(flags.will){if(packet.protocolVersion===5){var willProperties=this._parseProperties();if(Object.getOwnPropertyNames(willProperties).length){packet.will.properties=willProperties}}topic=this._parseString();if(topic===null)return this._emitError(new Error("Cannot parse will topic"));packet.will.topic=topic;debug("_parseConnect: packet.will.topic: %s",packet.will.topic);payload=this._parseBuffer();if(payload===null)return this._emitError(new Error("Cannot parse will payload"));packet.will.payload=payload;debug("_parseConnect: packet.will.paylaod: %s",packet.will.payload)}if(flags.username){username=this._parseString();if(username===null)return this._emitError(new Error("Cannot parse username"));packet.username=username;debug("_parseConnect: packet.username: %s",packet.username)}if(flags.password){password=this._parseBuffer();if(password===null)return this._emitError(new Error("Cannot parse password"));packet.password=password}this.settings=packet;debug("_parseConnect: complete");return packet}},{key:"_parseConnack",value:function _parseConnack(){debug("_parseConnack");var packet=this.packet;if(this._list.length<2)return null;packet.sessionPresent=!!(this._list.readUInt8(this._pos++)&constants.SESSIONPRESENT_MASK);if(this.settings.protocolVersion===5){packet.reasonCode=this._list.readUInt8(this._pos++)}else{packet.returnCode=this._list.readUInt8(this._pos++)}if(packet.returnCode===-1||packet.reasonCode===-1)return this._emitError(new Error("Cannot parse return code"));if(this.settings.protocolVersion===5){var properties=this._parseProperties();if(Object.getOwnPropertyNames(properties).length){packet.properties=properties}}debug("_parseConnack: complete")}},{key:"_parsePublish",value:function _parsePublish(){debug("_parsePublish");var packet=this.packet;packet.topic=this._parseString();if(packet.topic===null)return this._emitError(new Error("Cannot parse topic"));if(packet.qos>0)if(!this._parseMessageId()){return}if(this.settings.protocolVersion===5){var properties=this._parseProperties();if(Object.getOwnPropertyNames(properties).length){packet.properties=properties}}packet.payload=this._list.slice(this._pos,packet.length);debug("_parsePublish: payload from buffer list: %o",packet.payload)}},{key:"_parseSubscribe",value:function _parseSubscribe(){debug("_parseSubscribe");var packet=this.packet;var topic;var options;var qos;var rh;var rap;var nl;var subscription;if(packet.qos!==1){return this._emitError(new Error("Wrong subscribe header"))}packet.subscriptions=[];if(!this._parseMessageId()){return}if(this.settings.protocolVersion===5){var properties=this._parseProperties();if(Object.getOwnPropertyNames(properties).length){packet.properties=properties}}while(this._pos<packet.length){topic=this._parseString();if(topic===null)return this._emitError(new Error("Cannot parse topic"));if(this._pos>=packet.length)return this._emitError(new Error("Malformed Subscribe Payload"));options=this._parseByte();qos=options&constants.SUBSCRIBE_OPTIONS_QOS_MASK;nl=(options>>constants.SUBSCRIBE_OPTIONS_NL_SHIFT&constants.SUBSCRIBE_OPTIONS_NL_MASK)!==0;rap=(options>>constants.SUBSCRIBE_OPTIONS_RAP_SHIFT&constants.SUBSCRIBE_OPTIONS_RAP_MASK)!==0;rh=options>>constants.SUBSCRIBE_OPTIONS_RH_SHIFT&constants.SUBSCRIBE_OPTIONS_RH_MASK;subscription={topic:topic,qos:qos};if(this.settings.protocolVersion===5){subscription.nl=nl;subscription.rap=rap;subscription.rh=rh}debug("_parseSubscribe: push subscription `%s` to subscription",subscription);packet.subscriptions.push(subscription)}}},{key:"_parseSuback",value:function _parseSuback(){debug("_parseSuback");var packet=this.packet;this.packet.granted=[];if(!this._parseMessageId()){return}if(this.settings.protocolVersion===5){var properties=this._parseProperties();if(Object.getOwnPropertyNames(properties).length){packet.properties=properties}}while(this._pos<this.packet.length){this.packet.granted.push(this._list.readUInt8(this._pos++))}}},{key:"_parseUnsubscribe",value:function _parseUnsubscribe(){debug("_parseUnsubscribe");var packet=this.packet;packet.unsubscriptions=[];if(!this._parseMessageId()){return}if(this.settings.protocolVersion===5){var properties=this._parseProperties();if(Object.getOwnPropertyNames(properties).length){packet.properties=properties}}while(this._pos<packet.length){var topic=this._parseString();if(topic===null)return this._emitError(new Error("Cannot parse topic"));debug("_parseUnsubscribe: push topic `%s` to unsubscriptions",topic);packet.unsubscriptions.push(topic)}}},{key:"_parseUnsuback",value:function _parseUnsuback(){debug("_parseUnsuback");var packet=this.packet;if(!this._parseMessageId())return this._emitError(new Error("Cannot parse messageId"));if(this.settings.protocolVersion===5){var properties=this._parseProperties();if(Object.getOwnPropertyNames(properties).length){packet.properties=properties}packet.granted=[];while(this._pos<this.packet.length){this.packet.granted.push(this._list.readUInt8(this._pos++))}}}},{key:"_parseConfirmation",value:function _parseConfirmation(){debug("_parseConfirmation: packet.cmd: `%s`",this.packet.cmd);var packet=this.packet;this._parseMessageId();if(this.settings.protocolVersion===5){if(packet.length>2){packet.reasonCode=this._parseByte();debug("_parseConfirmation: packet.reasonCode `%d`",packet.reasonCode)}if(packet.length>3){var properties=this._parseProperties();if(Object.getOwnPropertyNames(properties).length){packet.properties=properties}}}return true}},{key:"_parseDisconnect",value:function _parseDisconnect(){var packet=this.packet;debug("_parseDisconnect");if(this.settings.protocolVersion===5){packet.reasonCode=this._parseByte();var properties=this._parseProperties();if(Object.getOwnPropertyNames(properties).length){packet.properties=properties}}debug("_parseDisconnect result: true");return true}},{key:"_parseAuth",value:function _parseAuth(){debug("_parseAuth");var packet=this.packet;if(this.settings.protocolVersion!==5){return this._emitError(new Error("Not supported auth packet for this version MQTT"))}packet.reasonCode=this._parseByte();var properties=this._parseProperties();if(Object.getOwnPropertyNames(properties).length){packet.properties=properties}debug("_parseAuth: result: true");return true}},{key:"_parseMessageId",value:function _parseMessageId(){var packet=this.packet;packet.messageId=this._parseNum();if(packet.messageId===null){this._emitError(new Error("Cannot parse messageId"));return false}debug("_parseMessageId: packet.messageId %d",packet.messageId);return true}},{key:"_parseString",value:function _parseString(maybeBuffer){var length=this._parseNum();var end=length+this._pos;if(length===-1||end>this._list.length||end>this.packet.length)return null;var result=this._list.toString("utf8",this._pos,end);this._pos+=length;debug("_parseString: result: %s",result);return result}},{key:"_parseStringPair",value:function _parseStringPair(){debug("_parseStringPair");return{name:this._parseString(),value:this._parseString()}}},{key:"_parseBuffer",value:function _parseBuffer(){var length=this._parseNum();var end=length+this._pos;if(length===-1||end>this._list.length||end>this.packet.length)return null;var result=this._list.slice(this._pos,end);this._pos+=length;debug("_parseBuffer: result: %o",result);return result}},{key:"_parseNum",value:function _parseNum(){if(this._list.length-this._pos<2)return-1;var result=this._list.readUInt16BE(this._pos);this._pos+=2;debug("_parseNum: result: %s",result);return result}},{key:"_parse4ByteNum",value:function _parse4ByteNum(){if(this._list.length-this._pos<4)return-1;var result=this._list.readUInt32BE(this._pos);this._pos+=4;debug("_parse4ByteNum: result: %s",result);return result}},{key:"_parseVarByteNum",value:function _parseVarByteNum(fullInfoFlag){debug("_parseVarByteNum");var bytes=0;var mul=1;var value=0;var result=false;var current;var padding=this._pos?this._pos:0;while(bytes<5){current=this._list.readUInt8(padding+bytes++);value+=mul*(current&constants.VARBYTEINT_MASK);mul*=128;if((current&constants.VARBYTEINT_FIN_MASK)===0){result=true;break}if(this._list.length<=bytes){break}}if(padding){this._pos+=bytes}result=result?fullInfoFlag?{bytes:bytes,value:value}:value:false;debug("_parseVarByteNum: result: %o",result);return result}},{key:"_parseByte",value:function _parseByte(){var result=this._list.readUInt8(this._pos);this._pos++;debug("_parseByte: result: %o",result);return result}},{key:"_parseByType",value:function _parseByType(type){debug("_parseByType: type: %s",type);switch(type){case"byte":{return this._parseByte()!==0}case"int8":{return this._parseByte()}case"int16":{return this._parseNum()}case"int32":{return this._parse4ByteNum()}case"var":{return this._parseVarByteNum()}case"string":{return this._parseString()}case"pair":{return this._parseStringPair()}case"binary":{return this._parseBuffer()}}}},{key:"_parseProperties",value:function _parseProperties(){debug("_parseProperties");var length=this._parseVarByteNum();var start=this._pos;var end=start+length;var result={};while(this._pos<end){var type=this._parseByte();var name=constants.propertiesCodes[type];if(!name){this._emitError(new Error("Unknown property"));return false}if(name==="userProperties"){if(!result[name]){result[name]=Object.create(null)}var currentUserProperty=this._parseByType(constants.propertiesTypes[name]);if(result[name][currentUserProperty.name]){if(Array.isArray(result[name][currentUserProperty.name])){result[name][currentUserProperty.name].push(currentUserProperty.value)}else{var currentValue=result[name][currentUserProperty.name];result[name][currentUserProperty.name]=[currentValue];result[name][currentUserProperty.name].push(currentUserProperty.value)}}else{result[name][currentUserProperty.name]=currentUserProperty.value}continue}if(result[name]){if(Array.isArray(result[name])){result[name].push(this._parseByType(constants.propertiesTypes[name]))}else{result[name]=[result[name]];result[name].push(this._parseByType(constants.propertiesTypes[name]))}}else{result[name]=this._parseByType(constants.propertiesTypes[name])}}return result}},{key:"_newPacket",value:function _newPacket(){debug("_newPacket");if(this.packet){this._list.consume(this.packet.length);debug("_newPacket: parser emit packet: packet.cmd: %s, packet.payload: %s, packet.length: %d",this.packet.cmd,this.packet.payload,this.packet.length);this.emit("packet",this.packet)}debug("_newPacket: new packet");this.packet=new Packet;this._pos=0;return true}},{key:"_emitError",value:function _emitError(err){debug("_emitError");this.error=err;this.emit("error",err)}}],[{key:"parser",value:function parser(opt){if(!(this instanceof Parser))return(new Parser).parser(opt);this.settings=opt||{};this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"];this._resetState();return this}}]);return Parser}(EventEmitter);module.exports=Parser},{"./constants":125,"./packet":132,bl:29,debug:128,events:34}],134:[function(require,module,exports){(function(Buffer){"use strict";function _createForOfIteratorHelper(o,allowArrayLike){var it;if(typeof Symbol==="undefined"||o[Symbol.iterator]==null){if(Array.isArray(o)||(it=_unsupportedIterableToArray(o))||allowArrayLike&&o&&typeof o.length==="number"){if(it)o=it;var i=0;var F=function F(){};return{s:F,n:function n(){if(i>=o.length)return{done:true};return{done:false,value:o[i++]}},e:function e(_e){throw _e},f:F}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var normalCompletion=true,didErr=false,err;return{s:function s(){it=o[Symbol.iterator]()},n:function n(){var step=it.next();normalCompletion=step.done;return step},e:function e(_e2){didErr=true;err=_e2},f:function f(){try{if(!normalCompletion&&it["return"]!=null)it["return"]()}finally{if(didErr)throw err}}}}function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen)}function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i<len;i++){arr2[i]=arr[i]}return arr2}function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}var protocol=require("./constants");var empty=Buffer.allocUnsafe(0);var zeroBuf=Buffer.from([0]);var numbers=require("./numbers");var nextTick=require("process-nextick-args").nextTick;var debug=require("debug")("mqtt-packet:writeToStream");var numCache=numbers.cache;var generateNumber=numbers.generateNumber;var generateCache=numbers.generateCache;var genBufVariableByteInt=numbers.genBufVariableByteInt;var generate4ByteBuffer=numbers.generate4ByteBuffer;var writeNumber=writeNumberCached;var toGenerate=true;function generate(packet,stream,opts){debug("generate called");if(stream.cork){stream.cork();nextTick(uncork,stream)}if(toGenerate){toGenerate=false;generateCache()}debug("generate: packet.cmd: %s",packet.cmd);switch(packet.cmd){case"connect":return connect(packet,stream,opts);case"connack":return connack(packet,stream,opts);case"publish":return publish(packet,stream,opts);case"puback":case"pubrec":case"pubrel":case"pubcomp":return confirmation(packet,stream,opts);case"subscribe":return subscribe(packet,stream,opts);case"suback":return suback(packet,stream,opts);case"unsubscribe":return unsubscribe(packet,stream,opts);case"unsuback":return unsuback(packet,stream,opts);case"pingreq":case"pingresp":return emptyPacket(packet,stream,opts);case"disconnect":return disconnect(packet,stream,opts);case"auth":return auth(packet,stream,opts);default:stream.emit("error",new Error("Unknown command"));return false}}Object.defineProperty(generate,"cacheNumbers",{get:function get(){return writeNumber===writeNumberCached},set:function set(value){if(value){if(!numCache||Object.keys(numCache).length===0)toGenerate=true;writeNumber=writeNumberCached}else{toGenerate=false;writeNumber=writeNumberGenerated}}});function uncork(stream){stream.uncork()}function connect(packet,stream,opts){var settings=packet||{};var protocolId=settings.protocolId||"MQTT";var protocolVersion=settings.protocolVersion||4;var will=settings.will;var clean=settings.clean;var keepalive=settings.keepalive||0;var clientId=settings.clientId||"";var username=settings.username;var password=settings.password;var properties=settings.properties;if(clean===undefined)clean=true;var length=0;if(!protocolId||typeof protocolId!=="string"&&!Buffer.isBuffer(protocolId)){stream.emit("error",new Error("Invalid protocolId"));return false}else length+=protocolId.length+2;if(protocolVersion!==3&&protocolVersion!==4&&protocolVersion!==5){stream.emit("error",new Error("Invalid protocol version"));return false}else length+=1;if((typeof clientId==="string"||Buffer.isBuffer(clientId))&&(clientId||protocolVersion===4)&&(clientId||clean)){length+=clientId.length+2}else{if(protocolVersion<4){stream.emit("error",new Error("clientId must be supplied before 3.1.1"));return false}if(clean*1===0){stream.emit("error",new Error("clientId must be given if cleanSession set to 0"));return false}}if(typeof keepalive!=="number"||keepalive<0||keepalive>65535||keepalive%1!==0){stream.emit("error",new Error("Invalid keepalive"));return false}else length+=2;length+=1;if(protocolVersion===5){var propertiesData=getProperties(stream,properties);if(!propertiesData){return false}length+=propertiesData.length}if(will){if(_typeof(will)!=="object"){stream.emit("error",new Error("Invalid will"));return false}if(!will.topic||typeof will.topic!=="string"){stream.emit("error",new Error("Invalid will topic"));return false}else{length+=Buffer.byteLength(will.topic)+2}length+=2;if(will.payload){if(will.payload.length>=0){if(typeof will.payload==="string"){length+=Buffer.byteLength(will.payload)}else{length+=will.payload.length}}else{stream.emit("error",new Error("Invalid will payload"));return false}}var willProperties={};if(protocolVersion===5){willProperties=getProperties(stream,will.properties);if(!willProperties){return false}length+=willProperties.length}}var providedUsername=false;if(username!=null){if(isStringOrBuffer(username)){providedUsername=true;length+=Buffer.byteLength(username)+2}else{stream.emit("error",new Error("Invalid username"));return false}}if(password!=null){if(!providedUsername){stream.emit("error",new Error("Username is required to use password"));return false}if(isStringOrBuffer(password)){length+=byteLength(password)+2}else{stream.emit("error",new Error("Invalid password"));return false}}stream.write(protocol.CONNECT_HEADER);writeVarByteInt(stream,length);writeStringOrBuffer(stream,protocolId);stream.write(protocolVersion===4?protocol.VERSION4:protocolVersion===5?protocol.VERSION5:protocol.VERSION3);var flags=0;flags|=username!=null?protocol.USERNAME_MASK:0;flags|=password!=null?protocol.PASSWORD_MASK:0;flags|=will&&will.retain?protocol.WILL_RETAIN_MASK:0;flags|=will&&will.qos?will.qos<<protocol.WILL_QOS_SHIFT:0;flags|=will?protocol.WILL_FLAG_MASK:0;flags|=clean?protocol.CLEAN_SESSION_MASK:0;stream.write(Buffer.from([flags]));writeNumber(stream,keepalive);if(protocolVersion===5){propertiesData.write()}writeStringOrBuffer(stream,clientId);if(will){if(protocolVersion===5){willProperties.write()}writeString(stream,will.topic);writeStringOrBuffer(stream,will.payload)}if(username!=null){writeStringOrBuffer(stream,username)}if(password!=null){writeStringOrBuffer(stream,password)}return true}function connack(packet,stream,opts){var version=opts?opts.protocolVersion:4;var settings=packet||{};var rc=version===5?settings.reasonCode:settings.returnCode;var properties=settings.properties;var length=2;if(typeof rc!=="number"){stream.emit("error",new Error("Invalid return code"));return false}var propertiesData=null;if(version===5){propertiesData=getProperties(stream,properties);if(!propertiesData){return false}length+=propertiesData.length}stream.write(protocol.CONNACK_HEADER);writeVarByteInt(stream,length);stream.write(settings.sessionPresent?protocol.SESSIONPRESENT_HEADER:zeroBuf);stream.write(Buffer.from([rc]));if(propertiesData!=null){propertiesData.write()}return true}function publish(packet,stream,opts){debug("publish: packet: %o",packet);var version=opts?opts.protocolVersion:4;var settings=packet||{};var qos=settings.qos||0;var retain=settings.retain?protocol.RETAIN_MASK:0;var topic=settings.topic;var payload=settings.payload||empty;var id=settings.messageId;var properties=settings.properties;var length=0;if(typeof topic==="string")length+=Buffer.byteLength(topic)+2;else if(Buffer.isBuffer(topic))length+=topic.length+2;else{stream.emit("error",new Error("Invalid topic"));return false}if(!Buffer.isBuffer(payload))length+=Buffer.byteLength(payload);else length+=payload.length;if(qos&&typeof id!=="number"){stream.emit("error",new Error("Invalid messageId"));return false}else if(qos)length+=2;var propertiesData=null;if(version===5){propertiesData=getProperties(stream,properties);if(!propertiesData){return false}length+=propertiesData.length}stream.write(protocol.PUBLISH_HEADER[qos][settings.dup?1:0][retain?1:0]);writeVarByteInt(stream,length);writeNumber(stream,byteLength(topic));stream.write(topic);if(qos>0)writeNumber(stream,id);if(propertiesData!=null){propertiesData.write()}debug("publish: payload: %o",payload);return stream.write(payload)}function confirmation(packet,stream,opts){var version=opts?opts.protocolVersion:4;var settings=packet||{};var type=settings.cmd||"puback";var id=settings.messageId;var dup=settings.dup&&type==="pubrel"?protocol.DUP_MASK:0;var qos=0;var reasonCode=settings.reasonCode;var properties=settings.properties;var length=version===5?3:2;if(type==="pubrel")qos=1;if(typeof id!=="number"){stream.emit("error",new Error("Invalid messageId"));return false}var propertiesData=null;if(version===5){if(_typeof(properties)==="object"){propertiesData=getPropertiesByMaximumPacketSize(stream,properties,opts,length);if(!propertiesData){return false}length+=propertiesData.length}}stream.write(protocol.ACKS[type][qos][dup][0]);writeVarByteInt(stream,length);writeNumber(stream,id);if(version===5){stream.write(Buffer.from([reasonCode]))}if(propertiesData!==null){propertiesData.write()}return true}function subscribe(packet,stream,opts){debug("subscribe: packet: ");var version=opts?opts.protocolVersion:4;var settings=packet||{};var dup=settings.dup?protocol.DUP_MASK:0;var id=settings.messageId;var subs=settings.subscriptions;var properties=settings.properties;var length=0;if(typeof id!=="number"){stream.emit("error",new Error("Invalid messageId"));return false}else length+=2;var propertiesData=null;if(version===5){propertiesData=getProperties(stream,properties);if(!propertiesData){return false}length+=propertiesData.length}if(_typeof(subs)==="object"&&subs.length){for(var i=0;i<subs.length;i+=1){var itopic=subs[i].topic;var iqos=subs[i].qos;if(typeof itopic!=="string"){stream.emit("error",new Error("Invalid subscriptions - invalid topic"));return false}if(typeof iqos!=="number"){stream.emit("error",new Error("Invalid subscriptions - invalid qos"));return false}if(version===5){var nl=subs[i].nl||false;if(typeof nl!=="boolean"){stream.emit("error",new Error("Invalid subscriptions - invalid No Local"));return false}var rap=subs[i].rap||false;if(typeof rap!=="boolean"){stream.emit("error",new Error("Invalid subscriptions - invalid Retain as Published"));return false}var rh=subs[i].rh||0;if(typeof rh!=="number"||rh>2){stream.emit("error",new Error("Invalid subscriptions - invalid Retain Handling"));return false}}length+=Buffer.byteLength(itopic)+2+1}}else{stream.emit("error",new Error("Invalid subscriptions"));return false}debug("subscribe: writing to stream: %o",protocol.SUBSCRIBE_HEADER);stream.write(protocol.SUBSCRIBE_HEADER[1][dup?1:0][0]);writeVarByteInt(stream,length);writeNumber(stream,id);if(propertiesData!==null){propertiesData.write()}var result=true;var _iterator=_createForOfIteratorHelper(subs),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var sub=_step.value;var jtopic=sub.topic;var jqos=sub.qos;var jnl=+sub.nl;var jrap=+sub.rap;var jrh=sub.rh;var joptions=void 0;writeString(stream,jtopic);joptions=protocol.SUBSCRIBE_OPTIONS_QOS[jqos];if(version===5){joptions|=jnl?protocol.SUBSCRIBE_OPTIONS_NL:0;joptions|=jrap?protocol.SUBSCRIBE_OPTIONS_RAP:0;joptions|=jrh?protocol.SUBSCRIBE_OPTIONS_RH[jrh]:0}result=stream.write(Buffer.from([joptions]))}}catch(err){_iterator.e(err)}finally{_iterator.f()}return result}function suback(packet,stream,opts){var version=opts?opts.protocolVersion:4;var settings=packet||{};var id=settings.messageId;var granted=settings.granted;var properties=settings.properties;var length=0;if(typeof id!=="number"){stream.emit("error",new Error("Invalid messageId"));return false}else length+=2;if(_typeof(granted)==="object"&&granted.length){for(var i=0;i<granted.length;i+=1){if(typeof granted[i]!=="number"){stream.emit("error",new Error("Invalid qos vector"));return false}length+=1}}else{stream.emit("error",new Error("Invalid qos vector"));return false}var propertiesData=null;if(version===5){propertiesData=getPropertiesByMaximumPacketSize(stream,properties,opts,length);if(!propertiesData){return false}length+=propertiesData.length}stream.write(protocol.SUBACK_HEADER);writeVarByteInt(stream,length);writeNumber(stream,id);if(propertiesData!==null){propertiesData.write()}return stream.write(Buffer.from(granted))}function unsubscribe(packet,stream,opts){var version=opts?opts.protocolVersion:4;var settings=packet||{};var id=settings.messageId;var dup=settings.dup?protocol.DUP_MASK:0;var unsubs=settings.unsubscriptions;var properties=settings.properties;var length=0;if(typeof id!=="number"){stream.emit("error",new Error("Invalid messageId"));return false}else{length+=2}if(_typeof(unsubs)==="object"&&unsubs.length){for(var i=0;i<unsubs.length;i+=1){if(typeof unsubs[i]!=="string"){stream.emit("error",new Error("Invalid unsubscriptions"));return false}length+=Buffer.byteLength(unsubs[i])+2}}else{stream.emit("error",new Error("Invalid unsubscriptions"));return false}var propertiesData=null;if(version===5){propertiesData=getProperties(stream,properties);if(!propertiesData){return false}length+=propertiesData.length}stream.write(protocol.UNSUBSCRIBE_HEADER[1][dup?1:0][0]);writeVarByteInt(stream,length);writeNumber(stream,id);if(propertiesData!==null){propertiesData.write()}var result=true;for(var j=0;j<unsubs.length;j++){result=writeString(stream,unsubs[j])}return result}function unsuback(packet,stream,opts){var version=opts?opts.protocolVersion:4;var settings=packet||{};var id=settings.messageId;var dup=settings.dup?protocol.DUP_MASK:0;var granted=settings.granted;var properties=settings.properties;var type=settings.cmd;var qos=0;var length=2;if(typeof id!=="number"){stream.emit("error",new Error("Invalid messageId"));return false}if(version===5){if(_typeof(granted)==="object"&&granted.length){for(var i=0;i<granted.length;i+=1){if(typeof granted[i]!=="number"){stream.emit("error",new Error("Invalid qos vector"));return false}length+=1}}else{stream.emit("error",new Error("Invalid qos vector"));return false}}var propertiesData=null;if(version===5){propertiesData=getPropertiesByMaximumPacketSize(stream,properties,opts,length);if(!propertiesData){return false}length+=propertiesData.length}stream.write(protocol.ACKS[type][qos][dup][0]);writeVarByteInt(stream,length);writeNumber(stream,id);if(propertiesData!==null){propertiesData.write()}if(version===5){stream.write(Buffer.from(granted))}return true}function emptyPacket(packet,stream,opts){return stream.write(protocol.EMPTY[packet.cmd])}function disconnect(packet,stream,opts){var version=opts?opts.protocolVersion:4;var settings=packet||{};var reasonCode=settings.reasonCode;var properties=settings.properties;var length=version===5?1:0;var propertiesData=null;if(version===5){propertiesData=getPropertiesByMaximumPacketSize(stream,properties,opts,length);if(!propertiesData){return false}length+=propertiesData.length}stream.write(Buffer.from([protocol.codes.disconnect<<4]));writeVarByteInt(stream,length);if(version===5){stream.write(Buffer.from([reasonCode]))}if(propertiesData!==null){propertiesData.write()}return true}function auth(packet,stream,opts){var version=opts?opts.protocolVersion:4;var settings=packet||{};var reasonCode=settings.reasonCode;var properties=settings.properties;var length=version===5?1:0;if(version!==5)stream.emit("error",new Error("Invalid mqtt version for auth packet"));var propertiesData=getPropertiesByMaximumPacketSize(stream,properties,opts,length);if(!propertiesData){return false}length+=propertiesData.length;stream.write(Buffer.from([protocol.codes.auth<<4]));writeVarByteInt(stream,length);stream.write(Buffer.from([reasonCode]));if(propertiesData!==null){propertiesData.write()}return true}var varByteIntCache={};function writeVarByteInt(stream,num){var buffer=varByteIntCache[num];if(!buffer){buffer=genBufVariableByteInt(num);if(num<16384)varByteIntCache[num]=buffer}debug("writeVarByteInt: writing to stream: %o",buffer);stream.write(buffer)}function writeString(stream,string){var strlen=Buffer.byteLength(string);writeNumber(stream,strlen);debug("writeString: %s",string);return stream.write(string,"utf8")}function writeStringPair(stream,name,value){writeString(stream,name);writeString(stream,value)}function writeNumberCached(stream,number){debug("writeNumberCached: number: %d",number);debug("writeNumberCached: %o",numCache[number]);return stream.write(numCache[number])}function writeNumberGenerated(stream,number){var generatedNumber=generateNumber(number);debug("writeNumberGenerated: %o",generatedNumber);return stream.write(generatedNumber)}function write4ByteNumber(stream,number){var generated4ByteBuffer=generate4ByteBuffer(number);debug("write4ByteNumber: %o",generated4ByteBuffer);return stream.write(generated4ByteBuffer)}function writeStringOrBuffer(stream,toWrite){if(typeof toWrite==="string"){writeString(stream,toWrite)}else if(toWrite){writeNumber(stream,toWrite.length);stream.write(toWrite)}else writeNumber(stream,0)}function getProperties(stream,properties){if(_typeof(properties)!=="object"||properties.length!=null){return{length:1,write:function write(){writeProperties(stream,{},0)}}}var propertiesLength=0;function getLengthProperty(name,value){var type=protocol.propertiesTypes[name];var length=0;switch(type){case"byte":{if(typeof value!=="boolean"){stream.emit("error",new Error("Invalid ".concat(name,": ").concat(value)));return false}length+=1+1;break}case"int8":{if(typeof value!=="number"||value<0||value>255){stream.emit("error",new Error("Invalid ".concat(name,": ").concat(value)));return false}length+=1+1;break}case"binary":{if(value&&value===null){stream.emit("error",new Error("Invalid ".concat(name,": ").concat(value)));return false}length+=1+Buffer.byteLength(value)+2;break}case"int16":{if(typeof value!=="number"||value<0||value>65535){stream.emit("error",new Error("Invalid ".concat(name,": ").concat(value)));return false}length+=1+2;break}case"int32":{if(typeof value!=="number"||value<0||value>4294967295){stream.emit("error",new Error("Invalid ".concat(name,": ").concat(value)));return false}length+=1+4;break}case"var":{if(typeof value!=="number"||value<0||value>268435455){stream.emit("error",new Error("Invalid ".concat(name,": ").concat(value)));return false}length+=1+Buffer.byteLength(genBufVariableByteInt(value));break}case"string":{if(typeof value!=="string"){stream.emit("error",new Error("Invalid ".concat(name,": ").concat(value)));return false}length+=1+2+Buffer.byteLength(value.toString());break}case"pair":{if(_typeof(value)!=="object"){stream.emit("error",new Error("Invalid ".concat(name,": ").concat(value)));return false}length+=Object.getOwnPropertyNames(value).reduce((function(result,name){var currentValue=value[name];if(Array.isArray(currentValue)){result+=currentValue.reduce((function(currentLength,value){currentLength+=1+2+Buffer.byteLength(name.toString())+2+Buffer.byteLength(value.toString());return currentLength}),0)}else{result+=1+2+Buffer.byteLength(name.toString())+2+Buffer.byteLength(value[name].toString())}return result}),0);break}default:{stream.emit("error",new Error("Invalid property ".concat(name,": ").concat(value)));return false}}return length}if(properties){for(var propName in properties){var propLength=0;var propValueLength=0;var propValue=properties[propName];if(Array.isArray(propValue)){for(var valueIndex=0;valueIndex<propValue.length;valueIndex++){propValueLength=getLengthProperty(propName,propValue[valueIndex]);if(!propValueLength){return false}propLength+=propValueLength}}else{propValueLength=getLengthProperty(propName,propValue);if(!propValueLength){return false}propLength=propValueLength}if(!propLength)return false;propertiesLength+=propLength}}var propertiesLengthLength=Buffer.byteLength(genBufVariableByteInt(propertiesLength));return{length:propertiesLengthLength+propertiesLength,write:function write(){writeProperties(stream,properties,propertiesLength)}}}function getPropertiesByMaximumPacketSize(stream,properties,opts,length){var mayEmptyProps=["reasonString","userProperties"];var maximumPacketSize=opts&&opts.properties&&opts.properties.maximumPacketSize?opts.properties.maximumPacketSize:0;var propertiesData=getProperties(stream,properties);if(maximumPacketSize){while(length+propertiesData.length>maximumPacketSize){var currentMayEmptyProp=mayEmptyProps.shift();if(currentMayEmptyProp&&properties[currentMayEmptyProp]){delete properties[currentMayEmptyProp];propertiesData=getProperties(stream,properties)}else{return false}}}return propertiesData}function writeProperty(stream,propName,value){var type=protocol.propertiesTypes[propName];switch(type){case"byte":{stream.write(Buffer.from([protocol.properties[propName]]));stream.write(Buffer.from([+value]));break}case"int8":{stream.write(Buffer.from([protocol.properties[propName]]));stream.write(Buffer.from([value]));break}case"binary":{stream.write(Buffer.from([protocol.properties[propName]]));writeStringOrBuffer(stream,value);break}case"int16":{stream.write(Buffer.from([protocol.properties[propName]]));writeNumber(stream,value);break}case"int32":{stream.write(Buffer.from([protocol.properties[propName]]));write4ByteNumber(stream,value);break}case"var":{stream.write(Buffer.from([protocol.properties[propName]]));writeVarByteInt(stream,value);break}case"string":{stream.write(Buffer.from([protocol.properties[propName]]));writeString(stream,value);break}case"pair":{Object.getOwnPropertyNames(value).forEach((function(name){var currentValue=value[name];if(Array.isArray(currentValue)){currentValue.forEach((function(value){stream.write(Buffer.from([protocol.properties[propName]]));writeStringPair(stream,name.toString(),value.toString())}))}else{stream.write(Buffer.from([protocol.properties[propName]]));writeStringPair(stream,name.toString(),currentValue.toString())}}));break}default:{stream.emit("error",new Error("Invalid property ".concat(propName," value: ").concat(value)));return false}}}function writeProperties(stream,properties,propertiesLength){writeVarByteInt(stream,propertiesLength);for(var propName in properties){if(Object.prototype.hasOwnProperty.call(properties,propName)&&properties[propName]!==null){var value=properties[propName];if(Array.isArray(value)){for(var valueIndex=0;valueIndex<value.length;valueIndex++){writeProperty(stream,propName,value[valueIndex])}}else{writeProperty(stream,propName,value)}}}}function byteLength(bufOrString){if(!bufOrString)return 0;else if(bufOrString instanceof Buffer)return bufOrString.length;else return Buffer.byteLength(bufOrString)}function isStringOrBuffer(field){return typeof field==="string"||field instanceof Buffer}module.exports=generate}).call(this,require("buffer").Buffer)},{"./constants":125,"./numbers":131,buffer:33,debug:128,"process-nextick-args":156}],135:[function(require,module,exports){(function(process,global){"use strict";function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}var events=require("events");var Store=require("./store");var mqttPacket=require("mqtt-packet");var Writable=require("readable-stream").Writable;var inherits=require("inherits");var reInterval=require("reinterval");var validations=require("./validations");var xtend=require("xtend");var setImmediate=global.setImmediate||function(callback){process.nextTick(callback)};var defaultConnectOptions={keepalive:60,reschedulePings:true,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:1e3,connectTimeout:30*1e3,clean:true,resubscribe:true};var errors={0:"",1:"Unacceptable protocol version",2:"Identifier rejected",3:"Server unavailable",4:"Bad username or password",5:"Not authorized",16:"No matching subscribers",17:"No subscription existed",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",132:"Unsupported Protocol Version",133:"Client Identifier not valid",134:"Bad User Name or Password",135:"Not authorized",136:"Server unavailable",137:"Server busy",138:"Banned",139:"Server shutting down",140:"Bad authentication method",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",145:"Packet identifier in use",146:"Packet Identifier not found",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};function defaultId(){return"mqttjs_"+Math.random().toString(16).substr(2,8)}function sendPacket(client,packet,cb){client.emit("packetsend",packet);var result=mqttPacket.writeToStream(packet,client.stream,client.options);if(!result&&cb){client.stream.once("drain",cb)}else if(cb){cb()}}function flush(queue){if(queue){Object.keys(queue).forEach((function(messageId){if(typeof queue[messageId].cb==="function"){queue[messageId].cb(new Error("Connection closed"));delete queue[messageId]}}))}}function flushVolatile(queue){if(queue){Object.keys(queue).forEach((function(messageId){if(queue[messageId]["volatile"]&&typeof queue[messageId].cb==="function"){queue[messageId].cb(new Error("Connection closed"));delete queue[messageId]}}))}}function storeAndSend(client,packet,cb,cbStorePut){client.outgoingStore.put(packet,(function storedPacket(err){if(err){return cb&&cb(err)}cbStorePut();sendPacket(client,packet,cb)}))}function nop(){}function MqttClient(streamBuilder,options){var k;var that=this;if(!(this instanceof MqttClient)){return new MqttClient(streamBuilder,options)}this.options=options||{};for(k in defaultConnectOptions){if(typeof this.options[k]==="undefined"){this.options[k]=defaultConnectOptions[k]}else{this.options[k]=options[k]}}this.options.clientId=typeof options.clientId==="string"?options.clientId:defaultId();this.options.customHandleAcks=options.protocolVersion===5&&options.customHandleAcks?options.customHandleAcks:function(){arguments[3](0)};this.streamBuilder=streamBuilder;this.outgoingStore=options.outgoingStore||new Store;this.incomingStore=options.incomingStore||new Store;this.queueQoSZero=options.queueQoSZero===undefined?true:options.queueQoSZero;this._resubscribeTopics={};this.messageIdToTopic={};this.pingTimer=null;this.connected=false;this.disconnecting=false;this.queue=[];this.connackTimer=null;this.reconnectTimer=null;this._storeProcessing=false;this._packetIdsDuringStoreProcessing={};this.nextId=Math.max(1,Math.floor(Math.random()*65535));this.outgoing={};this._firstConnection=true;this.on("close",(function(){this.connected=false;clearTimeout(this.connackTimer)}));this.on("connect",(function(){var queue=this.queue;function deliver(){var entry=queue.shift();var packet=null;if(!entry){return}packet=entry.packet;that._sendPacket(packet,(function(err){if(entry.cb){entry.cb(err)}deliver()}))}deliver()}));this.on("close",(function(){if(that.pingTimer!==null){that.pingTimer.clear();that.pingTimer=null}}));this.on("close",this._setupReconnect);events.EventEmitter.call(this);this._setupStream()}inherits(MqttClient,events.EventEmitter);MqttClient.prototype._setupStream=function(){var connectPacket;var that=this;var writable=new Writable;var parser=mqttPacket.parser(this.options);var completeParse=null;var packets=[];this._clearReconnect();this.stream=this.streamBuilder(this);parser.on("packet",(function(packet){packets.push(packet)}));function nextTickWork(){if(packets.length){process.nextTick(work)}else{var done=completeParse;completeParse=null;done()}}function work(){var packet=packets.shift();if(packet){that._handlePacket(packet,nextTickWork)}else{var done=completeParse;completeParse=null;if(done)done()}}writable._write=function(buf,enc,done){completeParse=done;parser.parse(buf);work()};this.stream.pipe(writable);this.stream.on("error",nop);this.stream.on("close",(function(){flushVolatile(that.outgoing);that.emit("close")}));connectPacket=Object.create(this.options);connectPacket.cmd="connect";sendPacket(this,connectPacket);parser.on("error",this.emit.bind(this,"error"));if(this.options.properties){if(!this.options.properties.authenticationMethod&&this.options.properties.authenticationData){this.emit("error",new Error("Packet has no Authentication Method"));return this}if(this.options.properties.authenticationMethod&&this.options.authPacket&&_typeof(this.options.authPacket)==="object"){var authPacket=xtend({cmd:"auth",reasonCode:0},this.options.authPacket);sendPacket(this,authPacket)}}this.stream.setMaxListeners(1e3);clearTimeout(this.connackTimer);this.connackTimer=setTimeout((function(){that._cleanUp(true)}),this.options.connectTimeout)};MqttClient.prototype._handlePacket=function(packet,done){var options=this.options;if(options.protocolVersion===5&&options.properties&&options.properties.maximumPacketSize&&options.properties.maximumPacketSize<packet.length){this.emit("error",new Error("exceeding packets size "+packet.cmd));this.end({reasonCode:149,properties:{reasonString:"Maximum packet size was exceeded"}});return this}this.emit("packetreceive",packet);switch(packet.cmd){case"publish":this._handlePublish(packet,done);break;case"puback":case"pubrec":case"pubcomp":case"suback":case"unsuback":this._handleAck(packet);done();break;case"pubrel":this._handlePubrel(packet,done);break;case"connack":this._handleConnack(packet);done();break;case"pingresp":this._handlePingresp(packet);done();break;case"disconnect":this._handleDisconnect(packet);done();break;default:break}};MqttClient.prototype._checkDisconnecting=function(callback){if(this.disconnecting){if(callback){callback(new Error("client disconnecting"))}else{this.emit("error",new Error("client disconnecting"))}}return this.disconnecting};MqttClient.prototype.publish=function(topic,message,opts,callback){var packet;var options=this.options;if(typeof opts==="function"){callback=opts;opts=null}var defaultOpts={qos:0,retain:false,dup:false};opts=xtend(defaultOpts,opts);if(this._checkDisconnecting(callback)){return this}packet={cmd:"publish",topic:topic,payload:message,qos:opts.qos,retain:opts.retain,messageId:this._nextId(),dup:opts.dup};if(options.protocolVersion===5){packet.properties=opts.properties;if(!options.properties&&packet.properties&&packet.properties.topicAlias||opts.properties&&options.properties&&(opts.properties.topicAlias&&options.properties.topicAliasMaximum&&opts.properties.topicAlias>options.properties.topicAliasMaximum||!options.properties.topicAliasMaximum&&opts.properties.topicAlias)){delete packet.properties.topicAlias}}switch(opts.qos){case 1:case 2:this.outgoing[packet.messageId]={volatile:false,cb:callback||nop};if(this._storeProcessing){this._packetIdsDuringStoreProcessing[packet.messageId]=false;this._storePacket(packet,undefined,opts.cbStorePut)}else{this._sendPacket(packet,undefined,opts.cbStorePut)}break;default:if(this._storeProcessing){this._storePacket(packet,callback,opts.cbStorePut)}else{this._sendPacket(packet,callback,opts.cbStorePut)}break}return this};MqttClient.prototype.subscribe=function(){var packet;var args=new Array(arguments.length);for(var i=0;i<arguments.length;i++){args[i]=arguments[i]}var subs=[];var obj=args.shift();var resubscribe=obj.resubscribe;var callback=args.pop()||nop;var opts=args.pop();var invalidTopic;var that=this;var version=this.options.protocolVersion;delete obj.resubscribe;if(typeof obj==="string"){obj=[obj]}if(typeof callback!=="function"){opts=callback;callback=nop}invalidTopic=validations.validateTopics(obj);if(invalidTopic!==null){setImmediate(callback,new Error("Invalid topic "+invalidTopic));return this}if(this._checkDisconnecting(callback)){return this}var defaultOpts={qos:0};if(version===5){defaultOpts.nl=false;defaultOpts.rap=false;defaultOpts.rh=0}opts=xtend(defaultOpts,opts);if(Array.isArray(obj)){obj.forEach((function(topic){if(!that._resubscribeTopics.hasOwnProperty(topic)||that._resubscribeTopics[topic].qos<opts.qos||resubscribe){var currentOpts={topic:topic,qos:opts.qos};if(version===5){currentOpts.nl=opts.nl;currentOpts.rap=opts.rap;currentOpts.rh=opts.rh;currentOpts.properties=opts.properties}subs.push(currentOpts)}}))}else{Object.keys(obj).forEach((function(k){if(!that._resubscribeTopics.hasOwnProperty(k)||that._resubscribeTopics[k].qos<obj[k].qos||resubscribe){var currentOpts={topic:k,qos:obj[k].qos};if(version===5){currentOpts.nl=obj[k].nl;currentOpts.rap=obj[k].rap;currentOpts.rh=obj[k].rh;currentOpts.properties=opts.properties}subs.push(currentOpts)}}))}packet={cmd:"subscribe",subscriptions:subs,qos:1,retain:false,dup:false,messageId:this._nextId()};if(opts.properties){packet.properties=opts.properties}if(!subs.length){callback(null,[]);return}if(this.options.resubscribe){var topics=[];subs.forEach((function(sub){if(that.options.reconnectPeriod>0){var topic={qos:sub.qos};if(version===5){topic.nl=sub.nl||false;topic.rap=sub.rap||false;topic.rh=sub.rh||0;topic.properties=sub.properties}that._resubscribeTopics[sub.topic]=topic;topics.push(sub.topic)}}));that.messageIdToTopic[packet.messageId]=topics}this.outgoing[packet.messageId]={volatile:true,cb:function cb(err,packet){if(!err){var granted=packet.granted;for(var i=0;i<granted.length;i+=1){subs[i].qos=granted[i]}}callback(err,subs)}};this._sendPacket(packet);return this};MqttClient.prototype.unsubscribe=function(){var packet={cmd:"unsubscribe",qos:1,messageId:this._nextId()};var that=this;var args=new Array(arguments.length);for(var i=0;i<arguments.length;i++){args[i]=arguments[i]}var topic=args.shift();var callback=args.pop()||nop;var opts=args.pop();if(typeof topic==="string"){topic=[topic]}if(typeof callback!=="function"){opts=callback;callback=nop}if(this._checkDisconnecting(callback)){return this}if(typeof topic==="string"){packet.unsubscriptions=[topic]}else if(_typeof(topic)==="object"&&topic.length){packet.unsubscriptions=topic}if(this.options.resubscribe){packet.unsubscriptions.forEach((function(topic){delete that._resubscribeTopics[topic]}))}if(_typeof(opts)==="object"&&opts.properties){packet.properties=opts.properties}this.outgoing[packet.messageId]={volatile:true,cb:callback};this._sendPacket(packet);return this};MqttClient.prototype.end=function(){var that=this;var force=arguments[0];var opts=arguments[1];var cb=arguments[2];if(force==null||typeof force!=="boolean"){cb=opts||nop;opts=force;force=false;if(_typeof(opts)!=="object"){cb=opts;opts=null;if(typeof cb!=="function"){cb=nop}}}if(_typeof(opts)!=="object"){cb=opts;opts=null}cb=cb||nop;function closeStores(){that.disconnected=true;that.incomingStore.close((function(){that.outgoingStore.close((function(){if(cb){cb.apply(null,arguments)}that.emit("end")}))}));if(that._deferredReconnect){that._deferredReconnect()}}function finish(){that._cleanUp(force,setImmediate.bind(null,closeStores),opts)}if(this.disconnecting){return this}this._clearReconnect();this.disconnecting=true;if(!force&&Object.keys(this.outgoing).length>0){this.once("outgoingEmpty",setTimeout.bind(null,finish,10))}else{finish()}return this};MqttClient.prototype.removeOutgoingMessage=function(mid){var cb=this.outgoing[mid]?this.outgoing[mid].cb:null;delete this.outgoing[mid];this.outgoingStore.del({messageId:mid},(function(){cb(new Error("Message removed"))}));return this};MqttClient.prototype.reconnect=function(opts){var that=this;var f=function f(){if(opts){that.options.incomingStore=opts.incomingStore;that.options.outgoingStore=opts.outgoingStore}else{that.options.incomingStore=null;that.options.outgoingStore=null}that.incomingStore=that.options.incomingStore||new Store;that.outgoingStore=that.options.outgoingStore||new Store;that.disconnecting=false;that.disconnected=false;that._deferredReconnect=null;that._reconnect()};if(this.disconnecting&&!this.disconnected){this._deferredReconnect=f}else{f()}return this};MqttClient.prototype._reconnect=function(){this.emit("reconnect");this._setupStream()};MqttClient.prototype._setupReconnect=function(){var that=this;if(!that.disconnecting&&!that.reconnectTimer&&that.options.reconnectPeriod>0){if(!this.reconnecting){this.emit("offline");this.reconnecting=true}that.reconnectTimer=setInterval((function(){that._reconnect()}),that.options.reconnectPeriod)}};MqttClient.prototype._clearReconnect=function(){if(this.reconnectTimer){clearInterval(this.reconnectTimer);this.reconnectTimer=null}};MqttClient.prototype._cleanUp=function(forced,done){var opts=arguments[2];if(done){this.stream.on("close",done)}if(forced){if(this.options.reconnectPeriod===0&&this.options.clean){flush(this.outgoing)}this.stream.destroy()}else{var packet=xtend({cmd:"disconnect"},opts);this._sendPacket(packet,setImmediate.bind(null,this.stream.end.bind(this.stream)))}if(!this.disconnecting){this._clearReconnect();this._setupReconnect()}if(this.pingTimer!==null){this.pingTimer.clear();this.pingTimer=null}if(done&&!this.connected){this.stream.removeListener("close",done);done()}};MqttClient.prototype._sendPacket=function(packet,cb,cbStorePut){cbStorePut=cbStorePut||nop;if(!this.connected){this._storePacket(packet,cb,cbStorePut);return}this._shiftPingInterval();switch(packet.cmd){case"publish":break;case"pubrel":storeAndSend(this,packet,cb,cbStorePut);return;default:sendPacket(this,packet,cb);return}switch(packet.qos){case 2:case 1:storeAndSend(this,packet,cb,cbStorePut);break;case 0:default:sendPacket(this,packet,cb);break}};MqttClient.prototype._storePacket=function(packet,cb,cbStorePut){cbStorePut=cbStorePut||nop;if((packet.qos||0)===0&&this.queueQoSZero||packet.cmd!=="publish"){this.queue.push({packet:packet,cb:cb})}else if(packet.qos>0){cb=this.outgoing[packet.messageId]?this.outgoing[packet.messageId].cb:null;this.outgoingStore.put(packet,(function(err){if(err){return cb&&cb(err)}cbStorePut()}))}else if(cb){cb(new Error("No connection to broker"))}};MqttClient.prototype._setupPingTimer=function(){var that=this;if(!this.pingTimer&&this.options.keepalive){this.pingResp=true;this.pingTimer=reInterval((function(){that._checkPing()}),this.options.keepalive*1e3)}};MqttClient.prototype._shiftPingInterval=function(){if(this.pingTimer&&this.options.keepalive&&this.options.reschedulePings){this.pingTimer.reschedule(this.options.keepalive*1e3)}};MqttClient.prototype._checkPing=function(){if(this.pingResp){this.pingResp=false;this._sendPacket({cmd:"pingreq"})}else{this._cleanUp(true)}};MqttClient.prototype._handlePingresp=function(){this.pingResp=true};MqttClient.prototype._handleConnack=function(packet){var options=this.options;var version=options.protocolVersion;var rc=version===5?packet.reasonCode:packet.returnCode;clearTimeout(this.connackTimer);if(packet.properties){if(packet.properties.topicAliasMaximum){if(!options.properties){options.properties={}}options.properties.topicAliasMaximum=packet.properties.topicAliasMaximum}if(packet.properties.serverKeepAlive&&options.keepalive){options.keepalive=packet.properties.serverKeepAlive;this._shiftPingInterval()}if(packet.properties.maximumPacketSize){if(!options.properties){options.properties={}}options.properties.maximumPacketSize=packet.properties.maximumPacketSize}}if(rc===0){this.reconnecting=false;this._onConnect(packet)}else if(rc>0){var err=new Error("Connection refused: "+errors[rc]);err.code=rc;this.emit("error",err)}};MqttClient.prototype._handlePublish=function(packet,done){done=typeof done!=="undefined"?done:nop;var topic=packet.topic.toString();var message=packet.payload;var qos=packet.qos;var mid=packet.messageId;var that=this;var options=this.options;var validReasonCodes=[0,16,128,131,135,144,145,151,153];switch(qos){case 2:{options.customHandleAcks(topic,message,packet,(function(error,code){if(!(error instanceof Error)){code=error;error=null}if(error){return that.emit("error",error)}if(validReasonCodes.indexOf(code)===-1){return that.emit("error",new Error("Wrong reason code for pubrec"))}if(code){that._sendPacket({cmd:"pubrec",messageId:mid,reasonCode:code},done)}else{that.incomingStore.put(packet,(function(){that._sendPacket({cmd:"pubrec",messageId:mid},done)}))}}));break}case 1:{options.customHandleAcks(topic,message,packet,(function(error,code){if(!(error instanceof Error)){code=error;error=null}if(error){return that.emit("error",error)}if(validReasonCodes.indexOf(code)===-1){return that.emit("error",new Error("Wrong reason code for puback"))}if(!code){that.emit("message",topic,message,packet)}that.handleMessage(packet,(function(err){if(err){return done&&done(err)}that._sendPacket({cmd:"puback",messageId:mid,reasonCode:code},done)}))}));break}case 0:this.emit("message",topic,message,packet);this.handleMessage(packet,done);break;default:break}};MqttClient.prototype.handleMessage=function(packet,callback){callback()};MqttClient.prototype._handleAck=function(packet){var mid=packet.messageId;var type=packet.cmd;var response=null;var cb=this.outgoing[mid]?this.outgoing[mid].cb:null;var that=this;var err;if(!cb){return}switch(type){case"pubcomp":case"puback":var pubackRC=packet.reasonCode;if(pubackRC&&pubackRC>0&&pubackRC!==16){err=new Error("Publish error: "+errors[pubackRC]);err.code=pubackRC;cb(err,packet)}delete this.outgoing[mid];this.outgoingStore.del(packet,cb);break;case"pubrec":response={cmd:"pubrel",qos:2,messageId:mid};var pubrecRC=packet.reasonCode;if(pubrecRC&&pubrecRC>0&&pubrecRC!==16){err=new Error("Publish error: "+errors[pubrecRC]);err.code=pubrecRC;cb(err,packet)}else{this._sendPacket(response)}break;case"suback":delete this.outgoing[mid];for(var grantedI=0;grantedI<packet.granted.length;grantedI++){if((packet.granted[grantedI]&128)!==0){var topics=this.messageIdToTopic[mid];if(topics){topics.forEach((function(topic){delete that._resubscribeTopics[topic]}))}}}cb(null,packet);break;case"unsuback":delete this.outgoing[mid];cb(null);break;default:that.emit("error",new Error("unrecognized packet type"))}if(this.disconnecting&&Object.keys(this.outgoing).length===0){this.emit("outgoingEmpty")}};MqttClient.prototype._handlePubrel=function(packet,callback){callback=typeof callback!=="undefined"?callback:nop;var mid=packet.messageId;var that=this;var comp={cmd:"pubcomp",messageId:mid};that.incomingStore.get(packet,(function(err,pub){if(!err){that.emit("message",pub.topic,pub.payload,pub);that.handleMessage(pub,(function(err){if(err){return callback(err)}that.incomingStore.del(pub,nop);that._sendPacket(comp,callback)}))}else{that._sendPacket(comp,callback)}}))};MqttClient.prototype._handleDisconnect=function(packet){this.emit("disconnect",packet)};MqttClient.prototype._nextId=function(){var id=this.nextId++;if(this.nextId===65536){this.nextId=1}return id};MqttClient.prototype.getLastMessageId=function(){return this.nextId===1?65535:this.nextId-1};MqttClient.prototype._resubscribe=function(connack){var _resubscribeTopicsKeys=Object.keys(this._resubscribeTopics);if(!this._firstConnection&&(this.options.clean||this.options.protocolVersion===5&&!connack.sessionPresent)&&_resubscribeTopicsKeys.length>0){if(this.options.resubscribe){if(this.options.protocolVersion===5){for(var topicI=0;topicI<_resubscribeTopicsKeys.length;topicI++){var resubscribeTopic={};resubscribeTopic[_resubscribeTopicsKeys[topicI]]=this._resubscribeTopics[_resubscribeTopicsKeys[topicI]];resubscribeTopic.resubscribe=true;this.subscribe(resubscribeTopic,{properties:resubscribeTopic[_resubscribeTopicsKeys[topicI]].properties})}}else{this._resubscribeTopics.resubscribe=true;this.subscribe(this._resubscribeTopics)}}else{this._resubscribeTopics={}}}this._firstConnection=false};MqttClient.prototype._onConnect=function(packet){if(this.disconnected){this.emit("connect",packet);return}var that=this;this._setupPingTimer();this._resubscribe(packet);this.connected=true;function startStreamProcess(){var outStore=that.outgoingStore.createStream();function clearStoreProcessing(){that._storeProcessing=false;that._packetIdsDuringStoreProcessing={}}that.once("close",remove);outStore.on("error",(function(err){clearStoreProcessing();that.removeListener("close",remove);that.emit("error",err)}));function remove(){outStore.destroy();outStore=null;clearStoreProcessing()}function storeDeliver(){if(!outStore){return}that._storeProcessing=true;var packet=outStore.read(1);var _cb;if(!packet){outStore.once("readable",storeDeliver);return}if(that._packetIdsDuringStoreProcessing[packet.messageId]){storeDeliver();return}if(!that.disconnecting&&!that.reconnectTimer){_cb=that.outgoing[packet.messageId]?that.outgoing[packet.messageId].cb:null;that.outgoing[packet.messageId]={volatile:false,cb:function cb(err,status){if(_cb){_cb(err,status)}storeDeliver()}};that._packetIdsDuringStoreProcessing[packet.messageId]=true;that._sendPacket(packet)}else if(outStore.destroy){outStore.destroy()}}outStore.on("end",(function(){var allProcessed=true;for(var id in that._packetIdsDuringStoreProcessing){if(!that._packetIdsDuringStoreProcessing[id]){allProcessed=false;break}}if(allProcessed){clearStoreProcessing();that.removeListener("close",remove);that.emit("connect",packet)}else{startStreamProcess()}}));storeDeliver()}startStreamProcess()};module.exports=MqttClient}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./store":142,"./validations":143,_process:157,events:34,inherits:120,"mqtt-packet":127,"readable-stream":152,reinterval:176,xtend:217}],136:[function(require,module,exports){(function(Buffer){"use strict";var Transform=require("readable-stream").Transform;var duplexify=require("duplexify");var base64=require("base64-js");var my;var proxy;var stream;var isInitialized=false;function buildProxy(){var proxy=new Transform;proxy._write=function(chunk,encoding,next){my.sendSocketMessage({data:chunk.buffer,success:function success(){next()},fail:function fail(){next(new Error)}})};proxy._flush=function socketEnd(done){my.closeSocket({success:function success(){done()}})};return proxy}function setDefaultOpts(opts){if(!opts.hostname){opts.hostname="localhost"}if(!opts.path){opts.path="/"}if(!opts.wsOptions){opts.wsOptions={}}}function buildUrl(opts,client){var protocol=opts.protocol==="alis"?"wss":"ws";var url=protocol+"://"+opts.hostname+opts.path;if(opts.port&&opts.port!==80&&opts.port!==443){url=protocol+"://"+opts.hostname+":"+opts.port+opts.path}if(typeof opts.transformWsUrl==="function"){url=opts.transformWsUrl(url,opts,client)}return url}function bindEventHandler(){if(isInitialized)return;isInitialized=true;my.onSocketOpen((function(){stream.setReadable(proxy);stream.setWritable(proxy);stream.emit("connect")}));my.onSocketMessage((function(res){if(typeof res.data==="string"){var array=base64.toByteArray(res.data);var buffer=Buffer.from(array);proxy.push(buffer)}else{var reader=new FileReader;reader.addEventListener("load",(function(){var data=reader.result;if(data instanceof ArrayBuffer)data=Buffer.from(data);else data=Buffer.from(data,"utf8");proxy.push(data)}));reader.readAsArrayBuffer(res.data)}}));my.onSocketClose((function(){stream.end();stream.destroy()}));my.onSocketError((function(res){stream.destroy(res)}))}function buildStream(client,opts){opts.hostname=opts.hostname||opts.host;if(!opts.hostname){throw new Error("Could not determine host. Specify host manually.")}var websocketSubProtocol=opts.protocolId==="MQIsdp"&&opts.protocolVersion===3?"mqttv3.1":"mqtt";setDefaultOpts(opts);var url=buildUrl(opts,client);my=opts.my;my.connectSocket({url:url,protocols:websocketSubProtocol});proxy=buildProxy();stream=duplexify.obj();bindEventHandler();return stream}module.exports=buildStream}).call(this,require("buffer").Buffer)},{"base64-js":27,buffer:33,duplexify:40,"readable-stream":152}],137:[function(require,module,exports){(function(process){"use strict";function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}var MqttClient=require("../client");var Store=require("../store");var url=require("url");var xtend=require("xtend");var protocols={};if(process.title!=="browser"){protocols.mqtt=require("./tcp");protocols.tcp=require("./tcp");protocols.ssl=require("./tls");protocols.tls=require("./tls");protocols.mqtts=require("./tls")}else{protocols.wx=require("./wx");protocols.wxs=require("./wx");protocols.ali=require("./ali");protocols.alis=require("./ali")}protocols.ws=require("./ws");protocols.wss=require("./ws");function parseAuthOptions(opts){var matches;if(opts.auth){matches=opts.auth.match(/^(.+):(.+)$/);if(matches){opts.username=matches[1];opts.password=matches[2]}else{opts.username=opts.auth}}}function connect(brokerUrl,opts){if(_typeof(brokerUrl)==="object"&&!opts){opts=brokerUrl;brokerUrl=null}opts=opts||{};if(brokerUrl){var parsed=url.parse(brokerUrl,true);if(parsed.port!=null){parsed.port=Number(parsed.port)}opts=xtend(parsed,opts);if(opts.protocol===null){throw new Error("Missing protocol")}opts.protocol=opts.protocol.replace(/:$/,"")}parseAuthOptions(opts);if(opts.query&&typeof opts.query.clientId==="string"){opts.clientId=opts.query.clientId}if(opts.cert&&opts.key){if(opts.protocol){if(["mqtts","wss","wxs","alis"].indexOf(opts.protocol)===-1){switch(opts.protocol){case"mqtt":opts.protocol="mqtts";break;case"ws":opts.protocol="wss";break;case"wx":opts.protocol="wxs";break;case"ali":opts.protocol="alis";break;default:throw new Error('Unknown protocol for secure connection: "'+opts.protocol+'"!')}}}else{throw new Error("Missing secure protocol key")}}if(!protocols[opts.protocol]){var isSecure=["mqtts","wss"].indexOf(opts.protocol)!==-1;opts.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((function(key,index){if(isSecure&&index%2===0){return false}return typeof protocols[key]==="function"}))[0]}if(opts.clean===false&&!opts.clientId){throw new Error("Missing clientId for unclean clients")}if(opts.protocol){opts.defaultProtocol=opts.protocol}function wrapper(client){if(opts.servers){if(!client._reconnectCount||client._reconnectCount===opts.servers.length){client._reconnectCount=0}opts.host=opts.servers[client._reconnectCount].host;opts.port=opts.servers[client._reconnectCount].port;opts.protocol=!opts.servers[client._reconnectCount].protocol?opts.defaultProtocol:opts.servers[client._reconnectCount].protocol;opts.hostname=opts.host;client._reconnectCount++}return protocols[opts.protocol](client,opts)}return new MqttClient(wrapper,opts)}module.exports=connect;module.exports.connect=connect;module.exports.MqttClient=MqttClient;module.exports.Store=Store}).call(this,require("_process"))},{"../client":135,"../store":142,"./ali":136,"./tcp":138,"./tls":139,"./ws":140,"./wx":141,_process:157,url:193,xtend:217}],138:[function(require,module,exports){"use strict";var net=require("net");function buildBuilder(client,opts){var port,host;opts.port=opts.port||1883;opts.hostname=opts.hostname||opts.host||"localhost";port=opts.port;host=opts.hostname;return net.createConnection(port,host)}module.exports=buildBuilder},{net:31}],139:[function(require,module,exports){"use strict";var tls=require("tls");function buildBuilder(mqttClient,opts){var connection;opts.port=opts.port||8883;opts.host=opts.hostname||opts.host||"localhost";opts.rejectUnauthorized=opts.rejectUnauthorized!==false;delete opts.path;connection=tls.connect(opts);connection.on("secureConnect",(function(){if(opts.rejectUnauthorized&&!connection.authorized){connection.emit("error",new Error("TLS not authorized"))}else{connection.removeListener("error",handleTLSerrors)}}));function handleTLSerrors(err){if(opts.rejectUnauthorized){mqttClient.emit("error",err)}connection.end()}connection.on("error",handleTLSerrors);return connection}module.exports=buildBuilder},{tls:31}],140:[function(require,module,exports){(function(process){"use strict";var websocket=require("websocket-stream");var urlModule=require("url");var WSS_OPTIONS=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];var IS_BROWSER=process.title==="browser";function buildUrl(opts,client){var url=opts.protocol+"://"+opts.hostname+":"+opts.port+opts.path;if(typeof opts.transformWsUrl==="function"){url=opts.transformWsUrl(url,opts,client)}return url}function setDefaultOpts(opts){if(!opts.hostname){opts.hostname="localhost"}if(!opts.port){if(opts.protocol==="wss"){opts.port=443}else{opts.port=80}}if(!opts.path){opts.path="/"}if(!opts.wsOptions){opts.wsOptions={}}if(!IS_BROWSER&&opts.protocol==="wss"){WSS_OPTIONS.forEach((function(prop){if(opts.hasOwnProperty(prop)&&!opts.wsOptions.hasOwnProperty(prop)){opts.wsOptions[prop]=opts[prop]}}))}}function createWebSocket(client,opts){var websocketSubProtocol=opts.protocolId==="MQIsdp"&&opts.protocolVersion===3?"mqttv3.1":"mqtt";setDefaultOpts(opts);var url=buildUrl(opts,client);return websocket(url,[websocketSubProtocol],opts.wsOptions)}function buildBuilder(client,opts){return createWebSocket(client,opts)}function buildBuilderBrowser(client,opts){if(!opts.hostname){opts.hostname=opts.host}if(!opts.hostname){if(typeof document==="undefined"){throw new Error("Could not determine host. Specify host manually.")}var parsed=urlModule.parse(document.URL);opts.hostname=parsed.hostname;if(!opts.port){opts.port=parsed.port}}return createWebSocket(client,opts)}if(IS_BROWSER){module.exports=buildBuilderBrowser}else{module.exports=buildBuilder}}).call(this,require("_process"))},{_process:157,url:193,"websocket-stream":214}],141:[function(require,module,exports){(function(process,Buffer){"use strict";var Transform=require("readable-stream").Transform;var duplexify=require("duplexify");var socketTask;var proxy;var stream;function buildProxy(){var proxy=new Transform;proxy._write=function(chunk,encoding,next){socketTask.send({data:chunk.buffer,success:function success(){next()},fail:function fail(errMsg){next(new Error(errMsg))}})};proxy._flush=function socketEnd(done){socketTask.close({success:function success(){done()}})};return proxy}function setDefaultOpts(opts){if(!opts.hostname){opts.hostname="localhost"}if(!opts.path){opts.path="/"}if(!opts.wsOptions){opts.wsOptions={}}}function buildUrl(opts,client){var protocol=opts.protocol==="wxs"?"wss":"ws";var url=protocol+"://"+opts.hostname+opts.path;if(opts.port&&opts.port!==80&&opts.port!==443){url=protocol+"://"+opts.hostname+":"+opts.port+opts.path}if(typeof opts.transformWsUrl==="function"){url=opts.transformWsUrl(url,opts,client)}return url}function bindEventHandler(){socketTask.onOpen((function(){stream.setReadable(proxy);stream.setWritable(proxy);stream.emit("connect")}));socketTask.onMessage((function(res){var data=res.data;if(data instanceof ArrayBuffer)data=Buffer.from(data);else data=Buffer.from(data,"utf8");proxy.push(data)}));socketTask.onClose((function(){stream.end();stream.destroy()}));socketTask.onError((function(res){stream.destroy(new Error(res.errMsg))}))}function buildStream(client,opts){opts.hostname=opts.hostname||opts.host;if(!opts.hostname){throw new Error("Could not determine host. Specify host manually.")}var websocketSubProtocol=opts.protocolId==="MQIsdp"&&opts.protocolVersion===3?"mqttv3.1":"mqtt";setDefaultOpts(opts);var url=buildUrl(opts,client);socketTask=wx.connectSocket({url:url,protocols:websocketSubProtocol});proxy=buildProxy();stream=duplexify.obj();stream._destroy=function(err,cb){socketTask.close({success:function success(){cb&&cb(err)}})};var destroyRef=stream.destroy;stream.destroy=function(){stream.destroy=destroyRef;var self=this;process.nextTick((function(){socketTask.close({fail:function fail(){self._destroy(new Error)}})}))}.bind(stream);bindEventHandler();return stream}module.exports=buildStream}).call(this,require("_process"),require("buffer").Buffer)},{_process:157,buffer:33,duplexify:40,"readable-stream":152}],142:[function(require,module,exports){(function(process){"use strict";var xtend=require("xtend");var Readable=require("readable-stream").Readable;var streamsOpts={objectMode:true};var defaultStoreOptions={clean:true};var Map=require("es6-map");function Store(options){if(!(this instanceof Store)){return new Store(options)}this.options=options||{};this.options=xtend(defaultStoreOptions,options);this._inflights=new Map}Store.prototype.put=function(packet,cb){this._inflights.set(packet.messageId,packet);if(cb){cb()}return this};Store.prototype.createStream=function(){var stream=new Readable(streamsOpts);var destroyed=false;var values=[];var i=0;this._inflights.forEach((function(value,key){values.push(value)}));stream._read=function(){if(!destroyed&&i<values.length){this.push(values[i++])}else{this.push(null)}};stream.destroy=function(){if(destroyed){return}var self=this;destroyed=true;process.nextTick((function(){self.emit("close")}))};return stream};Store.prototype.del=function(packet,cb){packet=this._inflights.get(packet.messageId);if(packet){this._inflights["delete"](packet.messageId);cb(null,packet)}else if(cb){cb(new Error("missing packet"))}return this};Store.prototype.get=function(packet,cb){packet=this._inflights.get(packet.messageId);if(packet){cb(null,packet)}else if(cb){cb(new Error("missing packet"))}return this};Store.prototype.close=function(cb){if(this.options.clean){this._inflights=null}if(cb){cb()}};module.exports=Store}).call(this,require("_process"))},{_process:157,"es6-map":100,"readable-stream":152,xtend:217}],143:[function(require,module,exports){"use strict";function validateTopic(topic){var parts=topic.split("/");for(var i=0;i<parts.length;i++){if(parts[i]==="+"){continue}if(parts[i]==="#"){return i===parts.length-1}if(parts[i].indexOf("+")!==-1||parts[i].indexOf("#")!==-1){return false}}return true}function validateTopics(topics){if(topics.length===0){return"empty_topic_list"}for(var i=0;i<topics.length;i++){if(!validateTopic(topics[i])){return topics[i]}}return null}module.exports={validateTopics:validateTopics}},{}],144:[function(require,module,exports){arguments[4][41][0].apply(exports,arguments)},{"./_stream_readable":146,"./_stream_writable":148,"core-util-is":37,dup:41,inherits:120,"process-nextick-args":156}],145:[function(require,module,exports){arguments[4][42][0].apply(exports,arguments)},{"./_stream_transform":147,"core-util-is":37,dup:42,inherits:120}],146:[function(require,module,exports){arguments[4][43][0].apply(exports,arguments)},{"./_stream_duplex":144,"./internal/streams/BufferList":149,"./internal/streams/destroy":150,"./internal/streams/stream":151,_process:157,"core-util-is":37,dup:43,events:34,inherits:120,isarray:122,"process-nextick-args":156,"safe-buffer":153,"string_decoder/":154,util:31}],147:[function(require,module,exports){arguments[4][44][0].apply(exports,arguments)},{"./_stream_duplex":144,"core-util-is":37,dup:44,inherits:120}],148:[function(require,module,exports){arguments[4][45][0].apply(exports,arguments)},{"./_stream_duplex":144,"./internal/streams/destroy":150,"./internal/streams/stream":151,_process:157,"core-util-is":37,dup:45,inherits:120,"process-nextick-args":156,"safe-buffer":153,timers:180,"util-deprecate":195}],149:[function(require,module,exports){arguments[4][46][0].apply(exports,arguments)},{dup:46,"safe-buffer":153,util:31}],150:[function(require,module,exports){arguments[4][47][0].apply(exports,arguments)},{dup:47,"process-nextick-args":156}],151:[function(require,module,exports){arguments[4][48][0].apply(exports,arguments)},{dup:48,events:34}],152:[function(require,module,exports){arguments[4][49][0].apply(exports,arguments)},{"./lib/_stream_duplex.js":144,"./lib/_stream_passthrough.js":145,"./lib/_stream_readable.js":146,"./lib/_stream_transform.js":147,"./lib/_stream_writable.js":148,dup:49}],153:[function(require,module,exports){arguments[4][50][0].apply(exports,arguments)},{buffer:33,dup:50}],154:[function(require,module,exports){arguments[4][51][0].apply(exports,arguments)},{dup:51,"safe-buffer":153}],155:[function(require,module,exports){"use strict";var wrappy=require("wrappy");module.exports=wrappy(once);module.exports.strict=wrappy(onceStrict);once.proto=once((function(){Object.defineProperty(Function.prototype,"once",{value:function value(){return once(this)},configurable:true});Object.defineProperty(Function.prototype,"onceStrict",{value:function value(){return onceStrict(this)},configurable:true})}));function once(fn){var f=function f(){if(f.called)return f.value;f.called=true;return f.value=fn.apply(this,arguments)};f.called=false;return f}function onceStrict(fn){var f=function f(){if(f.called)throw new Error(f.onceError);f.called=true;return f.value=fn.apply(this,arguments)};var name=fn.name||"Function wrapped with `once`";f.onceError=name+" shouldn't be called more than once";f.called=false;return f}},{wrappy:216}],156:[function(require,module,exports){(function(process){"use strict";if(typeof process==="undefined"||!process.version||process.version.indexOf("v0.")===0||process.version.indexOf("v1.")===0&&process.version.indexOf("v1.8.")!==0){module.exports={nextTick:nextTick}}else{module.exports=process}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:157}],157:[function(require,module,exports){"use strict";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}},{}],158:[function(require,module,exports){"use strict";function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}module.exports=function(qs,sep,eq,options){sep=sep||"&";eq=eq||"=";var obj={};if(typeof qs!=="string"||qs.length===0){return obj}var regexp=/\+/g;qs=qs.split(sep);var maxKeys=1e3;if(options&&typeof options.maxKeys==="number"){maxKeys=options.maxKeys}var len=qs.length;if(maxKeys>0&&len>maxKeys){len=maxKeys}for(var i=0;i<len;++i){var x=qs[i].replace(regexp,"%20"),idx=x.indexOf(eq),kstr,vstr,k,v;if(idx>=0){kstr=x.substr(0,idx);vstr=x.substr(idx+1)}else{kstr=x;vstr=""}k=decodeURIComponent(kstr);v=decodeURIComponent(vstr);if(!hasOwnProperty(obj,k)){obj[k]=v}else if(isArray(obj[k])){obj[k].push(v)}else{obj[k]=[obj[k],v]}}return obj};var isArray=Array.isArray||function(xs){return Object.prototype.toString.call(xs)==="[object Array]"}},{}],159:[function(require,module,exports){"use strict";function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}var stringifyPrimitive=function stringifyPrimitive(v){switch(_typeof(v)){case"string":return v;case"boolean":return v?"true":"false";case"number":return isFinite(v)?v:"";default:return""}};module.exports=function(obj,sep,eq,name){sep=sep||"&";eq=eq||"=";if(obj===null){obj=undefined}if(_typeof(obj)==="object"){return map(objectKeys(obj),(function(k){var ks=encodeURIComponent(stringifyPrimitive(k))+eq;if(isArray(obj[k])){return map(obj[k],(function(v){return ks+encodeURIComponent(stringifyPrimitive(v))})).join(sep)}else{return ks+encodeURIComponent(stringifyPrimitive(obj[k]))}})).join(sep)}if(!name)return"";return encodeURIComponent(stringifyPrimitive(name))+eq+encodeURIComponent(stringifyPrimitive(obj))};var isArray=Array.isArray||function(xs){return Object.prototype.toString.call(xs)==="[object Array]"};function map(xs,f){if(xs.map)return xs.map(f);var res=[];for(var i=0;i<xs.length;i++){res.push(f(xs[i],i))}return res}var objectKeys=Object.keys||function(obj){var res=[];for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))res.push(key)}return res}},{}],160:[function(require,module,exports){"use strict";exports.decode=exports.parse=require("./decode");exports.encode=exports.stringify=require("./encode")},{"./decode":158,"./encode":159}],161:[function(require,module,exports){"use strict";function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype);subClass.prototype.constructor=subClass;subClass.__proto__=superClass}var codes={};function createErrorType(code,message,Base){if(!Base){Base=Error}function getMessage(arg1,arg2,arg3){if(typeof message==="string"){return message}else{return message(arg1,arg2,arg3)}}var NodeError=function(_Base){_inheritsLoose(NodeError,_Base);function NodeError(arg1,arg2,arg3){return _Base.call(this,getMessage(arg1,arg2,arg3))||this}return NodeError}(Base);NodeError.prototype.name=Base.name;NodeError.prototype.code=code;codes[code]=NodeError}function oneOf(expected,thing){if(Array.isArray(expected)){var len=expected.length;expected=expected.map((function(i){return String(i)}));if(len>2){return"one of ".concat(thing," ").concat(expected.slice(0,len-1).join(", "),", or ")+expected[len-1]}else if(len===2){return"one of ".concat(thing," ").concat(expected[0]," or ").concat(expected[1])}else{return"of ".concat(thing," ").concat(expected[0])}}else{return"of ".concat(thing," ").concat(String(expected))}}function startsWith(str,search,pos){return str.substr(!pos||pos<0?0:+pos,search.length)===search}function endsWith(str,search,this_len){if(this_len===undefined||this_len>str.length){this_len=str.length}return str.substring(this_len-search.length,this_len)===search}function includes(str,search,start){if(typeof start!=="number"){start=0}if(start+search.length>str.length){return false}else{return str.indexOf(search,start)!==-1}}createErrorType("ERR_INVALID_OPT_VALUE",(function(name,value){return'The value "'+value+'" is invalid for option "'+name+'"'}),TypeError);createErrorType("ERR_INVALID_ARG_TYPE",(function(name,expected,actual){var determiner;if(typeof expected==="string"&&startsWith(expected,"not ")){determiner="must not be";expected=expected.replace(/^not /,"")}else{determiner="must be"}var msg;if(endsWith(name," argument")){msg="The ".concat(name," ").concat(determiner," ").concat(oneOf(expected,"type"))}else{var type=includes(name,".")?"property":"argument";msg='The "'.concat(name,'" ').concat(type," ").concat(determiner," ").concat(oneOf(expected,"type"))}msg+=". Received type ".concat(_typeof(actual));return msg}),TypeError);createErrorType("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF");createErrorType("ERR_METHOD_NOT_IMPLEMENTED",(function(name){return"The "+name+" method is not implemented"}));createErrorType("ERR_STREAM_PREMATURE_CLOSE","Premature close");createErrorType("ERR_STREAM_DESTROYED",(function(name){return"Cannot call "+name+" after a stream was destroyed"}));createErrorType("ERR_MULTIPLE_CALLBACK","Callback called multiple times");createErrorType("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable");createErrorType("ERR_STREAM_WRITE_AFTER_END","write after end");createErrorType("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);createErrorType("ERR_UNKNOWN_ENCODING",(function(arg){return"Unknown encoding: "+arg}),TypeError);createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event");module.exports.codes=codes},{}],162:[function(require,module,exports){(function(process){"use strict";var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj){keys.push(key)}return keys};module.exports=Duplex;var Readable=require("./_stream_readable");var Writable=require("./_stream_writable");require("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);this.allowHalfOpen=true;if(options){if(options.readable===false)this.readable=false;if(options.writable===false)this.writable=false;if(options.allowHalfOpen===false){this.allowHalfOpen=false;this.once("end",onend)}}}Object.defineProperty(Duplex.prototype,"writableHighWaterMark",{enumerable:false,get:function get(){return this._writableState.highWaterMark}});Object.defineProperty(Duplex.prototype,"writableBuffer",{enumerable:false,get:function get(){return this._writableState&&this._writableState.getBuffer()}});Object.defineProperty(Duplex.prototype,"writableLength",{enumerable:false,get:function get(){return this._writableState.length}});function onend(){if(this._writableState.ended)return;process.nextTick(onEndNT,this)}function onEndNT(self){self.end()}Object.defineProperty(Duplex.prototype,"destroyed",{enumerable:false,get:function get(){if(this._readableState===undefined||this._writableState===undefined){return false}return this._readableState.destroyed&&this._writableState.destroyed},set:function set(value){if(this._readableState===undefined||this._writableState===undefined){return}this._readableState.destroyed=value;this._writableState.destroyed=value}})}).call(this,require("_process"))},{"./_stream_readable":164,"./_stream_writable":166,_process:157,inherits:120}],163:[function(require,module,exports){"use strict";module.exports=PassThrough;var Transform=require("./_stream_transform");require("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":165,inherits:120}],164:[function(require,module,exports){(function(process,global){"use strict";module.exports=Readable;var Duplex;Readable.ReadableState=ReadableState;var EE=require("events").EventEmitter;var EElistenerCount=function EElistenerCount(emitter,type){return emitter.listeners(type).length};var Stream=require("./internal/streams/stream");var Buffer=require("buffer").Buffer;var OurUint8Array=global.Uint8Array||function(){};function _uint8ArrayToBuffer(chunk){return Buffer.from(chunk)}function _isUint8Array(obj){return Buffer.isBuffer(obj)||obj instanceof OurUint8Array}var debugUtil=require("util");var debug;if(debugUtil&&debugUtil.debuglog){debug=debugUtil.debuglog("stream")}else{debug=function debug(){}}var BufferList=require("./internal/streams/buffer_list");var destroyImpl=require("./internal/streams/destroy");var _require=require("./internal/streams/state"),getHighWaterMark=_require.getHighWaterMark;var _require$codes=require("../errors").codes,ERR_INVALID_ARG_TYPE=_require$codes.ERR_INVALID_ARG_TYPE,ERR_STREAM_PUSH_AFTER_EOF=_require$codes.ERR_STREAM_PUSH_AFTER_EOF,ERR_METHOD_NOT_IMPLEMENTED=_require$codes.ERR_METHOD_NOT_IMPLEMENTED,ERR_STREAM_UNSHIFT_AFTER_END_EVENT=_require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;var StringDecoder;var createReadableStreamAsyncIterator;var from;require("inherits")(Readable,Stream);var errorOrDestroy=destroyImpl.errorOrDestroy;var kProxyEvents=["error","close","destroy","pause","resume"];function prependListener(emitter,event,fn){if(typeof emitter.prependListener==="function")return emitter.prependListener(event,fn);if(!emitter._events||!emitter._events[event])emitter.on(event,fn);else if(Array.isArray(emitter._events[event]))emitter._events[event].unshift(fn);else emitter._events[event]=[fn,emitter._events[event]]}function ReadableState(options,stream,isDuplex){Duplex=Duplex||require("./_stream_duplex");options=options||{};if(typeof isDuplex!=="boolean")isDuplex=stream instanceof Duplex;this.objectMode=!!options.objectMode;if(isDuplex)this.objectMode=this.objectMode||!!options.readableObjectMode;this.highWaterMark=getHighWaterMark(this,options,"readableHighWaterMark",isDuplex);this.buffer=new BufferList;this.length=0;this.pipes=null;this.pipesCount=0;this.flowing=null;this.ended=false;this.endEmitted=false;this.reading=false;this.sync=true;this.needReadable=false;this.emittedReadable=false;this.readableListening=false;this.resumeScheduled=false;this.paused=true;this.emitClose=options.emitClose!==false;this.autoDestroy=!!options.autoDestroy;this.destroyed=false;this.defaultEncoding=options.defaultEncoding||"utf8";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);var isDuplex=this instanceof Duplex;this._readableState=new ReadableState(options,this,isDuplex);this.readable=true;if(options){if(typeof options.read==="function")this._read=options.read;if(typeof options.destroy==="function")this._destroy=options.destroy}Stream.call(this)}Object.defineProperty(Readable.prototype,"destroyed",{enumerable:false,get:function get(){if(this._readableState===undefined){return false}return this._readableState.destroyed},set:function set(value){if(!this._readableState){return}this._readableState.destroyed=value}});Readable.prototype.destroy=destroyImpl.destroy;Readable.prototype._undestroy=destroyImpl.undestroy;Readable.prototype._destroy=function(err,cb){cb(err)};Readable.prototype.push=function(chunk,encoding){var state=this._readableState;var skipChunkCheck;if(!state.objectMode){if(typeof chunk==="string"){encoding=encoding||state.defaultEncoding;if(encoding!==state.encoding){chunk=Buffer.from(chunk,encoding);encoding=""}skipChunkCheck=true}}else{skipChunkCheck=true}return readableAddChunk(this,chunk,encoding,false,skipChunkCheck)};Readable.prototype.unshift=function(chunk){return readableAddChunk(this,chunk,null,true,false)};function readableAddChunk(stream,chunk,encoding,addToFront,skipChunkCheck){debug("readableAddChunk",chunk);var state=stream._readableState;if(chunk===null){state.reading=false;onEofChunk(stream,state)}else{var er;if(!skipChunkCheck)er=chunkInvalid(state,chunk);if(er){errorOrDestroy(stream,er)}else if(state.objectMode||chunk&&chunk.length>0){if(typeof chunk!=="string"&&!state.objectMode&&Object.getPrototypeOf(chunk)!==Buffer.prototype){chunk=_uint8ArrayToBuffer(chunk)}if(addToFront){if(state.endEmitted)errorOrDestroy(stream,new ERR_STREAM_UNSHIFT_AFTER_END_EVENT);else addChunk(stream,state,chunk,true)}else if(state.ended){errorOrDestroy(stream,new ERR_STREAM_PUSH_AFTER_EOF)}else if(state.destroyed){return false}else{state.reading=false;if(state.decoder&&!encoding){chunk=state.decoder.write(chunk);if(state.objectMode||chunk.length!==0)addChunk(stream,state,chunk,false);else maybeReadMore(stream,state)}else{addChunk(stream,state,chunk,false)}}}else if(!addToFront){state.reading=false;maybeReadMore(stream,state)}}return!state.ended&&(state.length<state.highWaterMark||state.length===0)}function addChunk(stream,state,chunk,addToFront){if(state.flowing&&state.length===0&&!state.sync){state.awaitDrain=0;stream.emit("data",chunk)}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)}function chunkInvalid(state,chunk){var er;if(!_isUint8Array(chunk)&&typeof chunk!=="string"&&chunk!==undefined&&!state.objectMode){er=new ERR_INVALID_ARG_TYPE("chunk",["string","Buffer","Uint8Array"],chunk)}return er}Readable.prototype.isPaused=function(){return this._readableState.flowing===false};Readable.prototype.setEncoding=function(enc){if(!StringDecoder)StringDecoder=require("string_decoder/").StringDecoder;var decoder=new StringDecoder(enc);this._readableState.decoder=decoder;this._readableState.encoding=this._readableState.decoder.encoding;var p=this._readableState.buffer.head;var content="";while(p!==null){content+=decoder.write(p.data);p=p.next}this._readableState.buffer.clear();if(content!=="")this._readableState.buffer.push(content);this._readableState.length=content.length;return this};var MAX_HWM=1073741824;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.highWaterMark!==0?state.length>=state.highWaterMark:state.length>0)||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=state.length<=state.highWaterMark;n=0}else{state.length-=n;state.awaitDrain=0}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 onEofChunk(stream,state){debug("onEofChunk");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;if(state.sync){emitReadable(stream)}else{state.needReadable=false;if(!state.emittedReadable){state.emittedReadable=true;emitReadable_(stream)}}}function emitReadable(stream){var state=stream._readableState;debug("emitReadable",state.needReadable,state.emittedReadable);state.needReadable=false;if(!state.emittedReadable){debug("emitReadable",state.flowing);state.emittedReadable=true;process.nextTick(emitReadable_,stream)}}function emitReadable_(stream){var state=stream._readableState;debug("emitReadable_",state.destroyed,state.length,state.ended);if(!state.destroyed&&(state.length||state.ended)){stream.emit("readable");state.emittedReadable=false}state.needReadable=!state.flowing&&!state.ended&&state.length<=state.highWaterMark;flow(stream)}function maybeReadMore(stream,state){if(!state.readingMore){state.readingMore=true;process.nextTick(maybeReadMore_,stream,state)}}function maybeReadMore_(stream,state){while(!state.reading&&!state.ended&&(state.length<state.highWaterMark||state.flowing&&state.length===0)){var len=state.length;debug("maybeReadMore read 0");stream.read(0);if(len===state.length)break}state.readingMore=false}Readable.prototype._read=function(n){errorOrDestroy(this,new ERR_METHOD_NOT_IMPLEMENTED("_read()"))};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:unpipe;if(state.endEmitted)process.nextTick(endFn);else src.once("end",endFn);dest.on("unpipe",onunpipe);function onunpipe(readable,unpipeInfo){debug("onunpipe");if(readable===src){if(unpipeInfo&&unpipeInfo.hasUnpiped===false){unpipeInfo.hasUnpiped=true;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",unpipe);src.removeListener("data",ondata);cleanedUp=true;if(state.awaitDrain&&(!dest._writableState||dest._writableState.needDrain))ondrain()}src.on("data",ondata);function ondata(chunk){debug("ondata");var ret=dest.write(chunk);debug("dest.write",ret);if(ret===false){if((state.pipesCount===1&&state.pipes===dest||state.pipesCount>1&&indexOf(state.pipes,dest)!==-1)&&!cleanedUp){debug("false write response, pause",state.awaitDrain);state.awaitDrain++}src.pause()}}function onerror(er){debug("onerror",er);unpipe();dest.removeListener("error",onerror);if(EElistenerCount(dest,"error")===0)errorOrDestroy(dest,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 pipeOnDrainFunctionResult(){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;var unpipeInfo={hasUnpiped:false};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,unpipeInfo);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,{hasUnpiped:false})}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,unpipeInfo);return this};Readable.prototype.on=function(ev,fn){var res=Stream.prototype.on.call(this,ev,fn);var state=this._readableState;if(ev==="data"){state.readableListening=this.listenerCount("readable")>0;if(state.flowing!==false)this.resume()}else if(ev==="readable"){if(!state.endEmitted&&!state.readableListening){state.readableListening=state.needReadable=true;state.flowing=false;state.emittedReadable=false;debug("on readable",state.length,state.reading);if(state.length){emitReadable(this)}else if(!state.reading){process.nextTick(nReadingNextTick,this)}}}return res};Readable.prototype.addListener=Readable.prototype.on;Readable.prototype.removeListener=function(ev,fn){var res=Stream.prototype.removeListener.call(this,ev,fn);if(ev==="readable"){process.nextTick(updateReadableListening,this)}return res};Readable.prototype.removeAllListeners=function(ev){var res=Stream.prototype.removeAllListeners.apply(this,arguments);if(ev==="readable"||ev===undefined){process.nextTick(updateReadableListening,this)}return res};function updateReadableListening(self){var state=self._readableState;state.readableListening=self.listenerCount("readable")>0;if(state.resumeScheduled&&!state.paused){state.flowing=true}else if(self.listenerCount("data")>0){self.resume()}}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=!state.readableListening;resume(this,state)}state.paused=false;return this};function resume(stream,state){if(!state.resumeScheduled){state.resumeScheduled=true;process.nextTick(resume_,stream,state)}}function resume_(stream,state){debug("resume",state.reading);if(!state.reading){stream.read(0)}state.resumeScheduled=false;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(this._readableState.flowing!==false){debug("pause");this._readableState.flowing=false;this.emit("pause")}this._readableState.paused=true;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 _this=this;var state=this._readableState;var paused=false;stream.on("end",(function(){debug("wrapped end");if(state.decoder&&!state.ended){var chunk=state.decoder.end();if(chunk&&chunk.length)_this.push(chunk)}_this.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=_this.push(chunk);if(!ret){paused=true;stream.pause()}}));for(var i in stream){if(this[i]===undefined&&typeof stream[i]==="function"){this[i]=function methodWrap(method){return function methodWrapReturnFunction(){return stream[method].apply(stream,arguments)}}(i)}}for(var n=0;n<kProxyEvents.length;n++){stream.on(kProxyEvents[n],this.emit.bind(this,kProxyEvents[n]))}this._read=function(n){debug("wrapped _read",n);if(paused){paused=false;stream.resume()}};return this};if(typeof Symbol==="function"){Readable.prototype[Symbol.asyncIterator]=function(){if(createReadableStreamAsyncIterator===undefined){createReadableStreamAsyncIterator=require("./internal/streams/async_iterator")}return createReadableStreamAsyncIterator(this)}}Object.defineProperty(Readable.prototype,"readableHighWaterMark",{enumerable:false,get:function get(){return this._readableState.highWaterMark}});Object.defineProperty(Readable.prototype,"readableBuffer",{enumerable:false,get:function get(){return this._readableState&&this._readableState.buffer}});Object.defineProperty(Readable.prototype,"readableFlowing",{enumerable:false,get:function get(){return this._readableState.flowing},set:function set(state){if(this._readableState){this._readableState.flowing=state}}});Readable._fromList=fromList;Object.defineProperty(Readable.prototype,"readableLength",{enumerable:false,get:function get(){return this._readableState.length}});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.first();else ret=state.buffer.concat(state.length);state.buffer.clear()}else{ret=state.buffer.consume(n,state.decoder)}return ret}function endReadable(stream){var state=stream._readableState;debug("endReadable",state.endEmitted);if(!state.endEmitted){state.ended=true;process.nextTick(endReadableNT,state,stream)}}function endReadableNT(state,stream){debug("endReadableNT",state.endEmitted,state.length);if(!state.endEmitted&&state.length===0){state.endEmitted=true;stream.readable=false;stream.emit("end");if(state.autoDestroy){var wState=stream._writableState;if(!wState||wState.autoDestroy&&wState.finished){stream.destroy()}}}}if(typeof Symbol==="function"){Readable.from=function(iterable,opts){if(from===undefined){from=require("./internal/streams/from")}return from(Readable,iterable,opts)}}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"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../errors":161,"./_stream_duplex":162,"./internal/streams/async_iterator":167,"./internal/streams/buffer_list":168,"./internal/streams/destroy":169,"./internal/streams/from":171,"./internal/streams/state":173,"./internal/streams/stream":174,_process:157,buffer:33,events:34,inherits:120,"string_decoder/":179,util:31}],165:[function(require,module,exports){"use strict";module.exports=Transform;var _require$codes=require("../errors").codes,ERR_METHOD_NOT_IMPLEMENTED=_require$codes.ERR_METHOD_NOT_IMPLEMENTED,ERR_MULTIPLE_CALLBACK=_require$codes.ERR_MULTIPLE_CALLBACK,ERR_TRANSFORM_ALREADY_TRANSFORMING=_require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,ERR_TRANSFORM_WITH_LENGTH_0=_require$codes.ERR_TRANSFORM_WITH_LENGTH_0;var Duplex=require("./_stream_duplex");require("inherits")(Transform,Duplex);function afterTransform(er,data){var ts=this._transformState;ts.transforming=false;var cb=ts.writecb;if(cb===null){return this.emit("error",new ERR_MULTIPLE_CALLBACK)}ts.writechunk=null;ts.writecb=null;if(data!=null)this.push(data);cb(er);var rs=this._readableState;rs.reading=false;if(rs.needReadable||rs.length<rs.highWaterMark){this._read(rs.highWaterMark)}}function Transform(options){if(!(this instanceof Transform))return new Transform(options);Duplex.call(this,options);this._transformState={afterTransform:afterTransform.bind(this),needTransform:false,transforming:false,writecb:null,writechunk:null,writeencoding:null};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.on("prefinish",prefinish)}function prefinish(){var _this=this;if(typeof this._flush==="function"&&!this._readableState.destroyed){this._flush((function(er,data){done(_this,er,data)}))}else{done(this,null,null)}}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){cb(new ERR_METHOD_NOT_IMPLEMENTED("_transform()"))};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.transforming){ts.transforming=true;this._transform(ts.writechunk,ts.writeencoding,ts.afterTransform)}else{ts.needTransform=true}};Transform.prototype._destroy=function(err,cb){Duplex.prototype._destroy.call(this,err,(function(err2){cb(err2)}))};function done(stream,er,data){if(er)return stream.emit("error",er);if(data!=null)stream.push(data);if(stream._writableState.length)throw new ERR_TRANSFORM_WITH_LENGTH_0;if(stream._transformState.transforming)throw new ERR_TRANSFORM_ALREADY_TRANSFORMING;return stream.push(null)}},{"../errors":161,"./_stream_duplex":162,inherits:120}],166:[function(require,module,exports){(function(process,global){"use strict";module.exports=Writable;function WriteReq(chunk,encoding,cb){this.chunk=chunk;this.encoding=encoding;this.callback=cb;this.next=null}function CorkedRequest(state){var _this=this;this.next=null;this.entry=null;this.finish=function(){onCorkedFinish(_this,state)}}var Duplex;Writable.WritableState=WritableState;var internalUtil={deprecate:require("util-deprecate")};var Stream=require("./internal/streams/stream");var Buffer=require("buffer").Buffer;var OurUint8Array=global.Uint8Array||function(){};function _uint8ArrayToBuffer(chunk){return Buffer.from(chunk)}function _isUint8Array(obj){return Buffer.isBuffer(obj)||obj instanceof OurUint8Array}var destroyImpl=require("./internal/streams/destroy");var _require=require("./internal/streams/state"),getHighWaterMark=_require.getHighWaterMark;var _require$codes=require("../errors").codes,ERR_INVALID_ARG_TYPE=_require$codes.ERR_INVALID_ARG_TYPE,ERR_METHOD_NOT_IMPLEMENTED=_require$codes.ERR_METHOD_NOT_IMPLEMENTED,ERR_MULTIPLE_CALLBACK=_require$codes.ERR_MULTIPLE_CALLBACK,ERR_STREAM_CANNOT_PIPE=_require$codes.ERR_STREAM_CANNOT_PIPE,ERR_STREAM_DESTROYED=_require$codes.ERR_STREAM_DESTROYED,ERR_STREAM_NULL_VALUES=_require$codes.ERR_STREAM_NULL_VALUES,ERR_STREAM_WRITE_AFTER_END=_require$codes.ERR_STREAM_WRITE_AFTER_END,ERR_UNKNOWN_ENCODING=_require$codes.ERR_UNKNOWN_ENCODING;var errorOrDestroy=destroyImpl.errorOrDestroy;require("inherits")(Writable,Stream);function nop(){}function WritableState(options,stream,isDuplex){Duplex=Duplex||require("./_stream_duplex");options=options||{};if(typeof isDuplex!=="boolean")isDuplex=stream instanceof Duplex;this.objectMode=!!options.objectMode;if(isDuplex)this.objectMode=this.objectMode||!!options.writableObjectMode;this.highWaterMark=getHighWaterMark(this,options,"writableHighWaterMark",isDuplex);this.finalCalled=false;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;this.destroyed=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.emitClose=options.emitClose!==false;this.autoDestroy=!!options.autoDestroy;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 writableStateBufferGetter(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer "+"instead.","DEP0003")})}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 value(object){if(realHasInstance.call(this,object))return true;if(this!==Writable)return false;return object&&object._writableState instanceof WritableState}})}else{realHasInstance=function realHasInstance(object){return object instanceof this}}function Writable(options){Duplex=Duplex||require("./_stream_duplex");var isDuplex=this instanceof Duplex;if(!isDuplex&&!realHasInstance.call(Writable,this))return new Writable(options);this._writableState=new WritableState(options,this,isDuplex);this.writable=true;if(options){if(typeof options.write==="function")this._write=options.write;if(typeof options.writev==="function")this._writev=options.writev;if(typeof options.destroy==="function")this._destroy=options.destroy;if(typeof options["final"]==="function")this._final=options["final"]}Stream.call(this)}Writable.prototype.pipe=function(){errorOrDestroy(this,new ERR_STREAM_CANNOT_PIPE)};function writeAfterEnd(stream,cb){var er=new ERR_STREAM_WRITE_AFTER_END;errorOrDestroy(stream,er);process.nextTick(cb,er)}function validChunk(stream,state,chunk,cb){var er;if(chunk===null){er=new ERR_STREAM_NULL_VALUES}else if(typeof chunk!=="string"&&!state.objectMode){er=new ERR_INVALID_ARG_TYPE("chunk",["string","Buffer"],chunk)}if(er){errorOrDestroy(stream,er);process.nextTick(cb,er);return false}return true}Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState;var ret=false;var isBuf=!state.objectMode&&_isUint8Array(chunk);if(isBuf&&!Buffer.isBuffer(chunk)){chunk=_uint8ArrayToBuffer(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.ending)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(){this._writableState.corked++};Writable.prototype.uncork=function(){var state=this._writableState;if(state.corked){state.corked--;if(!state.writing&&!state.corked&&!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 ERR_UNKNOWN_ENCODING(encoding);this._writableState.defaultEncoding=encoding;return this};Object.defineProperty(Writable.prototype,"writableBuffer",{enumerable:false,get:function get(){return this._writableState&&this._writableState.getBuffer()}});function decodeChunk(state,chunk,encoding){if(!state.objectMode&&state.decodeStrings!==false&&typeof chunk==="string"){chunk=Buffer.from(chunk,encoding)}return chunk}Object.defineProperty(Writable.prototype,"writableHighWaterMark",{enumerable:false,get:function get(){return this._writableState.highWaterMark}});function writeOrBuffer(stream,state,isBuf,chunk,encoding,cb){if(!isBuf){var newChunk=decodeChunk(state,chunk,encoding);if(chunk!==newChunk){isBuf=true;encoding="buffer";chunk=newChunk}}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={chunk:chunk,encoding:encoding,isBuf:isBuf,callback:cb,next:null};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(state.destroyed)state.onwrite(new ERR_STREAM_DESTROYED("write"));else 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){process.nextTick(cb,er);process.nextTick(finishMaybe,stream,state);stream._writableState.errorEmitted=true;errorOrDestroy(stream,er)}else{cb(er);stream._writableState.errorEmitted=true;errorOrDestroy(stream,er);finishMaybe(stream,state)}}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;if(typeof cb!=="function")throw new ERR_MULTIPLE_CALLBACK;onwriteStateUpdate(state);if(er)onwriteError(stream,state,sync,er,cb);else{var finished=needFinish(state)||stream.destroyed;if(!finished&&!state.corked&&!state.bufferProcessing&&state.bufferedRequest){clearBuffer(stream,state)}if(sync){process.nextTick(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;var allBuffers=true;while(entry){buffer[count]=entry;if(!entry.isBuf)allBuffers=false;entry=entry.next;count+=1}buffer.allBuffers=allBuffers;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)}state.bufferedRequestCount=0}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;state.bufferedRequestCount--;if(state.writing){break}}if(entry===null)state.lastBufferedRequest=null}state.bufferedRequest=entry;state.bufferProcessing=false}Writable.prototype._write=function(chunk,encoding,cb){cb(new ERR_METHOD_NOT_IMPLEMENTED("_write()"))};Writable.prototype._writev=null;Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;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)endWritable(this,state,cb);return this};Object.defineProperty(Writable.prototype,"writableLength",{enumerable:false,get:function get(){return this._writableState.length}});function needFinish(state){return state.ending&&state.length===0&&state.bufferedRequest===null&&!state.finished&&!state.writing}function callFinal(stream,state){stream._final((function(err){state.pendingcb--;if(err){errorOrDestroy(stream,err)}state.prefinished=true;stream.emit("prefinish");finishMaybe(stream,state)}))}function prefinish(stream,state){if(!state.prefinished&&!state.finalCalled){if(typeof stream._final==="function"&&!state.destroyed){state.pendingcb++;state.finalCalled=true;process.nextTick(callFinal,stream,state)}else{state.prefinished=true;stream.emit("prefinish")}}}function finishMaybe(stream,state){var need=needFinish(state);if(need){prefinish(stream,state);if(state.pendingcb===0){state.finished=true;stream.emit("finish");if(state.autoDestroy){var rState=stream._readableState;if(!rState||rState.autoDestroy&&rState.endEmitted){stream.destroy()}}}}return need}function endWritable(stream,state,cb){state.ending=true;finishMaybe(stream,state);if(cb){if(state.finished)process.nextTick(cb);else stream.once("finish",cb)}state.ended=true;stream.writable=false}function onCorkedFinish(corkReq,state,err){var entry=corkReq.entry;corkReq.entry=null;while(entry){var cb=entry.callback;state.pendingcb--;cb(err);entry=entry.next}state.corkedRequestsFree.next=corkReq}Object.defineProperty(Writable.prototype,"destroyed",{enumerable:false,get:function get(){if(this._writableState===undefined){return false}return this._writableState.destroyed},set:function set(value){if(!this._writableState){return}this._writableState.destroyed=value}});Writable.prototype.destroy=destroyImpl.destroy;Writable.prototype._undestroy=destroyImpl.undestroy;Writable.prototype._destroy=function(err,cb){cb(err)}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../errors":161,"./_stream_duplex":162,"./internal/streams/destroy":169,"./internal/streams/state":173,"./internal/streams/stream":174,_process:157,buffer:33,inherits:120,"util-deprecate":195}],167:[function(require,module,exports){(function(process){"use strict";var _Object$setPrototypeO;function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true})}else{obj[key]=value}return obj}var finished=require("./end-of-stream");var kLastResolve=Symbol("lastResolve");var kLastReject=Symbol("lastReject");var kError=Symbol("error");var kEnded=Symbol("ended");var kLastPromise=Symbol("lastPromise");var kHandlePromise=Symbol("handlePromise");var kStream=Symbol("stream");function createIterResult(value,done){return{value:value,done:done}}function readAndResolve(iter){var resolve=iter[kLastResolve];if(resolve!==null){var data=iter[kStream].read();if(data!==null){iter[kLastPromise]=null;iter[kLastResolve]=null;iter[kLastReject]=null;resolve(createIterResult(data,false))}}}function onReadable(iter){process.nextTick(readAndResolve,iter)}function wrapForNext(lastPromise,iter){return function(resolve,reject){lastPromise.then((function(){if(iter[kEnded]){resolve(createIterResult(undefined,true));return}iter[kHandlePromise](resolve,reject)}),reject)}}var AsyncIteratorPrototype=Object.getPrototypeOf((function(){}));var ReadableStreamAsyncIteratorPrototype=Object.setPrototypeOf((_Object$setPrototypeO={get stream(){return this[kStream]},next:function next(){var _this=this;var error=this[kError];if(error!==null){return Promise.reject(error)}if(this[kEnded]){return Promise.resolve(createIterResult(undefined,true))}if(this[kStream].destroyed){return new Promise((function(resolve,reject){process.nextTick((function(){if(_this[kError]){reject(_this[kError])}else{resolve(createIterResult(undefined,true))}}))}))}var lastPromise=this[kLastPromise];var promise;if(lastPromise){promise=new Promise(wrapForNext(lastPromise,this))}else{var data=this[kStream].read();if(data!==null){return Promise.resolve(createIterResult(data,false))}promise=new Promise(this[kHandlePromise])}this[kLastPromise]=promise;return promise}},_defineProperty(_Object$setPrototypeO,Symbol.asyncIterator,(function(){return this})),_defineProperty(_Object$setPrototypeO,"return",(function _return(){var _this2=this;return new Promise((function(resolve,reject){_this2[kStream].destroy(null,(function(err){if(err){reject(err);return}resolve(createIterResult(undefined,true))}))}))})),_Object$setPrototypeO),AsyncIteratorPrototype);var createReadableStreamAsyncIterator=function createReadableStreamAsyncIterator(stream){var _Object$create;var iterator=Object.create(ReadableStreamAsyncIteratorPrototype,(_Object$create={},_defineProperty(_Object$create,kStream,{value:stream,writable:true}),_defineProperty(_Object$create,kLastResolve,{value:null,writable:true}),_defineProperty(_Object$create,kLastReject,{value:null,writable:true}),_defineProperty(_Object$create,kError,{value:null,writable:true}),_defineProperty(_Object$create,kEnded,{value:stream._readableState.endEmitted,writable:true}),_defineProperty(_Object$create,kHandlePromise,{value:function value(resolve,reject){var data=iterator[kStream].read();if(data){iterator[kLastPromise]=null;iterator[kLastResolve]=null;iterator[kLastReject]=null;resolve(createIterResult(data,false))}else{iterator[kLastResolve]=resolve;iterator[kLastReject]=reject}},writable:true}),_Object$create));iterator[kLastPromise]=null;finished(stream,(function(err){if(err&&err.code!=="ERR_STREAM_PREMATURE_CLOSE"){var reject=iterator[kLastReject];if(reject!==null){iterator[kLastPromise]=null;iterator[kLastResolve]=null;iterator[kLastReject]=null;reject(err)}iterator[kError]=err;return}var resolve=iterator[kLastResolve];if(resolve!==null){iterator[kLastPromise]=null;iterator[kLastResolve]=null;iterator[kLastReject]=null;resolve(createIterResult(undefined,true))}iterator[kEnded]=true}));stream.on("readable",onReadable.bind(null,iterator));return iterator};module.exports=createReadableStreamAsyncIterator}).call(this,require("_process"))},{"./end-of-stream":170,_process:157}],168:[function(require,module,exports){"use strict";function ownKeys(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);if(enumerableOnly)symbols=symbols.filter((function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable}));keys.push.apply(keys,symbols)}return keys}function _objectSpread(target){for(var i=1;i<arguments.length;i++){var source=arguments[i]!=null?arguments[i]:{};if(i%2){ownKeys(Object(source),true).forEach((function(key){_defineProperty(target,key,source[key])}))}else if(Object.getOwnPropertyDescriptors){Object.defineProperties(target,Object.getOwnPropertyDescriptors(source))}else{ownKeys(Object(source)).forEach((function(key){Object.defineProperty(target,key,Object.getOwnPropertyDescriptor(source,key))}))}}return target}function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true})}else{obj[key]=value}return obj}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}var _require=require("buffer"),Buffer=_require.Buffer;var _require2=require("util"),inspect=_require2.inspect;var custom=inspect&&inspect.custom||"inspect";function copyBuffer(src,target,offset){Buffer.prototype.copy.call(src,target,offset)}module.exports=function(){function BufferList(){_classCallCheck(this,BufferList);this.head=null;this.tail=null;this.length=0}_createClass(BufferList,[{key:"push",value:function push(v){var entry={data:v,next:null};if(this.length>0)this.tail.next=entry;else this.head=entry;this.tail=entry;++this.length}},{key:"unshift",value:function unshift(v){var entry={data:v,next:this.head};if(this.length===0)this.tail=entry;this.head=entry;++this.length}},{key:"shift",value:function shift(){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}},{key:"clear",value:function clear(){this.head=this.tail=null;this.length=0}},{key:"join",value:function join(s){if(this.length===0)return"";var p=this.head;var ret=""+p.data;while(p=p.next){ret+=s+p.data}return ret}},{key:"concat",value:function concat(n){if(this.length===0)return Buffer.alloc(0);var ret=Buffer.allocUnsafe(n>>>0);var p=this.head;var i=0;while(p){copyBuffer(p.data,ret,i);i+=p.data.length;p=p.next}return ret}},{key:"consume",value:function consume(n,hasStrings){var ret;if(n<this.head.data.length){ret=this.head.data.slice(0,n);this.head.data=this.head.data.slice(n)}else if(n===this.head.data.length){ret=this.shift()}else{ret=hasStrings?this._getString(n):this._getBuffer(n)}return ret}},{key:"first",value:function first(){return this.head.data}},{key:"_getString",value:function _getString(n){var p=this.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)this.head=p.next;else this.head=this.tail=null}else{this.head=p;p.data=str.slice(nb)}break}++c}this.length-=c;return ret}},{key:"_getBuffer",value:function _getBuffer(n){var ret=Buffer.allocUnsafe(n);var p=this.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)this.head=p.next;else this.head=this.tail=null}else{this.head=p;p.data=buf.slice(nb)}break}++c}this.length-=c;return ret}},{key:custom,value:function value(_,options){return inspect(this,_objectSpread({},options,{depth:0,customInspect:false}))}}]);return BufferList}()},{buffer:33,util:31}],169:[function(require,module,exports){(function(process){"use strict";function destroy(err,cb){var _this=this;var readableDestroyed=this._readableState&&this._readableState.destroyed;var writableDestroyed=this._writableState&&this._writableState.destroyed;if(readableDestroyed||writableDestroyed){if(cb){cb(err)}else if(err){if(!this._writableState){process.nextTick(emitErrorNT,this,err)}else if(!this._writableState.errorEmitted){this._writableState.errorEmitted=true;process.nextTick(emitErrorNT,this,err)}}return this}if(this._readableState){this._readableState.destroyed=true}if(this._writableState){this._writableState.destroyed=true}this._destroy(err||null,(function(err){if(!cb&&err){if(!_this._writableState){process.nextTick(emitErrorAndCloseNT,_this,err)}else if(!_this._writableState.errorEmitted){_this._writableState.errorEmitted=true;process.nextTick(emitErrorAndCloseNT,_this,err)}else{process.nextTick(emitCloseNT,_this)}}else if(cb){process.nextTick(emitCloseNT,_this);cb(err)}else{process.nextTick(emitCloseNT,_this)}}));return this}function emitErrorAndCloseNT(self,err){emitErrorNT(self,err);emitCloseNT(self)}function emitCloseNT(self){if(self._writableState&&!self._writableState.emitClose)return;if(self._readableState&&!self._readableState.emitClose)return;self.emit("close")}function undestroy(){if(this._readableState){this._readableState.destroyed=false;this._readableState.reading=false;this._readableState.ended=false;this._readableState.endEmitted=false}if(this._writableState){this._writableState.destroyed=false;this._writableState.ended=false;this._writableState.ending=false;this._writableState.finalCalled=false;this._writableState.prefinished=false;this._writableState.finished=false;this._writableState.errorEmitted=false}}function emitErrorNT(self,err){self.emit("error",err)}function errorOrDestroy(stream,err){var rState=stream._readableState;var wState=stream._writableState;if(rState&&rState.autoDestroy||wState&&wState.autoDestroy)stream.destroy(err);else stream.emit("error",err)}module.exports={destroy:destroy,undestroy:undestroy,errorOrDestroy:errorOrDestroy}}).call(this,require("_process"))},{_process:157}],170:[function(require,module,exports){"use strict";var ERR_STREAM_PREMATURE_CLOSE=require("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;function once(callback){var called=false;return function(){if(called)return;called=true;for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key]}callback.apply(this,args)}}function noop(){}function isRequest(stream){return stream.setHeader&&typeof stream.abort==="function"}function eos(stream,opts,callback){if(typeof opts==="function")return eos(stream,null,opts);if(!opts)opts={};callback=once(callback||noop);var readable=opts.readable||opts.readable!==false&&stream.readable;var writable=opts.writable||opts.writable!==false&&stream.writable;var onlegacyfinish=function onlegacyfinish(){if(!stream.writable)onfinish()};var writableEnded=stream._writableState&&stream._writableState.finished;var onfinish=function onfinish(){writable=false;writableEnded=true;if(!readable)callback.call(stream)};var readableEnded=stream._readableState&&stream._readableState.endEmitted;var onend=function onend(){readable=false;readableEnded=true;if(!writable)callback.call(stream)};var onerror=function onerror(err){callback.call(stream,err)};var onclose=function onclose(){var err;if(readable&&!readableEnded){if(!stream._readableState||!stream._readableState.ended)err=new ERR_STREAM_PREMATURE_CLOSE;return callback.call(stream,err)}if(writable&&!writableEnded){if(!stream._writableState||!stream._writableState.ended)err=new ERR_STREAM_PREMATURE_CLOSE;return callback.call(stream,err)}};var onrequest=function onrequest(){stream.req.on("finish",onfinish)};if(isRequest(stream)){stream.on("complete",onfinish);stream.on("abort",onclose);if(stream.req)onrequest();else stream.on("request",onrequest)}else if(writable&&!stream._writableState){stream.on("end",onlegacyfinish);stream.on("close",onlegacyfinish)}stream.on("end",onend);stream.on("finish",onfinish);if(opts.error!==false)stream.on("error",onerror);stream.on("close",onclose);return function(){stream.removeListener("complete",onfinish);stream.removeListener("abort",onclose);stream.removeListener("request",onrequest);if(stream.req)stream.req.removeListener("finish",onfinish);stream.removeListener("end",onlegacyfinish);stream.removeListener("close",onlegacyfinish);stream.removeListener("finish",onfinish);stream.removeListener("end",onend);stream.removeListener("error",onerror);stream.removeListener("close",onclose)}}module.exports=eos},{"../../../errors":161}],171:[function(require,module,exports){"use strict";module.exports=function(){throw new Error("Readable.from is not available in the browser")}},{}],172:[function(require,module,exports){"use strict";var eos;function once(callback){var called=false;return function(){if(called)return;called=true;callback.apply(void 0,arguments)}}var _require$codes=require("../../../errors").codes,ERR_MISSING_ARGS=_require$codes.ERR_MISSING_ARGS,ERR_STREAM_DESTROYED=_require$codes.ERR_STREAM_DESTROYED;function noop(err){if(err)throw err}function isRequest(stream){return stream.setHeader&&typeof stream.abort==="function"}function destroyer(stream,reading,writing,callback){callback=once(callback);var closed=false;stream.on("close",(function(){closed=true}));if(eos===undefined)eos=require("./end-of-stream");eos(stream,{readable:reading,writable:writing},(function(err){if(err)return callback(err);closed=true;callback()}));var destroyed=false;return function(err){if(closed)return;if(destroyed)return;destroyed=true;if(isRequest(stream))return stream.abort();if(typeof stream.destroy==="function")return stream.destroy();callback(err||new ERR_STREAM_DESTROYED("pipe"))}}function call(fn){fn()}function pipe(from,to){return from.pipe(to)}function popCallback(streams){if(!streams.length)return noop;if(typeof streams[streams.length-1]!=="function")return noop;return streams.pop()}function pipeline(){for(var _len=arguments.length,streams=new Array(_len),_key=0;_key<_len;_key++){streams[_key]=arguments[_key]}var callback=popCallback(streams);if(Array.isArray(streams[0]))streams=streams[0];if(streams.length<2){throw new ERR_MISSING_ARGS("streams")}var error;var destroys=streams.map((function(stream,i){var reading=i<streams.length-1;var writing=i>0;return destroyer(stream,reading,writing,(function(err){if(!error)error=err;if(err)destroys.forEach(call);if(reading)return;destroys.forEach(call);callback(error)}))}));return streams.reduce(pipe)}module.exports=pipeline},{"../../../errors":161,"./end-of-stream":170}],173:[function(require,module,exports){"use strict";var ERR_INVALID_OPT_VALUE=require("../../../errors").codes.ERR_INVALID_OPT_VALUE;function highWaterMarkFrom(options,isDuplex,duplexKey){return options.highWaterMark!=null?options.highWaterMark:isDuplex?options[duplexKey]:null}function getHighWaterMark(state,options,duplexKey,isDuplex){var hwm=highWaterMarkFrom(options,isDuplex,duplexKey);if(hwm!=null){if(!(isFinite(hwm)&&Math.floor(hwm)===hwm)||hwm<0){var name=isDuplex?duplexKey:"highWaterMark";throw new ERR_INVALID_OPT_VALUE(name,hwm)}return Math.floor(hwm)}return state.objectMode?16:16*1024}module.exports={getHighWaterMark:getHighWaterMark}},{"../../../errors":161}],174:[function(require,module,exports){arguments[4][48][0].apply(exports,arguments)},{dup:48,events:34}],175:[function(require,module,exports){"use strict";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");exports.finished=require("./lib/internal/streams/end-of-stream.js");exports.pipeline=require("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":162,"./lib/_stream_passthrough.js":163,"./lib/_stream_readable.js":164,"./lib/_stream_transform.js":165,"./lib/_stream_writable.js":166,"./lib/internal/streams/end-of-stream.js":170,"./lib/internal/streams/pipeline.js":172}],176:[function(require,module,exports){"use strict";function ReInterval(callback,interval,args){var self=this;this._callback=callback;this._args=args;this._interval=setInterval(callback,interval,this._args);this.reschedule=function(interval){if(!interval)interval=self._interval;if(self._interval)clearInterval(self._interval);self._interval=setInterval(self._callback,interval,self._args)};this.clear=function(){if(self._interval){clearInterval(self._interval);self._interval=undefined}};this.destroy=function(){if(self._interval){clearInterval(self._interval)}self._callback=undefined;self._interval=undefined;self._args=undefined}}function reInterval(){if(typeof arguments[0]!=="function")throw new Error("callback needed");if(typeof arguments[1]!=="number")throw new Error("interval needed");var args;if(arguments.length>0){args=new Array(arguments.length-2);for(var i=0;i<args.length;i++){args[i]=arguments[i+2]}}return new ReInterval(arguments[0],arguments[1],args)}module.exports=reInterval},{}],177:[function(require,module,exports){"use strict";
|
|
40
|
+
/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var buffer=require("buffer");var Buffer=buffer.Buffer;function copyProps(src,dst){for(var key in src){dst[key]=src[key]}}if(Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow){module.exports=buffer}else{copyProps(buffer,exports);exports.Buffer=SafeBuffer}function SafeBuffer(arg,encodingOrOffset,length){return Buffer(arg,encodingOrOffset,length)}SafeBuffer.prototype=Object.create(Buffer.prototype);copyProps(Buffer,SafeBuffer);SafeBuffer.from=function(arg,encodingOrOffset,length){if(typeof arg==="number"){throw new TypeError("Argument must not be a number")}return Buffer(arg,encodingOrOffset,length)};SafeBuffer.alloc=function(size,fill,encoding){if(typeof size!=="number"){throw new TypeError("Argument must be a number")}var buf=Buffer(size);if(fill!==undefined){if(typeof encoding==="string"){buf.fill(fill,encoding)}else{buf.fill(fill)}}else{buf.fill(0)}return buf};SafeBuffer.allocUnsafe=function(size){if(typeof size!=="number"){throw new TypeError("Argument must be a number")}return Buffer(size)};SafeBuffer.allocUnsafeSlow=function(size){if(typeof size!=="number"){throw new TypeError("Argument must be a number")}return buffer.SlowBuffer(size)}},{buffer:33}],178:[function(require,module,exports){"use strict";module.exports=shift;function shift(stream){var rs=stream._readableState;if(!rs)return null;return rs.objectMode||typeof stream._duplexState==="number"?stream.read():stream.read(getStateLength(rs))}function getStateLength(state){if(state.buffer.length){if(state.buffer.head){return state.buffer.head.data.length}return state.buffer[0].length}return state.length}},{}],179:[function(require,module,exports){arguments[4][51][0].apply(exports,arguments)},{dup:51,"safe-buffer":177}],180:[function(require,module,exports){(function(setImmediate,clearImmediate){"use strict";var nextTick=require("process/browser.js").nextTick;var apply=Function.prototype.apply;var slice=Array.prototype.slice;var immediateIds={};var nextImmediateId=0;exports.setTimeout=function(){return new Timeout(apply.call(setTimeout,window,arguments),clearTimeout)};exports.setInterval=function(){return new Timeout(apply.call(setInterval,window,arguments),clearInterval)};exports.clearTimeout=exports.clearInterval=function(timeout){timeout.close()};function Timeout(id,clearFn){this._id=id;this._clearFn=clearFn}Timeout.prototype.unref=Timeout.prototype.ref=function(){};Timeout.prototype.close=function(){this._clearFn.call(window,this._id)};exports.enroll=function(item,msecs){clearTimeout(item._idleTimeoutId);item._idleTimeout=msecs};exports.unenroll=function(item){clearTimeout(item._idleTimeoutId);item._idleTimeout=-1};exports._unrefActive=exports.active=function(item){clearTimeout(item._idleTimeoutId);var msecs=item._idleTimeout;if(msecs>=0){item._idleTimeoutId=setTimeout((function onTimeout(){if(item._onTimeout)item._onTimeout()}),msecs)}};exports.setImmediate=typeof setImmediate==="function"?setImmediate:function(fn){var id=nextImmediateId++;var args=arguments.length<2?false:slice.call(arguments,1);immediateIds[id]=true;nextTick((function onNextTick(){if(immediateIds[id]){if(args){fn.apply(null,args)}else{fn.call(null)}exports.clearImmediate(id)}}));return id};exports.clearImmediate=typeof clearImmediate==="function"?clearImmediate:function(id){delete immediateIds[id]}}).call(this,require("timers").setImmediate,require("timers").clearImmediate)},{"process/browser.js":157,timers:180}],181:[function(require,module,exports){"use strict";var sizeof=require("js-sizeof");var TinyCache=function TinyCache(){this._cache={};this._timeouts={};this._hits=0;this._misses=0;this._size=0;return this};TinyCache.prototype={get size(){return this._size},get memsize(){return sizeof(this._cache)},get hits(){return this._hits},get misses(){return this._misses},put:function put(key,value,time){if(this._timeouts[key]){clearTimeout(this._timeouts[key]);delete this._timeouts[key]}this._cache[key]=value;if(!isNaN(time)){this._timeouts[key]=setTimeout(this.del.bind(this,key),time)}++this._size},get:function get(key){if(typeof key==="undefined"){return this._cache}if(!(key in this._cache)){++this._misses;return null}++this._hits;return this._cache[key]},del:function del(key){clearTimeout(this._timeouts[key]);delete this._timeouts[key];if(!(key in this._cache)){return false}delete this._cache[key];--this._size;return true},clear:function clear(){for(var key in this._timeouts){clearTimeout(this._timeouts[key])}this._cache={};this._timeouts={};this._size=0}};TinyCache.shared=new TinyCache;if(typeof module!=="undefined"&&module.exports){module.exports=TinyCache}else if(typeof define==="function"&&define.amd){define([],(function(){return TinyCache}))}else{window.TinyCache=TinyCache}},{"js-sizeof":123}],182:[function(require,module,exports){"use strict";var isPrototype=require("../prototype/is");module.exports=function(value){if(typeof value!=="function")return false;if(!hasOwnProperty.call(value,"length"))return false;try{if(typeof value.length!=="number")return false;if(typeof value.call!=="function")return false;if(typeof value.apply!=="function")return false}catch(error){return false}return!isPrototype(value)}},{"../prototype/is":189}],183:[function(require,module,exports){"use strict";var isValue=require("../value/is"),isObject=require("../object/is"),stringCoerce=require("../string/coerce"),toShortString=require("./to-short-string");var resolveMessage=function resolveMessage(message,value){return message.replace("%v",toShortString(value))};module.exports=function(value,defaultMessage,inputOptions){if(!isObject(inputOptions))throw new TypeError(resolveMessage(defaultMessage,value));if(!isValue(value)){if("default"in inputOptions)return inputOptions["default"];if(inputOptions.isOptional)return null}var errorMessage=stringCoerce(inputOptions.errorMessage);if(!isValue(errorMessage))errorMessage=defaultMessage;throw new TypeError(resolveMessage(errorMessage,value))}},{"../object/is":186,"../string/coerce":190,"../value/is":192,"./to-short-string":185}],184:[function(require,module,exports){"use strict";module.exports=function(value){try{return value.toString()}catch(error){try{return String(value)}catch(error2){return null}}}},{}],185:[function(require,module,exports){"use strict";var safeToString=require("./safe-to-string");var reNewLine=/[\n\r\u2028\u2029]/g;module.exports=function(value){var string=safeToString(value);if(string===null)return"<Non-coercible to string value>";if(string.length>100)string=string.slice(0,99)+"…";string=string.replace(reNewLine,(function(_char){switch(_char){case"\n":return"\\n";case"\r":return"\\r";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:throw new Error("Unexpected character")}}));return string}},{"./safe-to-string":184}],186:[function(require,module,exports){"use strict";function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}var isValue=require("../value/is");var possibleTypes={object:true,function:true,undefined:true};module.exports=function(value){if(!isValue(value))return false;return hasOwnProperty.call(possibleTypes,_typeof(value))}},{"../value/is":192}],187:[function(require,module,exports){"use strict";var resolveException=require("../lib/resolve-exception"),is=require("./is");module.exports=function(value){if(is(value))return value;return resolveException(value,"%v is not a plain function",arguments[1])}},{"../lib/resolve-exception":183,"./is":188}],188:[function(require,module,exports){"use strict";var isFunction=require("../function/is");var classRe=/^\s*class[\s{/}]/,functionToString=Function.prototype.toString;module.exports=function(value){if(!isFunction(value))return false;if(classRe.test(functionToString.call(value)))return false;return true}},{"../function/is":182}],189:[function(require,module,exports){"use strict";var isObject=require("../object/is");module.exports=function(value){if(!isObject(value))return false;try{if(!value.constructor)return false;return value.constructor.prototype===value}catch(error){return false}}},{"../object/is":186}],190:[function(require,module,exports){"use strict";var isValue=require("../value/is"),isObject=require("../object/is");var objectToString=Object.prototype.toString;module.exports=function(value){if(!isValue(value))return null;if(isObject(value)){var valueToString=value.toString;if(typeof valueToString!=="function")return null;if(valueToString===objectToString)return null}try{return""+value}catch(error){return null}}},{"../object/is":186,"../value/is":192}],191:[function(require,module,exports){"use strict";var resolveException=require("../lib/resolve-exception"),is=require("./is");module.exports=function(value){if(is(value))return value;return resolveException(value,"Cannot use %v",arguments[1])}},{"../lib/resolve-exception":183,"./is":192}],192:[function(require,module,exports){"use strict";var _undefined=void 0;module.exports=function(value){return value!==_undefined&&value!==null}},{}],193:[function(require,module,exports){"use strict";function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}var punycode=require("punycode");var util=require("./util");exports.parse=urlParse;exports.resolve=urlResolve;exports.resolveObject=urlResolveObject;exports.format=urlFormat;exports.Url=Url;function Url(){this.protocol=null;this.slashes=null;this.auth=null;this.host=null;this.port=null;this.hostname=null;this.hash=null;this.search=null;this.query=null;this.pathname=null;this.path=null;this.href=null}var protocolPattern=/^([a-z0-9.+-]+:)/i,portPattern=/:[0-9]*$/,simplePathPattern=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,delims=["<",">",'"',"`"," ","\r","\n","\t"],unwise=["{","}","|","\\","^","`"].concat(delims),autoEscape=["'"].concat(unwise),nonHostChars=["%","/","?",";","#"].concat(autoEscape),hostEndingChars=["/","?","#"],hostnameMaxLen=255,hostnamePartPattern=/^[+a-z0-9A-Z_-]{0,63}$/,hostnamePartStart=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,unsafeProtocol={javascript:true,"javascript:":true},hostlessProtocol={javascript:true,"javascript:":true},slashedProtocol={http:true,https:true,ftp:true,gopher:true,file:true,"http:":true,"https:":true,"ftp:":true,"gopher:":true,"file:":true},querystring=require("querystring");function urlParse(url,parseQueryString,slashesDenoteHost){if(url&&util.isObject(url)&&url instanceof Url)return url;var u=new Url;u.parse(url,parseQueryString,slashesDenoteHost);return u}Url.prototype.parse=function(url,parseQueryString,slashesDenoteHost){if(!util.isString(url)){throw new TypeError("Parameter 'url' must be a string, not "+_typeof(url))}var queryIndex=url.indexOf("?"),splitter=queryIndex!==-1&&queryIndex<url.indexOf("#")?"?":"#",uSplit=url.split(splitter),slashRegex=/\\/g;uSplit[0]=uSplit[0].replace(slashRegex,"/");url=uSplit.join(splitter);var rest=url;rest=rest.trim();if(!slashesDenoteHost&&url.split("#").length===1){var simplePath=simplePathPattern.exec(rest);if(simplePath){this.path=rest;this.href=rest;this.pathname=simplePath[1];if(simplePath[2]){this.search=simplePath[2];if(parseQueryString){this.query=querystring.parse(this.search.substr(1))}else{this.query=this.search.substr(1)}}else if(parseQueryString){this.search="";this.query={}}return this}}var proto=protocolPattern.exec(rest);if(proto){proto=proto[0];var lowerProto=proto.toLowerCase();this.protocol=lowerProto;rest=rest.substr(proto.length)}if(slashesDenoteHost||proto||rest.match(/^\/\/[^@\/]+@[^@\/]+/)){var slashes=rest.substr(0,2)==="//";if(slashes&&!(proto&&hostlessProtocol[proto])){rest=rest.substr(2);this.slashes=true}}if(!hostlessProtocol[proto]&&(slashes||proto&&!slashedProtocol[proto])){var hostEnd=-1;for(var i=0;i<hostEndingChars.length;i++){var hec=rest.indexOf(hostEndingChars[i]);if(hec!==-1&&(hostEnd===-1||hec<hostEnd))hostEnd=hec}var auth,atSign;if(hostEnd===-1){atSign=rest.lastIndexOf("@")}else{atSign=rest.lastIndexOf("@",hostEnd)}if(atSign!==-1){auth=rest.slice(0,atSign);rest=rest.slice(atSign+1);this.auth=decodeURIComponent(auth)}hostEnd=-1;for(var i=0;i<nonHostChars.length;i++){var hec=rest.indexOf(nonHostChars[i]);if(hec!==-1&&(hostEnd===-1||hec<hostEnd))hostEnd=hec}if(hostEnd===-1)hostEnd=rest.length;this.host=rest.slice(0,hostEnd);rest=rest.slice(hostEnd);this.parseHost();this.hostname=this.hostname||"";var ipv6Hostname=this.hostname[0]==="["&&this.hostname[this.hostname.length-1]==="]";if(!ipv6Hostname){var hostparts=this.hostname.split(/\./);for(var i=0,l=hostparts.length;i<l;i++){var part=hostparts[i];if(!part)continue;if(!part.match(hostnamePartPattern)){var newpart="";for(var j=0,k=part.length;j<k;j++){if(part.charCodeAt(j)>127){newpart+="x"}else{newpart+=part[j]}}if(!newpart.match(hostnamePartPattern)){var validParts=hostparts.slice(0,i);var notHost=hostparts.slice(i+1);var bit=part.match(hostnamePartStart);if(bit){validParts.push(bit[1]);notHost.unshift(bit[2])}if(notHost.length){rest="/"+notHost.join(".")+rest}this.hostname=validParts.join(".");break}}}}if(this.hostname.length>hostnameMaxLen){this.hostname=""}else{this.hostname=this.hostname.toLowerCase()}if(!ipv6Hostname){this.hostname=punycode.toASCII(this.hostname)}var p=this.port?":"+this.port:"";var h=this.hostname||"";this.host=h+p;this.href+=this.host;if(ipv6Hostname){this.hostname=this.hostname.substr(1,this.hostname.length-2);if(rest[0]!=="/"){rest="/"+rest}}}if(!unsafeProtocol[lowerProto]){for(var i=0,l=autoEscape.length;i<l;i++){var ae=autoEscape[i];if(rest.indexOf(ae)===-1)continue;var esc=encodeURIComponent(ae);if(esc===ae){esc=escape(ae)}rest=rest.split(ae).join(esc)}}var hash=rest.indexOf("#");if(hash!==-1){this.hash=rest.substr(hash);rest=rest.slice(0,hash)}var qm=rest.indexOf("?");if(qm!==-1){this.search=rest.substr(qm);this.query=rest.substr(qm+1);if(parseQueryString){this.query=querystring.parse(this.query)}rest=rest.slice(0,qm)}else if(parseQueryString){this.search="";this.query={}}if(rest)this.pathname=rest;if(slashedProtocol[lowerProto]&&this.hostname&&!this.pathname){this.pathname="/"}if(this.pathname||this.search){var p=this.pathname||"";var s=this.search||"";this.path=p+s}this.href=this.format();return this};function urlFormat(obj){if(util.isString(obj))obj=urlParse(obj);if(!(obj instanceof Url))return Url.prototype.format.call(obj);return obj.format()}Url.prototype.format=function(){var auth=this.auth||"";if(auth){auth=encodeURIComponent(auth);auth=auth.replace(/%3A/i,":");auth+="@"}var protocol=this.protocol||"",pathname=this.pathname||"",hash=this.hash||"",host=false,query="";if(this.host){host=auth+this.host}else if(this.hostname){host=auth+(this.hostname.indexOf(":")===-1?this.hostname:"["+this.hostname+"]");if(this.port){host+=":"+this.port}}if(this.query&&util.isObject(this.query)&&Object.keys(this.query).length){query=querystring.stringify(this.query)}var search=this.search||query&&"?"+query||"";if(protocol&&protocol.substr(-1)!==":")protocol+=":";if(this.slashes||(!protocol||slashedProtocol[protocol])&&host!==false){host="//"+(host||"");if(pathname&&pathname.charAt(0)!=="/")pathname="/"+pathname}else if(!host){host=""}if(hash&&hash.charAt(0)!=="#")hash="#"+hash;if(search&&search.charAt(0)!=="?")search="?"+search;pathname=pathname.replace(/[?#]/g,(function(match){return encodeURIComponent(match)}));search=search.replace("#","%23");return protocol+host+pathname+search+hash};function urlResolve(source,relative){return urlParse(source,false,true).resolve(relative)}Url.prototype.resolve=function(relative){return this.resolveObject(urlParse(relative,false,true)).format()};function urlResolveObject(source,relative){if(!source)return relative;return urlParse(source,false,true).resolveObject(relative)}Url.prototype.resolveObject=function(relative){if(util.isString(relative)){var rel=new Url;rel.parse(relative,false,true);relative=rel}var result=new Url;var tkeys=Object.keys(this);for(var tk=0;tk<tkeys.length;tk++){var tkey=tkeys[tk];result[tkey]=this[tkey]}result.hash=relative.hash;if(relative.href===""){result.href=result.format();return result}if(relative.slashes&&!relative.protocol){var rkeys=Object.keys(relative);for(var rk=0;rk<rkeys.length;rk++){var rkey=rkeys[rk];if(rkey!=="protocol")result[rkey]=relative[rkey]}if(slashedProtocol[result.protocol]&&result.hostname&&!result.pathname){result.path=result.pathname="/"}result.href=result.format();return result}if(relative.protocol&&relative.protocol!==result.protocol){if(!slashedProtocol[relative.protocol]){var keys=Object.keys(relative);for(var v=0;v<keys.length;v++){var k=keys[v];result[k]=relative[k]}result.href=result.format();return result}result.protocol=relative.protocol;if(!relative.host&&!hostlessProtocol[relative.protocol]){var relPath=(relative.pathname||"").split("/");while(relPath.length&&!(relative.host=relPath.shift())){}if(!relative.host)relative.host="";if(!relative.hostname)relative.hostname="";if(relPath[0]!=="")relPath.unshift("");if(relPath.length<2)relPath.unshift("");result.pathname=relPath.join("/")}else{result.pathname=relative.pathname}result.search=relative.search;result.query=relative.query;result.host=relative.host||"";result.auth=relative.auth;result.hostname=relative.hostname||relative.host;result.port=relative.port;if(result.pathname||result.search){var p=result.pathname||"";var s=result.search||"";result.path=p+s}result.slashes=result.slashes||relative.slashes;result.href=result.format();return result}var isSourceAbs=result.pathname&&result.pathname.charAt(0)==="/",isRelAbs=relative.host||relative.pathname&&relative.pathname.charAt(0)==="/",mustEndAbs=isRelAbs||isSourceAbs||result.host&&relative.pathname,removeAllDots=mustEndAbs,srcPath=result.pathname&&result.pathname.split("/")||[],relPath=relative.pathname&&relative.pathname.split("/")||[],psychotic=result.protocol&&!slashedProtocol[result.protocol];if(psychotic){result.hostname="";result.port=null;if(result.host){if(srcPath[0]==="")srcPath[0]=result.host;else srcPath.unshift(result.host)}result.host="";if(relative.protocol){relative.hostname=null;relative.port=null;if(relative.host){if(relPath[0]==="")relPath[0]=relative.host;else relPath.unshift(relative.host)}relative.host=null}mustEndAbs=mustEndAbs&&(relPath[0]===""||srcPath[0]==="")}if(isRelAbs){result.host=relative.host||relative.host===""?relative.host:result.host;result.hostname=relative.hostname||relative.hostname===""?relative.hostname:result.hostname;result.search=relative.search;result.query=relative.query;srcPath=relPath}else if(relPath.length){if(!srcPath)srcPath=[];srcPath.pop();srcPath=srcPath.concat(relPath);result.search=relative.search;result.query=relative.query}else if(!util.isNullOrUndefined(relative.search)){if(psychotic){result.hostname=result.host=srcPath.shift();var authInHost=result.host&&result.host.indexOf("@")>0?result.host.split("@"):false;if(authInHost){result.auth=authInHost.shift();result.host=result.hostname=authInHost.shift()}}result.search=relative.search;result.query=relative.query;if(!util.isNull(result.pathname)||!util.isNull(result.search)){result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")}result.href=result.format();return result}if(!srcPath.length){result.pathname=null;if(result.search){result.path="/"+result.search}else{result.path=null}result.href=result.format();return result}var last=srcPath.slice(-1)[0];var hasTrailingSlash=(result.host||relative.host||srcPath.length>1)&&(last==="."||last==="..")||last==="";var up=0;for(var i=srcPath.length;i>=0;i--){last=srcPath[i];if(last==="."){srcPath.splice(i,1)}else if(last===".."){srcPath.splice(i,1);up++}else if(up){srcPath.splice(i,1);up--}}if(!mustEndAbs&&!removeAllDots){for(;up--;up){srcPath.unshift("..")}}if(mustEndAbs&&srcPath[0]!==""&&(!srcPath[0]||srcPath[0].charAt(0)!=="/")){srcPath.unshift("")}if(hasTrailingSlash&&srcPath.join("/").substr(-1)!=="/"){srcPath.push("")}var isAbsolute=srcPath[0]===""||srcPath[0]&&srcPath[0].charAt(0)==="/";if(psychotic){result.hostname=result.host=isAbsolute?"":srcPath.length?srcPath.shift():"";var authInHost=result.host&&result.host.indexOf("@")>0?result.host.split("@"):false;if(authInHost){result.auth=authInHost.shift();result.host=result.hostname=authInHost.shift()}}mustEndAbs=mustEndAbs||result.host&&srcPath.length;if(mustEndAbs&&!isAbsolute){srcPath.unshift("")}if(!srcPath.length){result.pathname=null;result.path=null}else{result.pathname=srcPath.join("/")}if(!util.isNull(result.pathname)||!util.isNull(result.search)){result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")}result.auth=relative.auth||result.auth;result.slashes=result.slashes||relative.slashes;result.href=result.format();return result};Url.prototype.parseHost=function(){var host=this.host;var port=portPattern.exec(host);if(port){port=port[0];if(port!==":"){this.port=port.substr(1)}host=host.substr(0,host.length-port.length)}if(host)this.hostname=host}},{"./util":194,punycode:35,querystring:160}],194:[function(require,module,exports){"use strict";function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}module.exports={isString:function isString(arg){return typeof arg==="string"},isObject:function isObject(arg){return _typeof(arg)==="object"&&arg!==null},isNull:function isNull(arg){return arg===null},isNullOrUndefined:function isNullOrUndefined(arg){return arg==null}}},{}],195:[function(require,module,exports){(function(global){"use strict";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:{})},{}],196:[function(require,module,exports){"use strict";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(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},{}],197:[function(require,module,exports){"use strict";function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}module.exports=function isBuffer(arg){return arg&&_typeof(arg)==="object"&&typeof arg.copy==="function"&&typeof arg.fill==="function"&&typeof arg.readUInt8==="function"}},{}],198:[function(require,module,exports){(function(process,global){"use strict";function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}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":197,_process:157,inherits:196}],199:[function(require,module,exports){"use strict";var byteToHex=[];for(var i=0;i<256;++i){byteToHex[i]=(i+256).toString(16).substr(1)}function bytesToUuid(buf,offset){var i=offset||0;var bth=byteToHex;return[bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],"-",bth[buf[i++]],bth[buf[i++]],"-",bth[buf[i++]],bth[buf[i++]],"-",bth[buf[i++]],bth[buf[i++]],"-",bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]]].join("")}module.exports=bytesToUuid},{}],200:[function(require,module,exports){"use strict";var getRandomValues=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof window.msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto);if(getRandomValues){var rnds8=new Uint8Array(16);module.exports=function whatwgRNG(){getRandomValues(rnds8);return rnds8}}else{var rnds=new Array(16);module.exports=function mathRNG(){for(var i=0,r;i<16;i++){if((i&3)===0)r=Math.random()*4294967296;rnds[i]=r>>>((i&3)<<3)&255}return rnds}}},{}],201:[function(require,module,exports){"use strict";var rng=require("./lib/rng");var bytesToUuid=require("./lib/bytesToUuid");function v4(options,buf,offset){var i=buf&&offset||0;if(typeof options=="string"){buf=options==="binary"?new Array(16):null;options=null}options=options||{};var rnds=options.random||(options.rng||rng)();rnds[6]=rnds[6]&15|64;rnds[8]=rnds[8]&63|128;if(buf){for(var ii=0;ii<16;++ii){buf[i+ii]=rnds[ii]}}return buf||bytesToUuid(rnds)}module.exports=v4},{"./lib/bytesToUuid":199,"./lib/rng":200}],202:[function(require,module,exports){arguments[4][41][0].apply(exports,arguments)},{"./_stream_readable":204,"./_stream_writable":206,"core-util-is":37,dup:41,inherits:120,"process-nextick-args":156}],203:[function(require,module,exports){arguments[4][42][0].apply(exports,arguments)},{"./_stream_transform":205,"core-util-is":37,dup:42,inherits:120}],204:[function(require,module,exports){arguments[4][43][0].apply(exports,arguments)},{"./_stream_duplex":202,"./internal/streams/BufferList":207,"./internal/streams/destroy":208,"./internal/streams/stream":209,_process:157,"core-util-is":37,dup:43,events:34,inherits:120,isarray:122,"process-nextick-args":156,"safe-buffer":210,"string_decoder/":212,util:31}],205:[function(require,module,exports){arguments[4][44][0].apply(exports,arguments)},{"./_stream_duplex":202,"core-util-is":37,dup:44,inherits:120}],206:[function(require,module,exports){arguments[4][45][0].apply(exports,arguments)},{"./_stream_duplex":202,"./internal/streams/destroy":208,"./internal/streams/stream":209,_process:157,"core-util-is":37,dup:45,inherits:120,"process-nextick-args":156,"safe-buffer":210,timers:180,"util-deprecate":195}],207:[function(require,module,exports){arguments[4][46][0].apply(exports,arguments)},{dup:46,"safe-buffer":210,util:31}],208:[function(require,module,exports){arguments[4][47][0].apply(exports,arguments)},{dup:47,"process-nextick-args":156}],209:[function(require,module,exports){arguments[4][48][0].apply(exports,arguments)},{dup:48,events:34}],210:[function(require,module,exports){arguments[4][50][0].apply(exports,arguments)},{buffer:33,dup:50}],211:[function(require,module,exports){arguments[4][49][0].apply(exports,arguments)},{"./lib/_stream_duplex.js":202,"./lib/_stream_passthrough.js":203,"./lib/_stream_readable.js":204,"./lib/_stream_transform.js":205,"./lib/_stream_writable.js":206,dup:49}],212:[function(require,module,exports){arguments[4][51][0].apply(exports,arguments)},{dup:51,"safe-buffer":213}],213:[function(require,module,exports){arguments[4][50][0].apply(exports,arguments)},{buffer:33,dup:50}],214:[function(require,module,exports){(function(process,global){"use strict";function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}var Transform=require("readable-stream").Transform;var duplexify=require("duplexify");var WS=require("ws");var Buffer=require("safe-buffer").Buffer;module.exports=WebSocketStream;function buildProxy(options,socketWrite,socketEnd){var proxy=new Transform({objectMode:options.objectMode});proxy._write=socketWrite;proxy._flush=socketEnd;return proxy}function WebSocketStream(target,protocols,options){var stream,socket;var isBrowser=process.title==="browser";var isNative=!!global.WebSocket;var socketWrite=isBrowser?socketWriteBrowser:socketWriteNode;if(protocols&&!Array.isArray(protocols)&&"object"===_typeof(protocols)){options=protocols;protocols=null;if(typeof options.protocol==="string"||Array.isArray(options.protocol)){protocols=options.protocol}}if(!options)options={};if(options.objectMode===undefined){options.objectMode=!(options.binary===true||options.binary===undefined)}var proxy=buildProxy(options,socketWrite,socketEnd);if(!options.objectMode){proxy._writev=writev}var bufferSize=options.browserBufferSize||1024*512;var bufferTimeout=options.browserBufferTimeout||1e3;if(_typeof(target)==="object"){socket=target}else{if(isNative&&isBrowser){socket=new WS(target,protocols)}else{socket=new WS(target,protocols,options)}socket.binaryType="arraybuffer"}var eventListenerSupport="undefined"===typeof socket.addEventListener;if(socket.readyState===socket.OPEN){stream=proxy}else{stream=stream=duplexify(undefined,undefined,options);if(!options.objectMode){stream._writev=writev}if(eventListenerSupport){socket.addEventListener("open",onopen)}else{socket.onopen=onopen}}stream.socket=socket;if(eventListenerSupport){socket.addEventListener("close",onclose);socket.addEventListener("error",onerror);socket.addEventListener("message",onmessage)}else{socket.onclose=onclose;socket.onerror=onerror;socket.onmessage=onmessage}proxy.on("close",destroy);var coerceToBuffer=!options.objectMode;function socketWriteNode(chunk,enc,next){if(socket.readyState!==socket.OPEN){next();return}if(coerceToBuffer&&typeof chunk==="string"){chunk=Buffer.from(chunk,"utf8")}socket.send(chunk,next)}function socketWriteBrowser(chunk,enc,next){if(socket.bufferedAmount>bufferSize){setTimeout(socketWriteBrowser,bufferTimeout,chunk,enc,next);return}if(coerceToBuffer&&typeof chunk==="string"){chunk=Buffer.from(chunk,"utf8")}try{socket.send(chunk)}catch(err){return next(err)}next()}function socketEnd(done){socket.close();done()}function onopen(){stream.setReadable(proxy);stream.setWritable(proxy);stream.emit("connect")}function onclose(){stream.end();stream.destroy()}function onerror(err){stream.destroy(err)}function onmessage(event){var data=event.data;if(data instanceof ArrayBuffer)data=Buffer.from(data);else data=Buffer.from(data,"utf8");proxy.push(data)}function destroy(){socket.close()}function writev(chunks,cb){var buffers=new Array(chunks.length);for(var i=0;i<chunks.length;i++){if(typeof chunks[i].chunk==="string"){buffers[i]=Buffer.from(chunks[i],"utf8")}else{buffers[i]=chunks[i].chunk}}this._write(Buffer.concat(buffers),"binary",cb)}return stream}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{_process:157,duplexify:40,"readable-stream":211,"safe-buffer":177,ws:215}],215:[function(require,module,exports){"use strict";var ws=null;if(typeof WebSocket!=="undefined"){ws=WebSocket}else if(typeof MozWebSocket!=="undefined"){ws=MozWebSocket}else if(typeof window!=="undefined"){ws=window.WebSocket||window.MozWebSocket}module.exports=ws},{}],216:[function(require,module,exports){"use strict";module.exports=wrappy;function wrappy(fn,cb){if(fn&&cb)return wrappy(fn)(cb);if(typeof fn!=="function")throw new TypeError("need wrapper function");Object.keys(fn).forEach((function(k){wrapper[k]=fn[k]}));return wrapper;function wrapper(){var args=new Array(arguments.length);for(var i=0;i<args.length;i++){args[i]=arguments[i]}var ret=fn.apply(this,args);var cb=args[args.length-1];if(typeof ret==="function"&&ret!==cb){Object.keys(cb).forEach((function(k){ret[k]=cb[k]}))}return ret}}},{}],217:[function(require,module,exports){"use strict";module.exports=extend;var hasOwnProperty=Object.prototype.hasOwnProperty;function extend(){var target={};for(var i=0;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(hasOwnProperty.call(source,key)){target[key]=source[key]}}}return target}},{}],218:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports._=_createForOfIteratorHelper;exports.a=_typeof;exports.b=_createClass;exports.c=_classCallCheck;exports.e=_defineProperty;exports.h=_slicedToArray;exports.j=_inherits;exports.k=_createSuper;exports.l=_get;exports.m=_getPrototypeOf;exports.p=_assertThisInitialized;exports.q=_toArray;exports.r=_possibleConstructorReturn;exports.o=exports.n=exports.i=exports.g=exports.f=exports.d=exports.Y=exports.T=exports.R=exports.P=exports.N=exports.C=void 0;function _typeof2(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof2=function _typeof2(obj){return typeof obj}}else{_typeof2=function _typeof2(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof2(obj)}function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){exports.a=_typeof=function _typeof(obj){return typeof obj}}else{exports.a=_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true})}else{obj[key]=value}return obj}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function")}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:true,configurable:true}});if(superClass)_setPrototypeOf(subClass,superClass)}function _getPrototypeOf(o){exports.m=_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o)};return _getPrototypeOf(o)}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o};return _setPrototypeOf(o,p)}function _isNativeReflectConstruct(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{Date.prototype.toString.call(Reflect.construct(Date,[],(function(){})));return true}catch(e){return false}}function _construct(Parent,args,Class){if(_isNativeReflectConstruct()){_construct=Reflect.construct}else{_construct=function _construct(Parent,args,Class){var a=[null];a.push.apply(a,args);var Constructor=Function.bind.apply(Parent,a);var instance=new Constructor;if(Class)_setPrototypeOf(instance,Class.prototype);return instance}}return _construct.apply(null,arguments)}function _isNativeFunction(fn){return Function.toString.call(fn).indexOf("[native code]")!==-1}function _wrapNativeSuper(Class){var _cache=typeof Map==="function"?new Map:undefined;_wrapNativeSuper=function _wrapNativeSuper(Class){if(Class===null||!_isNativeFunction(Class))return Class;if(typeof Class!=="function"){throw new TypeError("Super expression must either be null or a function")}if(typeof _cache!=="undefined"){if(_cache.has(Class))return _cache.get(Class);_cache.set(Class,Wrapper)}function Wrapper(){return _construct(Class,arguments,_getPrototypeOf(this).constructor)}Wrapper.prototype=Object.create(Class.prototype,{constructor:{value:Wrapper,enumerable:false,writable:true,configurable:true}});return _setPrototypeOf(Wrapper,Class)};return _wrapNativeSuper(Class)}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return self}function _possibleConstructorReturn(self,call){if(call&&(_typeof2(call)==="object"||typeof call==="function")){return call}return _assertThisInitialized(self)}function _createSuper(Derived){var hasNativeReflectConstruct=_isNativeReflectConstruct();return function(){var Super=_getPrototypeOf(Derived),result;if(hasNativeReflectConstruct){var NewTarget=_getPrototypeOf(this).constructor;result=Reflect.construct(Super,arguments,NewTarget)}else{result=Super.apply(this,arguments)}return _possibleConstructorReturn(this,result)}}function _superPropBase(object,property){while(!Object.prototype.hasOwnProperty.call(object,property)){object=_getPrototypeOf(object);if(object===null)break}return object}function _get(target,property,receiver){if(typeof Reflect!=="undefined"&&Reflect.get){exports.l=_get=Reflect.get}else{exports.l=_get=function _get(target,property,receiver){var base=_superPropBase(target,property);if(!base)return;var desc=Object.getOwnPropertyDescriptor(base,property);if(desc.get){return desc.get.call(receiver)}return desc.value}}return _get(target,property,receiver||target)}function _slicedToArray(arr,i){return _arrayWithHoles(arr)||_iterableToArrayLimit(arr,i)||_unsupportedIterableToArray(arr,i)||_nonIterableRest()}function _toArray(arr){return _arrayWithHoles(arr)||_iterableToArray(arr)||_unsupportedIterableToArray(arr)||_nonIterableRest()}function _arrayWithHoles(arr){if(Array.isArray(arr))return arr}function _iterableToArray(iter){if(typeof Symbol!=="undefined"&&Symbol.iterator in Object(iter))return Array.from(iter)}function _iterableToArrayLimit(arr,i){if(typeof Symbol==="undefined"||!(Symbol.iterator in Object(arr)))return;var _arr=[];var _n=true;var _d=false;var _e=undefined;try{for(var _i=arr[Symbol.iterator](),_s;!(_n=(_s=_i.next()).done);_n=true){_arr.push(_s.value);if(i&&_arr.length===i)break}}catch(err){_d=true;_e=err}finally{try{if(!_n&&_i["return"]!=null)_i["return"]()}finally{if(_d)throw _e}}return _arr}function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen)}function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i<len;i++){arr2[i]=arr[i]}return arr2}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _createForOfIteratorHelper(o){if(typeof Symbol==="undefined"||o[Symbol.iterator]==null){if(Array.isArray(o)||(o=_unsupportedIterableToArray(o))){var i=0;var F=function F(){};return{s:F,n:function n(){if(i>=o.length)return{done:true};return{done:false,value:o[i++]}},e:function e(_e2){throw _e2},f:F}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var it,normalCompletion=true,didErr=false,err;return{s:function s(){it=o[Symbol.iterator]()},n:function n(){var step=it.next();normalCompletion=step.done;return step},e:function e(_e3){didErr=true;err=_e3},f:function f(){try{if(!normalCompletion&&it["return"]!=null)it["return"]()}finally{if(didErr)throw err}}}}var Char={ANCHOR:"&",COMMENT:"#",TAG:"!",DIRECTIVES_END:"-",DOCUMENT_END:"."};exports.C=Char;var Type={ALIAS:"ALIAS",BLANK_LINE:"BLANK_LINE",BLOCK_FOLDED:"BLOCK_FOLDED",BLOCK_LITERAL:"BLOCK_LITERAL",COMMENT:"COMMENT",DIRECTIVE:"DIRECTIVE",DOCUMENT:"DOCUMENT",FLOW_MAP:"FLOW_MAP",FLOW_SEQ:"FLOW_SEQ",MAP:"MAP",MAP_KEY:"MAP_KEY",MAP_VALUE:"MAP_VALUE",PLAIN:"PLAIN",QUOTE_DOUBLE:"QUOTE_DOUBLE",QUOTE_SINGLE:"QUOTE_SINGLE",SEQ:"SEQ",SEQ_ITEM:"SEQ_ITEM"};exports.T=Type;var defaultTagPrefix="tag:yaml.org,2002:";exports.d=defaultTagPrefix;var defaultTags={MAP:"tag:yaml.org,2002:map",SEQ:"tag:yaml.org,2002:seq",STR:"tag:yaml.org,2002:str"};exports.n=defaultTags;function findLineStarts(src){var ls=[0];var offset=src.indexOf("\n");while(offset!==-1){offset+=1;ls.push(offset);offset=src.indexOf("\n",offset)}return ls}function getSrcInfo(cst){var lineStarts,src;if(typeof cst==="string"){lineStarts=findLineStarts(cst);src=cst}else{if(Array.isArray(cst))cst=cst[0];if(cst&&cst.context){if(!cst.lineStarts)cst.lineStarts=findLineStarts(cst.context.src);lineStarts=cst.lineStarts;src=cst.context.src}}return{lineStarts:lineStarts,src:src}}function getLinePos(offset,cst){if(typeof offset!=="number"||offset<0)return null;var _getSrcInfo=getSrcInfo(cst),lineStarts=_getSrcInfo.lineStarts,src=_getSrcInfo.src;if(!lineStarts||!src||offset>src.length)return null;for(var i=0;i<lineStarts.length;++i){var start=lineStarts[i];if(offset<start){return{line:i,col:offset-lineStarts[i-1]+1}}if(offset===start)return{line:i+1,col:1}}var line=lineStarts.length;return{line:line,col:offset-lineStarts[line-1]+1}}function getLine(line,cst){var _getSrcInfo2=getSrcInfo(cst),lineStarts=_getSrcInfo2.lineStarts,src=_getSrcInfo2.src;if(!lineStarts||!(line>=1)||line>lineStarts.length)return null;var start=lineStarts[line-1];var end=lineStarts[line];while(end&&end>start&&src[end-1]==="\n"){--end}return src.slice(start,end)}function getPrettyContext(_ref,cst){var start=_ref.start,end=_ref.end;var maxWidth=arguments.length>2&&arguments[2]!==undefined?arguments[2]:80;var src=getLine(start.line,cst);if(!src)return null;var col=start.col;if(src.length>maxWidth){if(col<=maxWidth-10){src=src.substr(0,maxWidth-1)+"…"}else{var halfWidth=Math.round(maxWidth/2);if(src.length>col+halfWidth)src=src.substr(0,col+halfWidth-1)+"…";col-=src.length-maxWidth;src="…"+src.substr(1-maxWidth)}}var errLen=1;var errEnd="";if(end){if(end.line===start.line&&col+(end.col-start.col)<=maxWidth+1){errLen=end.col-start.col}else{errLen=Math.min(src.length+1,maxWidth)-col;errEnd="…"}}var offset=col>1?" ".repeat(col-1):"";var err="^".repeat(errLen);return"".concat(src,"\n").concat(offset).concat(err).concat(errEnd)}var Range=function(){_createClass(Range,null,[{key:"copy",value:function copy(orig){return new Range(orig.start,orig.end)}}]);function Range(start,end){_classCallCheck(this,Range);this.start=start;this.end=end||start}_createClass(Range,[{key:"isEmpty",value:function isEmpty(){return typeof this.start!=="number"||!this.end||this.end<=this.start}},{key:"setOrigRange",value:function setOrigRange(cr,offset){var start=this.start,end=this.end;if(cr.length===0||end<=cr[0]){this.origStart=start;this.origEnd=end;return offset}var i=offset;while(i<cr.length){if(cr[i]>start)break;else++i}this.origStart=start+i;var nextOffset=i;while(i<cr.length){if(cr[i]>=end)break;else++i}this.origEnd=end+i;return nextOffset}}]);return Range}();exports.R=Range;var Node=function(){_createClass(Node,null,[{key:"addStringTerminator",value:function addStringTerminator(src,offset,str){if(str[str.length-1]==="\n")return str;var next=Node.endOfWhiteSpace(src,offset);return next>=src.length||src[next]==="\n"?str+"\n":str}},{key:"atDocumentBoundary",value:function atDocumentBoundary(src,offset,sep){var ch0=src[offset];if(!ch0)return true;var prev=src[offset-1];if(prev&&prev!=="\n")return false;if(sep){if(ch0!==sep)return false}else{if(ch0!==Char.DIRECTIVES_END&&ch0!==Char.DOCUMENT_END)return false}var ch1=src[offset+1];var ch2=src[offset+2];if(ch1!==ch0||ch2!==ch0)return false;var ch3=src[offset+3];return!ch3||ch3==="\n"||ch3==="\t"||ch3===" "}},{key:"endOfIdentifier",value:function endOfIdentifier(src,offset){var ch=src[offset];var isVerbatim=ch==="<";var notOk=isVerbatim?["\n","\t"," ",">"]:["\n","\t"," ","[","]","{","}",","];while(ch&¬Ok.indexOf(ch)===-1){ch=src[offset+=1]}if(isVerbatim&&ch===">")offset+=1;return offset}},{key:"endOfIndent",value:function endOfIndent(src,offset){var ch=src[offset];while(ch===" "){ch=src[offset+=1]}return offset}},{key:"endOfLine",value:function endOfLine(src,offset){var ch=src[offset];while(ch&&ch!=="\n"){ch=src[offset+=1]}return offset}},{key:"endOfWhiteSpace",value:function endOfWhiteSpace(src,offset){var ch=src[offset];while(ch==="\t"||ch===" "){ch=src[offset+=1]}return offset}},{key:"startOfLine",value:function startOfLine(src,offset){var ch=src[offset-1];if(ch==="\n")return offset;while(ch&&ch!=="\n"){ch=src[offset-=1]}return offset+1}},{key:"endOfBlockIndent",value:function endOfBlockIndent(src,indent,lineStart){var inEnd=Node.endOfIndent(src,lineStart);if(inEnd>lineStart+indent){return inEnd}else{var wsEnd=Node.endOfWhiteSpace(src,inEnd);var ch=src[wsEnd];if(!ch||ch==="\n")return wsEnd}return null}},{key:"atBlank",value:function atBlank(src,offset,endAsBlank){var ch=src[offset];return ch==="\n"||ch==="\t"||ch===" "||endAsBlank&&!ch}},{key:"nextNodeIsIndented",value:function nextNodeIsIndented(ch,indentDiff,indicatorAsIndent){if(!ch||indentDiff<0)return false;if(indentDiff>0)return true;return indicatorAsIndent&&ch==="-"}},{key:"normalizeOffset",value:function normalizeOffset(src,offset){var ch=src[offset];return!ch?offset:ch!=="\n"&&src[offset-1]==="\n"?offset-1:Node.endOfWhiteSpace(src,offset)}},{key:"foldNewline",value:function foldNewline(src,offset,indent){var inCount=0;var error=false;var fold="";var ch=src[offset+1];while(ch===" "||ch==="\t"||ch==="\n"){switch(ch){case"\n":inCount=0;offset+=1;fold+="\n";break;case"\t":if(inCount<=indent)error=true;offset=Node.endOfWhiteSpace(src,offset+2)-1;break;case" ":inCount+=1;offset+=1;break}ch=src[offset+1]}if(!fold)fold=" ";if(ch&&inCount<=indent)error=true;return{fold:fold,offset:offset,error:error}}}]);function Node(type,props,context){_classCallCheck(this,Node);Object.defineProperty(this,"context",{value:context||null,writable:true});this.error=null;this.range=null;this.valueRange=null;this.props=props||[];this.type=type;this.value=null}_createClass(Node,[{key:"getPropValue",value:function getPropValue(idx,key,skipKey){if(!this.context)return null;var src=this.context.src;var prop=this.props[idx];return prop&&src[prop.start]===key?src.slice(prop.start+(skipKey?1:0),prop.end):null}},{key:"commentHasRequiredWhitespace",value:function commentHasRequiredWhitespace(start){var src=this.context.src;if(this.header&&start===this.header.end)return false;if(!this.valueRange)return false;var end=this.valueRange.end;return start!==end||Node.atBlank(src,end-1)}},{key:"parseComment",value:function parseComment(start){var src=this.context.src;if(src[start]===Char.COMMENT){var end=Node.endOfLine(src,start+1);var commentRange=new Range(start,end);this.props.push(commentRange);return end}return start}},{key:"setOrigRanges",value:function setOrigRanges(cr,offset){if(this.range)offset=this.range.setOrigRange(cr,offset);if(this.valueRange)this.valueRange.setOrigRange(cr,offset);this.props.forEach((function(prop){return prop.setOrigRange(cr,offset)}));return offset}},{key:"toString",value:function toString(){var src=this.context.src,range=this.range,value=this.value;if(value!=null)return value;var str=src.slice(range.start,range.end);return Node.addStringTerminator(src,range.end,str)}},{key:"anchor",get:function get(){for(var i=0;i<this.props.length;++i){var anchor=this.getPropValue(i,Char.ANCHOR,true);if(anchor!=null)return anchor}return null}},{key:"comment",get:function get(){var comments=[];for(var i=0;i<this.props.length;++i){var comment=this.getPropValue(i,Char.COMMENT,true);if(comment!=null)comments.push(comment)}return comments.length>0?comments.join("\n"):null}},{key:"hasComment",get:function get(){if(this.context){var src=this.context.src;for(var i=0;i<this.props.length;++i){if(src[this.props[i].start]===Char.COMMENT)return true}}return false}},{key:"hasProps",get:function get(){if(this.context){var src=this.context.src;for(var i=0;i<this.props.length;++i){if(src[this.props[i].start]!==Char.COMMENT)return true}}return false}},{key:"includesTrailingLines",get:function get(){return false}},{key:"jsonLike",get:function get(){var jsonLikeTypes=[Type.FLOW_MAP,Type.FLOW_SEQ,Type.QUOTE_DOUBLE,Type.QUOTE_SINGLE];return jsonLikeTypes.indexOf(this.type)!==-1}},{key:"rangeAsLinePos",get:function get(){if(!this.range||!this.context)return undefined;var start=getLinePos(this.range.start,this.context.root);if(!start)return undefined;var end=getLinePos(this.range.end,this.context.root);return{start:start,end:end}}},{key:"rawValue",get:function get(){if(!this.valueRange||!this.context)return null;var _this$valueRange=this.valueRange,start=_this$valueRange.start,end=_this$valueRange.end;return this.context.src.slice(start,end)}},{key:"tag",get:function get(){for(var i=0;i<this.props.length;++i){var tag=this.getPropValue(i,Char.TAG,false);if(tag!=null){if(tag[1]==="<"){return{verbatim:tag.slice(2,-1)}}else{var _tag$match=tag.match(/^(.*!)([^!]*)$/),_tag$match2=_slicedToArray(_tag$match,3),_=_tag$match2[0],handle=_tag$match2[1],suffix=_tag$match2[2];return{handle:handle,suffix:suffix}}}}return null}},{key:"valueRangeContainsNewline",get:function get(){if(!this.valueRange||!this.context)return false;var _this$valueRange2=this.valueRange,start=_this$valueRange2.start,end=_this$valueRange2.end;var src=this.context.src;for(var i=start;i<end;++i){if(src[i]==="\n")return true}return false}}]);return Node}();exports.N=Node;var YAMLError=function(_Error){_inherits(YAMLError,_Error);var _super=_createSuper(YAMLError);function YAMLError(name,source,message){var _this;_classCallCheck(this,YAMLError);if(!message||!(source instanceof Node))throw new Error("Invalid arguments for new ".concat(name));_this=_super.call(this);_this.name=name;_this.message=message;_this.source=source;return _this}_createClass(YAMLError,[{key:"makePretty",value:function makePretty(){if(!this.source)return;this.nodeType=this.source.type;var cst=this.source.context&&this.source.context.root;if(typeof this.offset==="number"){this.range=new Range(this.offset,this.offset+1);var start=cst&&getLinePos(this.offset,cst);if(start){var end={line:start.line,col:start.col+1};this.linePos={start:start,end:end}}delete this.offset}else{this.range=this.source.range;this.linePos=this.source.rangeAsLinePos}if(this.linePos){var _this$linePos$start=this.linePos.start,line=_this$linePos$start.line,col=_this$linePos$start.col;this.message+=" at line ".concat(line,", column ").concat(col);var ctx=cst&&getPrettyContext(this.linePos,cst);if(ctx)this.message+=":\n\n".concat(ctx,"\n")}delete this.source}}]);return YAMLError}(_wrapNativeSuper(Error));exports.i=YAMLError;var YAMLReferenceError=function(_YAMLError){_inherits(YAMLReferenceError,_YAMLError);var _super2=_createSuper(YAMLReferenceError);function YAMLReferenceError(source,message){_classCallCheck(this,YAMLReferenceError);return _super2.call(this,"YAMLReferenceError",source,message)}return YAMLReferenceError}(YAMLError);exports.o=YAMLReferenceError;var YAMLSemanticError=function(_YAMLError2){_inherits(YAMLSemanticError,_YAMLError2);var _super3=_createSuper(YAMLSemanticError);function YAMLSemanticError(source,message){_classCallCheck(this,YAMLSemanticError);return _super3.call(this,"YAMLSemanticError",source,message)}return YAMLSemanticError}(YAMLError);exports.g=YAMLSemanticError;var YAMLSyntaxError=function(_YAMLError3){_inherits(YAMLSyntaxError,_YAMLError3);var _super4=_createSuper(YAMLSyntaxError);function YAMLSyntaxError(source,message){_classCallCheck(this,YAMLSyntaxError);return _super4.call(this,"YAMLSyntaxError",source,message)}return YAMLSyntaxError}(YAMLError);exports.Y=YAMLSyntaxError;var YAMLWarning=function(_YAMLError4){_inherits(YAMLWarning,_YAMLError4);var _super5=_createSuper(YAMLWarning);function YAMLWarning(source,message){_classCallCheck(this,YAMLWarning);return _super5.call(this,"YAMLWarning",source,message)}return YAMLWarning}(YAMLError);exports.f=YAMLWarning;var PlainValue=function(_Node){_inherits(PlainValue,_Node);var _super=_createSuper(PlainValue);function PlainValue(){_classCallCheck(this,PlainValue);return _super.apply(this,arguments)}_createClass(PlainValue,[{key:"parseBlockValue",value:function parseBlockValue(start){var _this$context=this.context,indent=_this$context.indent,inFlow=_this$context.inFlow,src=_this$context.src;var offset=start;var valueEnd=start;for(var ch=src[offset];ch==="\n";ch=src[offset]){if(Node.atDocumentBoundary(src,offset+1))break;var end=Node.endOfBlockIndent(src,indent,offset+1);if(end===null||src[end]==="#")break;if(src[end]==="\n"){offset=end}else{valueEnd=PlainValue.endOfLine(src,end,inFlow);offset=valueEnd}}if(this.valueRange.isEmpty())this.valueRange.start=start;this.valueRange.end=valueEnd;return valueEnd}},{key:"parse",value:function parse(context,start){this.context=context;var inFlow=context.inFlow,src=context.src;var offset=start;var ch=src[offset];if(ch&&ch!=="#"&&ch!=="\n"){offset=PlainValue.endOfLine(src,start,inFlow)}this.valueRange=new Range(start,offset);offset=Node.endOfWhiteSpace(src,offset);offset=this.parseComment(offset);if(!this.hasComment||this.valueRange.isEmpty()){offset=this.parseBlockValue(offset)}return offset}},{key:"strValue",get:function get(){if(!this.valueRange||!this.context)return null;var _this$valueRange=this.valueRange,start=_this$valueRange.start,end=_this$valueRange.end;var src=this.context.src;var ch=src[end-1];while(start<end&&(ch==="\n"||ch==="\t"||ch===" ")){ch=src[--end-1]}var str="";for(var i=start;i<end;++i){var _ch=src[i];if(_ch==="\n"){var _Node$foldNewline=Node.foldNewline(src,i,-1),fold=_Node$foldNewline.fold,offset=_Node$foldNewline.offset;str+=fold;i=offset}else if(_ch===" "||_ch==="\t"){var wsStart=i;var next=src[i+1];while(i<end&&(next===" "||next==="\t")){i+=1;next=src[i+1]}if(next!=="\n")str+=i>wsStart?src.slice(wsStart,i+1):_ch}else{str+=_ch}}var ch0=src[start];switch(ch0){case"\t":{var msg="Plain value cannot start with a tab character";var errors=[new YAMLSemanticError(this,msg)];return{errors:errors,str:str}}case"@":case"`":{var _msg="Plain value cannot start with reserved character ".concat(ch0);var _errors=[new YAMLSemanticError(this,_msg)];return{errors:_errors,str:str}}default:return str}}}],[{key:"endOfLine",value:function endOfLine(src,start,inFlow){var ch=src[start];var offset=start;while(ch&&ch!=="\n"){if(inFlow&&(ch==="["||ch==="]"||ch==="{"||ch==="}"||ch===","))break;var next=src[offset+1];if(ch===":"&&(!next||next==="\n"||next==="\t"||next===" "||inFlow&&next===","))break;if((ch===" "||ch==="\t")&&next==="#")break;offset+=1;ch=next}return offset}}]);return PlainValue}(Node);exports.P=PlainValue},{}],219:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.S=void 0;var _PlainValueFf5147c=require("./PlainValue-ff5147c6.js");var _resolveSeq04825f=require("./resolveSeq-04825f30.js");var _warnings0e4b70d=require("./warnings-0e4b70d3.js");function createMap(schema,obj,ctx){var map=new _resolveSeq04825f.d(schema);if(obj instanceof Map){var _iterator=(0,_PlainValueFf5147c._)(obj),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var _step$value=(0,_PlainValueFf5147c.h)(_step.value,2),key=_step$value[0],value=_step$value[1];map.items.push(schema.createPair(key,value,ctx))}}catch(err){_iterator.e(err)}finally{_iterator.f()}}else if(obj&&(0,_PlainValueFf5147c.a)(obj)==="object"){for(var _i=0,_Object$keys=Object.keys(obj);_i<_Object$keys.length;_i++){var _key=_Object$keys[_i];map.items.push(schema.createPair(_key,obj[_key],ctx))}}if(typeof schema.sortMapEntries==="function"){map.items.sort(schema.sortMapEntries)}return map}var map={createNode:createMap,default:true,nodeClass:_resolveSeq04825f.d,tag:"tag:yaml.org,2002:map",resolve:_resolveSeq04825f.g};function createSeq(schema,obj,ctx){var seq=new _resolveSeq04825f.Y(schema);if(obj&&obj[Symbol.iterator]){var _iterator=(0,_PlainValueFf5147c._)(obj),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var it=_step.value;var v=schema.createNode(it,ctx.wrapScalars,null,ctx);seq.items.push(v)}}catch(err){_iterator.e(err)}finally{_iterator.f()}}return seq}var seq={createNode:createSeq,default:true,nodeClass:_resolveSeq04825f.Y,tag:"tag:yaml.org,2002:seq",resolve:_resolveSeq04825f.h};var string={identify:function identify(value){return typeof value==="string"},default:true,tag:"tag:yaml.org,2002:str",resolve:_resolveSeq04825f.j,stringify:function stringify(item,ctx,onComment,onChompKeep){ctx=Object.assign({actualString:true},ctx);return(0,_resolveSeq04825f.c)(item,ctx,onComment,onChompKeep)},options:_resolveSeq04825f.s};var failsafe=[map,seq,string];var intIdentify=function intIdentify(value){return typeof value==="bigint"||Number.isInteger(value)};var intResolve=function intResolve(src,part,radix){return _resolveSeq04825f.i.asBigInt?BigInt(src):parseInt(part,radix)};function intStringify(node,radix,prefix){var value=node.value;if(intIdentify(value)&&value>=0)return prefix+value.toString(radix);return(0,_resolveSeq04825f.k)(node)}var nullObj={identify:function identify(value){return value==null},createNode:function createNode(schema,value,ctx){return ctx.wrapScalars?new _resolveSeq04825f.S(null):null},default:true,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:function resolve(){return null},options:_resolveSeq04825f.n,stringify:function stringify(){return _resolveSeq04825f.n.nullStr}};var boolObj={identify:function identify(value){return typeof value==="boolean"},default:true,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:function resolve(str){return str[0]==="t"||str[0]==="T"},options:_resolveSeq04825f.a,stringify:function stringify(_ref){var value=_ref.value;return value?_resolveSeq04825f.a.trueStr:_resolveSeq04825f.a.falseStr}};var octObj={identify:function identify(value){return intIdentify(value)&&value>=0},default:true,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o([0-7]+)$/,resolve:function resolve(str,oct){return intResolve(str,oct,8)},options:_resolveSeq04825f.i,stringify:function stringify(node){return intStringify(node,8,"0o")}};var intObj={identify:intIdentify,default:true,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:function resolve(str){return intResolve(str,str,10)},options:_resolveSeq04825f.i,stringify:_resolveSeq04825f.k};var hexObj={identify:function identify(value){return intIdentify(value)&&value>=0},default:true,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x([0-9a-fA-F]+)$/,resolve:function resolve(str,hex){return intResolve(str,hex,16)},options:_resolveSeq04825f.i,stringify:function stringify(node){return intStringify(node,16,"0x")}};var nanObj={identify:function identify(value){return typeof value==="number"},default:true,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.inf|(\.nan))$/i,resolve:function resolve(str,nan){return nan?NaN:str[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY},stringify:_resolveSeq04825f.k};var expObj={identify:function identify(value){return typeof value==="number"},default:true,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:function resolve(str){return parseFloat(str)},stringify:function stringify(_ref2){var value=_ref2.value;return Number(value).toExponential()}};var floatObj={identify:function identify(value){return typeof value==="number"},default:true,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.([0-9]+)|[0-9]+\.([0-9]*))$/,resolve:function resolve(str,frac1,frac2){var frac=frac1||frac2;var node=new _resolveSeq04825f.S(parseFloat(str));if(frac&&frac[frac.length-1]==="0")node.minFractionDigits=frac.length;return node},stringify:_resolveSeq04825f.k};var core=failsafe.concat([nullObj,boolObj,octObj,intObj,hexObj,nanObj,expObj,floatObj]);var intIdentify$1=function intIdentify(value){return typeof value==="bigint"||Number.isInteger(value)};var stringifyJSON=function stringifyJSON(_ref){var value=_ref.value;return JSON.stringify(value)};var json=[map,seq,{identify:function identify(value){return typeof value==="string"},default:true,tag:"tag:yaml.org,2002:str",resolve:_resolveSeq04825f.j,stringify:stringifyJSON},{identify:function identify(value){return value==null},createNode:function createNode(schema,value,ctx){return ctx.wrapScalars?new _resolveSeq04825f.S(null):null},default:true,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:function resolve(){return null},stringify:stringifyJSON},{identify:function identify(value){return typeof value==="boolean"},default:true,tag:"tag:yaml.org,2002:bool",test:/^true|false$/,resolve:function resolve(str){return str==="true"},stringify:stringifyJSON},{identify:intIdentify$1,default:true,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:function resolve(str){return _resolveSeq04825f.i.asBigInt?BigInt(str):parseInt(str,10)},stringify:function stringify(_ref2){var value=_ref2.value;return intIdentify$1(value)?value.toString():JSON.stringify(value)}},{identify:function identify(value){return typeof value==="number"},default:true,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:function resolve(str){return parseFloat(str)},stringify:stringifyJSON}];json.scalarFallback=function(str){throw new SyntaxError("Unresolved plain scalar ".concat(JSON.stringify(str)))};var boolStringify=function boolStringify(_ref){var value=_ref.value;return value?_resolveSeq04825f.a.trueStr:_resolveSeq04825f.a.falseStr};var intIdentify$2=function intIdentify(value){return typeof value==="bigint"||Number.isInteger(value)};function intResolve$1(sign,src,radix){var str=src.replace(/_/g,"");if(_resolveSeq04825f.i.asBigInt){switch(radix){case 2:str="0b".concat(str);break;case 8:str="0o".concat(str);break;case 16:str="0x".concat(str);break}var _n=BigInt(str);return sign==="-"?BigInt(-1)*_n:_n}var n=parseInt(str,radix);return sign==="-"?-1*n:n}function intStringify$1(node,radix,prefix){var value=node.value;if(intIdentify$2(value)){var str=value.toString(radix);return value<0?"-"+prefix+str.substr(1):prefix+str}return(0,_resolveSeq04825f.k)(node)}var yaml11=failsafe.concat([{identify:function identify(value){return value==null},createNode:function createNode(schema,value,ctx){return ctx.wrapScalars?new _resolveSeq04825f.S(null):null},default:true,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:function resolve(){return null},options:_resolveSeq04825f.n,stringify:function stringify(){return _resolveSeq04825f.n.nullStr}},{identify:function identify(value){return typeof value==="boolean"},default:true,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:function resolve(){return true},options:_resolveSeq04825f.a,stringify:boolStringify},{identify:function identify(value){return typeof value==="boolean"},default:true,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/i,resolve:function resolve(){return false},options:_resolveSeq04825f.a,stringify:boolStringify},{identify:intIdentify$2,default:true,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^([-+]?)0b([0-1_]+)$/,resolve:function resolve(str,sign,bin){return intResolve$1(sign,bin,2)},stringify:function stringify(node){return intStringify$1(node,2,"0b")}},{identify:intIdentify$2,default:true,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^([-+]?)0([0-7_]+)$/,resolve:function resolve(str,sign,oct){return intResolve$1(sign,oct,8)},stringify:function stringify(node){return intStringify$1(node,8,"0")}},{identify:intIdentify$2,default:true,tag:"tag:yaml.org,2002:int",test:/^([-+]?)([0-9][0-9_]*)$/,resolve:function resolve(str,sign,abs){return intResolve$1(sign,abs,10)},stringify:_resolveSeq04825f.k},{identify:intIdentify$2,default:true,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^([-+]?)0x([0-9a-fA-F_]+)$/,resolve:function resolve(str,sign,hex){return intResolve$1(sign,hex,16)},stringify:function stringify(node){return intStringify$1(node,16,"0x")}},{identify:function identify(value){return typeof value==="number"},default:true,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.inf|(\.nan))$/i,resolve:function resolve(str,nan){return nan?NaN:str[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY},stringify:_resolveSeq04825f.k},{identify:function identify(value){return typeof value==="number"},default:true,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?([0-9][0-9_]*)?(\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:function resolve(str){return parseFloat(str.replace(/_/g,""))},stringify:function stringify(_ref2){var value=_ref2.value;return Number(value).toExponential()}},{identify:function identify(value){return typeof value==="number"},default:true,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.([0-9_]*)$/,resolve:function resolve(str,frac){var node=new _resolveSeq04825f.S(parseFloat(str.replace(/_/g,"")));if(frac){var f=frac.replace(/_/g,"");if(f[f.length-1]==="0")node.minFractionDigits=f.length}return node},stringify:_resolveSeq04825f.k}],_warnings0e4b70d.b,_warnings0e4b70d.o,_warnings0e4b70d.p,_warnings0e4b70d.s,_warnings0e4b70d.i,_warnings0e4b70d.f,_warnings0e4b70d.t);var schemas={core:core,failsafe:failsafe,json:json,yaml11:yaml11};var tags={binary:_warnings0e4b70d.b,bool:boolObj,float:floatObj,floatExp:expObj,floatNaN:nanObj,floatTime:_warnings0e4b70d.f,int:intObj,intHex:hexObj,intOct:octObj,intTime:_warnings0e4b70d.i,map:map,null:nullObj,omap:_warnings0e4b70d.o,pairs:_warnings0e4b70d.p,seq:seq,set:_warnings0e4b70d.s,timestamp:_warnings0e4b70d.t};function findTagObject(value,tagName,tags){if(tagName){var match=tags.filter((function(t){return t.tag===tagName}));var tagObj=match.find((function(t){return!t.format}))||match[0];if(!tagObj)throw new Error("Tag ".concat(tagName," not found"));return tagObj}return tags.find((function(t){return(t.identify&&t.identify(value)||t["class"]&&value instanceof t["class"])&&!t.format}))}function createNode(value,tagName,ctx){if(value instanceof _resolveSeq04825f.N)return value;var defaultPrefix=ctx.defaultPrefix,onTagObj=ctx.onTagObj,prevObjects=ctx.prevObjects,schema=ctx.schema,wrapScalars=ctx.wrapScalars;if(tagName&&tagName.startsWith("!!"))tagName=defaultPrefix+tagName.slice(2);var tagObj=findTagObject(value,tagName,schema.tags);if(!tagObj){if(typeof value.toJSON==="function")value=value.toJSON();if((0,_PlainValueFf5147c.a)(value)!=="object")return wrapScalars?new _resolveSeq04825f.S(value):value;tagObj=value instanceof Map?map:value[Symbol.iterator]?seq:map}if(onTagObj){onTagObj(tagObj);delete ctx.onTagObj}var obj={};if(value&&(0,_PlainValueFf5147c.a)(value)==="object"&&prevObjects){var prev=prevObjects.get(value);if(prev){var alias=new _resolveSeq04825f.A(prev);ctx.aliasNodes.push(alias);return alias}obj.value=value;prevObjects.set(value,obj)}obj.node=tagObj.createNode?tagObj.createNode(ctx.schema,value,ctx):wrapScalars?new _resolveSeq04825f.S(value):value;if(tagName&&obj.node instanceof _resolveSeq04825f.N)obj.node.tag=tagName;return obj.node}function getSchemaTags(schemas,knownTags,customTags,schemaId){var tags=schemas[schemaId.replace(/\W/g,"")];if(!tags){var keys=Object.keys(schemas).map((function(key){return JSON.stringify(key)})).join(", ");throw new Error('Unknown schema "'.concat(schemaId,'"; use one of ').concat(keys))}if(Array.isArray(customTags)){var _iterator=(0,_PlainValueFf5147c._)(customTags),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var tag=_step.value;tags=tags.concat(tag)}}catch(err){_iterator.e(err)}finally{_iterator.f()}}else if(typeof customTags==="function"){tags=customTags(tags.slice())}for(var i=0;i<tags.length;++i){var _tag=tags[i];if(typeof _tag==="string"){var tagObj=knownTags[_tag];if(!tagObj){var _keys=Object.keys(knownTags).map((function(key){return JSON.stringify(key)})).join(", ");throw new Error('Unknown custom tag "'.concat(_tag,'"; use one of ').concat(_keys))}tags[i]=tagObj}}return tags}var sortMapEntriesByKey=function sortMapEntriesByKey(a,b){return a.key<b.key?-1:a.key>b.key?1:0};var Schema=function(){function Schema(_ref){var customTags=_ref.customTags,merge=_ref.merge,schema=_ref.schema,sortMapEntries=_ref.sortMapEntries,deprecatedCustomTags=_ref.tags;(0,_PlainValueFf5147c.c)(this,Schema);this.merge=!!merge;this.name=schema;this.sortMapEntries=sortMapEntries===true?sortMapEntriesByKey:sortMapEntries||null;if(!customTags&&deprecatedCustomTags)(0,_warnings0e4b70d.a)("tags","customTags");this.tags=getSchemaTags(schemas,tags,customTags||deprecatedCustomTags,schema)}(0,_PlainValueFf5147c.b)(Schema,[{key:"createNode",value:function createNode$1(value,wrapScalars,tagName,ctx){var baseCtx={defaultPrefix:Schema.defaultPrefix,schema:this,wrapScalars:wrapScalars};var createCtx=ctx?Object.assign(ctx,baseCtx):baseCtx;return createNode(value,tagName,createCtx)}},{key:"createPair",value:function createPair(key,value,ctx){if(!ctx)ctx={wrapScalars:true};var k=this.createNode(key,ctx.wrapScalars,null,ctx);var v=this.createNode(value,ctx.wrapScalars,null,ctx);return new _resolveSeq04825f.P(k,v)}}]);return Schema}();exports.S=Schema;(0,_PlainValueFf5147c.e)(Schema,"defaultPrefix",_PlainValueFf5147c.d);(0,_PlainValueFf5147c.e)(Schema,"defaultTags",_PlainValueFf5147c.n)},{"./PlainValue-ff5147c6.js":218,"./resolveSeq-04825f30.js":222,"./warnings-0e4b70d3.js":223}],220:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.YAML=void 0;var _PlainValueFf5147c=require("./PlainValue-ff5147c6.js");var _parseCst=require("./parse-cst.js");var _resolveSeq04825f=require("./resolveSeq-04825f30.js");var _Schema2bf2c74e=require("./Schema-2bf2c74e.js");var _warnings0e4b70d=require("./warnings-0e4b70d3.js");var defaultOptions={anchorPrefix:"a",customTags:null,indent:2,indentSeq:true,keepCstNodes:false,keepNodeTypes:true,keepBlobsInJSON:true,mapAsMap:false,maxAliasCount:100,prettyErrors:false,simpleKeys:false,version:"1.2"};var scalarOptions={get binary(){return _resolveSeq04825f.b},set binary(opt){Object.assign(_resolveSeq04825f.b,opt)},get bool(){return _resolveSeq04825f.a},set bool(opt){Object.assign(_resolveSeq04825f.a,opt)},get int(){return _resolveSeq04825f.i},set int(opt){Object.assign(_resolveSeq04825f.i,opt)},get null(){return _resolveSeq04825f.n},set null(opt){Object.assign(_resolveSeq04825f.n,opt)},get str(){return _resolveSeq04825f.s},set str(opt){Object.assign(_resolveSeq04825f.s,opt)}};var documentOptions={"1.0":{schema:"yaml-1.1",merge:true,tagPrefixes:[{handle:"!",prefix:_PlainValueFf5147c.d},{handle:"!!",prefix:"tag:private.yaml.org,2002:"}]},1.1:{schema:"yaml-1.1",merge:true,tagPrefixes:[{handle:"!",prefix:"!"},{handle:"!!",prefix:_PlainValueFf5147c.d}]},1.2:{schema:"core",merge:false,tagPrefixes:[{handle:"!",prefix:"!"},{handle:"!!",prefix:_PlainValueFf5147c.d}]}};function stringifyTag(doc,tag){if((doc.version||doc.options.version)==="1.0"){var priv=tag.match(/^tag:private\.yaml\.org,2002:([^:/]+)$/);if(priv)return"!"+priv[1];var vocab=tag.match(/^tag:([a-zA-Z0-9-]+)\.yaml\.org,2002:(.*)/);return vocab?"!".concat(vocab[1],"/").concat(vocab[2]):"!".concat(tag.replace(/^tag:/,""))}var p=doc.tagPrefixes.find((function(p){return tag.indexOf(p.prefix)===0}));if(!p){var dtp=doc.getDefaults().tagPrefixes;p=dtp&&dtp.find((function(p){return tag.indexOf(p.prefix)===0}))}if(!p)return tag[0]==="!"?tag:"!<".concat(tag,">");var suffix=tag.substr(p.prefix.length).replace(/[!,[\]{}]/g,(function(ch){return{"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"}[ch]}));return p.handle+suffix}function getTagObject(tags,item){if(item instanceof _resolveSeq04825f.A)return _resolveSeq04825f.A;if(item.tag){var match=tags.filter((function(t){return t.tag===item.tag}));if(match.length>0)return match.find((function(t){return t.format===item.format}))||match[0]}var tagObj,obj;if(item instanceof _resolveSeq04825f.S){obj=item.value;var _match=tags.filter((function(t){return t.identify&&t.identify(obj)||t["class"]&&obj instanceof t["class"]}));tagObj=_match.find((function(t){return t.format===item.format}))||_match.find((function(t){return!t.format}))}else{obj=item;tagObj=tags.find((function(t){return t.nodeClass&&obj instanceof t.nodeClass}))}if(!tagObj){var name=obj&&obj.constructor?obj.constructor.name:(0,_PlainValueFf5147c.a)(obj);throw new Error("Tag not resolved for ".concat(name," value"))}return tagObj}function stringifyProps(node,tagObj,_ref){var anchors=_ref.anchors,doc=_ref.doc;var props=[];var anchor=doc.anchors.getName(node);if(anchor){anchors[anchor]=node;props.push("&".concat(anchor))}if(node.tag){props.push(stringifyTag(doc,node.tag))}else if(!tagObj["default"]){props.push(stringifyTag(doc,tagObj.tag))}return props.join(" ")}function stringify(item,ctx,onComment,onChompKeep){var _ctx$doc=ctx.doc,anchors=_ctx$doc.anchors,schema=_ctx$doc.schema;var tagObj;if(!(item instanceof _resolveSeq04825f.N)){var createCtx={aliasNodes:[],onTagObj:function onTagObj(o){return tagObj=o},prevObjects:new Map};item=schema.createNode(item,true,null,createCtx);var _iterator=(0,_PlainValueFf5147c._)(createCtx.aliasNodes),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var alias=_step.value;alias.source=alias.source.node;var name=anchors.getName(alias.source);if(!name){name=anchors.newName();anchors.map[name]=alias.source}}}catch(err){_iterator.e(err)}finally{_iterator.f()}}if(item instanceof _resolveSeq04825f.P)return item.toString(ctx,onComment,onChompKeep);if(!tagObj)tagObj=getTagObject(schema.tags,item);var props=stringifyProps(item,tagObj,ctx);if(props.length>0)ctx.indentAtStart=(ctx.indentAtStart||0)+props.length+1;var str=typeof tagObj.stringify==="function"?tagObj.stringify(item,ctx,onComment,onChompKeep):item instanceof _resolveSeq04825f.S?(0,_resolveSeq04825f.c)(item,ctx,onComment,onChompKeep):item.toString(ctx,onComment,onChompKeep);if(!props)return str;return item instanceof _resolveSeq04825f.S||str[0]==="{"||str[0]==="["?"".concat(props," ").concat(str):"".concat(props,"\n").concat(ctx.indent).concat(str)}var Anchors=function(){(0,_PlainValueFf5147c.b)(Anchors,null,[{key:"validAnchorNode",value:function validAnchorNode(node){return node instanceof _resolveSeq04825f.S||node instanceof _resolveSeq04825f.Y||node instanceof _resolveSeq04825f.d}}]);function Anchors(prefix){(0,_PlainValueFf5147c.c)(this,Anchors);(0,_PlainValueFf5147c.e)(this,"map",{});this.prefix=prefix}(0,_PlainValueFf5147c.b)(Anchors,[{key:"createAlias",value:function createAlias(node,name){this.setAnchor(node,name);return new _resolveSeq04825f.A(node)}},{key:"createMergePair",value:function createMergePair(){var _this=this;var merge=new _resolveSeq04825f.M;for(var _len=arguments.length,sources=new Array(_len),_key=0;_key<_len;_key++){sources[_key]=arguments[_key]}merge.value.items=sources.map((function(s){if(s instanceof _resolveSeq04825f.A){if(s.source instanceof _resolveSeq04825f.d)return s}else if(s instanceof _resolveSeq04825f.d){return _this.createAlias(s)}throw new Error("Merge sources must be Map nodes or their Aliases")}));return merge}},{key:"getName",value:function getName(node){var map=this.map;return Object.keys(map).find((function(a){return map[a]===node}))}},{key:"getNames",value:function getNames(){return Object.keys(this.map)}},{key:"getNode",value:function getNode(name){return this.map[name]}},{key:"newName",value:function newName(prefix){if(!prefix)prefix=this.prefix;var names=Object.keys(this.map);for(var i=1;true;++i){var name="".concat(prefix).concat(i);if(!names.includes(name))return name}}},{key:"resolveNodes",value:function resolveNodes(){var map=this.map,_cstAliases=this._cstAliases;Object.keys(map).forEach((function(a){map[a]=map[a].resolved}));_cstAliases.forEach((function(a){a.source=a.source.resolved}));delete this._cstAliases}},{key:"setAnchor",value:function setAnchor(node,name){if(node!=null&&!Anchors.validAnchorNode(node)){throw new Error("Anchors may only be set for Scalar, Seq and Map nodes")}if(name&&/[\x00-\x19\s,[\]{}]/.test(name)){throw new Error("Anchor names must not contain whitespace or control characters")}var map=this.map;var prev=node&&Object.keys(map).find((function(a){return map[a]===node}));if(prev){if(!name){return prev}else if(prev!==name){delete map[prev];map[name]=node}}else{if(!name){if(!node)return null;name=this.newName()}map[name]=node}return name}}]);return Anchors}();var visit=function visit(node,tags){if(node&&(0,_PlainValueFf5147c.a)(node)==="object"){var tag=node.tag;if(node instanceof _resolveSeq04825f.C){if(tag)tags[tag]=true;node.items.forEach((function(n){return visit(n,tags)}))}else if(node instanceof _resolveSeq04825f.P){visit(node.key,tags);visit(node.value,tags)}else if(node instanceof _resolveSeq04825f.S){if(tag)tags[tag]=true}}return tags};var listTagNames=function listTagNames(node){return Object.keys(visit(node,{}))};function parseContents(doc,contents){var comments={before:[],after:[]};var body=undefined;var spaceBefore=false;var _iterator=(0,_PlainValueFf5147c._)(contents),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var node=_step.value;if(node.valueRange){if(body!==undefined){var msg="Document contains trailing content not separated by a ... or --- line";doc.errors.push(new _PlainValueFf5147c.Y(node,msg));break}var res=(0,_resolveSeq04825f.r)(doc,node);if(spaceBefore){res.spaceBefore=true;spaceBefore=false}body=res}else if(node.comment!==null){var cc=body===undefined?comments.before:comments.after;cc.push(node.comment)}else if(node.type===_PlainValueFf5147c.T.BLANK_LINE){spaceBefore=true;if(body===undefined&&comments.before.length>0&&!doc.commentBefore){doc.commentBefore=comments.before.join("\n");comments.before=[]}}}}catch(err){_iterator.e(err)}finally{_iterator.f()}doc.contents=body||null;if(!body){doc.comment=comments.before.concat(comments.after).join("\n")||null}else{var cb=comments.before.join("\n");if(cb){var cbNode=body instanceof _resolveSeq04825f.C&&body.items[0]?body.items[0]:body;cbNode.commentBefore=cbNode.commentBefore?"".concat(cb,"\n").concat(cbNode.commentBefore):cb}doc.comment=comments.after.join("\n")||null}}function resolveTagDirective(_ref,directive){var tagPrefixes=_ref.tagPrefixes;var _directive$parameters=(0,_PlainValueFf5147c.h)(directive.parameters,2),handle=_directive$parameters[0],prefix=_directive$parameters[1];if(!handle||!prefix){var msg="Insufficient parameters given for %TAG directive";throw new _PlainValueFf5147c.g(directive,msg)}if(tagPrefixes.some((function(p){return p.handle===handle}))){var _msg="The %TAG directive must only be given at most once per handle in the same document.";throw new _PlainValueFf5147c.g(directive,_msg)}return{handle:handle,prefix:prefix}}function resolveYamlDirective(doc,directive){var _directive$parameters2=(0,_PlainValueFf5147c.h)(directive.parameters,1),version=_directive$parameters2[0];if(directive.name==="YAML:1.0")version="1.0";if(!version){var msg="Insufficient parameters given for %YAML directive";throw new _PlainValueFf5147c.g(directive,msg)}if(!documentOptions[version]){var v0=doc.version||doc.options.version;var _msg2="Document will be parsed as YAML ".concat(v0," rather than YAML ").concat(version);doc.warnings.push(new _PlainValueFf5147c.f(directive,_msg2))}return version}function parseDirectives(doc,directives,prevDoc){var directiveComments=[];var hasDirectives=false;var _iterator=(0,_PlainValueFf5147c._)(directives),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var directive=_step.value;var comment=directive.comment,name=directive.name;switch(name){case"TAG":try{doc.tagPrefixes.push(resolveTagDirective(doc,directive))}catch(error){doc.errors.push(error)}hasDirectives=true;break;case"YAML":case"YAML:1.0":if(doc.version){var msg="The %YAML directive must only be given at most once per document.";doc.errors.push(new _PlainValueFf5147c.g(directive,msg))}try{doc.version=resolveYamlDirective(doc,directive)}catch(error){doc.errors.push(error)}hasDirectives=true;break;default:if(name){var _msg3="YAML only supports %TAG and %YAML directives, and not %".concat(name);doc.warnings.push(new _PlainValueFf5147c.f(directive,_msg3))}}if(comment)directiveComments.push(comment)}}catch(err){_iterator.e(err)}finally{_iterator.f()}if(prevDoc&&!hasDirectives&&"1.1"===(doc.version||prevDoc.version||doc.options.version)){var copyTagPrefix=function copyTagPrefix(_ref2){var handle=_ref2.handle,prefix=_ref2.prefix;return{handle:handle,prefix:prefix}};doc.tagPrefixes=prevDoc.tagPrefixes.map(copyTagPrefix);doc.version=prevDoc.version}doc.commentBefore=directiveComments.join("\n")||null}function assertCollection(contents){if(contents instanceof _resolveSeq04825f.C)return true;throw new Error("Expected a YAML collection as document contents")}var Document=function(){function Document(options){(0,_PlainValueFf5147c.c)(this,Document);this.anchors=new Anchors(options.anchorPrefix);this.commentBefore=null;this.comment=null;this.contents=null;this.directivesEndMarker=null;this.errors=[];this.options=options;this.schema=null;this.tagPrefixes=[];this.version=null;this.warnings=[]}(0,_PlainValueFf5147c.b)(Document,[{key:"add",value:function add(value){assertCollection(this.contents);return this.contents.add(value)}},{key:"addIn",value:function addIn(path,value){assertCollection(this.contents);this.contents.addIn(path,value)}},{key:"delete",value:function _delete(key){assertCollection(this.contents);return this.contents["delete"](key)}},{key:"deleteIn",value:function deleteIn(path){if((0,_resolveSeq04825f.e)(path)){if(this.contents==null)return false;this.contents=null;return true}assertCollection(this.contents);return this.contents.deleteIn(path)}},{key:"getDefaults",value:function getDefaults(){return Document.defaults[this.version]||Document.defaults[this.options.version]||{}}},{key:"get",value:function get(key,keepScalar){return this.contents instanceof _resolveSeq04825f.C?this.contents.get(key,keepScalar):undefined}},{key:"getIn",value:function getIn(path,keepScalar){if((0,_resolveSeq04825f.e)(path))return!keepScalar&&this.contents instanceof _resolveSeq04825f.S?this.contents.value:this.contents;return this.contents instanceof _resolveSeq04825f.C?this.contents.getIn(path,keepScalar):undefined}},{key:"has",value:function has(key){return this.contents instanceof _resolveSeq04825f.C?this.contents.has(key):false}},{key:"hasIn",value:function hasIn(path){if((0,_resolveSeq04825f.e)(path))return this.contents!==undefined;return this.contents instanceof _resolveSeq04825f.C?this.contents.hasIn(path):false}},{key:"set",value:function set(key,value){assertCollection(this.contents);this.contents.set(key,value)}},{key:"setIn",value:function setIn(path,value){if((0,_resolveSeq04825f.e)(path))this.contents=value;else{assertCollection(this.contents);this.contents.setIn(path,value)}}},{key:"setSchema",value:function setSchema(id,customTags){if(!id&&!customTags&&this.schema)return;if(typeof id==="number")id=id.toFixed(1);if(id==="1.0"||id==="1.1"||id==="1.2"){if(this.version)this.version=id;else this.options.version=id;delete this.options.schema}else if(id&&typeof id==="string"){this.options.schema=id}if(Array.isArray(customTags))this.options.customTags=customTags;var opt=Object.assign({},this.getDefaults(),this.options);this.schema=new _Schema2bf2c74e.S(opt)}},{key:"parse",value:function parse(node,prevDoc){if(this.options.keepCstNodes)this.cstNode=node;if(this.options.keepNodeTypes)this.type="DOCUMENT";var _node$directives=node.directives,directives=_node$directives===void 0?[]:_node$directives,_node$contents=node.contents,contents=_node$contents===void 0?[]:_node$contents,directivesEndMarker=node.directivesEndMarker,error=node.error,valueRange=node.valueRange;if(error){if(!error.source)error.source=this;this.errors.push(error)}parseDirectives(this,directives,prevDoc);if(directivesEndMarker)this.directivesEndMarker=true;this.range=valueRange?[valueRange.start,valueRange.end]:null;this.setSchema();this.anchors._cstAliases=[];parseContents(this,contents);this.anchors.resolveNodes();if(this.options.prettyErrors){var _iterator=(0,_PlainValueFf5147c._)(this.errors),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var _error=_step.value;if(_error instanceof _PlainValueFf5147c.i)_error.makePretty()}}catch(err){_iterator.e(err)}finally{_iterator.f()}var _iterator2=(0,_PlainValueFf5147c._)(this.warnings),_step2;try{for(_iterator2.s();!(_step2=_iterator2.n()).done;){var warn=_step2.value;if(warn instanceof _PlainValueFf5147c.i)warn.makePretty()}}catch(err){_iterator2.e(err)}finally{_iterator2.f()}}return this}},{key:"listNonDefaultTags",value:function listNonDefaultTags(){return listTagNames(this.contents).filter((function(t){return t.indexOf(_Schema2bf2c74e.S.defaultPrefix)!==0}))}},{key:"setTagPrefix",value:function setTagPrefix(handle,prefix){if(handle[0]!=="!"||handle[handle.length-1]!=="!")throw new Error("Handle must start and end with !");if(prefix){var prev=this.tagPrefixes.find((function(p){return p.handle===handle}));if(prev)prev.prefix=prefix;else this.tagPrefixes.push({handle:handle,prefix:prefix})}else{this.tagPrefixes=this.tagPrefixes.filter((function(p){return p.handle!==handle}))}}},{key:"toJSON",value:function toJSON$1(arg,onAnchor){var _this=this;var _this$options=this.options,keepBlobsInJSON=_this$options.keepBlobsInJSON,mapAsMap=_this$options.mapAsMap,maxAliasCount=_this$options.maxAliasCount;var keep=keepBlobsInJSON&&(typeof arg!=="string"||!(this.contents instanceof _resolveSeq04825f.S));var ctx={doc:this,indentStep:" ",keep:keep,mapAsMap:keep&&!!mapAsMap,maxAliasCount:maxAliasCount,stringify:stringify};var anchorNames=Object.keys(this.anchors.map);if(anchorNames.length>0)ctx.anchors=new Map(anchorNames.map((function(name){return[_this.anchors.map[name],{alias:[],aliasCount:0,count:1}]})));var res=(0,_resolveSeq04825f.t)(this.contents,arg,ctx);if(typeof onAnchor==="function"&&ctx.anchors){var _iterator3=(0,_PlainValueFf5147c._)(ctx.anchors.values()),_step3;try{for(_iterator3.s();!(_step3=_iterator3.n()).done;){var _step3$value=_step3.value,count=_step3$value.count,_res=_step3$value.res;onAnchor(_res,count)}}catch(err){_iterator3.e(err)}finally{_iterator3.f()}}return res}},{key:"toString",value:function toString(){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");var indentSize=this.options.indent;if(!Number.isInteger(indentSize)||indentSize<=0){var s=JSON.stringify(indentSize);throw new Error('"indent" option must be a positive integer, not '.concat(s))}this.setSchema();var lines=[];var hasDirectives=false;if(this.version){var vd="%YAML 1.2";if(this.schema.name==="yaml-1.1"){if(this.version==="1.0")vd="%YAML:1.0";else if(this.version==="1.1")vd="%YAML 1.1"}lines.push(vd);hasDirectives=true}var tagNames=this.listNonDefaultTags();this.tagPrefixes.forEach((function(_ref){var handle=_ref.handle,prefix=_ref.prefix;if(tagNames.some((function(t){return t.indexOf(prefix)===0}))){lines.push("%TAG ".concat(handle," ").concat(prefix));hasDirectives=true}}));if(hasDirectives||this.directivesEndMarker)lines.push("---");if(this.commentBefore){if(hasDirectives||!this.directivesEndMarker)lines.unshift("");lines.unshift(this.commentBefore.replace(/^/gm,"#"))}var ctx={anchors:{},doc:this,indent:"",indentStep:" ".repeat(indentSize),stringify:stringify};var chompKeep=false;var contentComment=null;if(this.contents){if(this.contents instanceof _resolveSeq04825f.N){if(this.contents.spaceBefore&&(hasDirectives||this.directivesEndMarker))lines.push("");if(this.contents.commentBefore)lines.push(this.contents.commentBefore.replace(/^/gm,"#"));ctx.forceBlockIndent=!!this.comment;contentComment=this.contents.comment}var onChompKeep=contentComment?null:function(){return chompKeep=true};var body=stringify(this.contents,ctx,(function(){return contentComment=null}),onChompKeep);lines.push((0,_resolveSeq04825f.f)(body,"",contentComment))}else if(this.contents!==undefined){lines.push(stringify(this.contents,ctx))}if(this.comment){if((!chompKeep||contentComment)&&lines[lines.length-1]!=="")lines.push("");lines.push(this.comment.replace(/^/gm,"#"))}return lines.join("\n")+"\n"}}]);return Document}();(0,_PlainValueFf5147c.e)(Document,"defaults",documentOptions);function createNode(value){var wrapScalars=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;var tag=arguments.length>2?arguments[2]:undefined;if(tag===undefined&&typeof wrapScalars==="string"){tag=wrapScalars;wrapScalars=true}var options=Object.assign({},Document.defaults[defaultOptions.version],defaultOptions);var schema=new _Schema2bf2c74e.S(options);return schema.createNode(value,wrapScalars,tag)}var Document$1=function(_YAMLDocument){(0,_PlainValueFf5147c.j)(Document,_YAMLDocument);var _super=(0,_PlainValueFf5147c.k)(Document);function Document(options){(0,_PlainValueFf5147c.c)(this,Document);return _super.call(this,Object.assign({},defaultOptions,options))}return Document}(Document);function parseAllDocuments(src,options){var stream=[];var prev;var _iterator=(0,_PlainValueFf5147c._)((0,_parseCst.parse)(src)),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var cstDoc=_step.value;var doc=new Document$1(options);doc.parse(cstDoc,prev);stream.push(doc);prev=doc}}catch(err){_iterator.e(err)}finally{_iterator.f()}return stream}function parseDocument(src,options){var cst=(0,_parseCst.parse)(src);var doc=new Document$1(options).parse(cst[0]);if(cst.length>1){var errMsg="Source contains multiple documents; please use YAML.parseAllDocuments()";doc.errors.unshift(new _PlainValueFf5147c.g(cst[1],errMsg))}return doc}function parse(src,options){var doc=parseDocument(src,options);doc.warnings.forEach((function(warning){return(0,_warnings0e4b70d.w)(warning)}));if(doc.errors.length>0)throw doc.errors[0];return doc.toJSON()}function stringify$1(value,options){var doc=new Document$1(options);doc.contents=value;return String(doc)}var YAML={createNode:createNode,defaultOptions:defaultOptions,Document:Document$1,parse:parse,parseAllDocuments:parseAllDocuments,parseCST:_parseCst.parse,parseDocument:parseDocument,scalarOptions:scalarOptions,stringify:stringify$1};exports.YAML=YAML},{"./PlainValue-ff5147c6.js":218,"./Schema-2bf2c74e.js":219,"./parse-cst.js":221,"./resolveSeq-04825f30.js":222,"./warnings-0e4b70d3.js":223}],221:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.parse=parse;var _PlainValueFf5147c=require("./PlainValue-ff5147c6.js");var BlankLine=function(_Node){(0,_PlainValueFf5147c.j)(BlankLine,_Node);var _super=(0,_PlainValueFf5147c.k)(BlankLine);function BlankLine(){(0,_PlainValueFf5147c.c)(this,BlankLine);return _super.call(this,_PlainValueFf5147c.T.BLANK_LINE)}(0,_PlainValueFf5147c.b)(BlankLine,[{key:"parse",value:function parse(context,start){this.context=context;this.range=new _PlainValueFf5147c.R(start,start+1);return start+1}},{key:"includesTrailingLines",get:function get(){return true}}]);return BlankLine}(_PlainValueFf5147c.N);var CollectionItem=function(_Node){(0,_PlainValueFf5147c.j)(CollectionItem,_Node);var _super=(0,_PlainValueFf5147c.k)(CollectionItem);function CollectionItem(type,props){var _this;(0,_PlainValueFf5147c.c)(this,CollectionItem);_this=_super.call(this,type,props);_this.node=null;return _this}(0,_PlainValueFf5147c.b)(CollectionItem,[{key:"parse",value:function parse(context,start){this.context=context;var parseNode=context.parseNode,src=context.src;var atLineStart=context.atLineStart,lineStart=context.lineStart;if(!atLineStart&&this.type===_PlainValueFf5147c.T.SEQ_ITEM)this.error=new _PlainValueFf5147c.g(this,"Sequence items must not have preceding content on the same line");var indent=atLineStart?start-lineStart:context.indent;var offset=_PlainValueFf5147c.N.endOfWhiteSpace(src,start+1);var ch=src[offset];var inlineComment=ch==="#";var comments=[];var blankLine=null;while(ch==="\n"||ch==="#"){if(ch==="#"){var _end=_PlainValueFf5147c.N.endOfLine(src,offset+1);comments.push(new _PlainValueFf5147c.R(offset,_end));offset=_end}else{atLineStart=true;lineStart=offset+1;var wsEnd=_PlainValueFf5147c.N.endOfWhiteSpace(src,lineStart);if(src[wsEnd]==="\n"&&comments.length===0){blankLine=new BlankLine;lineStart=blankLine.parse({src:src},lineStart)}offset=_PlainValueFf5147c.N.endOfIndent(src,lineStart)}ch=src[offset]}if(_PlainValueFf5147c.N.nextNodeIsIndented(ch,offset-(lineStart+indent),this.type!==_PlainValueFf5147c.T.SEQ_ITEM)){this.node=parseNode({atLineStart:atLineStart,inCollection:false,indent:indent,lineStart:lineStart,parent:this},offset)}else if(ch&&lineStart>start+1){offset=lineStart-1}if(this.node){if(blankLine){var items=context.parent.items||context.parent.contents;if(items)items.push(blankLine)}if(comments.length)Array.prototype.push.apply(this.props,comments);offset=this.node.range.end}else{if(inlineComment){var c=comments[0];this.props.push(c);offset=c.end}else{offset=_PlainValueFf5147c.N.endOfLine(src,start+1)}}var end=this.node?this.node.valueRange.end:offset;this.valueRange=new _PlainValueFf5147c.R(start,end);return offset}},{key:"setOrigRanges",value:function setOrigRanges(cr,offset){offset=(0,_PlainValueFf5147c.l)((0,_PlainValueFf5147c.m)(CollectionItem.prototype),"setOrigRanges",this).call(this,cr,offset);return this.node?this.node.setOrigRanges(cr,offset):offset}},{key:"toString",value:function toString(){var src=this.context.src,node=this.node,range=this.range,value=this.value;if(value!=null)return value;var str=node?src.slice(range.start,node.range.start)+String(node):src.slice(range.start,range.end);return _PlainValueFf5147c.N.addStringTerminator(src,range.end,str)}},{key:"includesTrailingLines",get:function get(){return!!this.node&&this.node.includesTrailingLines}}]);return CollectionItem}(_PlainValueFf5147c.N);var Comment=function(_Node){(0,_PlainValueFf5147c.j)(Comment,_Node);var _super=(0,_PlainValueFf5147c.k)(Comment);function Comment(){(0,_PlainValueFf5147c.c)(this,Comment);return _super.call(this,_PlainValueFf5147c.T.COMMENT)}(0,_PlainValueFf5147c.b)(Comment,[{key:"parse",value:function parse(context,start){this.context=context;var offset=this.parseComment(start);this.range=new _PlainValueFf5147c.R(start,offset);return offset}}]);return Comment}(_PlainValueFf5147c.N);function grabCollectionEndComments(node){var cnode=node;while(cnode instanceof CollectionItem){cnode=cnode.node}if(!(cnode instanceof Collection))return null;var len=cnode.items.length;var ci=-1;for(var i=len-1;i>=0;--i){var n=cnode.items[i];if(n.type===_PlainValueFf5147c.T.COMMENT){var _n$context=n.context,indent=_n$context.indent,lineStart=_n$context.lineStart;if(indent>0&&n.range.start>=lineStart+indent)break;ci=i}else if(n.type===_PlainValueFf5147c.T.BLANK_LINE)ci=i;else break}if(ci===-1)return null;var ca=cnode.items.splice(ci,len-ci);var prevEnd=ca[0].range.start;while(true){cnode.range.end=prevEnd;if(cnode.valueRange&&cnode.valueRange.end>prevEnd)cnode.valueRange.end=prevEnd;if(cnode===node)break;cnode=cnode.context.parent}return ca}var Collection=function(_Node){(0,_PlainValueFf5147c.j)(Collection,_Node);var _super=(0,_PlainValueFf5147c.k)(Collection);(0,_PlainValueFf5147c.b)(Collection,null,[{key:"nextContentHasIndent",value:function nextContentHasIndent(src,offset,indent){var lineStart=_PlainValueFf5147c.N.endOfLine(src,offset)+1;offset=_PlainValueFf5147c.N.endOfWhiteSpace(src,lineStart);var ch=src[offset];if(!ch)return false;if(offset>=lineStart+indent)return true;if(ch!=="#"&&ch!=="\n")return false;return Collection.nextContentHasIndent(src,offset,indent)}}]);function Collection(firstItem){var _this;(0,_PlainValueFf5147c.c)(this,Collection);_this=_super.call(this,firstItem.type===_PlainValueFf5147c.T.SEQ_ITEM?_PlainValueFf5147c.T.SEQ:_PlainValueFf5147c.T.MAP);for(var i=firstItem.props.length-1;i>=0;--i){if(firstItem.props[i].start<firstItem.context.lineStart){_this.props=firstItem.props.slice(0,i+1);firstItem.props=firstItem.props.slice(i+1);var itemRange=firstItem.props[0]||firstItem.valueRange;firstItem.range.start=itemRange.start;break}}_this.items=[firstItem];var ec=grabCollectionEndComments(firstItem);if(ec)Array.prototype.push.apply(_this.items,ec);return _this}(0,_PlainValueFf5147c.b)(Collection,[{key:"parse",value:function parse(context,start){this.context=context;var parseNode=context.parseNode,src=context.src;var lineStart=_PlainValueFf5147c.N.startOfLine(src,start);var firstItem=this.items[0];firstItem.context.parent=this;this.valueRange=_PlainValueFf5147c.R.copy(firstItem.valueRange);var indent=firstItem.range.start-firstItem.context.lineStart;var offset=start;offset=_PlainValueFf5147c.N.normalizeOffset(src,offset);var ch=src[offset];var atLineStart=_PlainValueFf5147c.N.endOfWhiteSpace(src,lineStart)===offset;var prevIncludesTrailingLines=false;while(ch){while(ch==="\n"||ch==="#"){if(atLineStart&&ch==="\n"&&!prevIncludesTrailingLines){var blankLine=new BlankLine;offset=blankLine.parse({src:src},offset);this.valueRange.end=offset;if(offset>=src.length){ch=null;break}this.items.push(blankLine);offset-=1}else if(ch==="#"){if(offset<lineStart+indent&&!Collection.nextContentHasIndent(src,offset,indent)){return offset}var comment=new Comment;offset=comment.parse({indent:indent,lineStart:lineStart,src:src},offset);this.items.push(comment);this.valueRange.end=offset;if(offset>=src.length){ch=null;break}}lineStart=offset+1;offset=_PlainValueFf5147c.N.endOfIndent(src,lineStart);if(_PlainValueFf5147c.N.atBlank(src,offset)){var wsEnd=_PlainValueFf5147c.N.endOfWhiteSpace(src,offset);var next=src[wsEnd];if(!next||next==="\n"||next==="#"){offset=wsEnd}}ch=src[offset];atLineStart=true}if(!ch){break}if(offset!==lineStart+indent&&(atLineStart||ch!==":")){if(offset<lineStart+indent){if(lineStart>start)offset=lineStart;break}else if(!this.error){var msg="All collection items must start at the same column";this.error=new _PlainValueFf5147c.Y(this,msg)}}if(firstItem.type===_PlainValueFf5147c.T.SEQ_ITEM){if(ch!=="-"){if(lineStart>start)offset=lineStart;break}}else if(ch==="-"&&!this.error){var _next=src[offset+1];if(!_next||_next==="\n"||_next==="\t"||_next===" "){var _msg="A collection cannot be both a mapping and a sequence";this.error=new _PlainValueFf5147c.Y(this,_msg)}}var node=parseNode({atLineStart:atLineStart,inCollection:true,indent:indent,lineStart:lineStart,parent:this},offset);if(!node)return offset;this.items.push(node);this.valueRange.end=node.valueRange.end;offset=_PlainValueFf5147c.N.normalizeOffset(src,node.range.end);ch=src[offset];atLineStart=false;prevIncludesTrailingLines=node.includesTrailingLines;if(ch){var ls=offset-1;var prev=src[ls];while(prev===" "||prev==="\t"){prev=src[--ls]}if(prev==="\n"){lineStart=ls+1;atLineStart=true}}var ec=grabCollectionEndComments(node);if(ec)Array.prototype.push.apply(this.items,ec)}return offset}},{key:"setOrigRanges",value:function setOrigRanges(cr,offset){offset=(0,_PlainValueFf5147c.l)((0,_PlainValueFf5147c.m)(Collection.prototype),"setOrigRanges",this).call(this,cr,offset);this.items.forEach((function(node){offset=node.setOrigRanges(cr,offset)}));return offset}},{key:"toString",value:function toString(){var src=this.context.src,items=this.items,range=this.range,value=this.value;if(value!=null)return value;var str=src.slice(range.start,items[0].range.start)+String(items[0]);for(var i=1;i<items.length;++i){var item=items[i];var _item$context=item.context,atLineStart=_item$context.atLineStart,indent=_item$context.indent;if(atLineStart)for(var _i=0;_i<indent;++_i){str+=" "}str+=String(item)}return _PlainValueFf5147c.N.addStringTerminator(src,range.end,str)}},{key:"includesTrailingLines",get:function get(){return this.items.length>0}}]);return Collection}(_PlainValueFf5147c.N);var Directive=function(_Node){(0,_PlainValueFf5147c.j)(Directive,_Node);var _super=(0,_PlainValueFf5147c.k)(Directive);function Directive(){var _this;(0,_PlainValueFf5147c.c)(this,Directive);_this=_super.call(this,_PlainValueFf5147c.T.DIRECTIVE);_this.name=null;return _this}(0,_PlainValueFf5147c.b)(Directive,[{key:"parseName",value:function parseName(start){var src=this.context.src;var offset=start;var ch=src[offset];while(ch&&ch!=="\n"&&ch!=="\t"&&ch!==" "){ch=src[offset+=1]}this.name=src.slice(start,offset);return offset}},{key:"parseParameters",value:function parseParameters(start){var src=this.context.src;var offset=start;var ch=src[offset];while(ch&&ch!=="\n"&&ch!=="#"){ch=src[offset+=1]}this.valueRange=new _PlainValueFf5147c.R(start,offset);return offset}},{key:"parse",value:function parse(context,start){this.context=context;var offset=this.parseName(start+1);offset=this.parseParameters(offset);offset=this.parseComment(offset);this.range=new _PlainValueFf5147c.R(start,offset);return offset}},{key:"parameters",get:function get(){var raw=this.rawValue;return raw?raw.trim().split(/[ \t]+/):[]}}]);return Directive}(_PlainValueFf5147c.N);var Document=function(_Node){(0,_PlainValueFf5147c.j)(Document,_Node);var _super=(0,_PlainValueFf5147c.k)(Document);(0,_PlainValueFf5147c.b)(Document,null,[{key:"startCommentOrEndBlankLine",value:function startCommentOrEndBlankLine(src,start){var offset=_PlainValueFf5147c.N.endOfWhiteSpace(src,start);var ch=src[offset];return ch==="#"||ch==="\n"?offset:start}}]);function Document(){var _this;(0,_PlainValueFf5147c.c)(this,Document);_this=_super.call(this,_PlainValueFf5147c.T.DOCUMENT);_this.directives=null;_this.contents=null;_this.directivesEndMarker=null;_this.documentEndMarker=null;return _this}(0,_PlainValueFf5147c.b)(Document,[{key:"parseDirectives",value:function parseDirectives(start){var src=this.context.src;this.directives=[];var atLineStart=true;var hasDirectives=false;var offset=start;while(!_PlainValueFf5147c.N.atDocumentBoundary(src,offset,_PlainValueFf5147c.C.DIRECTIVES_END)){offset=Document.startCommentOrEndBlankLine(src,offset);switch(src[offset]){case"\n":if(atLineStart){var blankLine=new BlankLine;offset=blankLine.parse({src:src},offset);if(offset<src.length){this.directives.push(blankLine)}}else{offset+=1;atLineStart=true}break;case"#":{var comment=new Comment;offset=comment.parse({src:src},offset);this.directives.push(comment);atLineStart=false}break;case"%":{var directive=new Directive;offset=directive.parse({parent:this,src:src},offset);this.directives.push(directive);hasDirectives=true;atLineStart=false}break;default:if(hasDirectives){this.error=new _PlainValueFf5147c.g(this,"Missing directives-end indicator line")}else if(this.directives.length>0){this.contents=this.directives;this.directives=[]}return offset}}if(src[offset]){this.directivesEndMarker=new _PlainValueFf5147c.R(offset,offset+3);return offset+3}if(hasDirectives){this.error=new _PlainValueFf5147c.g(this,"Missing directives-end indicator line")}else if(this.directives.length>0){this.contents=this.directives;this.directives=[]}return offset}},{key:"parseContents",value:function parseContents(start){var _this$context=this.context,parseNode=_this$context.parseNode,src=_this$context.src;if(!this.contents)this.contents=[];var lineStart=start;while(src[lineStart-1]==="-"){lineStart-=1}var offset=_PlainValueFf5147c.N.endOfWhiteSpace(src,start);var atLineStart=lineStart===start;this.valueRange=new _PlainValueFf5147c.R(offset);while(!_PlainValueFf5147c.N.atDocumentBoundary(src,offset,_PlainValueFf5147c.C.DOCUMENT_END)){switch(src[offset]){case"\n":if(atLineStart){var blankLine=new BlankLine;offset=blankLine.parse({src:src},offset);if(offset<src.length){this.contents.push(blankLine)}}else{offset+=1;atLineStart=true}lineStart=offset;break;case"#":{var comment=new Comment;offset=comment.parse({src:src},offset);this.contents.push(comment);atLineStart=false}break;default:{var iEnd=_PlainValueFf5147c.N.endOfIndent(src,offset);var context={atLineStart:atLineStart,indent:-1,inFlow:false,inCollection:false,lineStart:lineStart,parent:this};var node=parseNode(context,iEnd);if(!node)return this.valueRange.end=iEnd;this.contents.push(node);offset=node.range.end;atLineStart=false;var ec=grabCollectionEndComments(node);if(ec)Array.prototype.push.apply(this.contents,ec)}}offset=Document.startCommentOrEndBlankLine(src,offset)}this.valueRange.end=offset;if(src[offset]){this.documentEndMarker=new _PlainValueFf5147c.R(offset,offset+3);offset+=3;if(src[offset]){offset=_PlainValueFf5147c.N.endOfWhiteSpace(src,offset);if(src[offset]==="#"){var _comment=new Comment;offset=_comment.parse({src:src},offset);this.contents.push(_comment)}switch(src[offset]){case"\n":offset+=1;break;case undefined:break;default:this.error=new _PlainValueFf5147c.Y(this,"Document end marker line cannot have a non-comment suffix")}}}return offset}},{key:"parse",value:function parse(context,start){context.root=this;this.context=context;var src=context.src;var offset=src.charCodeAt(start)===65279?start+1:start;offset=this.parseDirectives(offset);offset=this.parseContents(offset);return offset}},{key:"setOrigRanges",value:function setOrigRanges(cr,offset){offset=(0,_PlainValueFf5147c.l)((0,_PlainValueFf5147c.m)(Document.prototype),"setOrigRanges",this).call(this,cr,offset);this.directives.forEach((function(node){offset=node.setOrigRanges(cr,offset)}));if(this.directivesEndMarker)offset=this.directivesEndMarker.setOrigRange(cr,offset);this.contents.forEach((function(node){offset=node.setOrigRanges(cr,offset)}));if(this.documentEndMarker)offset=this.documentEndMarker.setOrigRange(cr,offset);return offset}},{key:"toString",value:function toString(){var contents=this.contents,directives=this.directives,value=this.value;if(value!=null)return value;var str=directives.join("");if(contents.length>0){if(directives.length>0||contents[0].type===_PlainValueFf5147c.T.COMMENT)str+="---\n";str+=contents.join("")}if(str[str.length-1]!=="\n")str+="\n";return str}}]);return Document}(_PlainValueFf5147c.N);var Alias=function(_Node){(0,_PlainValueFf5147c.j)(Alias,_Node);var _super=(0,_PlainValueFf5147c.k)(Alias);function Alias(){(0,_PlainValueFf5147c.c)(this,Alias);return _super.apply(this,arguments)}(0,_PlainValueFf5147c.b)(Alias,[{key:"parse",value:function parse(context,start){this.context=context;var src=context.src;var offset=_PlainValueFf5147c.N.endOfIdentifier(src,start+1);this.valueRange=new _PlainValueFf5147c.R(start+1,offset);offset=_PlainValueFf5147c.N.endOfWhiteSpace(src,offset);offset=this.parseComment(offset);return offset}}]);return Alias}(_PlainValueFf5147c.N);var Chomp={CLIP:"CLIP",KEEP:"KEEP",STRIP:"STRIP"};var BlockValue=function(_Node){(0,_PlainValueFf5147c.j)(BlockValue,_Node);var _super=(0,_PlainValueFf5147c.k)(BlockValue);function BlockValue(type,props){var _this;(0,_PlainValueFf5147c.c)(this,BlockValue);_this=_super.call(this,type,props);_this.blockIndent=null;_this.chomping=Chomp.CLIP;_this.header=null;return _this}(0,_PlainValueFf5147c.b)(BlockValue,[{key:"parseBlockHeader",value:function parseBlockHeader(start){var src=this.context.src;var offset=start+1;var bi="";while(true){var ch=src[offset];switch(ch){case"-":this.chomping=Chomp.STRIP;break;case"+":this.chomping=Chomp.KEEP;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":bi+=ch;break;default:this.blockIndent=Number(bi)||null;this.header=new _PlainValueFf5147c.R(start,offset);return offset}offset+=1}}},{key:"parseBlockValue",value:function parseBlockValue(start){var _this$context=this.context,indent=_this$context.indent,src=_this$context.src;var explicit=!!this.blockIndent;var offset=start;var valueEnd=start;var minBlockIndent=1;for(var ch=src[offset];ch==="\n";ch=src[offset]){offset+=1;if(_PlainValueFf5147c.N.atDocumentBoundary(src,offset))break;var end=_PlainValueFf5147c.N.endOfBlockIndent(src,indent,offset);if(end===null)break;var _ch=src[end];var lineIndent=end-(offset+indent);if(!this.blockIndent){if(src[end]!=="\n"){if(lineIndent<minBlockIndent){var msg="Block scalars with more-indented leading empty lines must use an explicit indentation indicator";this.error=new _PlainValueFf5147c.g(this,msg)}this.blockIndent=lineIndent}else if(lineIndent>minBlockIndent){minBlockIndent=lineIndent}}else if(_ch&&_ch!=="\n"&&lineIndent<this.blockIndent){if(src[end]==="#")break;if(!this.error){var _src=explicit?"explicit indentation indicator":"first line";var _msg="Block scalars must not be less indented than their ".concat(_src);this.error=new _PlainValueFf5147c.g(this,_msg)}}if(src[end]==="\n"){offset=end}else{offset=valueEnd=_PlainValueFf5147c.N.endOfLine(src,end)}}if(this.chomping!==Chomp.KEEP){offset=src[valueEnd]?valueEnd+1:valueEnd}this.valueRange=new _PlainValueFf5147c.R(start+1,offset);return offset}},{key:"parse",value:function parse(context,start){this.context=context;var src=context.src;var offset=this.parseBlockHeader(start);offset=_PlainValueFf5147c.N.endOfWhiteSpace(src,offset);offset=this.parseComment(offset);offset=this.parseBlockValue(offset);return offset}},{key:"setOrigRanges",value:function setOrigRanges(cr,offset){offset=(0,_PlainValueFf5147c.l)((0,_PlainValueFf5147c.m)(BlockValue.prototype),"setOrigRanges",this).call(this,cr,offset);return this.header?this.header.setOrigRange(cr,offset):offset}},{key:"includesTrailingLines",get:function get(){return this.chomping===Chomp.KEEP}},{key:"strValue",get:function get(){if(!this.valueRange||!this.context)return null;var _this$valueRange=this.valueRange,start=_this$valueRange.start,end=_this$valueRange.end;var _this$context2=this.context,indent=_this$context2.indent,src=_this$context2.src;if(this.valueRange.isEmpty())return"";var lastNewLine=null;var ch=src[end-1];while(ch==="\n"||ch==="\t"||ch===" "){end-=1;if(end<=start){if(this.chomping===Chomp.KEEP)break;else return""}if(ch==="\n")lastNewLine=end;ch=src[end-1]}var keepStart=end+1;if(lastNewLine){if(this.chomping===Chomp.KEEP){keepStart=lastNewLine;end=this.valueRange.end}else{end=lastNewLine}}var bi=indent+this.blockIndent;var folded=this.type===_PlainValueFf5147c.T.BLOCK_FOLDED;var atStart=true;var str="";var sep="";var prevMoreIndented=false;for(var i=start;i<end;++i){for(var j=0;j<bi;++j){if(src[i]!==" ")break;i+=1}var _ch2=src[i];if(_ch2==="\n"){if(sep==="\n")str+="\n";else sep="\n"}else{var lineEnd=_PlainValueFf5147c.N.endOfLine(src,i);var line=src.slice(i,lineEnd);i=lineEnd;if(folded&&(_ch2===" "||_ch2==="\t")&&i<keepStart){if(sep===" ")sep="\n";else if(!prevMoreIndented&&!atStart&&sep==="\n")sep="\n\n";str+=sep+line;sep=lineEnd<end&&src[lineEnd]||"";prevMoreIndented=true}else{str+=sep+line;sep=folded&&i<keepStart?" ":"\n";prevMoreIndented=false}if(atStart&&line!=="")atStart=false}}return this.chomping===Chomp.STRIP?str:str+"\n"}}]);return BlockValue}(_PlainValueFf5147c.N);var FlowCollection=function(_Node){(0,_PlainValueFf5147c.j)(FlowCollection,_Node);var _super=(0,_PlainValueFf5147c.k)(FlowCollection);function FlowCollection(type,props){var _this;(0,_PlainValueFf5147c.c)(this,FlowCollection);_this=_super.call(this,type,props);_this.items=null;return _this}(0,_PlainValueFf5147c.b)(FlowCollection,[{key:"prevNodeIsJsonLike",value:function prevNodeIsJsonLike(){var idx=arguments.length>0&&arguments[0]!==undefined?arguments[0]:this.items.length;var node=this.items[idx-1];return!!node&&(node.jsonLike||node.type===_PlainValueFf5147c.T.COMMENT&&this.prevNodeIsJsonLike(idx-1))}},{key:"parse",value:function parse(context,start){this.context=context;var parseNode=context.parseNode,src=context.src;var indent=context.indent,lineStart=context.lineStart;var _char=src[start];this.items=[{char:_char,offset:start}];var offset=_PlainValueFf5147c.N.endOfWhiteSpace(src,start+1);_char=src[offset];while(_char&&_char!=="]"&&_char!=="}"){switch(_char){case"\n":{lineStart=offset+1;var wsEnd=_PlainValueFf5147c.N.endOfWhiteSpace(src,lineStart);if(src[wsEnd]==="\n"){var blankLine=new BlankLine;lineStart=blankLine.parse({src:src},lineStart);this.items.push(blankLine)}offset=_PlainValueFf5147c.N.endOfIndent(src,lineStart);if(offset<=lineStart+indent){_char=src[offset];if(offset<lineStart+indent||_char!=="]"&&_char!=="}"){var msg="Insufficient indentation in flow collection";this.error=new _PlainValueFf5147c.g(this,msg)}}}break;case",":{this.items.push({char:_char,offset:offset});offset+=1}break;case"#":{var comment=new Comment;offset=comment.parse({src:src},offset);this.items.push(comment)}break;case"?":case":":{var next=src[offset+1];if(next==="\n"||next==="\t"||next===" "||next===","||_char===":"&&this.prevNodeIsJsonLike()){this.items.push({char:_char,offset:offset});offset+=1;break}}default:{var node=parseNode({atLineStart:false,inCollection:false,inFlow:true,indent:-1,lineStart:lineStart,parent:this},offset);if(!node){this.valueRange=new _PlainValueFf5147c.R(start,offset);return offset}this.items.push(node);offset=_PlainValueFf5147c.N.normalizeOffset(src,node.range.end)}}offset=_PlainValueFf5147c.N.endOfWhiteSpace(src,offset);_char=src[offset]}this.valueRange=new _PlainValueFf5147c.R(start,offset+1);if(_char){this.items.push({char:_char,offset:offset});offset=_PlainValueFf5147c.N.endOfWhiteSpace(src,offset+1);offset=this.parseComment(offset)}return offset}},{key:"setOrigRanges",value:function setOrigRanges(cr,offset){offset=(0,_PlainValueFf5147c.l)((0,_PlainValueFf5147c.m)(FlowCollection.prototype),"setOrigRanges",this).call(this,cr,offset);this.items.forEach((function(node){if(node instanceof _PlainValueFf5147c.N){offset=node.setOrigRanges(cr,offset)}else if(cr.length===0){node.origOffset=node.offset}else{var i=offset;while(i<cr.length){if(cr[i]>node.offset)break;else++i}node.origOffset=node.offset+i;offset=i}}));return offset}},{key:"toString",value:function toString(){var src=this.context.src,items=this.items,range=this.range,value=this.value;if(value!=null)return value;var nodes=items.filter((function(item){return item instanceof _PlainValueFf5147c.N}));var str="";var prevEnd=range.start;nodes.forEach((function(node){var prefix=src.slice(prevEnd,node.range.start);prevEnd=node.range.end;str+=prefix+String(node);if(str[str.length-1]==="\n"&&src[prevEnd-1]!=="\n"&&src[prevEnd]==="\n"){prevEnd+=1}}));str+=src.slice(prevEnd,range.end);return _PlainValueFf5147c.N.addStringTerminator(src,range.end,str)}}]);return FlowCollection}(_PlainValueFf5147c.N);var QuoteDouble=function(_Node){(0,_PlainValueFf5147c.j)(QuoteDouble,_Node);var _super=(0,_PlainValueFf5147c.k)(QuoteDouble);function QuoteDouble(){(0,_PlainValueFf5147c.c)(this,QuoteDouble);return _super.apply(this,arguments)}(0,_PlainValueFf5147c.b)(QuoteDouble,[{key:"parseCharCode",value:function parseCharCode(offset,length,errors){var src=this.context.src;var cc=src.substr(offset,length);var ok=cc.length===length&&/^[0-9a-fA-F]+$/.test(cc);var code=ok?parseInt(cc,16):NaN;if(isNaN(code)){errors.push(new _PlainValueFf5147c.Y(this,"Invalid escape sequence ".concat(src.substr(offset-2,length+2))));return src.substr(offset-2,length+2)}return String.fromCodePoint(code)}},{key:"parse",value:function parse(context,start){this.context=context;var src=context.src;var offset=QuoteDouble.endOfQuote(src,start+1);this.valueRange=new _PlainValueFf5147c.R(start,offset);offset=_PlainValueFf5147c.N.endOfWhiteSpace(src,offset);offset=this.parseComment(offset);return offset}},{key:"strValue",get:function get(){if(!this.valueRange||!this.context)return null;var errors=[];var _this$valueRange=this.valueRange,start=_this$valueRange.start,end=_this$valueRange.end;var _this$context=this.context,indent=_this$context.indent,src=_this$context.src;if(src[end-1]!=='"')errors.push(new _PlainValueFf5147c.Y(this,'Missing closing "quote'));var str="";for(var i=start+1;i<end-1;++i){var ch=src[i];if(ch==="\n"){if(_PlainValueFf5147c.N.atDocumentBoundary(src,i+1))errors.push(new _PlainValueFf5147c.g(this,"Document boundary indicators are not allowed within string values"));var _Node$foldNewline=_PlainValueFf5147c.N.foldNewline(src,i,indent),fold=_Node$foldNewline.fold,offset=_Node$foldNewline.offset,error=_Node$foldNewline.error;str+=fold;i=offset;if(error)errors.push(new _PlainValueFf5147c.g(this,"Multi-line double-quoted string needs to be sufficiently indented"))}else if(ch==="\\"){i+=1;switch(src[i]){case"0":str+="\0";break;case"a":str+="";break;case"b":str+="\b";break;case"e":str+="";break;case"f":str+="\f";break;case"n":str+="\n";break;case"r":str+="\r";break;case"t":str+="\t";break;case"v":str+="\v";break;case"N":str+="
";break;case"_":str+=" ";break;case"L":str+="\u2028";break;case"P":str+="\u2029";break;case" ":str+=" ";break;case'"':str+='"';break;case"/":str+="/";break;case"\\":str+="\\";break;case"\t":str+="\t";break;case"x":str+=this.parseCharCode(i+1,2,errors);i+=2;break;case"u":str+=this.parseCharCode(i+1,4,errors);i+=4;break;case"U":str+=this.parseCharCode(i+1,8,errors);i+=8;break;case"\n":while(src[i+1]===" "||src[i+1]==="\t"){i+=1}break;default:errors.push(new _PlainValueFf5147c.Y(this,"Invalid escape sequence ".concat(src.substr(i-1,2))));str+="\\"+src[i]}}else if(ch===" "||ch==="\t"){var wsStart=i;var next=src[i+1];while(next===" "||next==="\t"){i+=1;next=src[i+1]}if(next!=="\n")str+=i>wsStart?src.slice(wsStart,i+1):ch}else{str+=ch}}return errors.length>0?{errors:errors,str:str}:str}}],[{key:"endOfQuote",value:function endOfQuote(src,offset){var ch=src[offset];while(ch&&ch!=='"'){offset+=ch==="\\"?2:1;ch=src[offset]}return offset+1}}]);return QuoteDouble}(_PlainValueFf5147c.N);var QuoteSingle=function(_Node){(0,_PlainValueFf5147c.j)(QuoteSingle,_Node);var _super=(0,_PlainValueFf5147c.k)(QuoteSingle);function QuoteSingle(){(0,_PlainValueFf5147c.c)(this,QuoteSingle);return _super.apply(this,arguments)}(0,_PlainValueFf5147c.b)(QuoteSingle,[{key:"parse",value:function parse(context,start){this.context=context;var src=context.src;var offset=QuoteSingle.endOfQuote(src,start+1);this.valueRange=new _PlainValueFf5147c.R(start,offset);offset=_PlainValueFf5147c.N.endOfWhiteSpace(src,offset);offset=this.parseComment(offset);return offset}},{key:"strValue",get:function get(){if(!this.valueRange||!this.context)return null;var errors=[];var _this$valueRange=this.valueRange,start=_this$valueRange.start,end=_this$valueRange.end;var _this$context=this.context,indent=_this$context.indent,src=_this$context.src;if(src[end-1]!=="'")errors.push(new _PlainValueFf5147c.Y(this,"Missing closing 'quote"));var str="";for(var i=start+1;i<end-1;++i){var ch=src[i];if(ch==="\n"){if(_PlainValueFf5147c.N.atDocumentBoundary(src,i+1))errors.push(new _PlainValueFf5147c.g(this,"Document boundary indicators are not allowed within string values"));var _Node$foldNewline=_PlainValueFf5147c.N.foldNewline(src,i,indent),fold=_Node$foldNewline.fold,offset=_Node$foldNewline.offset,error=_Node$foldNewline.error;str+=fold;i=offset;if(error)errors.push(new _PlainValueFf5147c.g(this,"Multi-line single-quoted string needs to be sufficiently indented"))}else if(ch==="'"){str+=ch;i+=1;if(src[i]!=="'")errors.push(new _PlainValueFf5147c.Y(this,"Unescaped single quote? This should not happen."))}else if(ch===" "||ch==="\t"){var wsStart=i;var next=src[i+1];while(next===" "||next==="\t"){i+=1;next=src[i+1]}if(next!=="\n")str+=i>wsStart?src.slice(wsStart,i+1):ch}else{str+=ch}}return errors.length>0?{errors:errors,str:str}:str}}],[{key:"endOfQuote",value:function endOfQuote(src,offset){var ch=src[offset];while(ch){if(ch==="'"){if(src[offset+1]!=="'")break;ch=src[offset+=2]}else{ch=src[offset+=1]}}return offset+1}}]);return QuoteSingle}(_PlainValueFf5147c.N);function createNewNode(type,props){switch(type){case _PlainValueFf5147c.T.ALIAS:return new Alias(type,props);case _PlainValueFf5147c.T.BLOCK_FOLDED:case _PlainValueFf5147c.T.BLOCK_LITERAL:return new BlockValue(type,props);case _PlainValueFf5147c.T.FLOW_MAP:case _PlainValueFf5147c.T.FLOW_SEQ:return new FlowCollection(type,props);case _PlainValueFf5147c.T.MAP_KEY:case _PlainValueFf5147c.T.MAP_VALUE:case _PlainValueFf5147c.T.SEQ_ITEM:return new CollectionItem(type,props);case _PlainValueFf5147c.T.COMMENT:case _PlainValueFf5147c.T.PLAIN:return new _PlainValueFf5147c.P(type,props);case _PlainValueFf5147c.T.QUOTE_DOUBLE:return new QuoteDouble(type,props);case _PlainValueFf5147c.T.QUOTE_SINGLE:return new QuoteSingle(type,props);default:return null}}var ParseContext=function(){(0,_PlainValueFf5147c.b)(ParseContext,null,[{key:"parseType",value:function parseType(src,offset,inFlow){switch(src[offset]){case"*":return _PlainValueFf5147c.T.ALIAS;case">":return _PlainValueFf5147c.T.BLOCK_FOLDED;case"|":return _PlainValueFf5147c.T.BLOCK_LITERAL;case"{":return _PlainValueFf5147c.T.FLOW_MAP;case"[":return _PlainValueFf5147c.T.FLOW_SEQ;case"?":return!inFlow&&_PlainValueFf5147c.N.atBlank(src,offset+1,true)?_PlainValueFf5147c.T.MAP_KEY:_PlainValueFf5147c.T.PLAIN;case":":return!inFlow&&_PlainValueFf5147c.N.atBlank(src,offset+1,true)?_PlainValueFf5147c.T.MAP_VALUE:_PlainValueFf5147c.T.PLAIN;case"-":return!inFlow&&_PlainValueFf5147c.N.atBlank(src,offset+1,true)?_PlainValueFf5147c.T.SEQ_ITEM:_PlainValueFf5147c.T.PLAIN;case'"':return _PlainValueFf5147c.T.QUOTE_DOUBLE;case"'":return _PlainValueFf5147c.T.QUOTE_SINGLE;default:return _PlainValueFf5147c.T.PLAIN}}}]);function ParseContext(){var _this=this;var orig=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var _ref=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},atLineStart=_ref.atLineStart,inCollection=_ref.inCollection,inFlow=_ref.inFlow,indent=_ref.indent,lineStart=_ref.lineStart,parent=_ref.parent;(0,_PlainValueFf5147c.c)(this,ParseContext);(0,_PlainValueFf5147c.e)(this,"parseNode",(function(overlay,start){if(_PlainValueFf5147c.N.atDocumentBoundary(_this.src,start))return null;var context=new ParseContext(_this,overlay);var _context$parseProps=context.parseProps(start),props=_context$parseProps.props,type=_context$parseProps.type,valueStart=_context$parseProps.valueStart;var node=createNewNode(type,props);var offset=node.parse(context,valueStart);node.range=new _PlainValueFf5147c.R(start,offset);if(offset<=start){node.error=new Error("Node#parse consumed no characters");node.error.parseEnd=offset;node.error.source=node;node.range.end=start+1}if(context.nodeStartsCollection(node)){if(!node.error&&!context.atLineStart&&context.parent.type===_PlainValueFf5147c.T.DOCUMENT){node.error=new _PlainValueFf5147c.Y(node,"Block collection must not have preceding content here (e.g. directives-end indicator)")}var collection=new Collection(node);offset=collection.parse(new ParseContext(context),offset);collection.range=new _PlainValueFf5147c.R(start,offset);return collection}return node}));this.atLineStart=atLineStart!=null?atLineStart:orig.atLineStart||false;this.inCollection=inCollection!=null?inCollection:orig.inCollection||false;this.inFlow=inFlow!=null?inFlow:orig.inFlow||false;this.indent=indent!=null?indent:orig.indent;this.lineStart=lineStart!=null?lineStart:orig.lineStart;this.parent=parent!=null?parent:orig.parent||{};this.root=orig.root;this.src=orig.src}(0,_PlainValueFf5147c.b)(ParseContext,[{key:"nodeStartsCollection",value:function nodeStartsCollection(node){var inCollection=this.inCollection,inFlow=this.inFlow,src=this.src;if(inCollection||inFlow)return false;if(node instanceof CollectionItem)return true;var offset=node.range.end;if(src[offset]==="\n"||src[offset-1]==="\n")return false;offset=_PlainValueFf5147c.N.endOfWhiteSpace(src,offset);return src[offset]===":"}},{key:"parseProps",value:function parseProps(offset){var inFlow=this.inFlow,parent=this.parent,src=this.src;var props=[];var lineHasProps=false;offset=this.atLineStart?_PlainValueFf5147c.N.endOfIndent(src,offset):_PlainValueFf5147c.N.endOfWhiteSpace(src,offset);var ch=src[offset];while(ch===_PlainValueFf5147c.C.ANCHOR||ch===_PlainValueFf5147c.C.COMMENT||ch===_PlainValueFf5147c.C.TAG||ch==="\n"){if(ch==="\n"){var lineStart=offset+1;var inEnd=_PlainValueFf5147c.N.endOfIndent(src,lineStart);var indentDiff=inEnd-(lineStart+this.indent);var noIndicatorAsIndent=parent.type===_PlainValueFf5147c.T.SEQ_ITEM&&parent.context.atLineStart;if(!_PlainValueFf5147c.N.nextNodeIsIndented(src[inEnd],indentDiff,!noIndicatorAsIndent))break;this.atLineStart=true;this.lineStart=lineStart;lineHasProps=false;offset=inEnd}else if(ch===_PlainValueFf5147c.C.COMMENT){var end=_PlainValueFf5147c.N.endOfLine(src,offset+1);props.push(new _PlainValueFf5147c.R(offset,end));offset=end}else{var _end=_PlainValueFf5147c.N.endOfIdentifier(src,offset+1);if(ch===_PlainValueFf5147c.C.TAG&&src[_end]===","&&/^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+,\d\d\d\d(-\d\d){0,2}\/\S/.test(src.slice(offset+1,_end+13))){_end=_PlainValueFf5147c.N.endOfIdentifier(src,_end+5)}props.push(new _PlainValueFf5147c.R(offset,_end));lineHasProps=true;offset=_PlainValueFf5147c.N.endOfWhiteSpace(src,_end)}ch=src[offset]}if(lineHasProps&&ch===":"&&_PlainValueFf5147c.N.atBlank(src,offset+1,true))offset-=1;var type=ParseContext.parseType(src,offset,inFlow);return{props:props,type:type,valueStart:offset}}}]);return ParseContext}();function parse(src){var cr=[];if(src.indexOf("\r")!==-1){src=src.replace(/\r\n?/g,(function(match,offset){if(match.length>1)cr.push(offset);return"\n"}))}var documents=[];var offset=0;do{var doc=new Document;var context=new ParseContext({src:src});offset=doc.parse(context,offset);documents.push(doc)}while(offset<src.length);documents.setOrigRanges=function(){if(cr.length===0)return false;for(var i=1;i<cr.length;++i){cr[i]-=i}var crOffset=0;for(var _i=0;_i<documents.length;++_i){crOffset=documents[_i].setOrigRanges(cr,crOffset)}cr.splice(0,cr.length);return true};documents.toString=function(){return documents.join("...\n")};return documents}},{"./PlainValue-ff5147c6.js":218}],222:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.c=stringifyString;exports.f=addComment;exports.g=resolveMap;exports.h=resolveSeq;exports.j=resolveString;exports.k=stringifyNumber;exports.l=findPair;exports.r=resolveNode;exports.t=toJSON;exports.s=exports.n=exports.i=exports.e=exports.d=exports.b=exports.a=exports.Y=exports.S=exports.P=exports.N=exports.M=exports.C=exports.A=void 0;var _PlainValueFf5147c=require("./PlainValue-ff5147c6.js");function addCommentBefore(str,indent,comment){if(!comment)return str;var cc=comment.replace(/[\s\S]^/gm,"$&".concat(indent,"#"));return"#".concat(cc,"\n").concat(indent).concat(str)}function addComment(str,indent,comment){return!comment?str:comment.indexOf("\n")===-1?"".concat(str," #").concat(comment):"".concat(str,"\n")+comment.replace(/^/gm,"".concat(indent||"","#"))}var Node=function Node(){(0,_PlainValueFf5147c.c)(this,Node)};exports.N=Node;function toJSON(value,arg,ctx){if(Array.isArray(value))return value.map((function(v,i){return toJSON(v,String(i),ctx)}));if(value&&typeof value.toJSON==="function"){var anchor=ctx&&ctx.anchors&&ctx.anchors.get(value);if(anchor)ctx.onCreate=function(res){anchor.res=res;delete ctx.onCreate};var res=value.toJSON(arg,ctx);if(anchor&&ctx.onCreate)ctx.onCreate(res);return res}if((!ctx||!ctx.keep)&&typeof value==="bigint")return Number(value);return value}var Scalar=function(_Node){(0,_PlainValueFf5147c.j)(Scalar,_Node);var _super=(0,_PlainValueFf5147c.k)(Scalar);function Scalar(value){var _this;(0,_PlainValueFf5147c.c)(this,Scalar);_this=_super.call(this);_this.value=value;return _this}(0,_PlainValueFf5147c.b)(Scalar,[{key:"toJSON",value:function toJSON$1(arg,ctx){return ctx&&ctx.keep?this.value:toJSON(this.value,arg,ctx)}},{key:"toString",value:function toString(){return String(this.value)}}]);return Scalar}(Node);exports.S=Scalar;function collectionFromPath(schema,path,value){var v=value;for(var i=path.length-1;i>=0;--i){var k=path[i];var o=Number.isInteger(k)&&k>=0?[]:{};o[k]=v;v=o}return schema.createNode(v,false)}var isEmptyPath=function isEmptyPath(path){return path==null||(0,_PlainValueFf5147c.a)(path)==="object"&&path[Symbol.iterator]().next().done};exports.e=isEmptyPath;var Collection=function(_Node){(0,_PlainValueFf5147c.j)(Collection,_Node);var _super=(0,_PlainValueFf5147c.k)(Collection);function Collection(schema){var _this;(0,_PlainValueFf5147c.c)(this,Collection);_this=_super.call(this);(0,_PlainValueFf5147c.e)((0,_PlainValueFf5147c.p)(_this),"items",[]);_this.schema=schema;return _this}(0,_PlainValueFf5147c.b)(Collection,[{key:"addIn",value:function addIn(path,value){if(isEmptyPath(path))this.add(value);else{var _path=(0,_PlainValueFf5147c.q)(path),key=_path[0],rest=_path.slice(1);var node=this.get(key,true);if(node instanceof Collection)node.addIn(rest,value);else if(node===undefined&&this.schema)this.set(key,collectionFromPath(this.schema,rest,value));else throw new Error("Expected YAML collection at ".concat(key,". Remaining path: ").concat(rest))}}},{key:"deleteIn",value:function deleteIn(_ref){var _ref2=(0,_PlainValueFf5147c.q)(_ref),key=_ref2[0],rest=_ref2.slice(1);if(rest.length===0)return this["delete"](key);var node=this.get(key,true);if(node instanceof Collection)return node.deleteIn(rest);else throw new Error("Expected YAML collection at ".concat(key,". Remaining path: ").concat(rest))}},{key:"getIn",value:function getIn(_ref3,keepScalar){var _ref4=(0,_PlainValueFf5147c.q)(_ref3),key=_ref4[0],rest=_ref4.slice(1);var node=this.get(key,true);if(rest.length===0)return!keepScalar&&node instanceof Scalar?node.value:node;else return node instanceof Collection?node.getIn(rest,keepScalar):undefined}},{key:"hasAllNullValues",value:function hasAllNullValues(){return this.items.every((function(node){if(!node||node.type!=="PAIR")return false;var n=node.value;return n==null||n instanceof Scalar&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag}))}},{key:"hasIn",value:function hasIn(_ref5){var _ref6=(0,_PlainValueFf5147c.q)(_ref5),key=_ref6[0],rest=_ref6.slice(1);if(rest.length===0)return this.has(key);var node=this.get(key,true);return node instanceof Collection?node.hasIn(rest):false}},{key:"setIn",value:function setIn(_ref7,value){var _ref8=(0,_PlainValueFf5147c.q)(_ref7),key=_ref8[0],rest=_ref8.slice(1);if(rest.length===0){this.set(key,value)}else{var node=this.get(key,true);if(node instanceof Collection)node.setIn(rest,value);else if(node===undefined&&this.schema)this.set(key,collectionFromPath(this.schema,rest,value));else throw new Error("Expected YAML collection at ".concat(key,". Remaining path: ").concat(rest))}}},{key:"toJSON",value:function toJSON(){return null}},{key:"toString",value:function toString(ctx,_ref9,onComment,onChompKeep){var _this2=this;var blockItem=_ref9.blockItem,flowChars=_ref9.flowChars,isMap=_ref9.isMap,itemIndent=_ref9.itemIndent;var _ctx=ctx,indent=_ctx.indent,indentStep=_ctx.indentStep,stringify=_ctx.stringify;var inFlow=this.type===_PlainValueFf5147c.T.FLOW_MAP||this.type===_PlainValueFf5147c.T.FLOW_SEQ||ctx.inFlow;if(inFlow)itemIndent+=indentStep;var allNullValues=isMap&&this.hasAllNullValues();ctx=Object.assign({},ctx,{allNullValues:allNullValues,indent:itemIndent,inFlow:inFlow,type:null});var chompKeep=false;var hasItemWithNewLine=false;var nodes=this.items.reduce((function(nodes,item,i){var comment;if(item){if(!chompKeep&&item.spaceBefore)nodes.push({type:"comment",str:""});if(item.commentBefore)item.commentBefore.match(/^.*$/gm).forEach((function(line){nodes.push({type:"comment",str:"#".concat(line)})}));if(item.comment)comment=item.comment;if(inFlow&&(!chompKeep&&item.spaceBefore||item.commentBefore||item.comment||item.key&&(item.key.commentBefore||item.key.comment)||item.value&&(item.value.commentBefore||item.value.comment)))hasItemWithNewLine=true}chompKeep=false;var str=stringify(item,ctx,(function(){return comment=null}),(function(){return chompKeep=true}));if(inFlow&&!hasItemWithNewLine&&str.includes("\n"))hasItemWithNewLine=true;if(inFlow&&i<_this2.items.length-1)str+=",";str=addComment(str,itemIndent,comment);if(chompKeep&&(comment||inFlow))chompKeep=false;nodes.push({type:"item",str:str});return nodes}),[]);var str;if(nodes.length===0){str=flowChars.start+flowChars.end}else if(inFlow){var start=flowChars.start,end=flowChars.end;var strings=nodes.map((function(n){return n.str}));if(hasItemWithNewLine||strings.reduce((function(sum,str){return sum+str.length+2}),2)>Collection.maxFlowStringSingleLineLength){str=start;var _iterator=(0,_PlainValueFf5147c._)(strings),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var s=_step.value;str+=s?"\n".concat(indentStep).concat(indent).concat(s):"\n"}}catch(err){_iterator.e(err)}finally{_iterator.f()}str+="\n".concat(indent).concat(end)}else{str="".concat(start," ").concat(strings.join(" ")," ").concat(end)}}else{var _strings=nodes.map(blockItem);str=_strings.shift();var _iterator2=(0,_PlainValueFf5147c._)(_strings),_step2;try{for(_iterator2.s();!(_step2=_iterator2.n()).done;){var _s=_step2.value;str+=_s?"\n".concat(indent).concat(_s):"\n"}}catch(err){_iterator2.e(err)}finally{_iterator2.f()}}if(this.comment){str+="\n"+this.comment.replace(/^/gm,"".concat(indent,"#"));if(onComment)onComment()}else if(chompKeep&&onChompKeep)onChompKeep();return str}}]);return Collection}(Node);exports.C=Collection;(0,_PlainValueFf5147c.e)(Collection,"maxFlowStringSingleLineLength",60);function asItemIndex(key){var idx=key instanceof Scalar?key.value:key;if(idx&&typeof idx==="string")idx=Number(idx);return Number.isInteger(idx)&&idx>=0?idx:null}var YAMLSeq=function(_Collection){(0,_PlainValueFf5147c.j)(YAMLSeq,_Collection);var _super=(0,_PlainValueFf5147c.k)(YAMLSeq);function YAMLSeq(){(0,_PlainValueFf5147c.c)(this,YAMLSeq);return _super.apply(this,arguments)}(0,_PlainValueFf5147c.b)(YAMLSeq,[{key:"add",value:function add(value){this.items.push(value)}},{key:"delete",value:function _delete(key){var idx=asItemIndex(key);if(typeof idx!=="number")return false;var del=this.items.splice(idx,1);return del.length>0}},{key:"get",value:function get(key,keepScalar){var idx=asItemIndex(key);if(typeof idx!=="number")return undefined;var it=this.items[idx];return!keepScalar&&it instanceof Scalar?it.value:it}},{key:"has",value:function has(key){var idx=asItemIndex(key);return typeof idx==="number"&&idx<this.items.length}},{key:"set",value:function set(key,value){var idx=asItemIndex(key);if(typeof idx!=="number")throw new Error("Expected a valid index, not ".concat(key,"."));this.items[idx]=value}},{key:"toJSON",value:function toJSON$1(_,ctx){var seq=[];if(ctx&&ctx.onCreate)ctx.onCreate(seq);var i=0;var _iterator=(0,_PlainValueFf5147c._)(this.items),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var item=_step.value;seq.push(toJSON(item,String(i++),ctx))}}catch(err){_iterator.e(err)}finally{_iterator.f()}return seq}},{key:"toString",value:function toString(ctx,onComment,onChompKeep){if(!ctx)return JSON.stringify(this);return(0,_PlainValueFf5147c.l)((0,_PlainValueFf5147c.m)(YAMLSeq.prototype),"toString",this).call(this,ctx,{blockItem:function blockItem(n){return n.type==="comment"?n.str:"- ".concat(n.str)},flowChars:{start:"[",end:"]"},isMap:false,itemIndent:(ctx.indent||"")+" "},onComment,onChompKeep)}}]);return YAMLSeq}(Collection);exports.Y=YAMLSeq;var stringifyKey=function stringifyKey(key,jsKey,ctx){if(jsKey===null)return"";if((0,_PlainValueFf5147c.a)(jsKey)!=="object")return String(jsKey);if(key instanceof Node&&ctx&&ctx.doc)return key.toString({anchors:{},doc:ctx.doc,indent:"",indentStep:ctx.indentStep,inFlow:true,inStringifyKey:true,stringify:ctx.stringify});return JSON.stringify(jsKey)};var Pair=function(_Node){(0,_PlainValueFf5147c.j)(Pair,_Node);var _super=(0,_PlainValueFf5147c.k)(Pair);function Pair(key){var _this;var value=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;(0,_PlainValueFf5147c.c)(this,Pair);_this=_super.call(this);_this.key=key;_this.value=value;_this.type=Pair.Type.PAIR;return _this}(0,_PlainValueFf5147c.b)(Pair,[{key:"addToJSMap",value:function addToJSMap(ctx,map){var key=toJSON(this.key,"",ctx);if(map instanceof Map){var value=toJSON(this.value,key,ctx);map.set(key,value)}else if(map instanceof Set){map.add(key)}else{var stringKey=stringifyKey(this.key,key,ctx);map[stringKey]=toJSON(this.value,stringKey,ctx)}return map}},{key:"toJSON",value:function toJSON(_,ctx){var pair=ctx&&ctx.mapAsMap?new Map:{};return this.addToJSMap(ctx,pair)}},{key:"toString",value:function toString(ctx,onComment,onChompKeep){if(!ctx||!ctx.doc)return JSON.stringify(this);var _ctx$doc$options=ctx.doc.options,indentSize=_ctx$doc$options.indent,indentSeq=_ctx$doc$options.indentSeq,simpleKeys=_ctx$doc$options.simpleKeys;var key=this.key,value=this.value;var keyComment=key instanceof Node&&key.comment;if(simpleKeys){if(keyComment){throw new Error("With simple keys, key nodes cannot have comments")}if(key instanceof Collection){var msg="With simple keys, collection cannot be used as a key value";throw new Error(msg)}}var explicitKey=!simpleKeys&&(!key||keyComment||key instanceof Collection||key.type===_PlainValueFf5147c.T.BLOCK_FOLDED||key.type===_PlainValueFf5147c.T.BLOCK_LITERAL);var _ctx=ctx,doc=_ctx.doc,indent=_ctx.indent,indentStep=_ctx.indentStep,stringify=_ctx.stringify;ctx=Object.assign({},ctx,{implicitKey:!explicitKey,indent:indent+indentStep});var chompKeep=false;var str=stringify(key,ctx,(function(){return keyComment=null}),(function(){return chompKeep=true}));str=addComment(str,ctx.indent,keyComment);if(ctx.allNullValues&&!simpleKeys){if(this.comment){str=addComment(str,ctx.indent,this.comment);if(onComment)onComment()}else if(chompKeep&&!keyComment&&onChompKeep)onChompKeep();return ctx.inFlow?str:"? ".concat(str)}str=explicitKey?"? ".concat(str,"\n").concat(indent,":"):"".concat(str,":");if(this.comment){str=addComment(str,ctx.indent,this.comment);if(onComment)onComment()}var vcb="";var valueComment=null;if(value instanceof Node){if(value.spaceBefore)vcb="\n";if(value.commentBefore){var cs=value.commentBefore.replace(/^/gm,"".concat(ctx.indent,"#"));vcb+="\n".concat(cs)}valueComment=value.comment}else if(value&&(0,_PlainValueFf5147c.a)(value)==="object"){value=doc.schema.createNode(value,true)}ctx.implicitKey=false;if(!explicitKey&&!this.comment&&value instanceof Scalar)ctx.indentAtStart=str.length+1;chompKeep=false;if(!indentSeq&&indentSize>=2&&!ctx.inFlow&&!explicitKey&&value instanceof YAMLSeq&&value.type!==_PlainValueFf5147c.T.FLOW_SEQ&&!value.tag&&!doc.anchors.getName(value)){ctx.indent=ctx.indent.substr(2)}var valueStr=stringify(value,ctx,(function(){return valueComment=null}),(function(){return chompKeep=true}));var ws=" ";if(vcb||this.comment){ws="".concat(vcb,"\n").concat(ctx.indent)}else if(!explicitKey&&value instanceof Collection){var flow=valueStr[0]==="["||valueStr[0]==="{";if(!flow||valueStr.includes("\n"))ws="\n".concat(ctx.indent)}if(chompKeep&&!valueComment&&onChompKeep)onChompKeep();return addComment(str+ws+valueStr,ctx.indent,valueComment)}},{key:"commentBefore",get:function get(){return this.key instanceof Node?this.key.commentBefore:undefined},set:function set(cb){if(this.key==null)this.key=new Scalar(null);if(this.key instanceof Node)this.key.commentBefore=cb;else{var msg="Pair.commentBefore is an alias for Pair.key.commentBefore. To set it, the key must be a Node.";throw new Error(msg)}}}]);return Pair}(Node);exports.P=Pair;(0,_PlainValueFf5147c.e)(Pair,"Type",{PAIR:"PAIR",MERGE_PAIR:"MERGE_PAIR"});var getAliasCount=function getAliasCount(node,anchors){if(node instanceof Alias){var anchor=anchors.get(node.source);return anchor.count*anchor.aliasCount}else if(node instanceof Collection){var count=0;var _iterator=(0,_PlainValueFf5147c._)(node.items),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var item=_step.value;var c=getAliasCount(item,anchors);if(c>count)count=c}}catch(err){_iterator.e(err)}finally{_iterator.f()}return count}else if(node instanceof Pair){var kc=getAliasCount(node.key,anchors);var vc=getAliasCount(node.value,anchors);return Math.max(kc,vc)}return 1};var Alias=function(_Node){(0,_PlainValueFf5147c.j)(Alias,_Node);var _super=(0,_PlainValueFf5147c.k)(Alias);(0,_PlainValueFf5147c.b)(Alias,null,[{key:"stringify",value:function stringify(_ref,_ref2){var range=_ref.range,source=_ref.source;var anchors=_ref2.anchors,doc=_ref2.doc,implicitKey=_ref2.implicitKey,inStringifyKey=_ref2.inStringifyKey;var anchor=Object.keys(anchors).find((function(a){return anchors[a]===source}));if(!anchor&&inStringifyKey)anchor=doc.anchors.getName(source)||doc.anchors.newName();if(anchor)return"*".concat(anchor).concat(implicitKey?" ":"");var msg=doc.anchors.getName(source)?"Alias node must be after source node":"Source node not found for alias node";throw new Error("".concat(msg," [").concat(range,"]"))}}]);function Alias(source){var _this;(0,_PlainValueFf5147c.c)(this,Alias);_this=_super.call(this);_this.source=source;_this.type=_PlainValueFf5147c.T.ALIAS;return _this}(0,_PlainValueFf5147c.b)(Alias,[{key:"toJSON",value:function toJSON$1(arg,ctx){if(!ctx)return toJSON(this.source,arg,ctx);var anchors=ctx.anchors,maxAliasCount=ctx.maxAliasCount;var anchor=anchors.get(this.source);if(!anchor||anchor.res===undefined){var msg="This should not happen: Alias anchor was not resolved?";if(this.cstNode)throw new _PlainValueFf5147c.o(this.cstNode,msg);else throw new ReferenceError(msg)}if(maxAliasCount>=0){anchor.count+=1;if(anchor.aliasCount===0)anchor.aliasCount=getAliasCount(this.source,anchors);if(anchor.count*anchor.aliasCount>maxAliasCount){var _msg="Excessive alias count indicates a resource exhaustion attack";if(this.cstNode)throw new _PlainValueFf5147c.o(this.cstNode,_msg);else throw new ReferenceError(_msg)}}return anchor.res}},{key:"toString",value:function toString(ctx){return Alias.stringify(this,ctx)}},{key:"tag",set:function set(t){throw new Error("Alias nodes cannot have tags")}}]);return Alias}(Node);exports.A=Alias;(0,_PlainValueFf5147c.e)(Alias,"default",true);function findPair(items,key){var k=key instanceof Scalar?key.value:key;var _iterator=(0,_PlainValueFf5147c._)(items),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var it=_step.value;if(it instanceof Pair){if(it.key===key||it.key===k)return it;if(it.key&&it.key.value===k)return it}}}catch(err){_iterator.e(err)}finally{_iterator.f()}return undefined}var YAMLMap=function(_Collection){(0,_PlainValueFf5147c.j)(YAMLMap,_Collection);var _super=(0,_PlainValueFf5147c.k)(YAMLMap);function YAMLMap(){(0,_PlainValueFf5147c.c)(this,YAMLMap);return _super.apply(this,arguments)}(0,_PlainValueFf5147c.b)(YAMLMap,[{key:"add",value:function add(pair,overwrite){if(!pair)pair=new Pair(pair);else if(!(pair instanceof Pair))pair=new Pair(pair.key||pair,pair.value);var prev=findPair(this.items,pair.key);var sortEntries=this.schema&&this.schema.sortMapEntries;if(prev){if(overwrite)prev.value=pair.value;else throw new Error("Key ".concat(pair.key," already set"))}else if(sortEntries){var i=this.items.findIndex((function(item){return sortEntries(pair,item)<0}));if(i===-1)this.items.push(pair);else this.items.splice(i,0,pair)}else{this.items.push(pair)}}},{key:"delete",value:function _delete(key){var it=findPair(this.items,key);if(!it)return false;var del=this.items.splice(this.items.indexOf(it),1);return del.length>0}},{key:"get",value:function get(key,keepScalar){var it=findPair(this.items,key);var node=it&&it.value;return!keepScalar&&node instanceof Scalar?node.value:node}},{key:"has",value:function has(key){return!!findPair(this.items,key)}},{key:"set",value:function set(key,value){this.add(new Pair(key,value),true)}},{key:"toJSON",value:function toJSON(_,ctx,Type){var map=Type?new Type:ctx&&ctx.mapAsMap?new Map:{};if(ctx&&ctx.onCreate)ctx.onCreate(map);var _iterator2=(0,_PlainValueFf5147c._)(this.items),_step2;try{for(_iterator2.s();!(_step2=_iterator2.n()).done;){var item=_step2.value;item.addToJSMap(ctx,map)}}catch(err){_iterator2.e(err)}finally{_iterator2.f()}return map}},{key:"toString",value:function toString(ctx,onComment,onChompKeep){if(!ctx)return JSON.stringify(this);var _iterator3=(0,_PlainValueFf5147c._)(this.items),_step3;try{for(_iterator3.s();!(_step3=_iterator3.n()).done;){var item=_step3.value;if(!(item instanceof Pair))throw new Error("Map items must all be pairs; found ".concat(JSON.stringify(item)," instead"))}}catch(err){_iterator3.e(err)}finally{_iterator3.f()}return(0,_PlainValueFf5147c.l)((0,_PlainValueFf5147c.m)(YAMLMap.prototype),"toString",this).call(this,ctx,{blockItem:function blockItem(n){return n.str},flowChars:{start:"{",end:"}"},isMap:true,itemIndent:ctx.indent||""},onComment,onChompKeep)}}]);return YAMLMap}(Collection);exports.d=YAMLMap;var MERGE_KEY="<<";var Merge=function(_Pair){(0,_PlainValueFf5147c.j)(Merge,_Pair);var _super=(0,_PlainValueFf5147c.k)(Merge);function Merge(pair){var _this;(0,_PlainValueFf5147c.c)(this,Merge);if(pair instanceof Pair){var seq=pair.value;if(!(seq instanceof YAMLSeq)){seq=new YAMLSeq;seq.items.push(pair.value);seq.range=pair.value.range}_this=_super.call(this,pair.key,seq);_this.range=pair.range}else{_this=_super.call(this,new Scalar(MERGE_KEY),new YAMLSeq)}_this.type=Pair.Type.MERGE_PAIR;return(0,_PlainValueFf5147c.r)(_this)}(0,_PlainValueFf5147c.b)(Merge,[{key:"addToJSMap",value:function addToJSMap(ctx,map){var _iterator=(0,_PlainValueFf5147c._)(this.value.items),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var source=_step.value.source;if(!(source instanceof YAMLMap))throw new Error("Merge sources must be maps");var srcMap=source.toJSON(null,ctx,Map);var _iterator2=(0,_PlainValueFf5147c._)(srcMap),_step2;try{for(_iterator2.s();!(_step2=_iterator2.n()).done;){var _step2$value=(0,_PlainValueFf5147c.h)(_step2.value,2),key=_step2$value[0],value=_step2$value[1];if(map instanceof Map){if(!map.has(key))map.set(key,value)}else if(map instanceof Set){map.add(key)}else{if(!Object.prototype.hasOwnProperty.call(map,key))map[key]=value}}}catch(err){_iterator2.e(err)}finally{_iterator2.f()}}}catch(err){_iterator.e(err)}finally{_iterator.f()}return map}},{key:"toString",value:function toString(ctx,onComment){var seq=this.value;if(seq.items.length>1)return(0,_PlainValueFf5147c.l)((0,_PlainValueFf5147c.m)(Merge.prototype),"toString",this).call(this,ctx,onComment);this.value=seq.items[0];var str=(0,_PlainValueFf5147c.l)((0,_PlainValueFf5147c.m)(Merge.prototype),"toString",this).call(this,ctx,onComment);this.value=seq;return str}}]);return Merge}(Pair);exports.M=Merge;var binaryOptions={defaultType:_PlainValueFf5147c.T.BLOCK_LITERAL,lineWidth:76};exports.b=binaryOptions;var boolOptions={trueStr:"true",falseStr:"false"};exports.a=boolOptions;var intOptions={asBigInt:false};exports.i=intOptions;var nullOptions={nullStr:"null"};exports.n=nullOptions;var strOptions={defaultType:_PlainValueFf5147c.T.PLAIN,doubleQuoted:{jsonEncoding:false,minMultiLineLength:40},fold:{lineWidth:80,minContentWidth:20}};exports.s=strOptions;function resolveScalar(str,tags,scalarFallback){var _iterator=(0,_PlainValueFf5147c._)(tags),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var _step$value=_step.value,format=_step$value.format,test=_step$value.test,resolve=_step$value.resolve;if(test){var match=str.match(test);if(match){var res=resolve.apply(null,match);if(!(res instanceof Scalar))res=new Scalar(res);if(format)res.format=format;return res}}}}catch(err){_iterator.e(err)}finally{_iterator.f()}if(scalarFallback)str=scalarFallback(str);return new Scalar(str)}var FOLD_FLOW="flow";var FOLD_BLOCK="block";var FOLD_QUOTED="quoted";var consumeMoreIndentedLines=function consumeMoreIndentedLines(text,i){var ch=text[i+1];while(ch===" "||ch==="\t"){do{ch=text[i+=1]}while(ch&&ch!=="\n");ch=text[i+1]}return i};function foldFlowLines(text,indent,mode,_ref){var indentAtStart=_ref.indentAtStart,_ref$lineWidth=_ref.lineWidth,lineWidth=_ref$lineWidth===void 0?80:_ref$lineWidth,_ref$minContentWidth=_ref.minContentWidth,minContentWidth=_ref$minContentWidth===void 0?20:_ref$minContentWidth,onFold=_ref.onFold,onOverflow=_ref.onOverflow;if(!lineWidth||lineWidth<0)return text;var endStep=Math.max(1+minContentWidth,1+lineWidth-indent.length);if(text.length<=endStep)return text;var folds=[];var escapedFolds={};var end=lineWidth-(typeof indentAtStart==="number"?indentAtStart:indent.length);var split=undefined;var prev=undefined;var overflow=false;var i=-1;if(mode===FOLD_BLOCK){i=consumeMoreIndentedLines(text,i);if(i!==-1)end=i+endStep}for(var ch;ch=text[i+=1];){if(mode===FOLD_QUOTED&&ch==="\\"){switch(text[i+1]){case"x":i+=3;break;case"u":i+=5;break;case"U":i+=9;break;default:i+=1}}if(ch==="\n"){if(mode===FOLD_BLOCK)i=consumeMoreIndentedLines(text,i);end=i+endStep;split=undefined}else{if(ch===" "&&prev&&prev!==" "&&prev!=="\n"&&prev!=="\t"){var next=text[i+1];if(next&&next!==" "&&next!=="\n"&&next!=="\t")split=i}if(i>=end){if(split){folds.push(split);end=split+endStep;split=undefined}else if(mode===FOLD_QUOTED){while(prev===" "||prev==="\t"){prev=ch;ch=text[i+=1];overflow=true}folds.push(i-2);escapedFolds[i-2]=true;end=i-2+endStep;split=undefined}else{overflow=true}}}prev=ch}if(overflow&&onOverflow)onOverflow();if(folds.length===0)return text;if(onFold)onFold();var res=text.slice(0,folds[0]);for(var _i=0;_i<folds.length;++_i){var fold=folds[_i];var _end=folds[_i+1]||text.length;if(mode===FOLD_QUOTED&&escapedFolds[fold])res+="".concat(text[fold],"\\");res+="\n".concat(indent).concat(text.slice(fold+1,_end))}return res}var getFoldOptions=function getFoldOptions(_ref){var indentAtStart=_ref.indentAtStart;return indentAtStart?Object.assign({indentAtStart:indentAtStart},strOptions.fold):strOptions.fold};var containsDocumentMarker=function containsDocumentMarker(str){return/^(%|---|\.\.\.)/m.test(str)};function lineLengthOverLimit(str,limit){var strLen=str.length;if(strLen<=limit)return false;for(var i=0,start=0;i<strLen;++i){if(str[i]==="\n"){if(i-start>limit)return true;start=i+1;if(strLen-start<=limit)return false}}return true}function doubleQuotedString(value,ctx){var implicitKey=ctx.implicitKey;var _strOptions$doubleQuo=strOptions.doubleQuoted,jsonEncoding=_strOptions$doubleQuo.jsonEncoding,minMultiLineLength=_strOptions$doubleQuo.minMultiLineLength;var json=JSON.stringify(value);if(jsonEncoding)return json;var indent=ctx.indent||(containsDocumentMarker(value)?" ":"");var str="";var start=0;for(var i=0,ch=json[i];ch;ch=json[++i]){if(ch===" "&&json[i+1]==="\\"&&json[i+2]==="n"){str+=json.slice(start,i)+"\\ ";i+=1;start=i;ch="\\"}if(ch==="\\")switch(json[i+1]){case"u":{str+=json.slice(start,i);var code=json.substr(i+2,4);switch(code){case"0000":str+="\\0";break;case"0007":str+="\\a";break;case"000b":str+="\\v";break;case"001b":str+="\\e";break;case"0085":str+="\\N";break;case"00a0":str+="\\_";break;case"2028":str+="\\L";break;case"2029":str+="\\P";break;default:if(code.substr(0,2)==="00")str+="\\x"+code.substr(2);else str+=json.substr(i,6)}i+=5;start=i+1}break;case"n":if(implicitKey||json[i+2]==='"'||json.length<minMultiLineLength){i+=1}else{str+=json.slice(start,i)+"\n\n";while(json[i+2]==="\\"&&json[i+3]==="n"&&json[i+4]!=='"'){str+="\n";i+=2}str+=indent;if(json[i+2]===" ")str+="\\";i+=1;start=i+1}break;default:i+=1}}str=start?str+json.slice(start):json;return implicitKey?str:foldFlowLines(str,indent,FOLD_QUOTED,getFoldOptions(ctx))}function singleQuotedString(value,ctx){if(ctx.implicitKey){if(/\n/.test(value))return doubleQuotedString(value,ctx)}else{if(/[ \t]\n|\n[ \t]/.test(value))return doubleQuotedString(value,ctx)}var indent=ctx.indent||(containsDocumentMarker(value)?" ":"");var res="'"+value.replace(/'/g,"''").replace(/\n+/g,"$&\n".concat(indent))+"'";return ctx.implicitKey?res:foldFlowLines(res,indent,FOLD_FLOW,getFoldOptions(ctx))}function blockString(_ref2,ctx,onComment,onChompKeep){var comment=_ref2.comment,type=_ref2.type,value=_ref2.value;if(/\n[\t ]+$/.test(value)||/^\s*$/.test(value)){return doubleQuotedString(value,ctx)}var indent=ctx.indent||(ctx.forceBlockIndent||containsDocumentMarker(value)?" ":"");var indentSize=indent?"2":"1";var literal=type===_PlainValueFf5147c.T.BLOCK_FOLDED?false:type===_PlainValueFf5147c.T.BLOCK_LITERAL?true:!lineLengthOverLimit(value,strOptions.fold.lineWidth-indent.length);var header=literal?"|":">";if(!value)return header+"\n";var wsStart="";var wsEnd="";value=value.replace(/[\n\t ]*$/,(function(ws){var n=ws.indexOf("\n");if(n===-1){header+="-"}else if(value===ws||n!==ws.length-1){header+="+";if(onChompKeep)onChompKeep()}wsEnd=ws.replace(/\n$/,"");return""})).replace(/^[\n ]*/,(function(ws){if(ws.indexOf(" ")!==-1)header+=indentSize;var m=ws.match(/ +$/);if(m){wsStart=ws.slice(0,-m[0].length);return m[0]}else{wsStart=ws;return""}}));if(wsEnd)wsEnd=wsEnd.replace(/\n+(?!\n|$)/g,"$&".concat(indent));if(wsStart)wsStart=wsStart.replace(/\n+/g,"$&".concat(indent));if(comment){header+=" #"+comment.replace(/ ?[\r\n]+/g," ");if(onComment)onComment()}if(!value)return"".concat(header).concat(indentSize,"\n").concat(indent).concat(wsEnd);if(literal){value=value.replace(/\n+/g,"$&".concat(indent));return"".concat(header,"\n").concat(indent).concat(wsStart).concat(value).concat(wsEnd)}value=value.replace(/\n+/g,"\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,"$&".concat(indent));var body=foldFlowLines("".concat(wsStart).concat(value).concat(wsEnd),indent,FOLD_BLOCK,strOptions.fold);return"".concat(header,"\n").concat(indent).concat(body)}function plainString(item,ctx,onComment,onChompKeep){var comment=item.comment,type=item.type,value=item.value;var actualString=ctx.actualString,implicitKey=ctx.implicitKey,indent=ctx.indent,inFlow=ctx.inFlow;if(implicitKey&&/[\n[\]{},]/.test(value)||inFlow&&/[[\]{},]/.test(value)){return doubleQuotedString(value,ctx)}if(!value||/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)){return implicitKey||inFlow||value.indexOf("\n")===-1?value.indexOf('"')!==-1&&value.indexOf("'")===-1?singleQuotedString(value,ctx):doubleQuotedString(value,ctx):blockString(item,ctx,onComment,onChompKeep)}if(!implicitKey&&!inFlow&&type!==_PlainValueFf5147c.T.PLAIN&&value.indexOf("\n")!==-1){return blockString(item,ctx,onComment,onChompKeep)}if(indent===""&&containsDocumentMarker(value)){ctx.forceBlockIndent=true;return blockString(item,ctx,onComment,onChompKeep)}var str=value.replace(/\n+/g,"$&\n".concat(indent));if(actualString){var tags=ctx.doc.schema.tags;var resolved=resolveScalar(str,tags,tags.scalarFallback).value;if(typeof resolved!=="string")return doubleQuotedString(value,ctx)}var body=implicitKey?str:foldFlowLines(str,indent,FOLD_FLOW,getFoldOptions(ctx));if(comment&&!inFlow&&(body.indexOf("\n")!==-1||comment.indexOf("\n")!==-1)){if(onComment)onComment();return addCommentBefore(body,indent,comment)}return body}function stringifyString(item,ctx,onComment,onChompKeep){var defaultType=strOptions.defaultType;var implicitKey=ctx.implicitKey,inFlow=ctx.inFlow;var _item=item,type=_item.type,value=_item.value;if(typeof value!=="string"){value=String(value);item=Object.assign({},item,{value:value})}var _stringify=function _stringify(_type){switch(_type){case _PlainValueFf5147c.T.BLOCK_FOLDED:case _PlainValueFf5147c.T.BLOCK_LITERAL:return blockString(item,ctx,onComment,onChompKeep);case _PlainValueFf5147c.T.QUOTE_DOUBLE:return doubleQuotedString(value,ctx);case _PlainValueFf5147c.T.QUOTE_SINGLE:return singleQuotedString(value,ctx);case _PlainValueFf5147c.T.PLAIN:return plainString(item,ctx,onComment,onChompKeep);default:return null}};if(type!==_PlainValueFf5147c.T.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f]/.test(value)){type=_PlainValueFf5147c.T.QUOTE_DOUBLE}else if((implicitKey||inFlow)&&(type===_PlainValueFf5147c.T.BLOCK_FOLDED||type===_PlainValueFf5147c.T.BLOCK_LITERAL)){type=_PlainValueFf5147c.T.QUOTE_DOUBLE}var res=_stringify(type);if(res===null){res=_stringify(defaultType);if(res===null)throw new Error("Unsupported default string type ".concat(defaultType))}return res}function stringifyNumber(_ref){var format=_ref.format,minFractionDigits=_ref.minFractionDigits,tag=_ref.tag,value=_ref.value;if(typeof value==="bigint")return String(value);if(!isFinite(value))return isNaN(value)?".nan":value<0?"-.inf":".inf";var n=JSON.stringify(value);if(!format&&minFractionDigits&&(!tag||tag==="tag:yaml.org,2002:float")&&/^\d/.test(n)){var i=n.indexOf(".");if(i<0){i=n.length;n+="."}var d=minFractionDigits-(n.length-i-1);while(d-- >0){n+="0"}}return n}function checkFlowCollectionEnd(errors,cst){var _char,name;switch(cst.type){case _PlainValueFf5147c.T.FLOW_MAP:_char="}";name="flow map";break;case _PlainValueFf5147c.T.FLOW_SEQ:_char="]";name="flow sequence";break;default:errors.push(new _PlainValueFf5147c.g(cst,"Not a flow collection!?"));return}var lastItem;for(var i=cst.items.length-1;i>=0;--i){var item=cst.items[i];if(!item||item.type!==_PlainValueFf5147c.T.COMMENT){lastItem=item;break}}if(lastItem&&lastItem["char"]!==_char){var msg="Expected ".concat(name," to end with ").concat(_char);var err;if(typeof lastItem.offset==="number"){err=new _PlainValueFf5147c.g(cst,msg);err.offset=lastItem.offset+1}else{err=new _PlainValueFf5147c.g(lastItem,msg);if(lastItem.range&&lastItem.range.end)err.offset=lastItem.range.end-lastItem.range.start}errors.push(err)}}function checkFlowCommentSpace(errors,comment){var prev=comment.context.src[comment.range.start-1];if(prev!=="\n"&&prev!=="\t"&&prev!==" "){var msg="Comments must be separated from other tokens by white space characters";errors.push(new _PlainValueFf5147c.g(comment,msg))}}function getLongKeyError(source,key){var sk=String(key);var k=sk.substr(0,8)+"..."+sk.substr(-8);return new _PlainValueFf5147c.g(source,'The "'.concat(k,'" key is too long'))}function resolveComments(collection,comments){var _iterator=(0,_PlainValueFf5147c._)(comments),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var _step$value=_step.value,afterKey=_step$value.afterKey,before=_step$value.before,comment=_step$value.comment;var item=collection.items[before];if(!item){if(comment!==undefined){if(collection.comment)collection.comment+="\n"+comment;else collection.comment=comment}}else{if(afterKey&&item.value)item=item.value;if(comment===undefined){if(afterKey||!item.commentBefore)item.spaceBefore=true}else{if(item.commentBefore)item.commentBefore+="\n"+comment;else item.commentBefore=comment}}}}catch(err){_iterator.e(err)}finally{_iterator.f()}}function resolveString(doc,node){var res=node.strValue;if(!res)return"";if(typeof res==="string")return res;res.errors.forEach((function(error){if(!error.source)error.source=node;doc.errors.push(error)}));return res.str}function resolveTagHandle(doc,node){var _node$tag=node.tag,handle=_node$tag.handle,suffix=_node$tag.suffix;var prefix=doc.tagPrefixes.find((function(p){return p.handle===handle}));if(!prefix){var dtp=doc.getDefaults().tagPrefixes;if(dtp)prefix=dtp.find((function(p){return p.handle===handle}));if(!prefix)throw new _PlainValueFf5147c.g(node,"The ".concat(handle," tag handle is non-default and was not declared."))}if(!suffix)throw new _PlainValueFf5147c.g(node,"The ".concat(handle," tag has no suffix."));if(handle==="!"&&(doc.version||doc.options.version)==="1.0"){if(suffix[0]==="^"){doc.warnings.push(new _PlainValueFf5147c.f(node,"YAML 1.0 ^ tag expansion is not supported"));return suffix}if(/[:/]/.test(suffix)){var vocab=suffix.match(/^([a-z0-9-]+)\/(.*)/i);return vocab?"tag:".concat(vocab[1],".yaml.org,2002:").concat(vocab[2]):"tag:".concat(suffix)}}return prefix.prefix+decodeURIComponent(suffix)}function resolveTagName(doc,node){var tag=node.tag,type=node.type;var nonSpecific=false;if(tag){var handle=tag.handle,suffix=tag.suffix,verbatim=tag.verbatim;if(verbatim){if(verbatim!=="!"&&verbatim!=="!!")return verbatim;var msg="Verbatim tags aren't resolved, so ".concat(verbatim," is invalid.");doc.errors.push(new _PlainValueFf5147c.g(node,msg))}else if(handle==="!"&&!suffix){nonSpecific=true}else{try{return resolveTagHandle(doc,node)}catch(error){doc.errors.push(error)}}}switch(type){case _PlainValueFf5147c.T.BLOCK_FOLDED:case _PlainValueFf5147c.T.BLOCK_LITERAL:case _PlainValueFf5147c.T.QUOTE_DOUBLE:case _PlainValueFf5147c.T.QUOTE_SINGLE:return _PlainValueFf5147c.n.STR;case _PlainValueFf5147c.T.FLOW_MAP:case _PlainValueFf5147c.T.MAP:return _PlainValueFf5147c.n.MAP;case _PlainValueFf5147c.T.FLOW_SEQ:case _PlainValueFf5147c.T.SEQ:return _PlainValueFf5147c.n.SEQ;case _PlainValueFf5147c.T.PLAIN:return nonSpecific?_PlainValueFf5147c.n.STR:null;default:return null}}function resolveByTagName(doc,node,tagName){var tags=doc.schema.tags;var matchWithTest=[];var _iterator=(0,_PlainValueFf5147c._)(tags),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var tag=_step.value;if(tag.tag===tagName){if(tag.test)matchWithTest.push(tag);else{var res=tag.resolve(doc,node);return res instanceof Collection?res:new Scalar(res)}}}}catch(err){_iterator.e(err)}finally{_iterator.f()}var str=resolveString(doc,node);if(typeof str==="string"&&matchWithTest.length>0)return resolveScalar(str,matchWithTest,tags.scalarFallback);return null}function getFallbackTagName(_ref){var type=_ref.type;switch(type){case _PlainValueFf5147c.T.FLOW_MAP:case _PlainValueFf5147c.T.MAP:return _PlainValueFf5147c.n.MAP;case _PlainValueFf5147c.T.FLOW_SEQ:case _PlainValueFf5147c.T.SEQ:return _PlainValueFf5147c.n.SEQ;default:return _PlainValueFf5147c.n.STR}}function resolveTag(doc,node,tagName){try{var res=resolveByTagName(doc,node,tagName);if(res){if(tagName&&node.tag)res.tag=tagName;return res}}catch(error){if(!error.source)error.source=node;doc.errors.push(error);return null}try{var fallback=getFallbackTagName(node);if(!fallback)throw new Error("The tag ".concat(tagName," is unavailable"));var msg="The tag ".concat(tagName," is unavailable, falling back to ").concat(fallback);doc.warnings.push(new _PlainValueFf5147c.f(node,msg));var _res=resolveByTagName(doc,node,fallback);_res.tag=tagName;return _res}catch(error){var refError=new _PlainValueFf5147c.o(node,error.message);refError.stack=error.stack;doc.errors.push(refError);return null}}var isCollectionItem=function isCollectionItem(node){if(!node)return false;var type=node.type;return type===_PlainValueFf5147c.T.MAP_KEY||type===_PlainValueFf5147c.T.MAP_VALUE||type===_PlainValueFf5147c.T.SEQ_ITEM};function resolveNodeProps(errors,node){var comments={before:[],after:[]};var hasAnchor=false;var hasTag=false;var props=isCollectionItem(node.context.parent)?node.context.parent.props.concat(node.props):node.props;var _iterator=(0,_PlainValueFf5147c._)(props),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var _step$value=_step.value,start=_step$value.start,end=_step$value.end;switch(node.context.src[start]){case _PlainValueFf5147c.C.COMMENT:{if(!node.commentHasRequiredWhitespace(start)){var msg="Comments must be separated from other tokens by white space characters";errors.push(new _PlainValueFf5147c.g(node,msg))}var header=node.header,valueRange=node.valueRange;var cc=valueRange&&(start>valueRange.start||header&&start>header.start)?comments.after:comments.before;cc.push(node.context.src.slice(start+1,end));break}case _PlainValueFf5147c.C.ANCHOR:if(hasAnchor){var _msg="A node can have at most one anchor";errors.push(new _PlainValueFf5147c.g(node,_msg))}hasAnchor=true;break;case _PlainValueFf5147c.C.TAG:if(hasTag){var _msg2="A node can have at most one tag";errors.push(new _PlainValueFf5147c.g(node,_msg2))}hasTag=true;break}}}catch(err){_iterator.e(err)}finally{_iterator.f()}return{comments:comments,hasAnchor:hasAnchor,hasTag:hasTag}}function resolveNodeValue(doc,node){var anchors=doc.anchors,errors=doc.errors,schema=doc.schema;if(node.type===_PlainValueFf5147c.T.ALIAS){var name=node.rawValue;var src=anchors.getNode(name);if(!src){var msg="Aliased anchor not found: ".concat(name);errors.push(new _PlainValueFf5147c.o(node,msg));return null}var res=new Alias(src);anchors._cstAliases.push(res);return res}var tagName=resolveTagName(doc,node);if(tagName)return resolveTag(doc,node,tagName);if(node.type!==_PlainValueFf5147c.T.PLAIN){var _msg3="Failed to resolve ".concat(node.type," node here");errors.push(new _PlainValueFf5147c.Y(node,_msg3));return null}try{var str=resolveString(doc,node);return resolveScalar(str,schema.tags,schema.tags.scalarFallback)}catch(error){if(!error.source)error.source=node;errors.push(error);return null}}function resolveNode(doc,node){if(!node)return null;if(node.error)doc.errors.push(node.error);var _resolveNodeProps=resolveNodeProps(doc.errors,node),comments=_resolveNodeProps.comments,hasAnchor=_resolveNodeProps.hasAnchor,hasTag=_resolveNodeProps.hasTag;if(hasAnchor){var anchors=doc.anchors;var name=node.anchor;var prev=anchors.getNode(name);if(prev)anchors.map[anchors.newName(name)]=prev;anchors.map[name]=node}if(node.type===_PlainValueFf5147c.T.ALIAS&&(hasAnchor||hasTag)){var msg="An alias node must not specify any properties";doc.errors.push(new _PlainValueFf5147c.g(node,msg))}var res=resolveNodeValue(doc,node);if(res){res.range=[node.range.start,node.range.end];if(doc.options.keepCstNodes)res.cstNode=node;if(doc.options.keepNodeTypes)res.type=node.type;var cb=comments.before.join("\n");if(cb){res.commentBefore=res.commentBefore?"".concat(res.commentBefore,"\n").concat(cb):cb}var ca=comments.after.join("\n");if(ca)res.comment=res.comment?"".concat(res.comment,"\n").concat(ca):ca}return node.resolved=res}function resolveMap(doc,cst){if(cst.type!==_PlainValueFf5147c.T.MAP&&cst.type!==_PlainValueFf5147c.T.FLOW_MAP){var msg="A ".concat(cst.type," node cannot be resolved as a mapping");doc.errors.push(new _PlainValueFf5147c.Y(cst,msg));return null}var _ref=cst.type===_PlainValueFf5147c.T.FLOW_MAP?resolveFlowMapItems(doc,cst):resolveBlockMapItems(doc,cst),comments=_ref.comments,items=_ref.items;var map=new YAMLMap;map.items=items;resolveComments(map,comments);var hasCollectionKey=false;for(var i=0;i<items.length;++i){var iKey=items[i].key;if(iKey instanceof Collection)hasCollectionKey=true;if(doc.schema.merge&&iKey&&iKey.value===MERGE_KEY){items[i]=new Merge(items[i]);var sources=items[i].value.items;var error=null;sources.some((function(node){if(node instanceof Alias){var type=node.source.type;if(type===_PlainValueFf5147c.T.MAP||type===_PlainValueFf5147c.T.FLOW_MAP)return false;return error="Merge nodes aliases can only point to maps"}return error="Merge nodes can only have Alias nodes as values"}));if(error)doc.errors.push(new _PlainValueFf5147c.g(cst,error))}else{for(var j=i+1;j<items.length;++j){var jKey=items[j].key;if(iKey===jKey||iKey&&jKey&&Object.prototype.hasOwnProperty.call(iKey,"value")&&iKey.value===jKey.value){var _msg='Map keys must be unique; "'.concat(iKey,'" is repeated');doc.errors.push(new _PlainValueFf5147c.g(cst,_msg));break}}}}if(hasCollectionKey&&!doc.options.mapAsMap){var warn="Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.";doc.warnings.push(new _PlainValueFf5147c.f(cst,warn))}cst.resolved=map;return map}var valueHasPairComment=function valueHasPairComment(_ref2){var _ref2$context=_ref2.context,lineStart=_ref2$context.lineStart,node=_ref2$context.node,src=_ref2$context.src,props=_ref2.props;if(props.length===0)return false;var start=props[0].start;if(node&&start>node.valueRange.start)return false;if(src[start]!==_PlainValueFf5147c.C.COMMENT)return false;for(var i=lineStart;i<start;++i){if(src[i]==="\n")return false}return true};function resolvePairComment(item,pair){if(!valueHasPairComment(item))return;var comment=item.getPropValue(0,_PlainValueFf5147c.C.COMMENT,true);var found=false;var cb=pair.value.commentBefore;if(cb&&cb.startsWith(comment)){pair.value.commentBefore=cb.substr(comment.length+1);found=true}else{var cc=pair.value.comment;if(!item.node&&cc&&cc.startsWith(comment)){pair.value.comment=cc.substr(comment.length+1);found=true}}if(found)pair.comment=comment}function resolveBlockMapItems(doc,cst){var comments=[];var items=[];var key=undefined;var keyStart=null;for(var i=0;i<cst.items.length;++i){var item=cst.items[i];switch(item.type){case _PlainValueFf5147c.T.BLANK_LINE:comments.push({afterKey:!!key,before:items.length});break;case _PlainValueFf5147c.T.COMMENT:comments.push({afterKey:!!key,before:items.length,comment:item.comment});break;case _PlainValueFf5147c.T.MAP_KEY:if(key!==undefined)items.push(new Pair(key));if(item.error)doc.errors.push(item.error);key=resolveNode(doc,item.node);keyStart=null;break;case _PlainValueFf5147c.T.MAP_VALUE:{if(key===undefined)key=null;if(item.error)doc.errors.push(item.error);if(!item.context.atLineStart&&item.node&&item.node.type===_PlainValueFf5147c.T.MAP&&!item.node.context.atLineStart){var msg="Nested mappings are not allowed in compact mappings";doc.errors.push(new _PlainValueFf5147c.g(item.node,msg))}var valueNode=item.node;if(!valueNode&&item.props.length>0){valueNode=new _PlainValueFf5147c.P(_PlainValueFf5147c.T.PLAIN,[]);valueNode.context={parent:item,src:item.context.src};var pos=item.range.start+1;valueNode.range={start:pos,end:pos};valueNode.valueRange={start:pos,end:pos};if(typeof item.range.origStart==="number"){var origPos=item.range.origStart+1;valueNode.range.origStart=valueNode.range.origEnd=origPos;valueNode.valueRange.origStart=valueNode.valueRange.origEnd=origPos}}var pair=new Pair(key,resolveNode(doc,valueNode));resolvePairComment(item,pair);items.push(pair);if(key&&typeof keyStart==="number"){if(item.range.start>keyStart+1024)doc.errors.push(getLongKeyError(cst,key))}key=undefined;keyStart=null}break;default:if(key!==undefined)items.push(new Pair(key));key=resolveNode(doc,item);keyStart=item.range.start;if(item.error)doc.errors.push(item.error);next:for(var j=i+1;;++j){var nextItem=cst.items[j];switch(nextItem&&nextItem.type){case _PlainValueFf5147c.T.BLANK_LINE:case _PlainValueFf5147c.T.COMMENT:continue next;case _PlainValueFf5147c.T.MAP_VALUE:break next;default:{var _msg2="Implicit map keys need to be followed by map values";doc.errors.push(new _PlainValueFf5147c.g(item,_msg2));break next}}}if(item.valueRangeContainsNewline){var _msg3="Implicit map keys need to be on a single line";doc.errors.push(new _PlainValueFf5147c.g(item,_msg3))}}}if(key!==undefined)items.push(new Pair(key));return{comments:comments,items:items}}function resolveFlowMapItems(doc,cst){var comments=[];var items=[];var key=undefined;var explicitKey=false;var next="{";for(var i=0;i<cst.items.length;++i){var item=cst.items[i];if(typeof item["char"]==="string"){var _char2=item["char"],offset=item.offset;if(_char2==="?"&&key===undefined&&!explicitKey){explicitKey=true;next=":";continue}if(_char2===":"){if(key===undefined)key=null;if(next===":"){next=",";continue}}else{if(explicitKey){if(key===undefined&&_char2!==",")key=null;explicitKey=false}if(key!==undefined){items.push(new Pair(key));key=undefined;if(_char2===","){next=":";continue}}}if(_char2==="}"){if(i===cst.items.length-1)continue}else if(_char2===next){next=":";continue}var msg="Flow map contains an unexpected ".concat(_char2);var err=new _PlainValueFf5147c.Y(cst,msg);err.offset=offset;doc.errors.push(err)}else if(item.type===_PlainValueFf5147c.T.BLANK_LINE){comments.push({afterKey:!!key,before:items.length})}else if(item.type===_PlainValueFf5147c.T.COMMENT){checkFlowCommentSpace(doc.errors,item);comments.push({afterKey:!!key,before:items.length,comment:item.comment})}else if(key===undefined){if(next===",")doc.errors.push(new _PlainValueFf5147c.g(item,"Separator , missing in flow map"));key=resolveNode(doc,item)}else{if(next!==",")doc.errors.push(new _PlainValueFf5147c.g(item,"Indicator : missing in flow map entry"));items.push(new Pair(key,resolveNode(doc,item)));key=undefined;explicitKey=false}}checkFlowCollectionEnd(doc.errors,cst);if(key!==undefined)items.push(new Pair(key));return{comments:comments,items:items}}function resolveSeq(doc,cst){if(cst.type!==_PlainValueFf5147c.T.SEQ&&cst.type!==_PlainValueFf5147c.T.FLOW_SEQ){var msg="A ".concat(cst.type," node cannot be resolved as a sequence");doc.errors.push(new _PlainValueFf5147c.Y(cst,msg));return null}var _ref=cst.type===_PlainValueFf5147c.T.FLOW_SEQ?resolveFlowSeqItems(doc,cst):resolveBlockSeqItems(doc,cst),comments=_ref.comments,items=_ref.items;var seq=new YAMLSeq;seq.items=items;resolveComments(seq,comments);if(!doc.options.mapAsMap&&items.some((function(it){return it instanceof Pair&&it.key instanceof Collection}))){var warn="Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.";doc.warnings.push(new _PlainValueFf5147c.f(cst,warn))}cst.resolved=seq;return seq}function resolveBlockSeqItems(doc,cst){var comments=[];var items=[];for(var i=0;i<cst.items.length;++i){var item=cst.items[i];switch(item.type){case _PlainValueFf5147c.T.BLANK_LINE:comments.push({before:items.length});break;case _PlainValueFf5147c.T.COMMENT:comments.push({comment:item.comment,before:items.length});break;case _PlainValueFf5147c.T.SEQ_ITEM:if(item.error)doc.errors.push(item.error);items.push(resolveNode(doc,item.node));if(item.hasProps){var msg="Sequence items cannot have tags or anchors before the - indicator";doc.errors.push(new _PlainValueFf5147c.g(item,msg))}break;default:if(item.error)doc.errors.push(item.error);doc.errors.push(new _PlainValueFf5147c.Y(item,"Unexpected ".concat(item.type," node in sequence")))}}return{comments:comments,items:items}}function resolveFlowSeqItems(doc,cst){var comments=[];var items=[];var explicitKey=false;var key=undefined;var keyStart=null;var next="[";var prevItem=null;for(var i=0;i<cst.items.length;++i){var item=cst.items[i];if(typeof item["char"]==="string"){var _char3=item["char"],offset=item.offset;if(_char3!==":"&&(explicitKey||key!==undefined)){if(explicitKey&&key===undefined)key=next?items.pop():null;items.push(new Pair(key));explicitKey=false;key=undefined;keyStart=null}if(_char3===next){next=null}else if(!next&&_char3==="?"){explicitKey=true}else if(next!=="["&&_char3===":"&&key===undefined){if(next===","){key=items.pop();if(key instanceof Pair){var msg="Chaining flow sequence pairs is invalid";var err=new _PlainValueFf5147c.g(cst,msg);err.offset=offset;doc.errors.push(err)}if(!explicitKey&&typeof keyStart==="number"){var keyEnd=item.range?item.range.start:item.offset;if(keyEnd>keyStart+1024)doc.errors.push(getLongKeyError(cst,key));var src=prevItem.context.src;for(var _i=keyStart;_i<keyEnd;++_i){if(src[_i]==="\n"){var _msg="Implicit keys of flow sequence pairs need to be on a single line";doc.errors.push(new _PlainValueFf5147c.g(prevItem,_msg));break}}}}else{key=null}keyStart=null;explicitKey=false;next=null}else if(next==="["||_char3!=="]"||i<cst.items.length-1){var _msg2="Flow sequence contains an unexpected ".concat(_char3);var _err=new _PlainValueFf5147c.Y(cst,_msg2);_err.offset=offset;doc.errors.push(_err)}}else if(item.type===_PlainValueFf5147c.T.BLANK_LINE){comments.push({before:items.length})}else if(item.type===_PlainValueFf5147c.T.COMMENT){checkFlowCommentSpace(doc.errors,item);comments.push({comment:item.comment,before:items.length})}else{if(next){var _msg3="Expected a ".concat(next," in flow sequence");doc.errors.push(new _PlainValueFf5147c.g(item,_msg3))}var value=resolveNode(doc,item);if(key===undefined){items.push(value);prevItem=item}else{items.push(new Pair(key,value));key=undefined}keyStart=item.range.start;next=","}}checkFlowCollectionEnd(doc.errors,cst);if(key!==undefined)items.push(new Pair(key));return{comments:comments,items:items}}},{"./PlainValue-ff5147c6.js":218}],223:[function(require,module,exports){(function(process,Buffer){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.a=warnOptionDeprecation;exports.c=warnFileDeprecation;exports.w=warn;exports.t=exports.s=exports.p=exports.o=exports.i=exports.f=exports.b=void 0;var _PlainValueFf5147c=require("./PlainValue-ff5147c6.js");var _resolveSeq04825f=require("./resolveSeq-04825f30.js");var binary={identify:function identify(value){return value instanceof Uint8Array},default:false,tag:"tag:yaml.org,2002:binary",resolve:function resolve(doc,node){var src=(0,_resolveSeq04825f.j)(doc,node);if(typeof Buffer==="function"){return Buffer.from(src,"base64")}else if(typeof atob==="function"){var str=atob(src.replace(/[\n\r]/g,""));var buffer=new Uint8Array(str.length);for(var i=0;i<str.length;++i){buffer[i]=str.charCodeAt(i)}return buffer}else{var msg="This environment does not support reading binary tags; either Buffer or atob is required";doc.errors.push(new _PlainValueFf5147c.o(node,msg));return null}},options:_resolveSeq04825f.b,stringify:function stringify(_ref,ctx,onComment,onChompKeep){var comment=_ref.comment,type=_ref.type,value=_ref.value;var src;if(typeof Buffer==="function"){src=value instanceof Buffer?value.toString("base64"):Buffer.from(value.buffer).toString("base64")}else if(typeof btoa==="function"){var s="";for(var i=0;i<value.length;++i){s+=String.fromCharCode(value[i])}src=btoa(s)}else{throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required")}if(!type)type=_resolveSeq04825f.b.defaultType;if(type===_PlainValueFf5147c.T.QUOTE_DOUBLE){value=src}else{var lineWidth=_resolveSeq04825f.b.lineWidth;var n=Math.ceil(src.length/lineWidth);var lines=new Array(n);for(var _i=0,o=0;_i<n;++_i,o+=lineWidth){lines[_i]=src.substr(o,lineWidth)}value=lines.join(type===_PlainValueFf5147c.T.BLOCK_LITERAL?"\n":" ")}return(0,_resolveSeq04825f.c)({comment:comment,type:type,value:value},ctx,onComment,onChompKeep)}};exports.b=binary;function parsePairs(doc,cst){var seq=(0,_resolveSeq04825f.h)(doc,cst);for(var i=0;i<seq.items.length;++i){var item=seq.items[i];if(item instanceof _resolveSeq04825f.P)continue;else if(item instanceof _resolveSeq04825f.d){if(item.items.length>1){var msg="Each pair must have its own sequence indicator";throw new _PlainValueFf5147c.g(cst,msg)}var pair=item.items[0]||new _resolveSeq04825f.P;if(item.commentBefore)pair.commentBefore=pair.commentBefore?"".concat(item.commentBefore,"\n").concat(pair.commentBefore):item.commentBefore;if(item.comment)pair.comment=pair.comment?"".concat(item.comment,"\n").concat(pair.comment):item.comment;item=pair}seq.items[i]=item instanceof _resolveSeq04825f.P?item:new _resolveSeq04825f.P(item)}return seq}function createPairs(schema,iterable,ctx){var pairs=new _resolveSeq04825f.Y(schema);pairs.tag="tag:yaml.org,2002:pairs";var _iterator=(0,_PlainValueFf5147c._)(iterable),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var it=_step.value;var key=void 0,value=void 0;if(Array.isArray(it)){if(it.length===2){key=it[0];value=it[1]}else throw new TypeError("Expected [key, value] tuple: ".concat(it))}else if(it&&it instanceof Object){var keys=Object.keys(it);if(keys.length===1){key=keys[0];value=it[key]}else throw new TypeError("Expected { key: value } tuple: ".concat(it))}else{key=it}var pair=schema.createPair(key,value,ctx);pairs.items.push(pair)}}catch(err){_iterator.e(err)}finally{_iterator.f()}return pairs}var pairs={default:false,tag:"tag:yaml.org,2002:pairs",resolve:parsePairs,createNode:createPairs};exports.p=pairs;var YAMLOMap=function(_YAMLSeq){(0,_PlainValueFf5147c.j)(YAMLOMap,_YAMLSeq);var _super=(0,_PlainValueFf5147c.k)(YAMLOMap);function YAMLOMap(){var _this;(0,_PlainValueFf5147c.c)(this,YAMLOMap);_this=_super.call(this);(0,_PlainValueFf5147c.e)((0,_PlainValueFf5147c.p)(_this),"add",_resolveSeq04825f.d.prototype.add.bind((0,_PlainValueFf5147c.p)(_this)));(0,_PlainValueFf5147c.e)((0,_PlainValueFf5147c.p)(_this),"delete",_resolveSeq04825f.d.prototype["delete"].bind((0,_PlainValueFf5147c.p)(_this)));(0,_PlainValueFf5147c.e)((0,_PlainValueFf5147c.p)(_this),"get",_resolveSeq04825f.d.prototype.get.bind((0,_PlainValueFf5147c.p)(_this)));(0,_PlainValueFf5147c.e)((0,_PlainValueFf5147c.p)(_this),"has",_resolveSeq04825f.d.prototype.has.bind((0,_PlainValueFf5147c.p)(_this)));(0,_PlainValueFf5147c.e)((0,_PlainValueFf5147c.p)(_this),"set",_resolveSeq04825f.d.prototype.set.bind((0,_PlainValueFf5147c.p)(_this)));_this.tag=YAMLOMap.tag;return _this}(0,_PlainValueFf5147c.b)(YAMLOMap,[{key:"toJSON",value:function toJSON$1(_,ctx){var map=new Map;if(ctx&&ctx.onCreate)ctx.onCreate(map);var _iterator=(0,_PlainValueFf5147c._)(this.items),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var pair=_step.value;var key=void 0,value=void 0;if(pair instanceof _resolveSeq04825f.P){key=(0,_resolveSeq04825f.t)(pair.key,"",ctx);value=(0,_resolveSeq04825f.t)(pair.value,key,ctx)}else{key=(0,_resolveSeq04825f.t)(pair,"",ctx)}if(map.has(key))throw new Error("Ordered maps must not include duplicate keys");map.set(key,value)}}catch(err){_iterator.e(err)}finally{_iterator.f()}return map}}]);return YAMLOMap}(_resolveSeq04825f.Y);(0,_PlainValueFf5147c.e)(YAMLOMap,"tag","tag:yaml.org,2002:omap");function parseOMap(doc,cst){var pairs=parsePairs(doc,cst);var seenKeys=[];var _iterator2=(0,_PlainValueFf5147c._)(pairs.items),_step2;try{for(_iterator2.s();!(_step2=_iterator2.n()).done;){var key=_step2.value.key;if(key instanceof _resolveSeq04825f.S){if(seenKeys.includes(key.value)){var msg="Ordered maps must not include duplicate keys";throw new _PlainValueFf5147c.g(cst,msg)}else{seenKeys.push(key.value)}}}}catch(err){_iterator2.e(err)}finally{_iterator2.f()}return Object.assign(new YAMLOMap,pairs)}function createOMap(schema,iterable,ctx){var pairs=createPairs(schema,iterable,ctx);var omap=new YAMLOMap;omap.items=pairs.items;return omap}var omap={identify:function identify(value){return value instanceof Map},nodeClass:YAMLOMap,default:false,tag:"tag:yaml.org,2002:omap",resolve:parseOMap,createNode:createOMap};exports.o=omap;var YAMLSet=function(_YAMLMap){(0,_PlainValueFf5147c.j)(YAMLSet,_YAMLMap);var _super=(0,_PlainValueFf5147c.k)(YAMLSet);function YAMLSet(){var _this;(0,_PlainValueFf5147c.c)(this,YAMLSet);_this=_super.call(this);_this.tag=YAMLSet.tag;return _this}(0,_PlainValueFf5147c.b)(YAMLSet,[{key:"add",value:function add(key){var pair=key instanceof _resolveSeq04825f.P?key:new _resolveSeq04825f.P(key);var prev=(0,_resolveSeq04825f.l)(this.items,pair.key);if(!prev)this.items.push(pair)}},{key:"get",value:function get(key,keepPair){var pair=(0,_resolveSeq04825f.l)(this.items,key);return!keepPair&&pair instanceof _resolveSeq04825f.P?pair.key instanceof _resolveSeq04825f.S?pair.key.value:pair.key:pair}},{key:"set",value:function set(key,value){if(typeof value!=="boolean")throw new Error("Expected boolean value for set(key, value) in a YAML set, not ".concat((0,_PlainValueFf5147c.a)(value)));var prev=(0,_resolveSeq04825f.l)(this.items,key);if(prev&&!value){this.items.splice(this.items.indexOf(prev),1)}else if(!prev&&value){this.items.push(new _resolveSeq04825f.P(key))}}},{key:"toJSON",value:function toJSON(_,ctx){return(0,_PlainValueFf5147c.l)((0,_PlainValueFf5147c.m)(YAMLSet.prototype),"toJSON",this).call(this,_,ctx,Set)}},{key:"toString",value:function toString(ctx,onComment,onChompKeep){if(!ctx)return JSON.stringify(this);if(this.hasAllNullValues())return(0,_PlainValueFf5147c.l)((0,_PlainValueFf5147c.m)(YAMLSet.prototype),"toString",this).call(this,ctx,onComment,onChompKeep);else throw new Error("Set items must all have null values")}}]);return YAMLSet}(_resolveSeq04825f.d);(0,_PlainValueFf5147c.e)(YAMLSet,"tag","tag:yaml.org,2002:set");function parseSet(doc,cst){var map=(0,_resolveSeq04825f.g)(doc,cst);if(!map.hasAllNullValues())throw new _PlainValueFf5147c.g(cst,"Set items must all have null values");return Object.assign(new YAMLSet,map)}function createSet(schema,iterable,ctx){var set=new YAMLSet;var _iterator=(0,_PlainValueFf5147c._)(iterable),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var value=_step.value;set.items.push(schema.createPair(value,null,ctx))}}catch(err){_iterator.e(err)}finally{_iterator.f()}return set}var set={identify:function identify(value){return value instanceof Set},nodeClass:YAMLSet,default:false,tag:"tag:yaml.org,2002:set",resolve:parseSet,createNode:createSet};exports.s=set;var parseSexagesimal=function parseSexagesimal(sign,parts){var n=parts.split(":").reduce((function(n,p){return n*60+Number(p)}),0);return sign==="-"?-n:n};var stringifySexagesimal=function stringifySexagesimal(_ref){var value=_ref.value;if(isNaN(value)||!isFinite(value))return(0,_resolveSeq04825f.k)(value);var sign="";if(value<0){sign="-";value=Math.abs(value)}var parts=[value%60];if(value<60){parts.unshift(0)}else{value=Math.round((value-parts[0])/60);parts.unshift(value%60);if(value>=60){value=Math.round((value-parts[0])/60);parts.unshift(value)}}return sign+parts.map((function(n){return n<10?"0"+String(n):String(n)})).join(":").replace(/000000\d*$/,"")};var intTime={identify:function identify(value){return typeof value==="number"},default:true,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+)$/,resolve:function resolve(str,sign,parts){return parseSexagesimal(sign,parts.replace(/_/g,""))},stringify:stringifySexagesimal};exports.i=intTime;var floatTime={identify:function identify(value){return typeof value==="number"},default:true,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*)$/,resolve:function resolve(str,sign,parts){return parseSexagesimal(sign,parts.replace(/_/g,""))},stringify:stringifySexagesimal};exports.f=floatTime;var timestamp={identify:function identify(value){return value instanceof Date},default:true,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^(?:"+"([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})"+"(?:(?:t|T|[ \\t]+)"+"([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)"+"(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?"+")?"+")$"),resolve:function resolve(str,year,month,day,hour,minute,second,millisec,tz){if(millisec)millisec=(millisec+"00").substr(1,3);var date=Date.UTC(year,month-1,day,hour||0,minute||0,second||0,millisec||0);if(tz&&tz!=="Z"){var d=parseSexagesimal(tz[0],tz.slice(1));if(Math.abs(d)<30)d*=60;date-=6e4*d}return new Date(date)},stringify:function stringify(_ref2){var value=_ref2.value;return value.toISOString().replace(/((T00:00)?:00)?\.000Z$/,"")}};exports.t=timestamp;function shouldWarn(deprecation){var env=typeof process!=="undefined"&&process.env||{};if(deprecation){if(typeof YAML_SILENCE_DEPRECATION_WARNINGS!=="undefined")return!YAML_SILENCE_DEPRECATION_WARNINGS;return!env.YAML_SILENCE_DEPRECATION_WARNINGS}if(typeof YAML_SILENCE_WARNINGS!=="undefined")return!YAML_SILENCE_WARNINGS;return!env.YAML_SILENCE_WARNINGS}function warn(warning,type){if(shouldWarn(false)){var emit=typeof process!=="undefined"&&process.emitWarning;if(emit)emit(warning,type);else{console.warn(type?"".concat(type,": ").concat(warning):warning)}}}function warnFileDeprecation(filename){if(shouldWarn(true)){var path=filename.replace(/.*yaml[/\\]/i,"").replace(/\.js$/,"").replace(/\\/g,"/");warn("The endpoint 'yaml/".concat(path,"' will be removed in a future release."),"DeprecationWarning")}}var warned={};function warnOptionDeprecation(name,alternative){if(!warned[name]&&shouldWarn(true)){warned[name]=true;var msg="The option '".concat(name,"' will be removed in a future release");msg+=alternative?", use '".concat(alternative,"' instead."):".";warn(msg,"DeprecationWarning")}}}).call(this,require("_process"),require("buffer").Buffer)},{"./PlainValue-ff5147c6.js":218,"./resolveSeq-04825f30.js":222,_process:157,buffer:33}],224:[function(require,module,exports){"use strict";module.exports=require("./dist").YAML},{"./dist":220}],225:[function(require,module,exports){(function(Buffer){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _events=_interopRequireDefault(require("events"));var _mqtt=_interopRequireDefault(require("mqtt"));var _loglevel=_interopRequireDefault(require("loglevel"));var _tinycache=_interopRequireDefault(require("tinycache"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function")}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:true,configurable:true}});if(superClass)_setPrototypeOf(subClass,superClass)}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o};return _setPrototypeOf(o,p)}function _createSuper(Derived){var hasNativeReflectConstruct=_isNativeReflectConstruct();return function _createSuperInternal(){var Super=_getPrototypeOf(Derived),result;if(hasNativeReflectConstruct){var NewTarget=_getPrototypeOf(this).constructor;result=Reflect.construct(Super,arguments,NewTarget)}else{result=Super.apply(this,arguments)}return _possibleConstructorReturn(this,result)}}function _possibleConstructorReturn(self,call){if(call&&(_typeof(call)==="object"||typeof call==="function")){return call}return _assertThisInitialized(self)}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return self}function _isNativeReflectConstruct(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{Date.prototype.toString.call(Reflect.construct(Date,[],(function(){})));return true}catch(e){return false}}function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o)};return _getPrototypeOf(o)}var uuidv4=require("uuid/v4");var BaseClient=function(_events$EventEmitter){_inherits(BaseClient,_events$EventEmitter);var _super=_createSuper(BaseClient);function BaseClient(config){var _this;_classCallCheck(this,BaseClient);_this=_super.call(this);_this.log=_loglevel["default"];_this.log.setDefaultLevel(config.options.logLevel);_this.config=config;_this.reconnectLog=0;_this.mqtt=null;_this.lostConnectionLog=new _tinycache["default"];return _this}_createClass(BaseClient,[{key:"isConnected",value:function isConnected(){if(this.mqtt==null){return false}return this.mqtt.connected}},{key:"connect",value:function connect(){var _this2=this;if(this.mqtt!=null){this.log.info("[BaseClient:connect] Reconnecting to "+this.config.getMqttHost()+" as "+this.config.getClientId());this.mqtt.reconnect();return}this.log.info("[BaseClient:connect] Connecting to "+this.config.getMqttHost()+" as "+this.config.getClientId());this.mqtt=_mqtt["default"].connect(this.config.getMqttHost(),this.config.getMqttConfig());this.mqtt.on("connect",(function(){_this2.log.info("[BaseClient:onConnect] MQTT client is connected.");_this2.emit("connect");var connectionLostCount=_this2.lostConnectionLog.size;var reconnectPeriod=1e3;if(connectionLostCount>=9){reconnectPeriod=2e4;_this2.log.warn("[BaseClient:onOffline] This client is likely suffering from clientId stealing (where two connections try to use the same client Id).");_this2.emit("error","Exceeded 9 connection losses in a 5 minute period. Check for clientId conflict with another connection.")}else if(connectionLostCount>=6){reconnectPeriod=5e3}else if(connectionLostCount>=3){reconnectPeriod=2e3}if(reconnectPeriod!=_this2.mqtt.options.reconnectPeriod){_this2.log.info("[BaseClient:onOffline] Client has lost connection "+connectionLostCount+" times during the last 5 minutes, reconnect delay adjusted to "+reconnectPeriod+" ms");_this2.mqtt.options.reconnectPeriod=reconnectPeriod}}));this.mqtt.on("reconnect",(function(){_this2.log.info("[BaseClient:onReconnect] MQTT client is reconnecting.");_this2.emit("reconnect")}));this.mqtt.on("close",(function(){_this2.log.info("[BaseClient:onClose] MQTT client connection was closed.");_this2.emit("close")}));this.mqtt.on("offline",(function(){var newId=uuidv4();_this2.log.info("[BaseClient:onOffline] MQTT client connection is offline. ["+newId+"]");_this2.emit("offline");_this2.lostConnectionLog.put(newId,"1",3e5);var connectionLostCount=_this2.lostConnectionLog.size;_this2.log.info("[BaseClient:onOffline] Connection losses in the last 5 minutes: "+connectionLostCount)}));this.mqtt.on("error",(function(error){_this2.log.error("[BaseClient:onError] "+error);var errorMsg=""+error;if(errorMsg.indexOf("Not authorized")>-1){_this2.log.error("[BaseClient:onError] One or more configuration parameters are wrong. Modify the configuration before trying to reconnect.");_this2.mqtt.end(false,(function(){_this2.log.info("[BaseClient:onError] Closed the MQTT connection due to client misconfiguration")}))}_this2.emit("error",error)}))}},{key:"disconnect",value:function disconnect(){var _this3=this;if(this.mqtt==null){this.log.info("[BaseClient:disconnect] Client was never connected");return}this.mqtt.end(false,(function(){_this3.log.info("[BaseClient:disconnect] Closed the MQTT connection due to disconnect() call")}))}},{key:"_subscribe",value:function _subscribe(topic,QoS,callback){if(this.mqtt==null){this.emit("error","[BaseClient:_subscribe] MQTT Client is not initialized - call connect() first");return}if(!this.mqtt.connected){this.emit("error","[BaseClient:_subscribe] MQTT Client is not connected - call connect() first");return}QoS=QoS||0;callback=callback||function(err,granted){if(err==null){for(var index in granted){var grant=granted[index];this.log.debug("[BaseClient:_subscribe] Subscribed to "+grant.topic+" at QoS "+grant.qos)}}else{this.log.error("[BaseClient:_subscribe] "+err);this.emit("error",err)}}.bind(this);this.log.debug("[BaseClient:_subscribe] Subscribing to topic "+topic+" with QoS "+QoS);this.mqtt.subscribe(topic,{qos:parseInt(QoS)},callback)}},{key:"_unsubscribe",value:function _unsubscribe(topic,callback){if(this.mqtt==null){this.emit("error","[BaseClient:_unsubscribe] MQTT Client is not initialized - call connect() first");return}if(!this.mqtt.connected){this.emit("error","[BaseClient:_unsubscribe] MQTT Client is not connected - call connect() first");return}callback=callback||function(err){if(err==null){this.log.debug("[BaseClient:_unsubscribe] Unsubscribed from: "+topic)}else{this.log.error("[BaseClient:_unsubscribe] "+err);this.emit("error",err)}}.bind(this);this.log.debug("[BaseClient:_unsubscribe] Unsubscribe: "+topic);this.mqtt.unsubscribe(topic,callback)}},{key:"_publish",value:function _publish(topic,msg,QoS,callback){QoS=QoS||0;if(this.mqtt==null){this.emit("error","[BaseClient:_unsubscribe] MQTT Client is not initialized - call connect() first");return}if(!this.mqtt.connected){this.emit("error","[BaseClient:_unsubscribe] MQTT Client is not connected - call connect() first");return}if((_typeof(msg)==="object"||typeof msg==="boolean"||typeof msg==="number")&&!Buffer.isBuffer(msg)){msg=JSON.stringify(msg)}this.log.debug("[BaseClient:_publish] Publish: "+topic+", "+msg+", QoS : "+QoS);this.mqtt.publish(topic,msg,{qos:parseInt(QoS)},callback)}}]);return BaseClient}(_events["default"].EventEmitter);exports["default"]=BaseClient}).call(this,{isBuffer:require("../node_modules/is-buffer/index.js")})},{"../node_modules/is-buffer/index.js":121,events:34,loglevel:124,mqtt:137,tinycache:181,"uuid/v4":201}],226:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}var BaseConfig=function(){function BaseConfig(identity,auth,options){_classCallCheck(this,BaseConfig);this.identity=identity;this.auth=auth;this.options=options;if(this.options!=null&&"mqtt"in this.options){if("port"in this.options.mqtt&&this.options.mqtt.port!=null){if(isNaN(this.options.mqtt.port)){throw new Error("Optional setting options.mqtt.port must be a number if provided")}}if("cleanStart"in this.options.mqtt&&typeof this.options.mqtt.cleanStart!="boolean"){throw new Error("Optional setting options.mqtt.cleanStart must be a boolean if provided")}}if(this.options==null){this.options={}}if(!("domain"in this.options)||this.options.domain==null){this.options.domain="internetofthings.ibmcloud.com"}if(!("logLevel"in this.options)||this.options.logLevel==null){this.options.logLevel="info"}if(!("mqtt"in this.options)){this.options.mqtt={}}if(!("port"in this.options.mqtt)||this.options.mqtt.port==null){this.options.mqtt.port=8883}if(!("transport"in this.options.mqtt)||this.options.mqtt.transport==null){this.options.mqtt.transport="tcp"}if(!("cleanStart"in this.options.mqtt)){this.options.mqtt.cleanStart=true}if(!("sessionExpiry"in this.options.mqtt)){this.options.mqtt.sessionExpiry=3600}if(!("keepAlive"in this.options.mqtt)){this.options.mqtt.keepAlive=60}if(!("caFile"in this.options.mqtt)){this.options.mqtt.caFile=null}}_createClass(BaseConfig,[{key:"getOrgId",value:function getOrgId(){throw new Error("Sub class must implement getOrgId()")}},{key:"isQuickstart",value:function isQuickstart(){return this.getOrgId()=="quickstart"}},{key:"getClientId",value:function getClientId(){throw new Error("Sub class must implement getClientId()")}},{key:"getMqttUsername",value:function getMqttUsername(){throw new Error("Sub class must implement getMqttUsername()")}},{key:"getMqttPassword",value:function getMqttPassword(){throw new Error("Sub class must implement getMqttPassowrd()")}},{key:"getMqttConfig",value:function getMqttConfig(){var mqttConfig={clientId:this.getClientId(),keepalive:this.options.mqtt.keepAlive,connectTimeout:90*1e3,reconnectPeriod:1e3,queueQoSZero:true,resubscribe:true,clean:this.options.mqtt.cleanStart,username:this.getMqttUsername(),password:this.getMqttPassword(),rejectUnauthorized:true};return mqttConfig}},{key:"getMqttHost",value:function getMqttHost(){var server=this.getOrgId()+".messaging."+this.options.domain+":"+this.options.mqtt.port;if(this.options.mqtt.port==80||this.options.mqtt.port==1883){if(this.options.mqtt.transport=="tcp"){return"tcp://"+server}if(this.options.mqtt.transport=="websockets"){return"ws://"+server}}if(this.options.mqtt.port==433||this.options.mqtt.port==8883){if(this.options.mqtt.transport=="tcp"){return"ssl://"+server}if(this.options.mqtt.transport=="websockets"){return"wss://"+server}}return"ssl://"+server}}],[{key:"parseEnvVars",value:function parseEnvVars(){throw new Error("Sub class must implement parseEnvVars()")}},{key:"parseConfigFile",value:function parseConfigFile(){throw new Error("Sub class must implement parseConfigFile()")}}]);return BaseConfig}();exports["default"]=BaseConfig},{}],227:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _axios=_interopRequireDefault(require("axios"));var _bluebird=_interopRequireDefault(require("bluebird"));var _btoa=_interopRequireDefault(require("btoa"));var _formData=_interopRequireDefault(require("form-data"));var _loglevel=_interopRequireDefault(require("loglevel"));var _util=require("../util");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}function ownKeys(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);if(enumerableOnly)symbols=symbols.filter((function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable}));keys.push.apply(keys,symbols)}return keys}function _objectSpread(target){for(var i=1;i<arguments.length;i++){var source=arguments[i]!=null?arguments[i]:{};if(i%2){ownKeys(Object(source),true).forEach((function(key){_defineProperty(target,key,source[key])}))}else if(Object.getOwnPropertyDescriptors){Object.defineProperties(target,Object.getOwnPropertyDescriptors(source))}else{ownKeys(Object(source)).forEach((function(key){Object.defineProperty(target,key,Object.getOwnPropertyDescriptor(source,key))}))}}return target}function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true})}else{obj[key]=value}return obj}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}var ApiClient=function(){function ApiClient(config){_classCallCheck(this,ApiClient);this.log=_loglevel["default"];this.log.setDefaultLevel(config.options.logLevel);this.config=config;this.useLtpa=this.config.auth&&this.config.auth.useLtpa;this.log.debug("[ApiClient:constructor] ApiClient initialized for "+this.config.getApiBaseUri())}_createClass(ApiClient,[{key:"parseSortSpec",value:function parseSortSpec(sortSpec){return sortSpec?sortSpec.map((function(s){var e=Object.entries(s)[0];return"".concat(e[1]?"-":"").concat(e[0])})).join(","):undefined}},{key:"callApi",value:function callApi(method,expectedHttpCode,expectJsonContent,paths,body,params){var _this=this;return new _bluebird["default"]((function(resolve,reject){var uri=_this.config.getApiBaseUri();if(Array.isArray(paths)){for(var i=0,l=paths.length;i<l;i++){uri+="/"+paths[i]}}var xhrConfig={url:uri,method:method,headers:{"Content-Type":"application/json"},validateStatus:function validateStatus(status){if(Array.isArray(expectedHttpCode)){return expectedHttpCode.includes(status)}else{return status===expectedHttpCode}}};if(_this.useLtpa){xhrConfig.withCredentials=true}else{xhrConfig.headers["Authorization"]="Basic "+(0,_btoa["default"])(_this.config.auth.key+":"+_this.config.auth.token)}if(body){xhrConfig.data=body}if(params){xhrConfig.params=params}if(_this.config.getAdditionalHeaders()){xhrConfig.headers=_objectSpread(_objectSpread({},xhrConfig.headers),_this.config.getAdditionalHeaders())}function transformResponse(response){if(expectJsonContent&&!(_typeof(response.data)==="object")){try{resolve(JSON.parse(response.data))}catch(e){reject(e)}}else{resolve(response.data)}}_this.log.debug("[ApiClient:transformResponse] "+xhrConfig);(0,_axios["default"])(xhrConfig).then(transformResponse,reject)}))}},{key:"getOrganizationDetails",value:function getOrganizationDetails(){this.log.debug("[ApiClient] getOrganizationDetails()");return this.callApi("GET",200,true,null,null)}},{key:"getServiceStatus",value:function getServiceStatus(){this.log.debug("[ApiClient] getServiceStatus()");return this.callApi("GET",200,true,["service-status"],null)}},{key:"getActiveDevices",value:function getActiveDevices(start,end,detail){this.log.debug("[ApiClient] getActiveDevices("+start+", "+end+")");detail=detail|false;var params={start:start,end:end,detail:detail};return this.callApi("GET",200,true,["usage","active-devices"],null,params)}},{key:"getHistoricalDataUsage",value:function getHistoricalDataUsage(start,end,detail){this.log.debug("[ApiClient] getHistoricalDataUsage("+start+", "+end+")");detail=detail|false;var params={start:start,end:end,detail:detail};return this.callApi("GET",200,true,["usage","historical-data"],null,params)}},{key:"getDataUsage",value:function getDataUsage(start,end,detail){this.log.debug("[ApiClient] getDataUsage("+start+", "+end+")");detail=detail|false;var params={start:start,end:end,detail:detail};return this.callApi("GET",200,true,["usage","data-traffic"],null,params)}},{key:"getConnectionStates",value:function getConnectionStates(){this.log.debug("[ApiClient] getConnectionStates() - client connectivity");return this.callApi("GET",200,true,["clientconnectionstates"],null)}},{key:"getConnectionState",value:function getConnectionState(id){this.log.debug("[ApiClient] getConnectionState() - client connectivity");return this.callApi("GET",200,true,["clientconnectionstates/"+id],null)}},{key:"getConnectedClientsConnectionStates",value:function getConnectedClientsConnectionStates(){this.log.debug("[ApiClient] getConnectedClientsConnectionStates() - client connectivity");return this.callApi("GET",200,true,["clientconnectionstates?connectionStatus=connected"],null)}},{key:"getRecentConnectionStates",value:function getRecentConnectionStates(date){this.log.debug("[ApiClient] getRecentConnectionStates() - client connectivity");return this.callApi("GET",200,true,["clientconnectionstates?connectedAfter="+date],null)}},{key:"getCustomConnectionState",value:function getCustomConnectionState(query){this.log.debug("[ApiClient] getCustomConnectionStates() - client connectivity");return this.callApi("GET",200,true,["clientconnectionstates"+query],null)}},{key:"getAllDevices",value:function getAllDevices(params){this.log.debug("[ApiClient] getAllDevices() - BULK");return this.callApi("GET",200,true,["bulk","devices"],null,params)}},{key:"getGroupIdsForDevice",value:function getGroupIdsForDevice(deviceId){this.log.debug("[ApiClient] getGroupIdsForDevice("+deviceId+")");return this.callApi("GET",200,true,["authorization","devices",deviceId],null)}},{key:"updateDeviceRoles",value:function updateDeviceRoles(deviceId,roles){this.log.debug("[ApiClient] updateDeviceRoles("+deviceId+","+roles+")");return this.callApi("PUT",200,false,["authorization","devices",deviceId,"roles"],roles)}},{key:"getAllDevicesInGroup",value:function getAllDevicesInGroup(groupId){this.log.debug("[ApiClient] getAllDevicesInGropu("+groupId+")");return this.callApi("GET",200,true,["bulk","devices",groupId],null)}},{key:"addDevicesToGroup",value:function addDevicesToGroup(groupId,deviceList){this.log.debug("[ApiClient] addDevicesToGroup("+groupId+","+deviceList+")");return this.callApi("PUT",200,false,["bulk","devices",groupId,"add"],deviceList)}},{key:"removeDevicesFromGroup",value:function removeDevicesFromGroup(groupId,deviceList){this.log.debug("[ApiClient] removeDevicesFromGroup("+groupId+","+deviceList+")");return this.callApi("PUT",200,false,["bulk","devices",groupId,"remove"],deviceList)}},{key:"getAllGroups",value:function getAllGroups(){this.log.debug("[ApiClient] getAllGroups()");return this.callApi("GET",200,true,["groups"],null)}},{key:"getAllDeviceIdsInGroup",value:function getAllDeviceIdsInGroup(groupId){this.log.debug("[ApiClient] getAllDeviceIdsInGroup("+groupId+")");return this.callApi("GET",200,true,["bulk","devices",groupId,"ids"],null)}},{key:"getGroup",value:function getGroup(groupId){this.log.debug("[ApiClient] getGroup("+groupId+")");return this.callApi("GET",200,true,["groups",groupId],null)}},{key:"createGroup",value:function createGroup(groupInfo){this.log.debug("[ApiClient] createGroup()");return this.callApi("POST",201,true,["groups"],groupInfo)}},{key:"deleteGroup",value:function deleteGroup(groupId){this.log.debug("[ApiClient] deleteGroup("+groupId+")");return this.callApi("DELETE",200,false,["groups",groupId],null)}},{key:"getAllDeviceAccessControlProperties",value:function getAllDeviceAccessControlProperties(){this.log.debug("[ApiClient] getAllDeviceAccessControlProperties()");return this.callApi("GET",200,true,["authorization","devices"],null)}},{key:"getDeviceAccessControlProperties",value:function getDeviceAccessControlProperties(deviceId){this.log.debug("[ApiClient] getDeviceAccessControlProperties("+deviceId+")");return this.callApi("GET",200,true,["authorization","devices",deviceId,"roles"],null)}},{key:"updateDeviceAccessControlProperties",value:function updateDeviceAccessControlProperties(deviceId,deviceProps){this.log.debug("[ApiClient] updateDeviceAccessControlProperties("+deviceId+")");return this.callApi("PUT",200,true,["authorization","devices",deviceId],deviceProps)}},{key:"updateDeviceAccessControlPropertiesWithRoles",value:function updateDeviceAccessControlPropertiesWithRoles(deviceId,devicePropsWithRoles){this.log.debug("[ApiClient] updateDeviceAccessControlPropertiesWithRoles("+deviceId+","+devicePropsWithRoles+")");return this.callApi("PUT",200,true,["authorization","devices",deviceId,"withroles"],devicePropsWithRoles)}},{key:"updateGatewayRoles",value:function updateGatewayRoles(gatewayId,roles){this.log.debug("[ApiClient] updateGatewayRoles("+gatewayId+","+roles+")");return this.callApi("PUT",200,false,["authorization","devices",gatewayId,"roles"],roles)}},{key:"getGroups",value:function getGroups(groupId){this.log.debug("[ApiClient] getGroups("+groupId+")");return this.callApi("GET",200,true,["groups",groupId],null)}},{key:"callFormDataApi",value:function callFormDataApi(method,expectedHttpCode,expectJsonContent,paths,body,params){var _this2=this;return new _bluebird["default"]((function(resolve,reject){var uri=_this2.config.getApiBaseUri();if(Array.isArray(paths)){for(var i=0,l=paths.length;i<l;i++){uri+="/"+paths[i]}}var xhrConfig={url:uri,method:method,headers:{"Content-Type":"multipart/form-data"}};if(_this2.useLtpa){xhrConfig.withCredentials=true}else{xhrConfig.headers["Authorization"]="Basic "+(0,_btoa["default"])(_this2.apiKey+":"+_this2.apiToken)}if(body){xhrConfig.data=body;if((0,_util.isBrowser)()){xhrConfig.transformRequest=[function(data){var formData=new _formData["default"];if(xhrConfig.method=="POST"){if(data.schemaFile){var blob=new Blob([data.schemaFile],{type:"application/json"});var schemaFileName="".concat(data.name||"schema",".json");formData.append("schemaFile",blob,schemaFileName)}if(data.name){formData.append("name",data.name)}if(data.schemaType){formData.append("schemaType","json-schema")}if(data.description){formData.append("description",data.description)}}else if(xhrConfig.method=="PUT"){if(data.schemaFile){var blob=new Blob([data.schemaFile],{type:"application/json",name:data.name});var schemaFileName="".concat(data.name||"schema",".json");formData.append("schemaFile",blob,schemaFileName)}}return formData}]}}if(params){xhrConfig.params=params}if(_this2.config.getAdditionalHeaders()){xhrConfig.headers=_objectSpread(_objectSpread({},xhrConfig.headers),_this2.config.getAdditionalHeaders())}function transformResponse(response){if(response.status===expectedHttpCode){if(expectJsonContent&&!(_typeof(response.data)==="object")){try{resolve(JSON.parse(response.data))}catch(e){reject(e)}}else{resolve(response.data)}}else{reject(new Error(method+" "+uri+": Expected HTTP "+expectedHttpCode+" from server but got HTTP "+response.status+". Error Body: "+JSON.stringify(response.data)))}}_this2.log.debug("[ApiClient:transformResponse] "+xhrConfig);if((0,_util.isBrowser)()){(0,_axios["default"])(xhrConfig).then(transformResponse,reject)}else{var formData=null;var config={url:uri,method:method,headers:{"Content-Type":"multipart/form-data"},auth:{user:_this2.apiKey,pass:_this2.apiToken},formData:{},rejectUnauthorized:false};if(xhrConfig.method=="POST"){formData={schemaFile:{value:body.schemaFile,options:{contentType:"application/json",filename:body.name}},schemaType:"json-schema",name:body.name};config.formData=formData}else if(xhrConfig.method=="PUT"){formData={schemaFile:{value:body.schemaFile,options:{contentType:"application/json",filename:body.name}}};config.formData=formData}request(config,(function optionalCallback(err,response,body){if(response.statusCode===expectedHttpCode){if(expectJsonContent&&!(_typeof(response.data)==="object")){try{resolve(JSON.parse(body))}catch(e){reject(e)}}else{resolve(body)}}else{reject(new Error(method+" "+uri+": Expected HTTP "+expectedHttpCode+" from server but got HTTP "+response.statusCode+". Error Body: "+err))}}))}}))}},{key:"invalidOperation",value:function invalidOperation(message){return new _bluebird["default"]((function(resolve,reject){resolve(message)}))}}]);return ApiClient}();exports["default"]=ApiClient},{"../util":241,axios:1,bluebird:30,btoa:36,"form-data":118,loglevel:124}],228:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=exports.handleError=exports.ServiceNotFound=exports.DestinationAlreadyExists=exports.InvalidServiceCredentials=exports.WiotpError=void 0;function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function")}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:true,configurable:true}});if(superClass)_setPrototypeOf(subClass,superClass)}function _createSuper(Derived){var hasNativeReflectConstruct=_isNativeReflectConstruct();return function _createSuperInternal(){var Super=_getPrototypeOf(Derived),result;if(hasNativeReflectConstruct){var NewTarget=_getPrototypeOf(this).constructor;result=Reflect.construct(Super,arguments,NewTarget)}else{result=Super.apply(this,arguments)}return _possibleConstructorReturn(this,result)}}function _possibleConstructorReturn(self,call){if(call&&(_typeof(call)==="object"||typeof call==="function")){return call}return _assertThisInitialized(self)}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return self}function _wrapNativeSuper(Class){var _cache=typeof Map==="function"?new Map:undefined;_wrapNativeSuper=function _wrapNativeSuper(Class){if(Class===null||!_isNativeFunction(Class))return Class;if(typeof Class!=="function"){throw new TypeError("Super expression must either be null or a function")}if(typeof _cache!=="undefined"){if(_cache.has(Class))return _cache.get(Class);_cache.set(Class,Wrapper)}function Wrapper(){return _construct(Class,arguments,_getPrototypeOf(this).constructor)}Wrapper.prototype=Object.create(Class.prototype,{constructor:{value:Wrapper,enumerable:false,writable:true,configurable:true}});return _setPrototypeOf(Wrapper,Class)};return _wrapNativeSuper(Class)}function _construct(Parent,args,Class){if(_isNativeReflectConstruct()){_construct=Reflect.construct}else{_construct=function _construct(Parent,args,Class){var a=[null];a.push.apply(a,args);var Constructor=Function.bind.apply(Parent,a);var instance=new Constructor;if(Class)_setPrototypeOf(instance,Class.prototype);return instance}}return _construct.apply(null,arguments)}function _isNativeReflectConstruct(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{Date.prototype.toString.call(Reflect.construct(Date,[],(function(){})));return true}catch(e){return false}}function _isNativeFunction(fn){return Function.toString.call(fn).indexOf("[native code]")!==-1}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o};return _setPrototypeOf(o,p)}function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o)};return _getPrototypeOf(o)}var WiotpError=function(_Error){_inherits(WiotpError,_Error);var _super=_createSuper(WiotpError);function WiotpError(message,cause){var _this;_classCallCheck(this,WiotpError);_this=_super.call(this,message);_this.cause=cause;_this.name=_this.constructor.name;return _this}return WiotpError}(_wrapNativeSuper(Error));exports.WiotpError=WiotpError;var InvalidServiceCredentials=function(_WiotpError){_inherits(InvalidServiceCredentials,_WiotpError);var _super2=_createSuper(InvalidServiceCredentials);function InvalidServiceCredentials(){_classCallCheck(this,InvalidServiceCredentials);return _super2.apply(this,arguments)}return InvalidServiceCredentials}(WiotpError);exports.InvalidServiceCredentials=InvalidServiceCredentials;var DestinationAlreadyExists=function(_WiotpError2){_inherits(DestinationAlreadyExists,_WiotpError2);var _super3=_createSuper(DestinationAlreadyExists);function DestinationAlreadyExists(){_classCallCheck(this,DestinationAlreadyExists);return _super3.apply(this,arguments)}return DestinationAlreadyExists}(WiotpError);exports.DestinationAlreadyExists=DestinationAlreadyExists;var ServiceNotFound=function(_WiotpError3){_inherits(ServiceNotFound,_WiotpError3);var _super4=_createSuper(ServiceNotFound);function ServiceNotFound(){_classCallCheck(this,ServiceNotFound);return _super4.apply(this,arguments)}return ServiceNotFound}(WiotpError);exports.ServiceNotFound=ServiceNotFound;var handleError=function handleError(err,errorMappings){if(err&&err.response&&err.response.data&&err.response.data.exception&&err.response.data.exception.id){if(errorMappings&&errorMappings[err.response.data.exception.id]){throw new errorMappings[err.response.data.exception.id](err.response.data.message,err)}else{throw new WiotpError(err.response.data.message,err)}}else{throw err}};exports.handleError=handleError;var _default={WiotpError:WiotpError,InvalidServiceCredentials:InvalidServiceCredentials,DestinationAlreadyExists:DestinationAlreadyExists,ServiceNotFound:ServiceNotFound};exports["default"]=_default},{}],229:[function(require,module,exports){"use strict";function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _loglevel=_interopRequireDefault(require("loglevel"));var errors=_interopRequireWildcard(require("./ApiErrors"));function _getRequireWildcardCache(){if(typeof WeakMap!=="function")return null;var cache=new WeakMap;_getRequireWildcardCache=function _getRequireWildcardCache(){return cache};return cache}function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}if(obj===null||_typeof(obj)!=="object"&&typeof obj!=="function"){return{default:obj}}var cache=_getRequireWildcardCache();if(cache&&cache.has(obj)){return cache.get(obj)}var newObj={};var hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;if(desc&&(desc.get||desc.set)){Object.defineProperty(newObj,key,desc)}else{newObj[key]=obj[key]}}}newObj["default"]=obj;if(cache){cache.set(obj,newObj)}return newObj}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}var DscClient=function(){function DscClient(apiClient){_classCallCheck(this,DscClient);this.log=_loglevel["default"];this.apiClient=apiClient}_createClass(DscClient,[{key:"createService",value:function createService(service){return this.apiClient.callApi("POST",201,true,["s2s","services"],service)["catch"]((function(err){return errors.handleError(err,{CUDSS0026E:errors.InvalidServiceCredentials})}))}},{key:"createCloudantService",value:function createCloudantService(_ref){var name=_ref.name,description=_ref.description,username=_ref.username,password=_ref.password,_ref$host=_ref.host,host=_ref$host===void 0?"".concat(username,".cloudant.com"):_ref$host,_ref$port=_ref.port,port=_ref$port===void 0?443:_ref$port,_ref$url=_ref.url,url=_ref$url===void 0?"https://".concat(username,":").concat(password,"@").concat(host):_ref$url,apikey=_ref.apikey,iam_apikey_name=_ref.iam_apikey_name,iam_apikey_description=_ref.iam_apikey_description,iam_role_crn=_ref.iam_role_crn,iam_serviceid_crn=_ref.iam_serviceid_crn;return this.createService({name:name,description:description,type:"cloudant",credentials:{username:username,password:password,host:host,port:port,url:url,apikey:apikey,iam_apikey_name:iam_apikey_name,iam_apikey_description:iam_apikey_description,iam_role_crn:iam_role_crn,iam_serviceid_crn:iam_serviceid_crn}})}},{key:"createEventstreamsService",value:function createEventstreamsService(_ref2){var name=_ref2.name,description=_ref2.description,api_key=_ref2.api_key,kafka_admin_url=_ref2.kafka_admin_url,kafka_brokers_sasl=_ref2.kafka_brokers_sasl,user=_ref2.user,password=_ref2.password,apikey=_ref2.apikey,iam_apikey_name=_ref2.iam_apikey_name,iam_apikey_description=_ref2.iam_apikey_description,iam_role_crn=_ref2.iam_role_crn,iam_serviceid_crn=_ref2.iam_serviceid_crn;return this.createService({name:name,description:description,type:"eventstreams",credentials:{api_key:api_key,kafka_admin_url:kafka_admin_url,kafka_brokers_sasl:kafka_brokers_sasl,user:user,password:password,apikey:apikey,iam_apikey_name:iam_apikey_name,iam_apikey_description:iam_apikey_description,iam_role_crn:iam_role_crn,iam_serviceid_crn:iam_serviceid_crn}})}},{key:"getService",value:function getService(serviceId){return this.apiClient.callApi("GET",200,true,["s2s","services",serviceId])["catch"]((function(err){return errors.handleError(err,{CUDSS0019E:errors.ServiceNotFound})}))}},{key:"getServices",value:function getServices(serviceType){return this.apiClient.callApi("GET",200,true,["s2s","services"],null,{bindingMode:"manual",serviceType:serviceType})["catch"]((function(err){return errors.handleError(err,{})}))}},{key:"deleteService",value:function deleteService(serviceId){return this.apiClient.callApi("DELETE",204,false,["s2s","services",serviceId])["catch"]((function(err){return errors.handleError(err,{})}))}},{key:"createConnector",value:function createConnector(_ref3){var name=_ref3.name,type=_ref3.type,_ref3$description=_ref3.description,description=_ref3$description===void 0?undefined:_ref3$description,serviceId=_ref3.serviceId,_ref3$timezone=_ref3.timezone,timezone=_ref3$timezone===void 0?"UTC":_ref3$timezone,_ref3$enabled=_ref3.enabled,enabled=_ref3$enabled===void 0?true:_ref3$enabled;return this.apiClient.callApi("POST",201,true,["historianconnectors"],{name:name,description:description,type:type,serviceId:serviceId,timezone:timezone,enabled:enabled})["catch"]((function(err){return errors.handleError(err,{})}))}},{key:"updateConnector",value:function updateConnector(_ref4){var id=_ref4.id,name=_ref4.name,description=_ref4.description,serviceId=_ref4.serviceId,type=_ref4.type,enabled=_ref4.enabled,timezone=_ref4.timezone;return this.apiClient.callApi("PUT",200,true,["historianconnectors",id],{id:id,name:name,description:description,serviceId:serviceId,type:type,enabled:enabled,timezone:timezone})["catch"]((function(err){return errors.handleError(err,{})}))}},{key:"getConnectors",value:function getConnectors(_ref5){var name=_ref5.name,serviceType=_ref5.serviceType,enabled=_ref5.enabled,serviceId=_ref5.serviceId;return this.apiClient.callApi("GET",200,true,["historianconnectors"],null,{name:name?name:undefined,type:serviceType?serviceType:undefined,enabled:enabled===undefined?undefined:enabled,serviceId:serviceId?serviceId:undefined})["catch"]((function(err){return errors.handleError(err,{})}))}},{key:"deleteConnector",value:function deleteConnector(connectorId){return this.apiClient.callApi("DELETE",204,false,["historianconnectors",connectorId])["catch"]((function(err){return errors.handleError(err,{})}))}},{key:"createDestination",value:function createDestination(connectorId,destination){return this.apiClient.callApi("POST",201,true,["historianconnectors",connectorId,"destinations"],destination)["catch"]((function(err){return errors.handleError(err,{CUDDSC0103E:errors.DestinationAlreadyExists})}))}},{key:"createCloudantDestination",value:function createCloudantDestination(connectorId,_ref6){var name=_ref6.name,bucketInterval=_ref6.bucketInterval;return this.createDestination(connectorId,{name:name,type:"cloudant",configuration:{bucketInterval:bucketInterval}})}},{key:"createEventstreamsDestination",value:function createEventstreamsDestination(connectorId,_ref7){var name=_ref7.name,_ref7$partitions=_ref7.partitions,partitions=_ref7$partitions===void 0?1:_ref7$partitions;return this.createDestination(connectorId,{name:name,type:"eventstreams",configuration:{partitions:partitions}})}},{key:"getDestinations",value:function getDestinations(connectorId){var params=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{name:undefined};var name=params.name;return this.apiClient.callApi("GET",200,true,["historianconnectors",connectorId,"destinations"],null,{name:name?name:undefined})["catch"]((function(err){return errors.handleError(err,{})}))}},{key:"deleteDestination",value:function deleteDestination(connectorId,destinationName){return this.apiClient.callApi("DELETE",[200,204],false,["historianconnectors",connectorId,"destinations",destinationName])["catch"]((function(err){return errors.handleError(err,{})}))}},{key:"createForwardingRule",value:function createForwardingRule(connectorId,forwardingrule){return this.apiClient.callApi("POST",201,true,["historianconnectors",connectorId,"forwardingrules"],forwardingrule)["catch"]((function(err){return errors.handleError(err,{})}))}},{key:"createEventForwardingRule",value:function createEventForwardingRule(connectorId,_ref8){var name=_ref8.name,destinationName=_ref8.destinationName,_ref8$deviceType=_ref8.deviceType,deviceType=_ref8$deviceType===void 0?"*":_ref8$deviceType,_ref8$eventId=_ref8.eventId,eventId=_ref8$eventId===void 0?"*":_ref8$eventId;return this.createForwardingRule(connectorId,{name:name,destinationName:destinationName,type:"event",selector:{deviceType:deviceType,eventId:eventId}})}},{key:"getForwardingRules",value:function getForwardingRules(connectorId){return this.apiClient.callApi("GET",200,true,["historianconnectors",connectorId,"forwardingrules"])["catch"]((function(err){return errors.handleError(err,{})}))}},{key:"deleteForwardingRule",value:function deleteForwardingRule(connectorId,forwardingRuleId){return this.apiClient.callApi("DELETE",204,false,["historianconnectors",connectorId,"forwardingrules",forwardingRuleId])["catch"]((function(err){return errors.handleError(err,{})}))}}]);return DscClient}();exports["default"]=DscClient},{"./ApiErrors":228,loglevel:124}],230:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _loglevel=_interopRequireDefault(require("loglevel"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}var LecClient=function(){function LecClient(apiClient){_classCallCheck(this,LecClient);this.log=_loglevel["default"];this.apiClient=apiClient;this.callApi=this.apiClient.callApi.bind(this.apiClient)}_createClass(LecClient,[{key:"getLastEvents",value:function getLastEvents(type,id){this.log.debug("[ApiClient] getLastEvents() - event cache");return this.callApi("GET",200,true,["device","types",type,"devices",id,"events"],null)}},{key:"getLastEventsByEventType",value:function getLastEventsByEventType(type,id,eventType){this.log.debug("[ApiClient] getLastEventsByEventType() - event cache");return this.callApi("GET",200,true,["device","types",type,"devices",id,"events",eventType],null)}}]);return LecClient}();exports["default"]=LecClient},{loglevel:124}],231:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _loglevel=_interopRequireDefault(require("loglevel"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}var MgmtClient=function(){function MgmtClient(apiClient){_classCallCheck(this,MgmtClient);this.log=_loglevel["default"];this.apiClient=apiClient;this.callApi=this.apiClient.callApi.bind(this.apiClient)}_createClass(MgmtClient,[{key:"getAllDeviceManagementRequests",value:function getAllDeviceManagementRequests(){this.log.debug("[ApiClient] getAllDeviceManagementRequests()");return this.callApi("GET",200,true,["mgmt","requests"],null)}},{key:"initiateDeviceManagementRequest",value:function initiateDeviceManagementRequest(action,parameters,devices){this.log.debug("[ApiClient] initiateDeviceManagementRequest("+action+", "+parameters+", "+devices+")");var body={action:action,parameters:parameters,devices:devices};return this.callApi("POST",202,true,["mgmt","requests"],JSON.stringify(body))}},{key:"getDeviceManagementRequest",value:function getDeviceManagementRequest(requestId){this.log.debug("[ApiClient] getDeviceManagementRequest("+requestId+")");return this.callApi("GET",200,true,["mgmt","requests",requestId],null)}},{key:"deleteDeviceManagementRequest",value:function deleteDeviceManagementRequest(requestId){this.log.debug("[ApiClient] deleteDeviceManagementRequest("+requestId+")");return this.callApi("DELETE",204,false,["mgmt","requests",requestId],null)}},{key:"getDeviceManagementRequestStatus",value:function getDeviceManagementRequestStatus(requestId){this.log.debug("[ApiClient] getDeviceManagementRequestStatus("+requestId+")");return this.callApi("GET",200,true,["mgmt","requests",requestId,"deviceStatus"],null)}},{key:"getDeviceManagementRequestStatusByDevice",value:function getDeviceManagementRequestStatusByDevice(requestId,typeId,deviceId){this.log.debug("[ApiClient] getDeviceManagementRequestStatusByDevice("+requestId+", "+typeId+", "+deviceId+")");return this.callApi("GET",200,true,["mgmt","requests",requestId,"deviceStatus",typeId,deviceId],null)}}]);return MgmtClient}();exports["default"]=MgmtClient},{loglevel:124}],232:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}var RegistryClient=function(){function RegistryClient(apiClient){_classCallCheck(this,RegistryClient);this.apiClient=apiClient}_createClass(RegistryClient,[{key:"listAllDevicesOfType",value:function listAllDevicesOfType(type){this.apiClient.log.debug("[ApiClient] listAllDevicesOfType("+type+")");return this.apiClient.callApi("GET",200,true,["device","types",type,"devices"],null)}},{key:"deleteDeviceType",value:function deleteDeviceType(type){this.apiClient.log.debug("[ApiClient] deleteDeviceType("+type+")");return this.apiClient.callApi("DELETE",204,false,["device","types",type],null)}},{key:"getDeviceType",value:function getDeviceType(type){this.apiClient.log.debug("[ApiClient] getDeviceType("+type+")");return this.apiClient.callApi("GET",200,true,["device","types",type],null)}},{key:"getAllDeviceTypes",value:function getAllDeviceTypes(){this.apiClient.log.debug("[ApiClient] getAllDeviceTypes()");return this.apiClient.callApi("GET",200,true,["device","types"],null)}},{key:"updateDeviceType",value:function updateDeviceType(type,description,deviceInfo,metadata){this.apiClient.log.debug("[ApiClient] updateDeviceType("+type+", "+description+", "+deviceInfo+", "+metadata+")");var body={deviceInfo:deviceInfo,description:description,metadata:metadata};return this.apiClient.callApi("PUT",200,true,["device","types",type],JSON.stringify(body))}},{key:"registerDeviceType",value:function registerDeviceType(typeId,description,deviceInfo,metadata,classId){this.apiClient.log.debug("[ApiClient] registerDeviceType("+typeId+", "+description+", "+deviceInfo+", "+metadata+", "+classId+")");classId=classId||"Device";var body={id:typeId,classId:classId,deviceInfo:deviceInfo,description:description,metadata:metadata};return this.apiClient.callApi("POST",201,true,["device","types"],JSON.stringify(body))}},{key:"registerDevice",value:function registerDevice(type,deviceId,authToken,deviceInfo,location,metadata){this.apiClient.log.debug("[ApiClient] registerDevice("+type+", "+deviceId+", "+deviceInfo+", "+location+", "+metadata+")");var body={deviceId:deviceId,authToken:authToken,deviceInfo:deviceInfo,location:location,metadata:metadata};return this.apiClient.callApi("POST",201,true,["device","types",type,"devices"],JSON.stringify(body))}},{key:"unregisterDevice",value:function unregisterDevice(type,deviceId){this.apiClient.log.debug("[ApiClient] unregisterDevice("+type+", "+deviceId+")");return this.apiClient.callApi("DELETE",204,false,["device","types",type,"devices",deviceId],null)}},{key:"updateDevice",value:function updateDevice(type,deviceId,deviceInfo,status,metadata,extensions){this.apiClient.log.debug("[ApiClient] updateDevice("+type+", "+deviceId+", "+deviceInfo+", "+status+", "+metadata+")");var body={deviceInfo:deviceInfo,status:status,metadata:metadata,extensions:extensions};return this.apiClient.callApi("PUT",200,true,["device","types",type,"devices",deviceId],JSON.stringify(body))}},{key:"getDevice",value:function getDevice(type,deviceId){this.apiClient.log.debug("[ApiClient] getDevice("+type+", "+deviceId+")");return this.apiClient.callApi("GET",200,true,["device","types",type,"devices",deviceId],null)}},{key:"registerMultipleDevices",value:function registerMultipleDevices(arryOfDevicesToBeAdded){this.apiClient.log.debug("[ApiClient] arryOfDevicesToBeAdded() - BULK");return this.apiClient.callApi("POST",201,true,["bulk","devices","add"],JSON.stringify(arryOfDevicesToBeAdded))}},{key:"deleteMultipleDevices",value:function deleteMultipleDevices(arryOfDevicesToBeDeleted){this.apiClient.log.debug("[ApiClient] deleteMultipleDevices() - BULK");return this.apiClient.callApi("POST",201,true,["bulk","devices","remove"],JSON.stringify(arryOfDevicesToBeDeleted))}},{key:"getDeviceLocation",value:function getDeviceLocation(type,deviceId){this.apiClient.log.debug("[ApiClient] getDeviceLocation("+type+", "+deviceId+")");return this.apiClient.callApi("GET",200,true,["device","types",type,"devices",deviceId,"location"],null)}},{key:"updateDeviceLocation",value:function updateDeviceLocation(type,deviceId,location){this.apiClient.log.debug("[ApiClient] updateDeviceLocation("+type+", "+deviceId+", "+location+")");return this.apiClient.callApi("PUT",200,true,["device","types",type,"devices",deviceId,"location"],JSON.stringify(location))}},{key:"getDeviceManagementInformation",value:function getDeviceManagementInformation(type,deviceId){this.apiClient.log.debug("[ApiClient] getDeviceManagementInformation("+type+", "+deviceId+")");return this.apiClient.callApi("GET",200,true,["device","types",type,"devices",deviceId,"mgmt"],null)}},{key:"getAllDiagnosticLogs",value:function getAllDiagnosticLogs(type,deviceId){this.apiClient.log.debug("[ApiClient] getAllDiagnosticLogs("+type+", "+deviceId+")");return this.apiClient.callApi("GET",200,true,["device","types",type,"devices",deviceId,"diag","logs"],null)}},{key:"clearAllDiagnosticLogs",value:function clearAllDiagnosticLogs(type,deviceId){this.apiClient.log.debug("[ApiClient] clearAllDiagnosticLogs("+type+", "+deviceId+")");return this.apiClient.callApi("DELETE",204,false,["device","types",type,"devices",deviceId,"diag","logs"],null)}},{key:"addDeviceDiagLogs",value:function addDeviceDiagLogs(type,deviceId,log){this.apiClient.log.debug("[ApiClient] addDeviceDiagLogs("+type+", "+deviceId+", "+log+")");return this.apiClient.callApi("POST",201,false,["device","types",type,"devices",deviceId,"diag","logs"],JSON.stringify(log))}},{key:"getDiagnosticLog",value:function getDiagnosticLog(type,deviceId,logId){this.apiClient.log.debug("[ApiClient] getAllDiagnosticLogs("+type+", "+deviceId+", "+logId+")");return this.apiClient.callApi("GET",200,true,["device","types",type,"devices",deviceId,"diag","logs",logId],null)}},{key:"deleteDiagnosticLog",value:function deleteDiagnosticLog(type,deviceId,logId){this.apiClient.log.debug("[ApiClient] deleteDiagnosticLog("+type+", "+deviceId+", "+logId+")");return this.apiClient.callApi("DELETE",204,false,["device","types",type,"devices",deviceId,"diag","logs",logId],null)}},{key:"getDeviceErrorCodes",value:function getDeviceErrorCodes(type,deviceId){this.apiClient.log.debug("[ApiClient] getDeviceErrorCodes("+type+", "+deviceId+")");return this.apiClient.callApi("GET",200,true,["device","types",type,"devices",deviceId,"diag","errorCodes"],null)}},{key:"clearDeviceErrorCodes",value:function clearDeviceErrorCodes(type,deviceId){this.apiClient.log.debug("[ApiClient] clearDeviceErrorCodes("+type+", "+deviceId+")");return this.apiClient.callApi("DELETE",204,false,["device","types",type,"devices",deviceId,"diag","errorCodes"],null)}},{key:"addErrorCode",value:function addErrorCode(type,deviceId,log){this.apiClient.log.debug("[ApiClient] addErrorCode("+type+", "+deviceId+", "+log+")");return this.apiClient.callApi("POST",201,false,["device","types",type,"devices",deviceId,"diag","errorCodes"],JSON.stringify(log))}},{key:"getDeviceConnectionLogs",value:function getDeviceConnectionLogs(typeId,deviceId){this.apiClient.log.debug("[ApiClient] getDeviceConnectionLogs("+typeId+", "+deviceId+")");var params={typeId:typeId,deviceId:deviceId};return this.apiClient.callApi("GET",200,true,["logs","connection"],null,params)}}]);return RegistryClient}();exports["default"]=RegistryClient},{}],233:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _loglevel=_interopRequireDefault(require("loglevel"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}var RulesClient=function(){function RulesClient(apiClient){_classCallCheck(this,RulesClient);this.log=_loglevel["default"];this.apiClient=apiClient;this.callApi=this.apiClient.callApi.bind(this.apiClient)}_createClass(RulesClient,[{key:"getRulesForLogicalInterface",value:function getRulesForLogicalInterface(logicalInterfaceId){if(this.draftMode){return this.getRulesForLogicalInterface(logicalInterfaceId)}else{return this.getActiveRulesForLogicalInterface(logicalInterfaceId)}}},{key:"getDraftRulesForLogicalInterface",value:function getDraftRulesForLogicalInterface(logicalInterfaceId){return this.callApi("GET",200,true,["draft","logicalinterfaces",logicalInterfaceId,"rules"])}},{key:"getActiveRulesForLogicalInterface",value:function getActiveRulesForLogicalInterface(logicalInterfaceId){return this.callApi("GET",200,true,["logicalinterfaces",logicalInterfaceId,"rules"])}},{key:"createRule",value:function createRule(logicalInterfaceId,name,condition){var description=arguments.length>3&&arguments[3]!==undefined?arguments[3]:undefined;var notificationStrategy=arguments.length>4&&arguments[4]!==undefined?arguments[4]:RulesClient.RuleNotificationStrategy.EVERY_TIME();var body={name:name,condition:condition,notificationStrategy:notificationStrategy};if(description)body["description"]=description;var base=this.draftMode?["draft","logicalinterfaces",logicalInterfaceId,"rules"]:["logicalinterfaces",logicalInterfaceId,"rules"];return this.callApi("POST",201,true,base,JSON.stringify(body))}},{key:"updateRule",value:function updateRule(rule){var base=this.draftMode?["draft","logicalinterfaces",rule.logicalInterfaceId,"rules",rule.id]:["logicalinterfaces",rule.logicalInterfaceId,"rules",rule.id];return this.callApi("PUT",200,true,base,JSON.stringify(rule))}},{key:"deleteRule",value:function deleteRule(logicalInterfaceId,ruleId){var base=this.draftMode?["draft","logicalinterfaces",logicalInterfaceId,"rules",ruleId]:["logicalinterfaces",logicalInterfaceId,"rules",ruleId];return this.callApi("DELETE",204,false,base)}}]);return RulesClient}();exports["default"]=RulesClient;RulesClient.RuleNotificationStrategy={EVERY_TIME:function EVERY_TIME(){return{when:"every-time"}},BECOMES_TRUE:function BECOMES_TRUE(){return{when:"becomes-true"}},X_IN_Y:function X_IN_Y(count){return{when:"x-in-y",count:count}},PERSISTS:function PERSISTS(count,timePeriod){return{when:"persists",count:count,timePeriod:timePeriod}}}},{loglevel:124}],234:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _loglevel=_interopRequireDefault(require("loglevel"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}var StateClient=function(){function StateClient(apiClient){_classCallCheck(this,StateClient);this.log=_loglevel["default"];this.apiClient=apiClient;this.draftMode=true;this.callApi=this.apiClient.callApi.bind(this.apiClient);this.parseSortSpec=this.apiClient.parseSortSpec.bind(this.apiClient);this.callFormDataApi=this.apiClient.callFormDataApi.bind(this.apiClient);this.invalidOperation=this.apiClient.invalidOperation.bind(this.apiClient)}_createClass(StateClient,[{key:"workWithActive",value:function workWithActive(){this.draftMode=false}},{key:"workWithDraft",value:function workWithDraft(){this.draftMode=true}},{key:"createSchema",value:function createSchema(schemaContents,name,description){var body={schemaFile:schemaContents,schemaType:"json-schema",name:name};if(description){body.description=description}var base=this.draftMode?["draft","schemas"]:["schemas"];return this.callFormDataApi("POST",201,true,base,body,null)}},{key:"getSchema",value:function getSchema(schemaId){var base=this.draftMode?["draft","schemas",schemaId]:["schemas",schemaId];return this.callApi("GET",200,true,base)}},{key:"getActiveSchema",value:function getActiveSchema(schemaId){return this.callApi("GET",200,true,["schemas",schemaId])}},{key:"getSchemas",value:function getSchemas(){var base=this.draftMode?["draft","schemas"]:["schemas"];return this.callApi("GET",200,true,base)}},{key:"getActiveSchemas",value:function getActiveSchemas(){return this.callApi("GET",200,true,["schemas"])}},{key:"updateSchema",value:function updateSchema(schemaId,name,description){var body={id:schemaId,name:name,description:description};var base=this.draftMode?["draft","schemas",schemaId]:["schemas",schemaId];return this.callApi("PUT",200,true,base,body)}},{key:"updateSchemaContent",value:function updateSchemaContent(schemaId,schemaContents,filename){var body={schemaFile:schemaContents,name:filename};var base=this.draftMode?["draft","schemas",schemaId,"content"]:["schemas",schemaId,"content"];return this.callFormDataApi("PUT",204,false,base,body,null)}},{key:"getSchemaContent",value:function getSchemaContent(schemaId){var base=this.draftMode?["draft","schemas",schemaId,"content"]:["schemas",schemaId,"content"];return this.callApi("GET",200,true,base)}},{key:"getActiveSchemaContent",value:function getActiveSchemaContent(schemaId){return this.callApi("GET",200,true,["schemas",schemaId,"content"])}},{key:"deleteSchema",value:function deleteSchema(schemaId){var base=this.draftMode?["draft","schemas",schemaId]:["schemas",schemaId];return this.callApi("DELETE",204,false,base,null)}},{key:"createEventType",value:function createEventType(name,description,schemaId){var body={name:name,description:description,schemaId:schemaId};var base=this.draftMode?["draft","event","types"]:["event","types"];return this.callApi("POST",201,true,base,JSON.stringify(body))}},{key:"getEventType",value:function getEventType(eventTypeId){var base=this.draftMode?["draft","event","types",eventTypeId]:["event","types",eventTypeId];return this.callApi("GET",200,true,base)}},{key:"getActiveEventType",value:function getActiveEventType(eventTypeId){return this.callApi("GET",200,true,["event","types",eventTypeId])}},{key:"deleteEventType",value:function deleteEventType(eventTypeId){var base=this.draftMode?["draft","event","types",eventTypeId]:["event","types",eventTypeId];return this.callApi("DELETE",204,false,base)}},{key:"updateEventType",value:function updateEventType(eventTypeId,name,description,schemaId){var body={id:eventTypeId,name:name,description:description,schemaId:schemaId};var base=this.draftMode?["draft","event","types",eventTypeId]:["event","types",eventTypeId];return this.callApi("PUT",200,true,base,body)}},{key:"getEventTypes",value:function getEventTypes(){var base=this.draftMode?["draft","event","types"]:["event","types"];return this.callApi("GET",200,true,base)}},{key:"getActiveEventTypes",value:function getActiveEventTypes(){return this.callApi("GET",200,true,["event","types"])}},{key:"createPhysicalInterface",value:function createPhysicalInterface(name,description){var body={name:name,description:description};var base=this.draftMode?["draft","physicalinterfaces"]:["physicalinterfaces"];return this.callApi("POST",201,true,base,body)}},{key:"getPhysicalInterface",value:function getPhysicalInterface(physicalInterfaceId){var base=this.draftMode?["draft","physicalinterfaces",physicalInterfaceId]:["physicalinterfaces",physicalInterfaceId];return this.callApi("GET",200,true,base)}},{key:"getActivePhysicalInterface",value:function getActivePhysicalInterface(physicalInterfaceId){return this.callApi("GET",200,true,["physicalinterfaces",physicalInterfaceId])}},{key:"deletePhysicalInterface",value:function deletePhysicalInterface(physicalInterfaceId){var base=this.draftMode?["draft","physicalinterfaces",physicalInterfaceId]:["physicalinterfaces",physicalInterfaceId];return this.callApi("DELETE",204,false,base)}},{key:"updatePhysicalInterface",value:function updatePhysicalInterface(physicalInterfaceId,name,description){var body={id:physicalInterfaceId,name:name,description:description};var base=this.draftMode?["draft","physicalinterfaces",physicalInterfaceId]:["physicalinterfaces",physicalInterfaceId];return this.callApi("PUT",200,true,base,body)}},{key:"getPhysicalInterfaces",value:function getPhysicalInterfaces(){var base=this.draftMode?["draft","physicalinterfaces"]:["physicalinterfaces"];return this.callApi("GET",200,true,base)}},{key:"getActivePhysicalInterfaces",value:function getActivePhysicalInterfaces(){return this.callApi("GET",200,true,["physicalinterfaces"])}},{key:"createPhysicalInterfaceEventMapping",value:function createPhysicalInterfaceEventMapping(physicalInterfaceId,eventId,eventTypeId){var body={eventId:eventId,eventTypeId:eventTypeId};var base=this.draftMode?["draft","physicalinterfaces",physicalInterfaceId,"events"]:["physicalinterfaces",physicalInterfaceId,"events"];return this.callApi("POST",201,true,base,body)}},{key:"getPhysicalInterfaceEventMappings",value:function getPhysicalInterfaceEventMappings(physicalInterfaceId){var base=this.draftMode?["draft","physicalinterfaces",physicalInterfaceId,"events"]:["physicalinterfaces",physicalInterfaceId,"events"];return this.callApi("GET",200,true,base)}},{key:"getActivePhysicalInterfaceEventMappings",value:function getActivePhysicalInterfaceEventMappings(physicalInterfaceId){return this.callApi("GET",200,true,["physicalinterfaces",physicalInterfaceId,"events"])}},{key:"deletePhysicalInterfaceEventMapping",value:function deletePhysicalInterfaceEventMapping(physicalInterfaceId,eventId){var base=this.draftMode?["draft","physicalinterfaces",physicalInterfaceId,"events",eventId]:["physicalinterfaces",physicalInterfaceId,"events",eventId];return this.callApi("DELETE",204,false,base)}},{key:"createLogicalInterface",value:function createLogicalInterface(name,description,schemaId,alias){var body={name:name,description:description,schemaId:schemaId};if(alias!==undefined){body.alias=alias}var base=this.draftMode?["draft","logicalinterfaces"]:["applicationinterfaces"];return this.callApi("POST",201,true,base,body)}},{key:"getLogicalInterface",value:function getLogicalInterface(logicalInterfaceId){var base=this.draftMode?["draft","logicalinterfaces",logicalInterfaceId]:["applicationinterfaces",logicalInterfaceId];return this.callApi("GET",200,true,base)}},{key:"getActiveLogicalInterface",value:function getActiveLogicalInterface(logicalInterfaceId){return this.callApi("GET",200,true,["logicalinterfaces",logicalInterfaceId])}},{key:"deleteLogicalInterface",value:function deleteLogicalInterface(logicalInterfaceId){var base=this.draftMode?["draft","logicalinterfaces",logicalInterfaceId]:["applicationinterfaces",logicalInterfaceId];return this.callApi("DELETE",204,false,base)}},{key:"updateLogicalInterface",value:function updateLogicalInterface(logicalInterfaceId,name,description,schemaId,alias){var body={id:logicalInterfaceId,name:name,description:description,schemaId:schemaId};if(alias!==undefined){body.alias=alias}var base=this.draftMode?["draft","logicalinterfaces",logicalInterfaceId]:["applicationinterfaces",logicalInterfaceId];return this.callApi("PUT",200,true,base,body)}},{key:"getLogicalInterfaces",value:function getLogicalInterfaces(bookmark,limit,sort,name){var base=this.draftMode?["draft","logicalinterfaces"]:["logicalinterfaces"];var _sort=this.parseSortSpec(sort);return this.callApi("GET",200,true,base,undefined,{_bookmark:bookmark,_limit:limit,_sort:_sort,name:name?name:undefined})}},{key:"getActiveLogicalInterfaces",value:function getActiveLogicalInterfaces(){return this.callApi("GET",200,true,["logicalinterfaces"])}},{key:"patchOperationLogicalInterface",value:function patchOperationLogicalInterface(logicalInterfaceId,operationId){var body={operation:operationId};if(this.draftMode){switch(operationId){case"validate-configuration":return this.callApi("PATCH",200,true,["draft","logicalinterfaces",logicalInterfaceId],body);case"activate-configuration":return this.callApi("PATCH",202,true,["draft","logicalinterfaces",logicalInterfaceId],body);case"deactivate-configuration":return this.callApi("PATCH",202,true,["draft","logicalinterfaces",logicalInterfaceId],body);case"list-differences":return this.callApi("PATCH",200,true,["draft","logicalinterfaces",logicalInterfaceId],body);default:return this.callApi("PATCH",200,true,["draft","logicalinterfaces",logicalInterfaceId],body)}}else{return this.invalidOperation("PATCH operation not allowed on active logical interface")}}},{key:"patchOperationActiveLogicalInterface",value:function patchOperationActiveLogicalInterface(logicalInterfaceId,operationId){var body={operation:operationId};if(this.draftMode){return this.callApi("PATCH",202,true,["logicalinterfaces",logicalInterfaceId],body)}else{return this.invalidOperation("PATCH operation 'deactivate-configuration' not allowed on logical interface")}}},{key:"patchOperationDeviceType",value:function patchOperationDeviceType(deviceTypeId,operationId){var body={operation:operationId};if(this.draftMode){switch(operationId){case"validate-configuration":return this.callApi("PATCH",200,true,["draft","device","types",deviceTypeId],body);case"activate-configuration":return this.callApi("PATCH",202,true,["draft","device","types",deviceTypeId],body);case"deactivate-configuration":return this.callApi("PATCH",202,true,["draft","device","types",deviceTypeId],body);case"list-differences":return this.callApi("PATCH",200,true,["draft","device","types",deviceTypeId],body);default:return this.callApi("PATCH",200,true,["draft","device","types",deviceTypeId],body)}}else{return this.invalidOperation("this method cannot be called when draftMode=false")}}},{key:"createDeviceType",value:function createDeviceType(typeId,description,deviceInfo,metadata,classId,physicalInterfaceId){this.log.debug("[ApiClient] registerDeviceType("+typeId+", "+description+", "+deviceInfo+", "+metadata+", "+classId+", "+physicalInterfaceId+")");classId=classId||"Device";var body={id:typeId,classId:classId,deviceInfo:deviceInfo,description:description,metadata:metadata,physicalInterfaceId:physicalInterfaceId};return this.callApi("POST",201,true,["device","types"],JSON.stringify(body))}},{key:"getDeviceTypesByLogicalInterfaceId",value:function getDeviceTypesByLogicalInterfaceId(logicalInterfaceId){var bookmark=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var limit=arguments.length>2&&arguments[2]!==undefined?arguments[2]:10;if(this.draftMode){return this.callApi("GET",200,true,["draft","device","types"],null,{logicalInterfaceId:logicalInterfaceId,_bookmark:bookmark,_limit:limit})}else{return this.callApi("GET",200,true,["device","types"],null,{_bookmark:bookmark,_limit:limit})}}},{key:"createDeviceTypePhysicalInterfaceAssociation",value:function createDeviceTypePhysicalInterfaceAssociation(typeId,physicalInterfaceId){var body={id:physicalInterfaceId};if(this.draftMode){return this.callApi("POST",201,true,["draft","device","types",typeId,"physicalinterface"],JSON.stringify(body))}else{return this.callApi("PUT",200,true,["device","types",typeId],JSON.stringify({physicalInterfaceId:physicalInterfaceId}))}}},{key:"getDeviceTypePhysicalInterfaces",value:function getDeviceTypePhysicalInterfaces(typeId){if(this.draftMode){return this.callApi("GET",200,true,["draft","device","types",typeId,"physicalinterface"])}else{return this.invalidOperation("GET Device type's physical interface is not allowed")}}},{key:"getActiveDeviceTypePhysicalInterfaces",value:function getActiveDeviceTypePhysicalInterfaces(typeId){return this.callApi("GET",200,true,["device","types",typeId,"physicalinterface"])}},{key:"deleteDeviceTypePhysicalInterfaceAssociation",value:function deleteDeviceTypePhysicalInterfaceAssociation(typeId){if(this.draftMode){return this.callApi("DELETE",204,false,["draft","device","types",typeId,"physicalinterface"])}else{return this.invalidOperation("DELETE Device type's physical interface is not allowed")}}},{key:"createDeviceTypeLogicalInterfaceAssociation",value:function createDeviceTypeLogicalInterfaceAssociation(typeId,logicalInterfaceId){var body={id:logicalInterfaceId};var base=this.draftMode?["draft","device","types",typeId,"logicalinterfaces"]:["device","types",typeId,"applicationinterfaces"];return this.callApi("POST",201,true,base,body)}},{key:"getDeviceTypeLogicalInterfaces",value:function getDeviceTypeLogicalInterfaces(typeId){var base=this.draftMode?["draft","device","types",typeId,"logicalinterfaces"]:["device","types",typeId,"applicationinterfaces"];return this.callApi("GET",200,true,base)}},{key:"getActiveDeviceTypeLogicalInterfaces",value:function getActiveDeviceTypeLogicalInterfaces(typeId){return this.callApi("GET",200,true,["device","types",typeId,"logicalinterfaces"])}},{key:"createDeviceTypeLogicalInterfacePropertyMappings",value:function createDeviceTypeLogicalInterfacePropertyMappings(typeId,logicalInterfaceId,mappings,notificationStrategy){var body=null,base=null;if(this.draftMode){body={logicalInterfaceId:logicalInterfaceId,propertyMappings:mappings,notificationStrategy:"never"};if(notificationStrategy){body.notificationStrategy=notificationStrategy}base=["draft","device","types",typeId,"mappings"]}else{body={applicationInterfaceId:logicalInterfaceId,propertyMappings:mappings};base=["device","types",typeId,"mappings"]}return this.callApi("POST",201,true,base,body)}},{key:"getDeviceTypePropertyMappings",value:function getDeviceTypePropertyMappings(typeId){var base=this.draftMode?["draft","device","types",typeId,"mappings"]:["device","types",typeId,"mappings"];return this.callApi("GET",200,true,base)}},{key:"getActiveDeviceTypePropertyMappings",value:function getActiveDeviceTypePropertyMappings(typeId){return this.callApi("GET",200,true,["device","types",typeId,"mappings"])}},{key:"getDeviceTypeLogicalInterfacePropertyMappings",value:function getDeviceTypeLogicalInterfacePropertyMappings(typeId,logicalInterfaceId){var base=this.draftMode?["draft","device","types",typeId,"mappings",logicalInterfaceId]:["device","types",typeId,"mappings",logicalInterfaceId];return this.callApi("GET",200,true,base)}},{key:"getActiveDeviceTypeLogicalInterfacePropertyMappings",value:function getActiveDeviceTypeLogicalInterfacePropertyMappings(typeId,logicalInterfaceId){return this.callApi("GET",200,true,["device","types",typeId,"mappings",logicalInterfaceId])}},{key:"updateDeviceTypeLogicalInterfacePropertyMappings",value:function updateDeviceTypeLogicalInterfacePropertyMappings(typeId,logicalInterfaceId,mappings,notificationStrategy){var body=null,base=null;if(this.draftMode){body={logicalInterfaceId:logicalInterfaceId,propertyMappings:mappings,notificationStrategy:"never"};if(notificationStrategy){body.notificationStrategy=notificationStrategy}base=["draft","device","types",typeId,"mappings",logicalInterfaceId]}else{body={applicationInterfaceId:logicalInterfaceId,propertyMappings:mappings};base=["device","types",typeId,"mappings",logicalInterfaceId]}return this.callApi("PUT",200,false,base,body)}},{key:"deleteDeviceTypeLogicalInterfacePropertyMappings",value:function deleteDeviceTypeLogicalInterfacePropertyMappings(typeId,logicalInterfaceId){var base=this.draftMode?["draft","device","types",typeId,"mappings",logicalInterfaceId]:["device","types",typeId,"mappings",logicalInterfaceId];return this.callApi("DELETE",204,false,base)}},{key:"deleteDeviceTypeLogicalInterfaceAssociation",value:function deleteDeviceTypeLogicalInterfaceAssociation(typeId,logicalInterfaceId){var base=this.draftMode?["draft","device","types",typeId,"logicalinterfaces",logicalInterfaceId]:["device","types",typeId,"applicationinterfaces",logicalInterfaceId];return this.callApi("DELETE",204,false,base)}},{key:"patchOperationDeviceType",value:function patchOperationDeviceType(typeId,operationId){if(!operationId){return invalidOperation("PATCH operation is not allowed. Operation id is expected")}var body={operation:operationId};var base=this.draftMode?["draft","device","types",typeId]:["device","types",typeId];if(this.draftMode){switch(operationId){case"validate-configuration":return this.callApi("PATCH",200,true,base,body);break;case"activate-configuration":return this.callApi("PATCH",202,true,base,body);break;case"deactivate-configuration":return this.callApi("PATCH",202,true,base,body);break;case"list-differences":return this.callApi("PATCH",200,true,base,body);break;default:return this.invalidOperation("PATCH operation is not allowed. Invalid operation id")}}else{switch(operationId){case"validate-configuration":return this.callApi("PATCH",200,true,base,body);break;case"deploy-configuration":return this.callApi("PATCH",202,true,base,body);break;case"remove-deployed-configuration":return this.callApi("PATCH",202,true,base,body);break;case"list-differences":return this.invalidOperation("PATCH operation 'list-differences' is not allowed");break;default:return this.invalidOperation("PATCH operation is not allowed. Invalid operation id")}}}},{key:"patchOperationActiveDeviceType",value:function patchOperationActiveDeviceType(typeId,operationId){var body={operation:operationId};if(this.draftMode){return this.callApi("PATCH",202,true,["device","types",typeId],body)}else{return this.invalidOperation("PATCH operation 'deactivate-configuration' is not allowed")}}},{key:"getDeviceTypeDeployedConfiguration",value:function getDeviceTypeDeployedConfiguration(typeId){if(this.draftMode){return this.invalidOperation("GET deployed configuration is not allowed")}else{return this.callApi("GET",200,true,["device","types",typeId,"deployedconfiguration"])}}},{key:"getDeviceState",value:function getDeviceState(typeId,deviceId,logicalInterfaceId){return this.callApi("GET",200,true,["device","types",typeId,"devices",deviceId,"state",logicalInterfaceId])}},{key:"createSchemaAndEventType",value:function createSchemaAndEventType(schemaContents,schemaFileName,eventTypeName,eventDescription){var _this=this;var body={schemaFile:schemaContents,schemaType:"json-schema",name:schemaFileName};var createSchema=new Promise((function(resolve,reject){var base=_this.draftMode?["draft","schemas"]:["schemas"];_this.callFormDataApi("POST",201,true,base,body,null).then((function(result){resolve(result)}),(function(error){reject(error)}))}));return createSchema.then((function(value){var schemaId=value["id"];return _this.createEventType(eventTypeName,eventDescription,schemaId)}))}},{key:"createSchemaAndLogicalInterface",value:function createSchemaAndLogicalInterface(schemaContents,schemaFileName,appInterfaceName,appInterfaceDescription,appInterfaceAlias){var _this2=this;var body={schemaFile:schemaContents,schemaType:"json-schema",name:schemaFileName};var createSchema=new Promise((function(resolve,reject){var base=_this2.draftMode?["draft","schemas"]:["schemas"];_this2.callFormDataApi("POST",201,true,base,body,null).then((function(result){resolve(result)}),(function(error){reject(error)}))}));return createSchema.then((function(value){var schemaId=value.id;return _this2.createLogicalInterface(appInterfaceName,appInterfaceDescription,schemaId,appInterfaceAlias)}))}},{key:"createPhysicalInterfaceWithEventMapping",value:function createPhysicalInterfaceWithEventMapping(physicalInterfaceName,description,eventId,eventTypeId){var _this3=this;var createPhysicalInterface=new Promise((function(resolve,reject){_this3.createPhysicalInterface(physicalInterfaceName,description).then((function(result){resolve(result)}),(function(error){reject(error)}))}));return createPhysicalInterface.then((function(value){var physicalInterface=value;var PhysicalInterfaceEventMapping=new Promise((function(resolve,reject){_this3.createPhysicalInterfaceEventMapping(physicalInterface.id,eventId,eventTypeId).then((function(result){resolve([physicalInterface,result])}),(function(error){reject(error)}))}));return PhysicalInterfaceEventMapping.then((function(result){return result}))}))}},{key:"createDeviceTypeLogicalInterfaceEventMapping",value:function createDeviceTypeLogicalInterfaceEventMapping(deviceTypeName,description,logicalInterfaceId,eventMapping,notificationStrategy){var _this4=this;var createDeviceType=new Promise((function(resolve,reject){_this4.createDeviceType(deviceTypeName,description).then((function(result){resolve(result)}),(function(error){reject(error)}))}));return createDeviceType.then((function(result){var deviceObject=result;var deviceTypeLogicalInterface=null;var deviceTypeLogicalInterface=new Promise((function(resolve,reject){_this4.createDeviceTypeLogicalInterfaceAssociation(deviceObject.id,logicalInterfaceId).then((function(result){resolve(result)}),(function(error){reject(error)}))}));return deviceTypeLogicalInterface.then((function(result){deviceTypeLogicalInterface=result;var deviceTypeLogicalInterfacePropertyMappings=new Promise((function(resolve,reject){var notificationstrategy="never";if(notificationStrategy){notificationstrategy=notificationStrategy}_this4.createDeviceTypeLogicalInterfacePropertyMappings(deviceObject.id,logicalInterfaceId,eventMapping,notificationstrategy).then((function(result){var arr=[deviceObject,deviceTypeLogicalInterface,result];resolve(arr)}),(function(error){reject(error)}))}));return deviceTypeLogicalInterfacePropertyMappings.then((function(result){return result}))}))}))}}]);return StateClient}();exports["default"]=StateClient},{loglevel:124}],235:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _util=require("../util");var _BaseClient2=_interopRequireDefault(require("../BaseClient"));var _ApiClient=_interopRequireDefault(require("../api/ApiClient"));var _RegistryClient=_interopRequireDefault(require("../api/RegistryClient"));var _MgmtClient=_interopRequireDefault(require("../api/MgmtClient"));var _LecClient=_interopRequireDefault(require("../api/LecClient"));var _DscClient=_interopRequireDefault(require("../api/DscClient"));var _RulesClient=_interopRequireDefault(require("../api/RulesClient"));var _StateClient=_interopRequireDefault(require("../api/StateClient"));var _ApplicationConfig=_interopRequireDefault(require("./ApplicationConfig"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}function _get(target,property,receiver){if(typeof Reflect!=="undefined"&&Reflect.get){_get=Reflect.get}else{_get=function _get(target,property,receiver){var base=_superPropBase(target,property);if(!base)return;var desc=Object.getOwnPropertyDescriptor(base,property);if(desc.get){return desc.get.call(receiver)}return desc.value}}return _get(target,property,receiver||target)}function _superPropBase(object,property){while(!Object.prototype.hasOwnProperty.call(object,property)){object=_getPrototypeOf(object);if(object===null)break}return object}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function")}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:true,configurable:true}});if(superClass)_setPrototypeOf(subClass,superClass)}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o};return _setPrototypeOf(o,p)}function _createSuper(Derived){var hasNativeReflectConstruct=_isNativeReflectConstruct();return function _createSuperInternal(){var Super=_getPrototypeOf(Derived),result;if(hasNativeReflectConstruct){var NewTarget=_getPrototypeOf(this).constructor;result=Reflect.construct(Super,arguments,NewTarget)}else{result=Super.apply(this,arguments)}return _possibleConstructorReturn(this,result)}}function _possibleConstructorReturn(self,call){if(call&&(_typeof(call)==="object"||typeof call==="function")){return call}return _assertThisInitialized(self)}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return self}function _isNativeReflectConstruct(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{Date.prototype.toString.call(Reflect.construct(Date,[],(function(){})));return true}catch(e){return false}}function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o)};return _getPrototypeOf(o)}var DEVICE_EVT_RE=/^iot-2\/type\/(.+)\/id\/(.+)\/evt\/(.+)\/fmt\/(.+)$/;var DEVICE_CMD_RE=/^iot-2\/type\/(.+)\/id\/(.+)\/cmd\/(.+)\/fmt\/(.+)$/;var DEVICE_STATE_RE=/^iot-2\/type\/(.+)\/id\/(.+)\/intf\/(.+)\/evt\/state$/;var DEVICE_STATE_ERROR_RE=/^iot-2\/type\/(.+)\/id\/(.+)\/err\/data$/;var RULE_TRIGGER_RE=/^iot-2\/intf\/(.+)\/rule\/(.+)\/evt\/trigger$/;var RULE_ERROR_RE=/^iot-2\/intf\/(.+)\/rule\/(.+)\/err\/data$/;var DEVICE_MON_RE=/^iot-2\/type\/(.+)\/id\/(.+)\/mon$/;var APP_MON_RE=/^iot-2\/app\/(.+)\/mon$/;var ApplicationClient=function(_BaseClient){_inherits(ApplicationClient,_BaseClient);var _super=_createSuper(ApplicationClient);function ApplicationClient(config){var _this;_classCallCheck(this,ApplicationClient);if(!config instanceof _ApplicationConfig["default"]){throw new Error("Config must be an instance of ApplicationConfig")}_this=_super.call(this,config);_this.useLtpa=config.auth&&config.auth.useLtpa;if(config.auth&&config.auth.useLtpa||config.getOrgId()!="quickstart"){_this._apiClient=new _ApiClient["default"](_this.config);_this.dsc=new _DscClient["default"](_this._apiClient);_this.lec=new _LecClient["default"](_this._apiClient);_this.mgmt=new _MgmtClient["default"](_this._apiClient);_this.registry=new _RegistryClient["default"](_this._apiClient);_this.rules=new _RulesClient["default"](_this._apiClient);_this.state=new _StateClient["default"](_this._apiClient)}_this.log.debug("[ApplicationClient:constructor] ApplicationClient initialized for organization : "+config.getOrgId());return _this}_createClass(ApplicationClient,[{key:"connect",value:function connect(){var _this2=this;_get(_getPrototypeOf(ApplicationClient.prototype),"connect",this).call(this);this.mqtt.on("message",(function(topic,payload){_this2.log.trace("[ApplicationClient:onMessage] mqtt: ",topic,payload.toString());var match=DEVICE_EVT_RE.exec(topic);if(match){_this2.emit("deviceEvent",match[1],match[2],match[3],match[4],payload,topic);return}var match=DEVICE_CMD_RE.exec(topic);if(match){_this2.emit("deviceCommand",match[1],match[2],match[3],match[4],payload,topic);return}var match=DEVICE_STATE_RE.exec(topic);if(match){_this2.emit("deviceState",match[1],match[2],match[3],payload,topic);return}var match=DEVICE_STATE_ERROR_RE.exec(topic);if(match){_this2.emit("deviceStateError",match[1],match[2],payload,topic);return}var match=RULE_TRIGGER_RE.exec(topic);if(match){_this2.emit("ruleTrigger",match[1],match[2],payload,topic);return}var match=RULE_ERROR_RE.exec(topic);if(match){_this2.emit("ruleError",match[1],match[2],payload,topic);return}var match=DEVICE_MON_RE.exec(topic);if(match){_this2.emit("deviceStatus",match[1],match[2],payload,topic);return}var match=APP_MON_RE.exec(topic);if(match){_this2.emit("appStatus",match[1],payload,topic);return}_this2.log.warn("[ApplicationClient:onMessage] Message received on unexpected topic"+", "+topic+", "+payload)}))}},{key:"publishEvent",value:function publishEvent(typeId,deviceId,eventId,format,data,qos,callback){qos=qos||0;if(!(0,_util.isDefined)(typeId)||!(0,_util.isDefined)(deviceId)||!(0,_util.isDefined)(eventId)||!(0,_util.isDefined)(format)){this.log.error("[ApplicationClient:publishDeviceEvent] Required params for publishDeviceEvent not present");this.emit("error","[ApplicationClient:publishDeviceEvent] Required params for publishDeviceEvent not present");return}var topic="iot-2/type/"+typeId+"/id/"+deviceId+"/evt/"+eventId+"/fmt/"+format;this._publish(topic,data,qos,callback);return this}},{key:"subscribeToEvents",value:function subscribeToEvents(typeId,deviceId,eventId,format,qos,callback){typeId=typeId||"+";deviceId=deviceId||"+";eventId=eventId||"+";format=format||"+";qos=qos||0;var topic="iot-2/type/"+typeId+"/id/"+deviceId+"/evt/"+eventId+"/fmt/"+format;this._subscribe(topic,qos,callback);return this}},{key:"unsubscribeFromEvents",value:function unsubscribeFromEvents(typeId,deviceId,eventId,format,callback){typeId=typeId||"+";deviceId=deviceId||"+";eventId=eventId||"+";format=format||"+";var topic="iot-2/type/"+typeId+"/id/"+deviceId+"/evt/"+eventId+"/fmt/"+format;this._unsubscribe(topic,callback);return this}},{key:"publishCommand",value:function publishCommand(typeId,deviceId,commandId,format,data,qos,callback){qos=qos||0;if(!(0,_util.isDefined)(typeId)||!(0,_util.isDefined)(deviceId)||!(0,_util.isDefined)(commandId)||!(0,_util.isDefined)(format)){this.log.error("[ApplicationClient:publishDeviceCommand] Required params for publishDeviceCommand not present");this.emit("error","[ApplicationClient:publishDeviceCommand] Required params for publishDeviceCommand not present");return}var topic="iot-2/type/"+typeId+"/id/"+deviceId+"/cmd/"+commandId+"/fmt/"+format;this._publish(topic,data,qos,callback);return this}},{key:"subscribeToCommands",value:function subscribeToCommands(typeId,deviceId,commandId,format,qos,callback){typeId=typeId||"+";deviceId=deviceId||"+";commandId=commandId||"+";format=format||"+";qos=qos||0;var topic="iot-2/type/"+typeId+"/id/"+deviceId+"/cmd/"+commandId+"/fmt/"+format;this.log.debug("[ApplicationClient:subscribeToDeviceCommands] Calling subscribe with QoS "+qos);this._subscribe(topic,qos,callback);return this}},{key:"unsubscribeFromCommands",value:function unsubscribeFromCommands(typeId,deviceId,commandId,format,callback){typeId=typeId||"+";deviceId=deviceId||"+";commandId=commandId||"+";format=format||"+";var topic="iot-2/type/"+typeId+"/id/"+deviceId+"/cmd/"+commandId+"/fmt/"+format;this._unsubscribe(topic,callback);return this}},{key:"subscribeToDeviceState",value:function subscribeToDeviceState(type,id,interfaceId,qos){type=type||"+";id=id||"+";interfaceId=interfaceId||"+";qos=qos||0;var topic="iot-2/type/"+type+"/id/"+id+"/intf/"+interfaceId+"/evt/state";this.log.debug("[ApplicationClient:subscribeToDeviceState] Calling subscribe with QoS "+qos);this._subscribe(topic,qos);return this}},{key:"unsubscribeToDeviceState",value:function unsubscribeToDeviceState(type,id,interfaceId){type=type||"+";id=id||"+";interfaceId=interfaceId||"+";var topic="iot-2/type/"+type+"/id/"+id+"/intf/"+interfaceId+"/evt/state";this._unsubscribe(topic);return this}},{key:"subscribeToDeviceErrors",value:function subscribeToDeviceErrors(type,id,qos){type=type||"+";id=id||"+";qos=qos||0;var topic="iot-2/type/"+type+"/id/"+id+"/err/data";this.log.debug("[ApplicationClient:subscribeToDeviceErrors] Calling subscribe with QoS "+qos);this._subscribe(topic,qos);return this}},{key:"unsubscribeToDeviceErrors",value:function unsubscribeToDeviceErrors(type,id){type=type||"+";id=id||"+";var topic="iot-2/type/"+type+"/id/"+id+"/err/data";this._unsubscribe(topic);return this}},{key:"subscribeToRuleTriggers",value:function subscribeToRuleTriggers(interfaceId,ruleId,qos){interfaceId=interfaceId||"+";ruleId=ruleId||"+";qos=qos||0;var topic="iot-2/intf/"+interfaceId+"/rule/"+ruleId+"/evt/trigger";this.log.debug("[ApplicationClient:subscribeToRuleTriggers] Calling subscribe with QoS "+qos);this._subscribe(topic,qos);return this}},{key:"unsubscribeToRuleTriggers",value:function unsubscribeToRuleTriggers(interfaceId,ruleId){interfaceId=interfaceId||"+";ruleId=ruleId||"+";var topic="iot-2/intf/"+interfaceId+"/rule/"+ruleId+"/evt/trigger";this._unsubscribe(topic);return this}},{key:"subscribeToRuleErrors",value:function subscribeToRuleErrors(interfaceId,ruleId,qos){interfaceId=interfaceId||"+";ruleId=ruleId||"+";qos=qos||0;var topic="iot-2/intf/"+interfaceId+"/rule/"+ruleId+"/err/data";this.log.debug("[ApplicationClient:subscribeToRuleErrors] Calling subscribe with QoS "+qos);this._subscribe(topic,qos);return this}},{key:"unsubscribeToRuleErrors",value:function unsubscribeToRuleErrors(interfaceId,ruleId){interfaceId=interfaceId||"+";ruleId=ruleId||"+";var topic="iot-2/intf/"+interfaceId+"/rule/"+ruleId+"/err/data";this._unsubscribe(topic);return this}},{key:"subscribeToDeviceStatus",value:function subscribeToDeviceStatus(type,id,qos){type=type||"+";id=id||"+";qos=qos||0;var topic="iot-2/type/"+type+"/id/"+id+"/mon";this.log.debug("[ApplicationClient:subscribeToDeviceStatus] Calling subscribe with QoS "+qos);this._subscribe(topic,qos);return this}},{key:"unsubscribeToDeviceStatus",value:function unsubscribeToDeviceStatus(type,id){type=type||"+";id=id||"+";var topic="iot-2/type/"+type+"/id/"+id+"/mon";this._unsubscribe(topic);return this}},{key:"subscribeToAppStatus",value:function subscribeToAppStatus(id,qos){id=id||"+";qos=qos||0;var topic="iot-2/app/"+id+"/mon";this.log.debug("[ApplicationClient:subscribeToAppStatus] Calling subscribe with QoS "+qos);this._subscribe(topic,qos);return this}},{key:"unsubscribeToAppStatus",value:function unsubscribeToAppStatus(id){id=id||"+";var topic="iot-2/app/"+id+"/mon";this._unsubscribe(topic);return this}}]);return ApplicationClient}(_BaseClient2["default"]);exports["default"]=ApplicationClient},{"../BaseClient":225,"../api/ApiClient":227,"../api/DscClient":229,"../api/LecClient":230,"../api/MgmtClient":231,"../api/RegistryClient":232,"../api/RulesClient":233,"../api/StateClient":234,"../util":241,"./ApplicationConfig":236}],236:[function(require,module,exports){(function(process){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _BaseConfig2=_interopRequireDefault(require("../BaseConfig"));var _loglevel=_interopRequireDefault(require("loglevel"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function")}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:true,configurable:true}});if(superClass)_setPrototypeOf(subClass,superClass)}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o};return _setPrototypeOf(o,p)}function _createSuper(Derived){var hasNativeReflectConstruct=_isNativeReflectConstruct();return function _createSuperInternal(){var Super=_getPrototypeOf(Derived),result;if(hasNativeReflectConstruct){var NewTarget=_getPrototypeOf(this).constructor;result=Reflect.construct(Super,arguments,NewTarget)}else{result=Super.apply(this,arguments)}return _possibleConstructorReturn(this,result)}}function _possibleConstructorReturn(self,call){if(call&&(_typeof(call)==="object"||typeof call==="function")){return call}return _assertThisInitialized(self)}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return self}function _isNativeReflectConstruct(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{Date.prototype.toString.call(Reflect.construct(Date,[],(function(){})));return true}catch(e){return false}}function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o)};return _getPrototypeOf(o)}var YAML=require("yaml");var fs=require("fs");var uuidv4=require("uuid/v4");var ApplicationConfig=function(_BaseConfig){_inherits(ApplicationConfig,_BaseConfig);var _super=_createSuper(ApplicationConfig);function ApplicationConfig(identity,auth,options){var _this;_classCallCheck(this,ApplicationConfig);_this=_super.call(this,identity,auth,options);if(_this.auth!=null&&!_this.auth.useLtpa){if(!("key"in _this.auth)||_this.auth.key==null){throw new Error("Missing auth.key from configuration")}if(!("token"in _this.auth)||_this.auth.token==null){throw new Error("Missing auth.token from configuration")}}if(_this.identity==null){_this.identity={}}if(!("appId"in _this.identity)){_this.identity.appId=uuidv4()}if(!("sharedSubscription"in _this.options.mqtt)){_this.options.mqtt.sharedSubscription=false}return _this}_createClass(ApplicationConfig,[{key:"getOrgId",value:function getOrgId(){if(this.auth==null){return"quickstart"}else if(this.auth.key){return this.auth.key.split("-")[1]}else{return null}}},{key:"getApiRoot",value:function getApiRoot(){return this.options.apiRoot||"api/v0002"}},{key:"getApiBaseUri",value:function getApiBaseUri(){return this.auth&&this.auth.useLtpa?"/".concat(this.getApiRoot()):"https://".concat(this.getOrgId(),".").concat(this.options.domain,"/").concat(this.getApiRoot())}},{key:"getClientId",value:function getClientId(){var clientIdPrefix="a";if(this.options.mqtt.sharedSubscription==true){clientIdPrefix="A"}return clientIdPrefix+":"+this.getOrgId()+":"+this.identity.appId}},{key:"getMqttUsername",value:function getMqttUsername(){return this.auth.key}},{key:"getMqttPassword",value:function getMqttPassword(){return this.auth.token}},{key:"getAdditionalHeaders",value:function getAdditionalHeaders(){return this.options&&this.options.http?this.options.http.additionalHeaders:[]}},{key:"setAdditionalHeader",value:function setAdditionalHeader(key,value){if(!this.options.http)this.options.http={};if(!this.options.http.additionalHeaders)this.options.http.additionalHeaders={};this.options.http.additionalHeaders[key]=value}}],[{key:"parseEnvVars",value:function parseEnvVars(){var authKey=process.env.WIOTP_AUTH_KEY||null;var authToken=process.env.WIOTP_AUTH_TOKEN||null;if(authKey==null&&authToken==null){authKey=process.env.WIOTP_API_KEY||null;authToken=process.env.WIOTP_API_TOKEN||null}var appId=process.env.WIOTP_IDENTITY_APPID||uuidv4();var domain=process.env.WIOTP_OPTIONS_DOMAIN||null;var apiRoot=process.env.WIOTP_OPTIONS_API_ROOT||null;var logLevel=process.env.WIOTP_OPTIONS_LOGLEVEL||"info";var port=process.env.WIOTP_OPTIONS_MQTT_PORT||null;var transport=process.env.WIOTP_OPTIONS_MQTT_TRANSPORT||null;var caFile=process.env.WIOTP_OPTIONS_MQTT_CAFILE||null;var cleanStart=process.env.WIOTP_OPTIONS_MQTT_CLEANSTART||"true";var sessionExpiry=process.env.WIOTP_OPTIONS_MQTT_SESSIONEXPIRY||3600;var keepAlive=process.env.WIOTP_OPTIONS_MQTT_KEEPALIVE||60;var sharedSubs=process.env.WIOTP_OPTIONS_MQTT_SHAREDSUBSCRIPTION||"false";var verifyCert=process.env.WIOTP_OPTIONS_HTTP_VERIFY||"true";if(port!=null){port=parseInt(port)}sessionExpiry=parseInt(sessionExpiry);keepAlive=parseInt(keepAlive);var identity={appId:appId};var options={domain:domain,apiRoot:apiRoot,logLevel:logLevel,mqtt:{port:port,transport:transport,cleanStart:["True","true","1"].includes(cleanStart),sessionExpiry:sessionExpiry,keepAlive:keepAlive,sharedSubscription:["True","true","1"].includes(sharedSubs),caFile:caFile},http:{verify:["True","true","1"].includes(verifyCert)}};var auth=null;if(authToken!=null){auth={key:authKey,token:authToken}}return new ApplicationConfig(identity,auth,options)}},{key:"parseConfigFile",value:function parseConfigFile(configFilePath){var configFile=fs.readFileSync(configFilePath,"utf8");var data=YAML.parse(configFile);if(!fs.existsSync(configFilePath)){throw new Error("File not found")}else{try{var _configFile=fs.readFileSync(configFilePath,"utf8");var data=YAML.parse(_configFile)}catch(err){throw new Error("Error reading device configuration file: "+err.code)}}if("options"in data&"logLevel"in data["options"]){var validLevels=["error","warning","info","debug"];if(!validLevels.includes(data["options"]["logLevel"])){throw new Error("Optional setting options.logLevel (Currently: "+data["options"]["logLevel"]+") must be one of error, warning, info, debug")}}else{data["options"]["logLevel"]=_loglevel["default"].GetLogger(data["options"]["logLevel"].toUpperCase())}return new ApplicationConfig(data["identity"],data["auth"],data["options"])}}]);return ApplicationConfig}(_BaseConfig2["default"]);exports["default"]=ApplicationConfig}).call(this,require("_process"))},{"../BaseConfig":226,_process:157,fs:32,loglevel:124,"uuid/v4":201,yaml:224}],237:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _util=require("../util");var _BaseClient2=_interopRequireDefault(require("../BaseClient"));var _DeviceConfig=_interopRequireDefault(require("./DeviceConfig"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}function _get(target,property,receiver){if(typeof Reflect!=="undefined"&&Reflect.get){_get=Reflect.get}else{_get=function _get(target,property,receiver){var base=_superPropBase(target,property);if(!base)return;var desc=Object.getOwnPropertyDescriptor(base,property);if(desc.get){return desc.get.call(receiver)}return desc.value}}return _get(target,property,receiver||target)}function _superPropBase(object,property){while(!Object.prototype.hasOwnProperty.call(object,property)){object=_getPrototypeOf(object);if(object===null)break}return object}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function")}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:true,configurable:true}});if(superClass)_setPrototypeOf(subClass,superClass)}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o};return _setPrototypeOf(o,p)}function _createSuper(Derived){var hasNativeReflectConstruct=_isNativeReflectConstruct();return function _createSuperInternal(){var Super=_getPrototypeOf(Derived),result;if(hasNativeReflectConstruct){var NewTarget=_getPrototypeOf(this).constructor;result=Reflect.construct(Super,arguments,NewTarget)}else{result=Super.apply(this,arguments)}return _possibleConstructorReturn(this,result)}}function _possibleConstructorReturn(self,call){if(call&&(_typeof(call)==="object"||typeof call==="function")){return call}return _assertThisInitialized(self)}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return self}function _isNativeReflectConstruct(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{Date.prototype.toString.call(Reflect.construct(Date,[],(function(){})));return true}catch(e){return false}}function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o)};return _getPrototypeOf(o)}var WILDCARD_TOPIC="iot-2/cmd/+/fmt/+";var CMD_RE=/^iot-2\/cmd\/(.+)\/fmt\/(.+)$/;var util=require("util");var DeviceClient=function(_BaseClient){_inherits(DeviceClient,_BaseClient);var _super=_createSuper(DeviceClient);function DeviceClient(config){var _this;_classCallCheck(this,DeviceClient);if(!config instanceof _DeviceConfig["default"]){throw new Error("Config must be an instance of DeviceConfig")}_this=_super.call(this,config);_this.log.debug("[DeviceClient:constructor] DeviceClient initialized for "+config.getClientId());return _this}_createClass(DeviceClient,[{key:"_commandSubscriptionCallback",value:function _commandSubscriptionCallback(err,granted){if(err==null){for(var index in granted){var grant=granted[index];this.log.debug("[DeviceClient:connect] Subscribed to device commands on "+grant.topic+" at QoS "+grant.qos)}}else{this.log.error("[DeviceClient:connect] Unable to establish subscription for device commands: "+err);this.emit("error",new Error("Unable to establish subscription for device commands: "+err))}}},{key:"connect",value:function connect(){var _this2=this;_get(_getPrototypeOf(DeviceClient.prototype),"connect",this).call(this);this.mqtt.on("connect",(function(){if(!_this2.config.isQuickstart()){_this2.mqtt.subscribe(WILDCARD_TOPIC,{qos:1},_this2._commandSubscriptionCallback.bind(_this2))}}));this.mqtt.on("message",(function(topic,payload){_this2.log.debug("[DeviceClient:onMessage] Message received on topic : "+topic+" with payload : "+payload);var match=CMD_RE.exec(topic);if(match){_this2.emit("command",match[1],match[2],payload,topic)}}))}},{key:"publishEvent",value:function publishEvent(eventId,format,data,qos,callback){qos=qos||0;if(!(0,_util.isDefined)(eventId)||!(0,_util.isDefined)(format)){this.log.error("[DeviceClient:publishEvent] Required params for publishEvent not present");this.emit("error","[DeviceClient:publishEvent] Required params for publishEvent not present");return}var topic=util.format("iot-2/evt/%s/fmt/%s",eventId,format);this._publish(topic,data,qos,callback);return this}}]);return DeviceClient}(_BaseClient2["default"]);exports["default"]=DeviceClient},{"../BaseClient":225,"../util":241,"./DeviceConfig":238,util:198}],238:[function(require,module,exports){(function(process){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _BaseConfig2=_interopRequireDefault(require("../BaseConfig"));var _loglevel=_interopRequireDefault(require("loglevel"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function")}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:true,configurable:true}});if(superClass)_setPrototypeOf(subClass,superClass)}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o};return _setPrototypeOf(o,p)}function _createSuper(Derived){var hasNativeReflectConstruct=_isNativeReflectConstruct();return function _createSuperInternal(){var Super=_getPrototypeOf(Derived),result;if(hasNativeReflectConstruct){var NewTarget=_getPrototypeOf(this).constructor;result=Reflect.construct(Super,arguments,NewTarget)}else{result=Super.apply(this,arguments)}return _possibleConstructorReturn(this,result)}}function _possibleConstructorReturn(self,call){if(call&&(_typeof(call)==="object"||typeof call==="function")){return call}return _assertThisInitialized(self)}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return self}function _isNativeReflectConstruct(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{Date.prototype.toString.call(Reflect.construct(Date,[],(function(){})));return true}catch(e){return false}}function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o)};return _getPrototypeOf(o)}var YAML=require("yaml");var fs=require("fs");var DeviceConfig=function(_BaseConfig){_inherits(DeviceConfig,_BaseConfig);var _super=_createSuper(DeviceConfig);function DeviceConfig(identity,auth,options){var _this;_classCallCheck(this,DeviceConfig);_this=_super.call(this,identity,auth,options);if(_this.identity==null){throw new Error("Missing identity from configuration")}if(!("orgId"in _this.identity)||_this.identity.orgId==null){throw new Error("Missing identity.orgId from configuration")}if(!("typeId"in _this.identity)||_this.identity.typeId==null){throw new Error("Missing identity.typeId from configuration")}if(!("deviceId"in _this.identity)||_this.identity.deviceId==null){throw new Error("Missing identity.deviceId from configuration")}if(_this.identity.orgId=="quickstart"){if(_this.auth!=null){throw new Error("Quickstart service does not support device authentication")}}else{if(_this.auth==null){throw new Error("Missing auth from configuration")}if(!("token"in _this.auth)||_this.auth.token==null){throw new Error("Missing auth.token from configuration")}}return _this}_createClass(DeviceConfig,[{key:"getOrgId",value:function getOrgId(){return this.identity.orgId}},{key:"getClientId",value:function getClientId(){return"d:"+this.identity.orgId+":"+this.identity.typeId+":"+this.identity.deviceId}},{key:"getMqttUsername",value:function getMqttUsername(){return"use-token-auth"}},{key:"getMqttPassword",value:function getMqttPassword(){if(this.identity.orgId!="quickstart"){return this.auth.token}else{return null}}}],[{key:"parseEnvVars",value:function parseEnvVars(){var orgId=process.env.WIOTP_IDENTITY_ORGID||null;var typeId=process.env.WIOTP_IDENTITY_TYPEID||null;var deviceId=process.env.WIOTP_IDENTITY_DEVICEID||null;var authToken=process.env.WIOTP_AUTH_TOKEN||null;if(authToken==null){authToken=process.env.WIOTP_API_TOKEN||null}var domain=process.env.WIOTP_OPTIONS_DOMAIN||null;var logLevel=process.env.WIOTP_OPTIONS_LOGLEVEL||"info";var port=process.env.WIOTP_OPTIONS_MQTT_PORT||null;var transport=process.env.WIOTP_OPTIONS_MQTT_TRANSPORT||null;var caFile=process.env.WIOTP_OPTIONS_MQTT_CAFILE||null;var cleanStart=process.env.WIOTP_OPTIONS_MQTT_CLEANSTART||"true";var sessionExpiry=process.env.WIOTP_OPTIONS_MQTT_SESSIONEXPIRY||3600;var keepAlive=process.env.WIOTP_OPTIONS_MQTT_KEEPALIVE||60;var sharedSubs=process.env.WIOTP_OPTIONS_MQTT_SHAREDSUBSCRIPTION||"false";if(port!=null){port=parseInt(port)}sessionExpiry=parseInt(sessionExpiry);keepAlive=parseInt(keepAlive);var identity={orgId:orgId,typeId:typeId,deviceId:deviceId};var options={domain:domain,logLevel:logLevel,mqtt:{port:port,transport:transport,cleanStart:["True","true","1"].includes(cleanStart),sessionExpiry:sessionExpiry,keepAlive:keepAlive,sharedSubscription:["True","true","1"].includes(sharedSubs),caFile:caFile}};var auth=null;if(authToken!=null){auth={token:authToken}}return new DeviceConfig(identity,auth,options)}},{key:"parseConfigFile",value:function parseConfigFile(configFilePath){var configFile=fs.readFileSync(configFilePath,"utf8");var data=YAML.parse(configFile);if(!fs.existsSync(configFilePath)){throw new Error("File not found")}else{try{var _configFile=fs.readFileSync(configFilePath,"utf8");var data=YAML.parse(_configFile)}catch(err){throw new Error("Error reading device configuration file: "+err.code)}}if("options"in data&"logLevel"in data["options"]){var validLevels=["error","warning","info","debug"];if(!validLevels.includes(data["options"]["logLevel"])){throw new Error("Optional setting options.logLevel (Currently: "+data["options"]["logLevel"]+") must be one of error, warning, info, debug")}}else{data["options"]["logLevel"]=_loglevel["default"].GetLogger(data["options"]["logLevel"].toUpperCase())}return new DeviceConfig(data["identity"],data["auth"],data["options"])}}]);return DeviceConfig}(_BaseConfig2["default"]);exports["default"]=DeviceConfig}).call(this,require("_process"))},{"../BaseConfig":226,_process:157,fs:32,loglevel:124,yaml:224}],239:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _BaseClient2=_interopRequireDefault(require("../BaseClient"));var _GatewayConfig=_interopRequireDefault(require("./GatewayConfig"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}function _get(target,property,receiver){if(typeof Reflect!=="undefined"&&Reflect.get){_get=Reflect.get}else{_get=function _get(target,property,receiver){var base=_superPropBase(target,property);if(!base)return;var desc=Object.getOwnPropertyDescriptor(base,property);if(desc.get){return desc.get.call(receiver)}return desc.value}}return _get(target,property,receiver||target)}function _superPropBase(object,property){while(!Object.prototype.hasOwnProperty.call(object,property)){object=_getPrototypeOf(object);if(object===null)break}return object}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function")}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:true,configurable:true}});if(superClass)_setPrototypeOf(subClass,superClass)}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o};return _setPrototypeOf(o,p)}function _createSuper(Derived){var hasNativeReflectConstruct=_isNativeReflectConstruct();return function _createSuperInternal(){var Super=_getPrototypeOf(Derived),result;if(hasNativeReflectConstruct){var NewTarget=_getPrototypeOf(this).constructor;result=Reflect.construct(Super,arguments,NewTarget)}else{result=Super.apply(this,arguments)}return _possibleConstructorReturn(this,result)}}function _possibleConstructorReturn(self,call){if(call&&(_typeof(call)==="object"||typeof call==="function")){return call}return _assertThisInitialized(self)}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return self}function _isNativeReflectConstruct(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{Date.prototype.toString.call(Reflect.construct(Date,[],(function(){})));return true}catch(e){return false}}function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o)};return _getPrototypeOf(o)}var CMD_RE=/^iot-2\/type\/(.+)\/id\/(.+)\/cmd\/(.+)\/fmt\/(.+)$/;var util=require("util");var GatewayClient=function(_BaseClient){_inherits(GatewayClient,_BaseClient);var _super=_createSuper(GatewayClient);function GatewayClient(config){var _this;_classCallCheck(this,GatewayClient);if(!config instanceof _GatewayConfig["default"]){throw new Error("Config must be an instance of GatewayConfig")}if(config.isQuickstart()){throw new Error("[GatewayClient:constructor] Quickstart not supported in Gateways")}_this=_super.call(this,config);_this.log.debug("[GatewayClient:constructor] GatewayClient initialized for "+config.getClientId());return _this}_createClass(GatewayClient,[{key:"connect",value:function connect(){var _this2=this;_get(_getPrototypeOf(GatewayClient.prototype),"connect",this).call(this);this.mqtt.on("connect",(function(){}));this.mqtt.on("message",(function(topic,payload){_this2.log.debug("[GatewayClient:onMessage] Message received on topic : "+topic+" with payload : "+payload);var match=CMD_RE.exec(topic);if(match){_this2.emit("command",match[1],match[2],match[3],match[4],payload,topic)}}))}},{key:"publishEvent",value:function publishEvent(eventId,format,payload,qos,callback){return this._publishEvent(this.config.identity.typeId,this.config.identity.deviceId,eventId,format,payload,qos,callback)}},{key:"publishDeviceEvent",value:function publishDeviceEvent(typeid,deviceId,eventid,format,payload,qos,callback){return this._publishEvent(typeId,deviceId,eventid,format,payload,qos,callback)}},{key:"_publishEvent",value:function _publishEvent(typeId,deviceId,eventId,format,data,qos,callback){var topic=util.format("iot-2/type/%s/id/%s/evt/%s/fmt/%s",typeId,deviceId,eventId,format);qos=qos||0;this._publish(topic,data,qos,callback);return this}},{key:"subscribeToDeviceCommands",value:function subscribeToDeviceCommands(typeId,deviceId,commandId,format,qos,callback){typeId=typeId||"+";deviceId=deviceId||"+";commandId=commandid||"+";format=format||"+";qos=qos||0;var topic="iot-2/type/"+typeId+"/id/"+deviceId+"/cmd/"+commandId+"/fmt/"+format;this._subscribe(topic,qos,callback);return this}},{key:"unsubscribeFromDeviceCommands",value:function unsubscribeFromDeviceCommands(typeId,deviceId,commandId,format,callback){typeId=typeId||"+";deviceId=deviceId||"+";commandId=commandId||"+";format=format||"+";var topic="iot-2/type/"+typeId+"/id/"+deviceId+"/cmd/"+commandId+"/fmt/"+format;this._unsubscribe(topic,callback);return this}},{key:"subscribeToCommands",value:function subscribeToCommands(commandId,format,qos,callback){commandId=commandId||"+";format=format||"+";qos=qos||0;var topic="iot-2/type/"+this.config.identity.typeId+"/id/"+this.config.identity.deviceId+"/cmd/"+commandId+"/fmt/"+format;this._subscribe(topic,qos,callback);return this}},{key:"unsubscribeFromCommands",value:function unsubscribeFromCommands(commandId,format,callback){commandId=commandId||"+";format=format||"+";var topic="iot-2/type/"+this.config.identity.typeId+"/id/"+this.config.identity.deviceId+"/cmd/"+commandId+"/fmt/"+format;this._unsubscribe(topic,callback);return this}}]);return GatewayClient}(_BaseClient2["default"]);exports["default"]=GatewayClient},{"../BaseClient":225,"./GatewayConfig":240,util:198}],240:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _DeviceConfig2=_interopRequireDefault(require("../device/DeviceConfig"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function")}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:true,configurable:true}});if(superClass)_setPrototypeOf(subClass,superClass)}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o};return _setPrototypeOf(o,p)}function _createSuper(Derived){var hasNativeReflectConstruct=_isNativeReflectConstruct();return function _createSuperInternal(){var Super=_getPrototypeOf(Derived),result;if(hasNativeReflectConstruct){var NewTarget=_getPrototypeOf(this).constructor;result=Reflect.construct(Super,arguments,NewTarget)}else{result=Super.apply(this,arguments)}return _possibleConstructorReturn(this,result)}}function _possibleConstructorReturn(self,call){if(call&&(_typeof(call)==="object"||typeof call==="function")){return call}return _assertThisInitialized(self)}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return self}function _isNativeReflectConstruct(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{Date.prototype.toString.call(Reflect.construct(Date,[],(function(){})));return true}catch(e){return false}}function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o)};return _getPrototypeOf(o)}var GatewayConfig=function(_DeviceConfig){_inherits(GatewayConfig,_DeviceConfig);var _super=_createSuper(GatewayConfig);function GatewayConfig(identity,auth,options){_classCallCheck(this,GatewayConfig);return _super.call(this,identity,auth,options)}_createClass(GatewayConfig,[{key:"getClientId",value:function getClientId(){return"g:"+this.identity.orgId+":"+this.identity.typeId+":"+this.identity.deviceId}}]);return GatewayConfig}(_DeviceConfig2["default"]);exports["default"]=GatewayConfig},{"../device/DeviceConfig":238}],241:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isString=isString;exports.isNumber=isNumber;exports.isBoolean=isBoolean;exports.isDefined=isDefined;exports.generateUUID=generateUUID;exports.isNode=exports.isBrowser=void 0;function isString(value){return typeof value==="string"}function isNumber(value){return typeof value==="number"}function isBoolean(value){return typeof value==="boolean"}function isDefined(value){return value!==undefined&&value!==null}var isBrowser=new Function("try {return this===window;}catch(e){ return false;}");exports.isBrowser=isBrowser;var isNode=new Function("try {return this===global;}catch(e){return false;}");exports.isNode=isNode;function generateUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(c){var r=Math.random()*16|0,v=c=="x"?r:r&3|8;return v.toString(16)}))}},{}],242:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"ApplicationClient",{enumerable:true,get:function get(){return _ApplicationClient["default"]}});Object.defineProperty(exports,"DeviceClient",{enumerable:true,get:function get(){return _DeviceClient["default"]}});Object.defineProperty(exports,"GatewayClient",{enumerable:true,get:function get(){return _GatewayClient["default"]}});Object.defineProperty(exports,"ApplicationConfig",{enumerable:true,get:function get(){return _ApplicationConfig["default"]}});Object.defineProperty(exports,"DeviceConfig",{enumerable:true,get:function get(){return _DeviceConfig["default"]}});Object.defineProperty(exports,"ApiClient",{enumerable:true,get:function get(){return _ApiClient["default"]}});Object.defineProperty(exports,"ApiErrors",{enumerable:true,get:function get(){return _ApiErrors["default"]}});Object.defineProperty(exports,"DscClient",{enumerable:true,get:function get(){return _DscClient["default"]}});Object.defineProperty(exports,"LecClient",{enumerable:true,get:function get(){return _LecClient["default"]}});Object.defineProperty(exports,"MgmtClient",{enumerable:true,get:function get(){return _MgmtClient["default"]}});Object.defineProperty(exports,"RegistryClient",{enumerable:true,get:function get(){return _RegistryClient["default"]}});Object.defineProperty(exports,"RulesClient",{enumerable:true,get:function get(){return _RulesClient["default"]}});Object.defineProperty(exports,"StateClient",{enumerable:true,get:function get(){return _StateClient["default"]}});var _ApplicationClient=_interopRequireDefault(require("./application/ApplicationClient"));var _DeviceClient=_interopRequireDefault(require("./device/DeviceClient"));var _GatewayClient=_interopRequireDefault(require("./gateway/GatewayClient"));var _ApplicationConfig=_interopRequireDefault(require("./application/ApplicationConfig"));var _DeviceConfig=_interopRequireDefault(require("./device/DeviceConfig"));var _ApiClient=_interopRequireDefault(require("./api/ApiClient"));var _ApiErrors=_interopRequireDefault(require("./api/ApiErrors"));var _DscClient=_interopRequireDefault(require("./api/DscClient"));var _LecClient=_interopRequireDefault(require("./api/LecClient"));var _MgmtClient=_interopRequireDefault(require("./api/MgmtClient"));var _RegistryClient=_interopRequireDefault(require("./api/RegistryClient"));var _RulesClient=_interopRequireDefault(require("./api/RulesClient"));var _StateClient=_interopRequireDefault(require("./api/StateClient"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}},{"./api/ApiClient":227,"./api/ApiErrors":228,"./api/DscClient":229,"./api/LecClient":230,"./api/MgmtClient":231,"./api/RegistryClient":232,"./api/RulesClient":233,"./api/StateClient":234,"./application/ApplicationClient":235,"./application/ApplicationConfig":236,"./device/DeviceClient":237,"./device/DeviceConfig":238,"./gateway/GatewayClient":239}]},{},[242]);
|