home-assistant-js-websocket
Advanced tools
Comparing version 3.1.4 to 3.1.5
import { ConnectionOptions, MessageBase } from "./types"; | ||
export declare type ConnectionEventListener = (conn: Connection, eventData?: any) => void; | ||
declare type Events = "ready" | "disconnected" | "reconnect-error"; | ||
declare type SubscribeEventCommmandInFlight = { | ||
resolve: (result?: any) => void; | ||
reject: (err: any) => void; | ||
eventCallback: (ev: any) => void; | ||
eventType?: string; | ||
unsubscribe: () => Promise<void>; | ||
}; | ||
declare type CommandWithAnswerInFlight = { | ||
resolve: (result?: any) => void; | ||
reject: (err: any) => void; | ||
}; | ||
declare type CommandInFlight = SubscribeEventCommmandInFlight | CommandWithAnswerInFlight; | ||
export declare class Connection { | ||
@@ -8,3 +20,3 @@ options: ConnectionOptions; | ||
commands: { | ||
[commandId: number]: any; | ||
[commandId: number]: CommandInFlight; | ||
}; | ||
@@ -25,3 +37,3 @@ eventListeners: { | ||
sendMessage(message: MessageBase, commandId?: number): void; | ||
sendMessagePromise<Result>(message: MessageBase, commandId?: number): Promise<Result>; | ||
sendMessagePromise<Result>(message: MessageBase): Promise<Result>; | ||
private _handleMessage; | ||
@@ -28,0 +40,0 @@ private _handleClose; |
@@ -1,2 +0,2 @@ | ||
function e(e,t,n,r){return new(n||(n=Promise))(function(s,i){function o(e){try{a(r.next(e))}catch(e){i(e)}}function c(e){try{a(r.throw(e))}catch(e){i(e)}}function a(e){e.done?s(e.value):new n(function(t){t(e.value)}).then(o,c)}a((r=r.apply(e,t||[])).next())})}function t(e,t){var n,r,s,i,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(i){return function(c){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(s=2&i[0]?r.return:i[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,i[1])).done)return s;switch(r=0,s&&(i=[2&i[0],s.value]),i[0]){case 0:case 1:s=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(s=(s=o.trys).length>0&&s[s.length-1])&&(6===i[0]||2===i[0])){o=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){o.label=i[1];break}if(6===i[0]&&o.label<s[1]){o.label=s[1],s=i;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(i);break}s[2]&&o.ops.pop(),o.trys.pop();continue}i=t.call(e,o)}catch(e){i=[6,e],r=0}finally{n=s=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,c])}}}var n=1,r=2,s=3,i=4;var o="auth_invalid",c="auth_ok";var a=function(){function n(e,t){this.options=t,this.commandId=1,this.commands={},this.eventListeners={},this.closeRequested=!1,this._handleClose=this._handleClose.bind(this),this.setSocket(e)}return n.prototype.setSocket=function(e){var t=this,n=this.socket;if(this.socket=e,e.addEventListener("message",function(e){return t._handleMessage(e)}),e.addEventListener("close",this._handleClose),n){var r=this.commands;this.commandId=1,this.commands={},Object.keys(r).forEach(function(e){var n=r[e];n.eventCallback&&t.subscribeEvents(n.eventCallback,n.eventType).then(function(e){n.unsubscribe=e})}),this.fireEvent("ready")}},n.prototype.addEventListener=function(e,t){var n=this.eventListeners[e];n||(n=this.eventListeners[e]=[]),n.push(t)},n.prototype.removeEventListener=function(e,t){var n=this.eventListeners[e];if(n){var r=n.indexOf(t);-1!==r&&n.splice(r,1)}},n.prototype.fireEvent=function(e,t){var n=this;(this.eventListeners[e]||[]).forEach(function(e){return e(n,t)})},n.prototype.close=function(){this.closeRequested=!0,this.socket.close()},n.prototype.subscribeEvents=function(n,r){return e(this,void 0,void 0,function(){var s,i,o=this;return t(this,function(c){switch(c.label){case 0:return s=this._genCmdId(),[4,this.sendMessagePromise(function(e){var t={type:"subscribe_events"};return e&&(t.event_type=e),t}(r),s)];case 1:return c.sent(),this.commands[s]=i={eventCallback:n,eventType:r,unsubscribe:function(){return e(o,void 0,void 0,function(){return t(this,function(e){switch(e.label){case 0:return[4,this.sendMessagePromise((t=s,{type:"unsubscribe_events",subscription:t}))];case 1:return e.sent(),delete this.commands[s],[2]}var t})})}},[2,function(){return i.unsubscribe()}]}})})},n.prototype.ping=function(){return this.sendMessagePromise({type:"ping"})},n.prototype.sendMessage=function(e,t){t||(t=this._genCmdId()),e.id=t,this.socket.send(JSON.stringify(e))},n.prototype.sendMessagePromise=function(e,t){var n=this;return new Promise(function(r,s){t||(t=n._genCmdId()),n.commands[t]={resolve:r,reject:s},n.sendMessage(e,t)})},n.prototype._handleMessage=function(e){var t=JSON.parse(e.data);switch(t.type){case"event":this.commands[t.id].eventCallback(t.event);break;case"result":t.id in this.commands&&(1==t.success?this.commands[t.id].resolve(t.result):this.commands[t.id].reject(t.error),delete this.commands[t.id]);break;case"pong":this.commands[t.id].resolve(),delete this.commands[t.id]}},n.prototype._handleClose=function(){var n=this;if(Object.keys(this.commands).forEach(function(e){var t=n.commands[e].reject;t&&t({type:"result",success:!1,error:{code:3,message:"Connection lost"}})}),!this.closeRequested){this.fireEvent("disconnected");var s=Object.assign({},this.options,{setupRetry:0}),i=function(o){setTimeout(function(){return e(n,void 0,void 0,function(){var e,n;return t(this,function(t){switch(t.label){case 0:t.label=1;case 1:return t.trys.push([1,3,,4]),[4,s.createSocket(s)];case 2:return e=t.sent(),this.setSocket(e),[3,4];case 3:return(n=t.sent())===r?this.fireEvent("reconnect-error",n):i(o+1),[3,4];case 4:return[2]}})})},1e3*Math.min(o,5))};i(0)}},n.prototype._genCmdId=function(){return++this.commandId},n}();function u(e,t,n,r){n+=(n.includes("?")?"&":"?")+"auth_callback=1",document.location.href=function(e,t,n,r){var s=e+"/auth/authorize?response_type=code&client_id="+encodeURIComponent(t)+"&redirect_uri="+encodeURIComponent(n);return r&&(s+="&state="+encodeURIComponent(r)),s}(e,t,n,r)}function h(n,s,i){return e(this,void 0,void 0,function(){var e,o,c;return t(this,function(t){switch(t.label){case 0:return(e=new FormData).append("client_id",s),Object.keys(i).forEach(function(t){e.append(t,i[t])}),[4,fetch(n+"/auth/token",{method:"POST",credentials:"same-origin",body:e})];case 1:if(!(o=t.sent()).ok)throw 400===o.status||403===o.status?r:new Error("Unable to fetch tokens");return[4,o.json()];case 2:return(c=t.sent()).hassUrl=n,c.clientId=s,c.expires=1e3*c.expires_in+Date.now(),[2,c]}})})}var d=function(){function n(e,t){this.data=e,this._saveTokens=t}return Object.defineProperty(n.prototype,"wsUrl",{get:function(){return"ws"+this.data.hassUrl.substr(4)+"/api/websocket"},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"accessToken",{get:function(){return this.data.access_token},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"expired",{get:function(){return Date.now()>this.data.expires},enumerable:!0,configurable:!0}),n.prototype.refreshAccessToken=function(){return e(this,void 0,void 0,function(){var e;return t(this,function(t){switch(t.label){case 0:return[4,h(this.data.hassUrl,this.data.clientId,{grant_type:"refresh_token",refresh_token:this.data.refresh_token})];case 1:return(e=t.sent()).refresh_token=this.data.refresh_token,this.data=e,this._saveTokens&&this._saveTokens(e),[2]}})})},n.prototype.revoke=function(){return e(this,void 0,void 0,function(){var e;return t(this,function(t){switch(t.label){case 0:return(e=new FormData).append("action","revoke"),e.append("token",this.data.refresh_token),[4,fetch(this.data.hassUrl+"/auth/token",{method:"POST",credentials:"same-origin",body:e})];case 1:return t.sent(),this._saveTokens&&this._saveTokens(null),[2]}})})},n}();function l(n){return void 0===n&&(n={}),e(this,void 0,void 0,function(){var e,r,s,o,c,a,l;return t(this,function(t){switch(t.label){case 0:if(!("auth_callback"in(r=function(e){for(var t={},n=e.split("&"),r=0;r<n.length;r++){var s=n[r].split("="),i=decodeURIComponent(s[0]),o=s.length>1?decodeURIComponent(s[1]):void 0;t[i]=o}return t}(location.search.substr(1)))))return[3,4];s=JSON.parse(atob(r.state)),t.label=1;case 1:return t.trys.push([1,3,,4]),[4,function(e,t,n){return h(e,t,{code:n,grant_type:"authorization_code"})}(s.hassUrl,s.clientId,r.code)];case 2:return e=t.sent(),n.saveTokens&&n.saveTokens(e),[3,4];case 3:return o=t.sent(),console.log("Unable to fetch access token",o),[3,4];case 4:return e||!n.loadTokens?[3,6]:[4,n.loadTokens()];case 5:e=t.sent(),t.label=6;case 6:if(e)return[2,new d(e,n.saveTokens)];if(void 0===(c=n.hassUrl))throw i;return"/"===c[c.length-1]&&(c=c.substr(0,c.length-1)),a=n.clientId||location.protocol+"//"+location.host+"/",l=n.redirectUrl||location.protocol+"//"+location.host+location.pathname+location.search,u(c,a,l,function(e){return btoa(JSON.stringify(e))}({hassUrl:c,clientId:a})),[2,new Promise(function(){})]}})})}var f=function(){function e(e){this._noSub=e,this.listeners=[]}return e.prototype.action=function(e){var t=this,n=function(e){return t.setState(e,!1)};return function(){for(var r=[],s=0;s<arguments.length;s++)r[s]=arguments[s];var i=e.apply(void 0,[t.state].concat(r));if(null!=i)return"then"in i?i.then(n):n(i)}},e.prototype.setState=function(e,t){this.state=t?e:Object.assign({},this.state,e);for(var n=this.listeners,r=0;r<n.length;r++)n[r](this.state)},e.prototype.subscribe=function(e){var t=this;return this.listeners.push(e),void 0!==this.state&&e(this.state),function(){t.unsubscribe(e)}},e.prototype.unsubscribe=function(e){for(var t=e,n=[],r=this.listeners,s=0;s<r.length;s++)r[s]===t?t=null:n.push(r[s]);this.listeners=n,0===n.length&&this._noSub()},e}();function v(n,r,s,i,o){if(n in i)return i[n](o);var c,a=new f(function(){c&&c.then(function(e){return e()}),i.removeEventListener("ready",u),delete i[n]});function u(){return e(this,void 0,void 0,function(){var e,n;return t(this,function(t){switch(t.label){case 0:return n=(e=a).setState,[4,r(i)];case 1:return n.apply(e,[t.sent(),!0]),[2]}})})}return i[n]=function(e){return a.subscribe(e)},s&&(c=s(i,a)),i.addEventListener("ready",u),u(),a.subscribe(o)}var p=function(e){return e.sendMessagePromise({type:"get_states"})},b=function(e){return e.sendMessagePromise({type:"get_services"})},m=function(e){return e.sendMessagePromise({type:"get_config"})},y=function(e){return e.sendMessagePromise({type:"auth/current_user"})},g=function(e,t,n,r){return e.sendMessagePromise(function(e,t,n){var r={type:"call_service",domain:e,service:t};return n&&(r.service_data=n),r}(t,n,r))};function k(e,t){return void 0===e?null:{components:e.components.concat(t.data.component)}}var _=function(e){return m(e)},w=function(e,t){return e.subscribeEvents(t.action(k),"component_loaded")},E=function(e,t){return v("_cnf",_,w,e,t)};function S(e,t){var n,r;if(void 0===e)return null;var s=t.data,i=s.domain,o=Object.assign({},e[i],((n={})[s.service]={description:"",fields:{}},n));return(r={})[i]=o,r}function O(e,t){var n;if(void 0===e)return null;var r=t.data,s=r.domain,i=r.service,o=e[s];if(!(o&&i in o))return null;var c={};return Object.keys(o).forEach(function(e){e!==i&&(c[e]=o[e])}),(n={})[s]=c,n}var T=function(e){return b(e)},L=function(e,t){return Promise.all([e.subscribeEvents(t.action(S),"service_registered"),e.subscribeEvents(t.action(O),"service_removed")]).then(function(e){return function(){return e.forEach(function(e){return e()})}})},P=function(e,t){return v("_srv",T,L,e,t)};function C(n){return e(this,void 0,void 0,function(){var e,r,s,i;return t(this,function(t){switch(t.label){case 0:return[4,p(n)];case 1:for(e=t.sent(),r={},s=0;s<e.length;s++)r[(i=e[s]).entity_id]=i;return[2,r]}})})}var I=function(e,t){return e.subscribeEvents(function(e){return function(e,t){var n,r=e.state;if(void 0!==r){var s=t.data,i=s.entity_id,o=s.new_state;if(o)e.setState(((n={})[o.entity_id]=o,n));else{var c=Object.assign({},r);delete c[i],e.setState(c,!0)}}}(t,e)},"state_changed")},U=function(e,t){return v("_ent",C,I,e,t)},j={setupRetry:0,createSocket:function(s){if(!s.auth)throw i;var a=s.auth,u=a.wsUrl;return new Promise(function(i,h){return function s(i,h,d){var l=this,f=new WebSocket(u),v=!1,p=function(){if(f.removeEventListener("close",p),v)d(r);else if(0!==i){var e=-1===i?-1:i-1;setTimeout(function(){return s(e,h,d)},1e3)}else d(n)},b=function(n){return e(l,void 0,void 0,function(){var e;return t(this,function(t){switch(t.label){case 0:return t.trys.push([0,3,,4]),a.expired?[4,a.refreshAccessToken()]:[3,2];case 1:t.sent(),t.label=2;case 2:return f.send(JSON.stringify({type:"auth",access_token:a.accessToken})),[3,4];case 3:return e=t.sent(),v=e===r,f.close(),[3,4];case 4:return[2]}})})},m=function(n){return e(l,void 0,void 0,function(){return t(this,function(e){switch(JSON.parse(n.data).type){case o:v=!0,f.close();break;case c:f.removeEventListener("open",b),f.removeEventListener("message",m),f.removeEventListener("close",p),f.removeEventListener("error",p),h(f)}return[2]})})};f.addEventListener("open",b),f.addEventListener("message",m),f.addEventListener("close",p),f.addEventListener("error",p)}(s.setupRetry,i,h)})}};function M(n){return e(this,void 0,void 0,function(){var e,r;return t(this,function(t){switch(t.label){case 0:return[4,(e=Object.assign({},j,n)).createSocket(e)];case 1:return r=t.sent(),[2,new a(r,e)]}})})}export{M as createConnection,d as Auth,l as getAuth,v as createCollection,a as Connection,E as subscribeConfig,P as subscribeServices,U as subscribeEntities,n as ERR_CANNOT_CONNECT,r as ERR_INVALID_AUTH,s as ERR_CONNECTION_LOST,i as ERR_HASS_HOST_REQUIRED,p as getStates,b as getServices,m as getConfig,y as getUser,g as callService}; | ||
function e(e,t,n,r){return new(n||(n=Promise))(function(s,i){function o(e){try{a(r.next(e))}catch(e){i(e)}}function c(e){try{a(r.throw(e))}catch(e){i(e)}}function a(e){e.done?s(e.value):new n(function(t){t(e.value)}).then(o,c)}a((r=r.apply(e,t||[])).next())})}function t(e,t){var n,r,s,i,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(i){return function(c){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(s=2&i[0]?r.return:i[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,i[1])).done)return s;switch(r=0,s&&(i=[2&i[0],s.value]),i[0]){case 0:case 1:s=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(s=(s=o.trys).length>0&&s[s.length-1])&&(6===i[0]||2===i[0])){o=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){o.label=i[1];break}if(6===i[0]&&o.label<s[1]){o.label=s[1],s=i;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(i);break}s[2]&&o.ops.pop(),o.trys.pop();continue}i=t.call(e,o)}catch(e){i=[6,e],r=0}finally{n=s=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,c])}}}var n=1,r=2,s=3,i=4;var o="auth_invalid",c="auth_ok";var a=function(){function n(e,t){this.options=t,this.commandId=1,this.commands={},this.eventListeners={},this.closeRequested=!1,this.setSocket(e)}return n.prototype.setSocket=function(e){var t=this,n=this.socket;if(this.socket=e,e.addEventListener("message",function(e){return t._handleMessage(e)}),e.addEventListener("close",function(e){return t._handleClose(e)}),n){var r=this.commands;this.commandId=1,this.commands={},Object.keys(r).forEach(function(e){var n=r[e];"eventCallback"in n&&t.subscribeEvents(n.eventCallback,n.eventType).then(function(e){n.unsubscribe=e,n.resolve()})}),this.fireEvent("ready")}},n.prototype.addEventListener=function(e,t){var n=this.eventListeners[e];n||(n=this.eventListeners[e]=[]),n.push(t)},n.prototype.removeEventListener=function(e,t){var n=this.eventListeners[e];if(n){var r=n.indexOf(t);-1!==r&&n.splice(r,1)}},n.prototype.fireEvent=function(e,t){var n=this;(this.eventListeners[e]||[]).forEach(function(e){return e(n,t)})},n.prototype.close=function(){this.closeRequested=!0,this.socket.close()},n.prototype.subscribeEvents=function(n,r){return e(this,void 0,void 0,function(){var s,i,o=this;return t(this,function(c){switch(c.label){case 0:return s=this._genCmdId(),[4,new Promise(function(c,a){i=o.commands[s]={resolve:c,reject:a,eventCallback:n,eventType:r,unsubscribe:function(){return e(o,void 0,void 0,function(){return t(this,function(e){switch(e.label){case 0:return[4,this.sendMessagePromise((t=s,{type:"unsubscribe_events",subscription:t}))];case 1:return e.sent(),delete this.commands[s],[2]}var t})})}};try{o.sendMessage(function(e){var t={type:"subscribe_events"};return e&&(t.event_type=e),t}(r),s)}catch(e){}})];case 1:return c.sent(),[2,function(){return i.unsubscribe()}]}})})},n.prototype.ping=function(){return this.sendMessagePromise({type:"ping"})},n.prototype.sendMessage=function(e,t){t||(t=this._genCmdId()),e.id=t,this.socket.send(JSON.stringify(e))},n.prototype.sendMessagePromise=function(e){var t=this;return new Promise(function(n,r){var s=t._genCmdId();t.commands[s]={resolve:n,reject:r},t.sendMessage(e,s)})},n.prototype._handleMessage=function(e){var t=JSON.parse(e.data);switch(t.type){case"event":this.commands[t.id].eventCallback(t.event);break;case"result":if(t.id in this.commands){var n=this.commands[t.id];t.success?(n.resolve(t.result),"eventCallback"in n||delete this.commands[t.id]):(n.reject(t.error),delete this.commands[t.id])}break;case"pong":this.commands[t.id].resolve(),delete this.commands[t.id]}},n.prototype._handleClose=function(n){var s=this;if(Object.keys(this.commands).forEach(function(e){var t=s.commands[e];"reject"in t&&t.reject({type:"result",success:!1,error:{code:3,message:"Connection lost"}})}),!this.closeRequested){this.fireEvent("disconnected");var i=Object.assign({},this.options,{setupRetry:0}),o=function(n){setTimeout(function(){return e(s,void 0,void 0,function(){var e,s;return t(this,function(t){switch(t.label){case 0:t.label=1;case 1:return t.trys.push([1,3,,4]),[4,i.createSocket(i)];case 2:return e=t.sent(),this.setSocket(e),[3,4];case 3:return(s=t.sent())===r?this.fireEvent("reconnect-error",s):o(n+1),[3,4];case 4:return[2]}})})},1e3*Math.min(n,5))};o(0)}},n.prototype._genCmdId=function(){return++this.commandId},n}();function u(e,t,n,r){n+=(n.includes("?")?"&":"?")+"auth_callback=1",document.location.href=function(e,t,n,r){var s=e+"/auth/authorize?response_type=code&client_id="+encodeURIComponent(t)+"&redirect_uri="+encodeURIComponent(n);return r&&(s+="&state="+encodeURIComponent(r)),s}(e,t,n,r)}function h(n,s,i){return e(this,void 0,void 0,function(){var e,o,c;return t(this,function(t){switch(t.label){case 0:return(e=new FormData).append("client_id",s),Object.keys(i).forEach(function(t){e.append(t,i[t])}),[4,fetch(n+"/auth/token",{method:"POST",credentials:"same-origin",body:e})];case 1:if(!(o=t.sent()).ok)throw 400===o.status||403===o.status?r:new Error("Unable to fetch tokens");return[4,o.json()];case 2:return(c=t.sent()).hassUrl=n,c.clientId=s,c.expires=1e3*c.expires_in+Date.now(),[2,c]}})})}var l=function(){function n(e,t){this.data=e,this._saveTokens=t}return Object.defineProperty(n.prototype,"wsUrl",{get:function(){return"ws"+this.data.hassUrl.substr(4)+"/api/websocket"},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"accessToken",{get:function(){return this.data.access_token},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"expired",{get:function(){return Date.now()>this.data.expires},enumerable:!0,configurable:!0}),n.prototype.refreshAccessToken=function(){return e(this,void 0,void 0,function(){var e;return t(this,function(t){switch(t.label){case 0:return[4,h(this.data.hassUrl,this.data.clientId,{grant_type:"refresh_token",refresh_token:this.data.refresh_token})];case 1:return(e=t.sent()).refresh_token=this.data.refresh_token,this.data=e,this._saveTokens&&this._saveTokens(e),[2]}})})},n.prototype.revoke=function(){return e(this,void 0,void 0,function(){var e;return t(this,function(t){switch(t.label){case 0:return(e=new FormData).append("action","revoke"),e.append("token",this.data.refresh_token),[4,fetch(this.data.hassUrl+"/auth/token",{method:"POST",credentials:"same-origin",body:e})];case 1:return t.sent(),this._saveTokens&&this._saveTokens(null),[2]}})})},n}();function d(n){return void 0===n&&(n={}),e(this,void 0,void 0,function(){var e,r,s,o,c,a,d;return t(this,function(t){switch(t.label){case 0:if(!("auth_callback"in(r=function(e){for(var t={},n=e.split("&"),r=0;r<n.length;r++){var s=n[r].split("="),i=decodeURIComponent(s[0]),o=s.length>1?decodeURIComponent(s[1]):void 0;t[i]=o}return t}(location.search.substr(1)))))return[3,4];s=JSON.parse(atob(r.state)),t.label=1;case 1:return t.trys.push([1,3,,4]),[4,function(e,t,n){return h(e,t,{code:n,grant_type:"authorization_code"})}(s.hassUrl,s.clientId,r.code)];case 2:return e=t.sent(),n.saveTokens&&n.saveTokens(e),[3,4];case 3:return o=t.sent(),console.log("Unable to fetch access token",o),[3,4];case 4:return e||!n.loadTokens?[3,6]:[4,n.loadTokens()];case 5:e=t.sent(),t.label=6;case 6:if(e)return[2,new l(e,n.saveTokens)];if(void 0===(c=n.hassUrl))throw i;return"/"===c[c.length-1]&&(c=c.substr(0,c.length-1)),a=n.clientId||location.protocol+"//"+location.host+"/",d=n.redirectUrl||location.protocol+"//"+location.host+location.pathname+location.search,u(c,a,d,function(e){return btoa(JSON.stringify(e))}({hassUrl:c,clientId:a})),[2,new Promise(function(){})]}})})}var f=function(){function e(e){this._noSub=e,this.listeners=[]}return e.prototype.action=function(e){var t=this,n=function(e){return t.setState(e,!1)};return function(){for(var r=[],s=0;s<arguments.length;s++)r[s]=arguments[s];var i=e.apply(void 0,[t.state].concat(r));if(null!=i)return"then"in i?i.then(n):n(i)}},e.prototype.setState=function(e,t){this.state=t?e:Object.assign({},this.state,e);for(var n=this.listeners,r=0;r<n.length;r++)n[r](this.state)},e.prototype.subscribe=function(e){var t=this;return this.listeners.push(e),void 0!==this.state&&e(this.state),function(){t.unsubscribe(e)}},e.prototype.unsubscribe=function(e){for(var t=e,n=[],r=this.listeners,s=0;s<r.length;s++)r[s]===t?t=null:n.push(r[s]);this.listeners=n,0===n.length&&this._noSub()},e}();function v(n,r,s,i,o){var c,a=this;if(n in i)return i[n](o);var u=new f(function(){c&&c.then(function(e){return e()}),i.removeEventListener("ready",h),delete i[n]});i[n]=function(e){return u.subscribe(e)},s&&(c=s(i,u));var h=function(){return e(a,void 0,void 0,function(){var e,n,s;return t(this,function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),n=(e=u).setState,[4,r(i)];case 1:return n.apply(e,[t.sent(),!0]),[3,3];case 2:if(s=t.sent(),i.socket.readyState==i.socket.OPEN)throw s;return[3,3];case 3:return[2]}})})};return i.addEventListener("ready",h),h(),u.subscribe(o)}var p=function(e){return e.sendMessagePromise({type:"get_states"})},b=function(e){return e.sendMessagePromise({type:"get_services"})},m=function(e){return e.sendMessagePromise({type:"get_config"})},y=function(e){return e.sendMessagePromise({type:"auth/current_user"})},k=function(e,t,n,r){return e.sendMessagePromise(function(e,t,n){var r={type:"call_service",domain:e,service:t};return n&&(r.service_data=n),r}(t,n,r))};function g(e,t){return void 0===e?null:{components:e.components.concat(t.data.component)}}var _=function(e){return m(e)},w=function(e,t){return e.subscribeEvents(t.action(g),"component_loaded")},E=function(e,t){return v("_cnf",_,w,e,t)};function S(e,t){var n,r;if(void 0===e)return null;var s=t.data,i=s.domain,o=Object.assign({},e[i],((n={})[s.service]={description:"",fields:{}},n));return(r={})[i]=o,r}function O(e,t){var n;if(void 0===e)return null;var r=t.data,s=r.domain,i=r.service,o=e[s];if(!(o&&i in o))return null;var c={};return Object.keys(o).forEach(function(e){e!==i&&(c[e]=o[e])}),(n={})[s]=c,n}var T=function(e){return b(e)},L=function(e,t){return Promise.all([e.subscribeEvents(t.action(S),"service_registered"),e.subscribeEvents(t.action(O),"service_removed")]).then(function(e){return function(){return e.forEach(function(e){return e()})}})},P=function(e,t){return v("_srv",T,L,e,t)};function j(n){return e(this,void 0,void 0,function(){var e,r,s,i;return t(this,function(t){switch(t.label){case 0:return[4,p(n)];case 1:for(e=t.sent(),r={},s=0;s<e.length;s++)r[(i=e[s]).entity_id]=i;return[2,r]}})})}var C=function(e,t){return e.subscribeEvents(function(e){return function(e,t){var n,r=e.state;if(void 0!==r){var s=t.data,i=s.entity_id,o=s.new_state;if(o)e.setState(((n={})[o.entity_id]=o,n));else{var c=Object.assign({},r);delete c[i],e.setState(c,!0)}}}(t,e)},"state_changed")},I=function(e,t){return v("_ent",j,C,e,t)},U={setupRetry:0,createSocket:function(s){if(!s.auth)throw i;var a=s.auth,u=a.wsUrl;return new Promise(function(i,h){return function s(i,h,l){var d=this,f=new WebSocket(u),v=!1,p=function(){if(f.removeEventListener("close",p),v)l(r);else if(0!==i){var e=-1===i?-1:i-1;setTimeout(function(){return s(e,h,l)},1e3)}else l(n)},b=function(n){return e(d,void 0,void 0,function(){var e;return t(this,function(t){switch(t.label){case 0:return t.trys.push([0,3,,4]),a.expired?[4,a.refreshAccessToken()]:[3,2];case 1:t.sent(),t.label=2;case 2:return f.send(JSON.stringify({type:"auth",access_token:a.accessToken})),[3,4];case 3:return e=t.sent(),v=e===r,f.close(),[3,4];case 4:return[2]}})})},m=function(n){return e(d,void 0,void 0,function(){return t(this,function(e){switch(JSON.parse(n.data).type){case o:v=!0,f.close();break;case c:f.removeEventListener("open",b),f.removeEventListener("message",m),f.removeEventListener("close",p),f.removeEventListener("error",p),h(f)}return[2]})})};f.addEventListener("open",b),f.addEventListener("message",m),f.addEventListener("close",p),f.addEventListener("error",p)}(s.setupRetry,i,h)})}};function M(n){return e(this,void 0,void 0,function(){var e,r;return t(this,function(t){switch(t.label){case 0:return[4,(e=Object.assign({},U,n)).createSocket(e)];case 1:return r=t.sent(),[2,new a(r,e)]}})})}export{M as createConnection,l as Auth,d as getAuth,v as createCollection,a as Connection,E as subscribeConfig,P as subscribeServices,I as subscribeEntities,n as ERR_CANNOT_CONNECT,r as ERR_INVALID_AUTH,s as ERR_CONNECTION_LOST,i as ERR_HASS_HOST_REQUIRED,p as getStates,b as getServices,m as getConfig,y as getUser,k as callService}; | ||
//# sourceMappingURL=haws.es.js.map |
@@ -1,2 +0,2 @@ | ||
function e(e,t,n,r){return new(n||(n=Promise))(function(s,i){function o(e){try{a(r.next(e))}catch(e){i(e)}}function c(e){try{a(r.throw(e))}catch(e){i(e)}}function a(e){e.done?s(e.value):new n(function(t){t(e.value)}).then(o,c)}a((r=r.apply(e,t||[])).next())})}function t(e,t){var n,r,s,i,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(i){return function(c){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(s=2&i[0]?r.return:i[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,i[1])).done)return s;switch(r=0,s&&(i=[2&i[0],s.value]),i[0]){case 0:case 1:s=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(s=(s=o.trys).length>0&&s[s.length-1])&&(6===i[0]||2===i[0])){o=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){o.label=i[1];break}if(6===i[0]&&o.label<s[1]){o.label=s[1],s=i;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(i);break}s[2]&&o.ops.pop(),o.trys.pop();continue}i=t.call(e,o)}catch(e){i=[6,e],r=0}finally{n=s=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,c])}}}var n=1,r=2,s=4;var i="auth_invalid",o="auth_ok";var c=function(){function n(e,t){this.options=t,this.commandId=1,this.commands={},this.eventListeners={},this.closeRequested=!1,this._handleClose=this._handleClose.bind(this),this.setSocket(e)}return n.prototype.setSocket=function(e){var t=this,n=this.socket;if(this.socket=e,e.addEventListener("message",function(e){return t._handleMessage(e)}),e.addEventListener("close",this._handleClose),n){var r=this.commands;this.commandId=1,this.commands={},Object.keys(r).forEach(function(e){var n=r[e];n.eventCallback&&t.subscribeEvents(n.eventCallback,n.eventType).then(function(e){n.unsubscribe=e})}),this.fireEvent("ready")}},n.prototype.addEventListener=function(e,t){var n=this.eventListeners[e];n||(n=this.eventListeners[e]=[]),n.push(t)},n.prototype.removeEventListener=function(e,t){var n=this.eventListeners[e];if(n){var r=n.indexOf(t);-1!==r&&n.splice(r,1)}},n.prototype.fireEvent=function(e,t){var n=this;(this.eventListeners[e]||[]).forEach(function(e){return e(n,t)})},n.prototype.close=function(){this.closeRequested=!0,this.socket.close()},n.prototype.subscribeEvents=function(n,r){return e(this,void 0,void 0,function(){var s,i,o=this;return t(this,function(c){switch(c.label){case 0:return s=this._genCmdId(),[4,this.sendMessagePromise(function(e){var t={type:"subscribe_events"};return e&&(t.event_type=e),t}(r),s)];case 1:return c.sent(),this.commands[s]=i={eventCallback:n,eventType:r,unsubscribe:function(){return e(o,void 0,void 0,function(){return t(this,function(e){switch(e.label){case 0:return[4,this.sendMessagePromise((t=s,{type:"unsubscribe_events",subscription:t}))];case 1:return e.sent(),delete this.commands[s],[2]}var t})})}},[2,function(){return i.unsubscribe()}]}})})},n.prototype.ping=function(){return this.sendMessagePromise({type:"ping"})},n.prototype.sendMessage=function(e,t){t||(t=this._genCmdId()),e.id=t,this.socket.send(JSON.stringify(e))},n.prototype.sendMessagePromise=function(e,t){var n=this;return new Promise(function(r,s){t||(t=n._genCmdId()),n.commands[t]={resolve:r,reject:s},n.sendMessage(e,t)})},n.prototype._handleMessage=function(e){var t=JSON.parse(e.data);switch(t.type){case"event":this.commands[t.id].eventCallback(t.event);break;case"result":t.id in this.commands&&(1==t.success?this.commands[t.id].resolve(t.result):this.commands[t.id].reject(t.error),delete this.commands[t.id]);break;case"pong":this.commands[t.id].resolve(),delete this.commands[t.id]}},n.prototype._handleClose=function(){var n=this;if(Object.keys(this.commands).forEach(function(e){var t=n.commands[e].reject;t&&t({type:"result",success:!1,error:{code:3,message:"Connection lost"}})}),!this.closeRequested){this.fireEvent("disconnected");var s=Object.assign({},this.options,{setupRetry:0}),i=function(o){setTimeout(function(){return e(n,void 0,void 0,function(){var e,n;return t(this,function(t){switch(t.label){case 0:t.label=1;case 1:return t.trys.push([1,3,,4]),[4,s.createSocket(s)];case 2:return e=t.sent(),this.setSocket(e),[3,4];case 3:return(n=t.sent())===r?this.fireEvent("reconnect-error",n):i(o+1),[3,4];case 4:return[2]}})})},1e3*Math.min(o,5))};i(0)}},n.prototype._genCmdId=function(){return++this.commandId},n}();function a(e,t,n,r){n+=(n.includes("?")?"&":"?")+"auth_callback=1",document.location.href=function(e,t,n,r){var s=e+"/auth/authorize?response_type=code&client_id="+encodeURIComponent(t)+"&redirect_uri="+encodeURIComponent(n);return r&&(s+="&state="+encodeURIComponent(r)),s}(e,t,n,r)}function u(n,s,i){return e(this,void 0,void 0,function(){var e,o,c;return t(this,function(t){switch(t.label){case 0:return(e=new FormData).append("client_id",s),Object.keys(i).forEach(function(t){e.append(t,i[t])}),[4,fetch(n+"/auth/token",{method:"POST",credentials:"same-origin",body:e})];case 1:if(!(o=t.sent()).ok)throw 400===o.status||403===o.status?r:new Error("Unable to fetch tokens");return[4,o.json()];case 2:return(c=t.sent()).hassUrl=n,c.clientId=s,c.expires=1e3*c.expires_in+Date.now(),[2,c]}})})}var h=function(){function n(e,t){this.data=e,this._saveTokens=t}return Object.defineProperty(n.prototype,"wsUrl",{get:function(){return"ws"+this.data.hassUrl.substr(4)+"/api/websocket"},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"accessToken",{get:function(){return this.data.access_token},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"expired",{get:function(){return Date.now()>this.data.expires},enumerable:!0,configurable:!0}),n.prototype.refreshAccessToken=function(){return e(this,void 0,void 0,function(){var e;return t(this,function(t){switch(t.label){case 0:return[4,u(this.data.hassUrl,this.data.clientId,{grant_type:"refresh_token",refresh_token:this.data.refresh_token})];case 1:return(e=t.sent()).refresh_token=this.data.refresh_token,this.data=e,this._saveTokens&&this._saveTokens(e),[2]}})})},n.prototype.revoke=function(){return e(this,void 0,void 0,function(){var e;return t(this,function(t){switch(t.label){case 0:return(e=new FormData).append("action","revoke"),e.append("token",this.data.refresh_token),[4,fetch(this.data.hassUrl+"/auth/token",{method:"POST",credentials:"same-origin",body:e})];case 1:return t.sent(),this._saveTokens&&this._saveTokens(null),[2]}})})},n}();var l=function(){function e(e){this._noSub=e,this.listeners=[]}return e.prototype.action=function(e){var t=this,n=function(e){return t.setState(e,!1)};return function(){for(var r=[],s=0;s<arguments.length;s++)r[s]=arguments[s];var i=e.apply(void 0,[t.state].concat(r));if(null!=i)return"then"in i?i.then(n):n(i)}},e.prototype.setState=function(e,t){this.state=t?e:Object.assign({},this.state,e);for(var n=this.listeners,r=0;r<n.length;r++)n[r](this.state)},e.prototype.subscribe=function(e){var t=this;return this.listeners.push(e),void 0!==this.state&&e(this.state),function(){t.unsubscribe(e)}},e.prototype.unsubscribe=function(e){for(var t=e,n=[],r=this.listeners,s=0;s<r.length;s++)r[s]===t?t=null:n.push(r[s]);this.listeners=n,0===n.length&&this._noSub()},e}();function d(n,r,s,i,o){if(n in i)return i[n](o);var c,a=new l(function(){c&&c.then(function(e){return e()}),i.removeEventListener("ready",u),delete i[n]});function u(){return e(this,void 0,void 0,function(){var e,n;return t(this,function(t){switch(t.label){case 0:return n=(e=a).setState,[4,r(i)];case 1:return n.apply(e,[t.sent(),!0]),[2]}})})}return i[n]=function(e){return a.subscribe(e)},s&&(c=s(i,a)),i.addEventListener("ready",u),u(),a.subscribe(o)}var f=function(e){return e.sendMessagePromise({type:"get_states"})},v=function(e){return e.sendMessagePromise({type:"get_services"})},p=function(e){return e.sendMessagePromise({type:"get_config"})};function b(e,t){return void 0===e?null:{components:e.components.concat(t.data.component)}}var m=function(e){return p(e)},y=function(e,t){return e.subscribeEvents(t.action(b),"component_loaded")};function g(e,t){var n,r;if(void 0===e)return null;var s=t.data,i=s.domain,o=Object.assign({},e[i],((n={})[s.service]={description:"",fields:{}},n));return(r={})[i]=o,r}function _(e,t){var n;if(void 0===e)return null;var r=t.data,s=r.domain,i=r.service,o=e[s];if(!(o&&i in o))return null;var c={};return Object.keys(o).forEach(function(e){e!==i&&(c[e]=o[e])}),(n={})[s]=c,n}var k=function(e){return v(e)},w=function(e,t){return Promise.all([e.subscribeEvents(t.action(g),"service_registered"),e.subscribeEvents(t.action(_),"service_removed")]).then(function(e){return function(){return e.forEach(function(e){return e()})}})};function E(n){return e(this,void 0,void 0,function(){var e,r,s,i;return t(this,function(t){switch(t.label){case 0:return[4,f(n)];case 1:for(e=t.sent(),r={},s=0;s<e.length;s++)r[(i=e[s]).entity_id]=i;return[2,r]}})})}var S=function(e,t){return e.subscribeEvents(function(e){return function(e,t){var n,r=e.state;if(void 0!==r){var s=t.data,i=s.entity_id,o=s.new_state;if(o)e.setState(((n={})[o.entity_id]=o,n));else{var c=Object.assign({},r);delete c[i],e.setState(c,!0)}}}(t,e)},"state_changed")},x={setupRetry:0,createSocket:function(c){if(!c.auth)throw s;var a=c.auth,u=a.wsUrl;return new Promise(function(s,h){return function s(c,h,l){var d=this,f=new WebSocket(u),v=!1,p=function(){if(f.removeEventListener("close",p),v)l(r);else if(0!==c){var e=-1===c?-1:c-1;setTimeout(function(){return s(e,h,l)},1e3)}else l(n)},b=function(n){return e(d,void 0,void 0,function(){var e;return t(this,function(t){switch(t.label){case 0:return t.trys.push([0,3,,4]),a.expired?[4,a.refreshAccessToken()]:[3,2];case 1:t.sent(),t.label=2;case 2:return f.send(JSON.stringify({type:"auth",access_token:a.accessToken})),[3,4];case 3:return e=t.sent(),v=e===r,f.close(),[3,4];case 4:return[2]}})})},m=function(n){return e(d,void 0,void 0,function(){return t(this,function(e){switch(JSON.parse(n.data).type){case i:v=!0,f.close();break;case o:f.removeEventListener("open",b),f.removeEventListener("message",m),f.removeEventListener("close",p),f.removeEventListener("error",p),h(f)}return[2]})})};f.addEventListener("open",b),f.addEventListener("message",m),f.addEventListener("close",p),f.addEventListener("error",p)}(c.setupRetry,s,h)})}};exports.createConnection=function(n){return e(this,void 0,void 0,function(){var e,r;return t(this,function(t){switch(t.label){case 0:return[4,(e=Object.assign({},x,n)).createSocket(e)];case 1:return r=t.sent(),[2,new c(r,e)]}})})},exports.Auth=h,exports.getAuth=function(n){return void 0===n&&(n={}),e(this,void 0,void 0,function(){var e,r,i,o,c,l,d;return t(this,function(t){switch(t.label){case 0:if(!("auth_callback"in(r=function(e){for(var t={},n=e.split("&"),r=0;r<n.length;r++){var s=n[r].split("="),i=decodeURIComponent(s[0]),o=s.length>1?decodeURIComponent(s[1]):void 0;t[i]=o}return t}(location.search.substr(1)))))return[3,4];i=JSON.parse(atob(r.state)),t.label=1;case 1:return t.trys.push([1,3,,4]),[4,function(e,t,n){return u(e,t,{code:n,grant_type:"authorization_code"})}(i.hassUrl,i.clientId,r.code)];case 2:return e=t.sent(),n.saveTokens&&n.saveTokens(e),[3,4];case 3:return o=t.sent(),console.log("Unable to fetch access token",o),[3,4];case 4:return e||!n.loadTokens?[3,6]:[4,n.loadTokens()];case 5:e=t.sent(),t.label=6;case 6:if(e)return[2,new h(e,n.saveTokens)];if(void 0===(c=n.hassUrl))throw s;return"/"===c[c.length-1]&&(c=c.substr(0,c.length-1)),l=n.clientId||location.protocol+"//"+location.host+"/",d=n.redirectUrl||location.protocol+"//"+location.host+location.pathname+location.search,a(c,l,d,function(e){return btoa(JSON.stringify(e))}({hassUrl:c,clientId:l})),[2,new Promise(function(){})]}})})},exports.createCollection=d,exports.Connection=c,exports.subscribeConfig=function(e,t){return d("_cnf",m,y,e,t)},exports.subscribeServices=function(e,t){return d("_srv",k,w,e,t)},exports.subscribeEntities=function(e,t){return d("_ent",E,S,e,t)},exports.ERR_CANNOT_CONNECT=n,exports.ERR_INVALID_AUTH=r,exports.ERR_CONNECTION_LOST=3,exports.ERR_HASS_HOST_REQUIRED=s,exports.getStates=f,exports.getServices=v,exports.getConfig=p,exports.getUser=function(e){return e.sendMessagePromise({type:"auth/current_user"})},exports.callService=function(e,t,n,r){return e.sendMessagePromise(function(e,t,n){var r={type:"call_service",domain:e,service:t};return n&&(r.service_data=n),r}(t,n,r))}; | ||
function e(e,t,n,r){return new(n||(n=Promise))(function(s,o){function i(e){try{a(r.next(e))}catch(e){o(e)}}function c(e){try{a(r.throw(e))}catch(e){o(e)}}function a(e){e.done?s(e.value):new n(function(t){t(e.value)}).then(i,c)}a((r=r.apply(e,t||[])).next())})}function t(e,t){var n,r,s,o,i={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return o={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function c(o){return function(c){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(s=2&o[0]?r.return:o[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,o[1])).done)return s;switch(r=0,s&&(o=[2&o[0],s.value]),o[0]){case 0:case 1:s=o;break;case 4:return i.label++,{value:o[1],done:!1};case 5:i.label++,r=o[1],o=[0];continue;case 7:o=i.ops.pop(),i.trys.pop();continue;default:if(!(s=(s=i.trys).length>0&&s[s.length-1])&&(6===o[0]||2===o[0])){i=0;continue}if(3===o[0]&&(!s||o[1]>s[0]&&o[1]<s[3])){i.label=o[1];break}if(6===o[0]&&i.label<s[1]){i.label=s[1],s=o;break}if(s&&i.label<s[2]){i.label=s[2],i.ops.push(o);break}s[2]&&i.ops.pop(),i.trys.pop();continue}o=t.call(e,i)}catch(e){o=[6,e],r=0}finally{n=s=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,c])}}}var n=1,r=2,s=4;var o="auth_invalid",i="auth_ok";var c=function(){function n(e,t){this.options=t,this.commandId=1,this.commands={},this.eventListeners={},this.closeRequested=!1,this.setSocket(e)}return n.prototype.setSocket=function(e){var t=this,n=this.socket;if(this.socket=e,e.addEventListener("message",function(e){return t._handleMessage(e)}),e.addEventListener("close",function(e){return t._handleClose(e)}),n){var r=this.commands;this.commandId=1,this.commands={},Object.keys(r).forEach(function(e){var n=r[e];"eventCallback"in n&&t.subscribeEvents(n.eventCallback,n.eventType).then(function(e){n.unsubscribe=e,n.resolve()})}),this.fireEvent("ready")}},n.prototype.addEventListener=function(e,t){var n=this.eventListeners[e];n||(n=this.eventListeners[e]=[]),n.push(t)},n.prototype.removeEventListener=function(e,t){var n=this.eventListeners[e];if(n){var r=n.indexOf(t);-1!==r&&n.splice(r,1)}},n.prototype.fireEvent=function(e,t){var n=this;(this.eventListeners[e]||[]).forEach(function(e){return e(n,t)})},n.prototype.close=function(){this.closeRequested=!0,this.socket.close()},n.prototype.subscribeEvents=function(n,r){return e(this,void 0,void 0,function(){var s,o,i=this;return t(this,function(c){switch(c.label){case 0:return s=this._genCmdId(),[4,new Promise(function(c,a){o=i.commands[s]={resolve:c,reject:a,eventCallback:n,eventType:r,unsubscribe:function(){return e(i,void 0,void 0,function(){return t(this,function(e){switch(e.label){case 0:return[4,this.sendMessagePromise((t=s,{type:"unsubscribe_events",subscription:t}))];case 1:return e.sent(),delete this.commands[s],[2]}var t})})}};try{i.sendMessage(function(e){var t={type:"subscribe_events"};return e&&(t.event_type=e),t}(r),s)}catch(e){}})];case 1:return c.sent(),[2,function(){return o.unsubscribe()}]}})})},n.prototype.ping=function(){return this.sendMessagePromise({type:"ping"})},n.prototype.sendMessage=function(e,t){t||(t=this._genCmdId()),e.id=t,this.socket.send(JSON.stringify(e))},n.prototype.sendMessagePromise=function(e){var t=this;return new Promise(function(n,r){var s=t._genCmdId();t.commands[s]={resolve:n,reject:r},t.sendMessage(e,s)})},n.prototype._handleMessage=function(e){var t=JSON.parse(e.data);switch(t.type){case"event":this.commands[t.id].eventCallback(t.event);break;case"result":if(t.id in this.commands){var n=this.commands[t.id];t.success?(n.resolve(t.result),"eventCallback"in n||delete this.commands[t.id]):(n.reject(t.error),delete this.commands[t.id])}break;case"pong":this.commands[t.id].resolve(),delete this.commands[t.id]}},n.prototype._handleClose=function(n){var s=this;if(Object.keys(this.commands).forEach(function(e){var t=s.commands[e];"reject"in t&&t.reject({type:"result",success:!1,error:{code:3,message:"Connection lost"}})}),!this.closeRequested){this.fireEvent("disconnected");var o=Object.assign({},this.options,{setupRetry:0}),i=function(n){setTimeout(function(){return e(s,void 0,void 0,function(){var e,s;return t(this,function(t){switch(t.label){case 0:t.label=1;case 1:return t.trys.push([1,3,,4]),[4,o.createSocket(o)];case 2:return e=t.sent(),this.setSocket(e),[3,4];case 3:return(s=t.sent())===r?this.fireEvent("reconnect-error",s):i(n+1),[3,4];case 4:return[2]}})})},1e3*Math.min(n,5))};i(0)}},n.prototype._genCmdId=function(){return++this.commandId},n}();function a(e,t,n,r){n+=(n.includes("?")?"&":"?")+"auth_callback=1",document.location.href=function(e,t,n,r){var s=e+"/auth/authorize?response_type=code&client_id="+encodeURIComponent(t)+"&redirect_uri="+encodeURIComponent(n);return r&&(s+="&state="+encodeURIComponent(r)),s}(e,t,n,r)}function u(n,s,o){return e(this,void 0,void 0,function(){var e,i,c;return t(this,function(t){switch(t.label){case 0:return(e=new FormData).append("client_id",s),Object.keys(o).forEach(function(t){e.append(t,o[t])}),[4,fetch(n+"/auth/token",{method:"POST",credentials:"same-origin",body:e})];case 1:if(!(i=t.sent()).ok)throw 400===i.status||403===i.status?r:new Error("Unable to fetch tokens");return[4,i.json()];case 2:return(c=t.sent()).hassUrl=n,c.clientId=s,c.expires=1e3*c.expires_in+Date.now(),[2,c]}})})}var h=function(){function n(e,t){this.data=e,this._saveTokens=t}return Object.defineProperty(n.prototype,"wsUrl",{get:function(){return"ws"+this.data.hassUrl.substr(4)+"/api/websocket"},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"accessToken",{get:function(){return this.data.access_token},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"expired",{get:function(){return Date.now()>this.data.expires},enumerable:!0,configurable:!0}),n.prototype.refreshAccessToken=function(){return e(this,void 0,void 0,function(){var e;return t(this,function(t){switch(t.label){case 0:return[4,u(this.data.hassUrl,this.data.clientId,{grant_type:"refresh_token",refresh_token:this.data.refresh_token})];case 1:return(e=t.sent()).refresh_token=this.data.refresh_token,this.data=e,this._saveTokens&&this._saveTokens(e),[2]}})})},n.prototype.revoke=function(){return e(this,void 0,void 0,function(){var e;return t(this,function(t){switch(t.label){case 0:return(e=new FormData).append("action","revoke"),e.append("token",this.data.refresh_token),[4,fetch(this.data.hassUrl+"/auth/token",{method:"POST",credentials:"same-origin",body:e})];case 1:return t.sent(),this._saveTokens&&this._saveTokens(null),[2]}})})},n}();var l=function(){function e(e){this._noSub=e,this.listeners=[]}return e.prototype.action=function(e){var t=this,n=function(e){return t.setState(e,!1)};return function(){for(var r=[],s=0;s<arguments.length;s++)r[s]=arguments[s];var o=e.apply(void 0,[t.state].concat(r));if(null!=o)return"then"in o?o.then(n):n(o)}},e.prototype.setState=function(e,t){this.state=t?e:Object.assign({},this.state,e);for(var n=this.listeners,r=0;r<n.length;r++)n[r](this.state)},e.prototype.subscribe=function(e){var t=this;return this.listeners.push(e),void 0!==this.state&&e(this.state),function(){t.unsubscribe(e)}},e.prototype.unsubscribe=function(e){for(var t=e,n=[],r=this.listeners,s=0;s<r.length;s++)r[s]===t?t=null:n.push(r[s]);this.listeners=n,0===n.length&&this._noSub()},e}();function f(n,r,s,o,i){var c,a=this;if(n in o)return o[n](i);var u=new l(function(){c&&c.then(function(e){return e()}),o.removeEventListener("ready",h),delete o[n]});o[n]=function(e){return u.subscribe(e)},s&&(c=s(o,u));var h=function(){return e(a,void 0,void 0,function(){var e,n,s;return t(this,function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),n=(e=u).setState,[4,r(o)];case 1:return n.apply(e,[t.sent(),!0]),[3,3];case 2:if(s=t.sent(),o.socket.readyState==o.socket.OPEN)throw s;return[3,3];case 3:return[2]}})})};return o.addEventListener("ready",h),h(),u.subscribe(i)}var d=function(e){return e.sendMessagePromise({type:"get_states"})},v=function(e){return e.sendMessagePromise({type:"get_services"})},p=function(e){return e.sendMessagePromise({type:"get_config"})};function b(e,t){return void 0===e?null:{components:e.components.concat(t.data.component)}}var m=function(e){return p(e)},y=function(e,t){return e.subscribeEvents(t.action(b),"component_loaded")};function g(e,t){var n,r;if(void 0===e)return null;var s=t.data,o=s.domain,i=Object.assign({},e[o],((n={})[s.service]={description:"",fields:{}},n));return(r={})[o]=i,r}function _(e,t){var n;if(void 0===e)return null;var r=t.data,s=r.domain,o=r.service,i=e[s];if(!(i&&o in i))return null;var c={};return Object.keys(i).forEach(function(e){e!==o&&(c[e]=i[e])}),(n={})[s]=c,n}var k=function(e){return v(e)},w=function(e,t){return Promise.all([e.subscribeEvents(t.action(g),"service_registered"),e.subscribeEvents(t.action(_),"service_removed")]).then(function(e){return function(){return e.forEach(function(e){return e()})}})};function E(n){return e(this,void 0,void 0,function(){var e,r,s,o;return t(this,function(t){switch(t.label){case 0:return[4,d(n)];case 1:for(e=t.sent(),r={},s=0;s<e.length;s++)r[(o=e[s]).entity_id]=o;return[2,r]}})})}var S=function(e,t){return e.subscribeEvents(function(e){return function(e,t){var n,r=e.state;if(void 0!==r){var s=t.data,o=s.entity_id,i=s.new_state;if(i)e.setState(((n={})[i.entity_id]=i,n));else{var c=Object.assign({},r);delete c[o],e.setState(c,!0)}}}(t,e)},"state_changed")},x={setupRetry:0,createSocket:function(c){if(!c.auth)throw s;var a=c.auth,u=a.wsUrl;return new Promise(function(s,h){return function s(c,h,l){var f=this,d=new WebSocket(u),v=!1,p=function(){if(d.removeEventListener("close",p),v)l(r);else if(0!==c){var e=-1===c?-1:c-1;setTimeout(function(){return s(e,h,l)},1e3)}else l(n)},b=function(n){return e(f,void 0,void 0,function(){var e;return t(this,function(t){switch(t.label){case 0:return t.trys.push([0,3,,4]),a.expired?[4,a.refreshAccessToken()]:[3,2];case 1:t.sent(),t.label=2;case 2:return d.send(JSON.stringify({type:"auth",access_token:a.accessToken})),[3,4];case 3:return e=t.sent(),v=e===r,d.close(),[3,4];case 4:return[2]}})})},m=function(n){return e(f,void 0,void 0,function(){return t(this,function(e){switch(JSON.parse(n.data).type){case o:v=!0,d.close();break;case i:d.removeEventListener("open",b),d.removeEventListener("message",m),d.removeEventListener("close",p),d.removeEventListener("error",p),h(d)}return[2]})})};d.addEventListener("open",b),d.addEventListener("message",m),d.addEventListener("close",p),d.addEventListener("error",p)}(c.setupRetry,s,h)})}};exports.createConnection=function(n){return e(this,void 0,void 0,function(){var e,r;return t(this,function(t){switch(t.label){case 0:return[4,(e=Object.assign({},x,n)).createSocket(e)];case 1:return r=t.sent(),[2,new c(r,e)]}})})},exports.Auth=h,exports.getAuth=function(n){return void 0===n&&(n={}),e(this,void 0,void 0,function(){var e,r,o,i,c,l,f;return t(this,function(t){switch(t.label){case 0:if(!("auth_callback"in(r=function(e){for(var t={},n=e.split("&"),r=0;r<n.length;r++){var s=n[r].split("="),o=decodeURIComponent(s[0]),i=s.length>1?decodeURIComponent(s[1]):void 0;t[o]=i}return t}(location.search.substr(1)))))return[3,4];o=JSON.parse(atob(r.state)),t.label=1;case 1:return t.trys.push([1,3,,4]),[4,function(e,t,n){return u(e,t,{code:n,grant_type:"authorization_code"})}(o.hassUrl,o.clientId,r.code)];case 2:return e=t.sent(),n.saveTokens&&n.saveTokens(e),[3,4];case 3:return i=t.sent(),console.log("Unable to fetch access token",i),[3,4];case 4:return e||!n.loadTokens?[3,6]:[4,n.loadTokens()];case 5:e=t.sent(),t.label=6;case 6:if(e)return[2,new h(e,n.saveTokens)];if(void 0===(c=n.hassUrl))throw s;return"/"===c[c.length-1]&&(c=c.substr(0,c.length-1)),l=n.clientId||location.protocol+"//"+location.host+"/",f=n.redirectUrl||location.protocol+"//"+location.host+location.pathname+location.search,a(c,l,f,function(e){return btoa(JSON.stringify(e))}({hassUrl:c,clientId:l})),[2,new Promise(function(){})]}})})},exports.createCollection=f,exports.Connection=c,exports.subscribeConfig=function(e,t){return f("_cnf",m,y,e,t)},exports.subscribeServices=function(e,t){return f("_srv",k,w,e,t)},exports.subscribeEntities=function(e,t){return f("_ent",E,S,e,t)},exports.ERR_CANNOT_CONNECT=n,exports.ERR_INVALID_AUTH=r,exports.ERR_CONNECTION_LOST=3,exports.ERR_HASS_HOST_REQUIRED=s,exports.getStates=d,exports.getServices=v,exports.getConfig=p,exports.getUser=function(e){return e.sendMessagePromise({type:"auth/current_user"})},exports.callService=function(e,t,n,r){return e.sendMessagePromise(function(e,t,n){var r={type:"call_service",domain:e,service:t};return n&&(r.service_data=n),r}(t,n,r))}; | ||
//# sourceMappingURL=haws.js.map |
@@ -1,2 +0,2 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(e.HAWS={})}(this,function(e){function t(e,t,n,r){return new(n||(n=Promise))(function(s,i){function o(e){try{a(r.next(e))}catch(e){i(e)}}function c(e){try{a(r.throw(e))}catch(e){i(e)}}function a(e){e.done?s(e.value):new n(function(t){t(e.value)}).then(o,c)}a((r=r.apply(e,t||[])).next())})}function n(e,t){var n,r,s,i,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(i){return function(c){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(s=2&i[0]?r.return:i[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,i[1])).done)return s;switch(r=0,s&&(i=[2&i[0],s.value]),i[0]){case 0:case 1:s=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(s=(s=o.trys).length>0&&s[s.length-1])&&(6===i[0]||2===i[0])){o=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){o.label=i[1];break}if(6===i[0]&&o.label<s[1]){o.label=s[1],s=i;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(i);break}s[2]&&o.ops.pop(),o.trys.pop();continue}i=t.call(e,o)}catch(e){i=[6,e],r=0}finally{n=s=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,c])}}}var r=1,s=2,i=4;var o="auth_invalid",c="auth_ok";var a=function(){function e(e,t){this.options=t,this.commandId=1,this.commands={},this.eventListeners={},this.closeRequested=!1,this._handleClose=this._handleClose.bind(this),this.setSocket(e)}return e.prototype.setSocket=function(e){var t=this,n=this.socket;if(this.socket=e,e.addEventListener("message",function(e){return t._handleMessage(e)}),e.addEventListener("close",this._handleClose),n){var r=this.commands;this.commandId=1,this.commands={},Object.keys(r).forEach(function(e){var n=r[e];n.eventCallback&&t.subscribeEvents(n.eventCallback,n.eventType).then(function(e){n.unsubscribe=e})}),this.fireEvent("ready")}},e.prototype.addEventListener=function(e,t){var n=this.eventListeners[e];n||(n=this.eventListeners[e]=[]),n.push(t)},e.prototype.removeEventListener=function(e,t){var n=this.eventListeners[e];if(n){var r=n.indexOf(t);-1!==r&&n.splice(r,1)}},e.prototype.fireEvent=function(e,t){var n=this;(this.eventListeners[e]||[]).forEach(function(e){return e(n,t)})},e.prototype.close=function(){this.closeRequested=!0,this.socket.close()},e.prototype.subscribeEvents=function(e,r){return t(this,void 0,void 0,function(){var s,i,o=this;return n(this,function(c){switch(c.label){case 0:return s=this._genCmdId(),[4,this.sendMessagePromise(function(e){var t={type:"subscribe_events"};return e&&(t.event_type=e),t}(r),s)];case 1:return c.sent(),this.commands[s]=i={eventCallback:e,eventType:r,unsubscribe:function(){return t(o,void 0,void 0,function(){return n(this,function(e){switch(e.label){case 0:return[4,this.sendMessagePromise((t=s,{type:"unsubscribe_events",subscription:t}))];case 1:return e.sent(),delete this.commands[s],[2]}var t})})}},[2,function(){return i.unsubscribe()}]}})})},e.prototype.ping=function(){return this.sendMessagePromise({type:"ping"})},e.prototype.sendMessage=function(e,t){t||(t=this._genCmdId()),e.id=t,this.socket.send(JSON.stringify(e))},e.prototype.sendMessagePromise=function(e,t){var n=this;return new Promise(function(r,s){t||(t=n._genCmdId()),n.commands[t]={resolve:r,reject:s},n.sendMessage(e,t)})},e.prototype._handleMessage=function(e){var t=JSON.parse(e.data);switch(t.type){case"event":this.commands[t.id].eventCallback(t.event);break;case"result":t.id in this.commands&&(1==t.success?this.commands[t.id].resolve(t.result):this.commands[t.id].reject(t.error),delete this.commands[t.id]);break;case"pong":this.commands[t.id].resolve(),delete this.commands[t.id]}},e.prototype._handleClose=function(){var e=this;if(Object.keys(this.commands).forEach(function(t){var n=e.commands[t].reject;n&&n({type:"result",success:!1,error:{code:3,message:"Connection lost"}})}),!this.closeRequested){this.fireEvent("disconnected");var r=Object.assign({},this.options,{setupRetry:0}),i=function(o){setTimeout(function(){return t(e,void 0,void 0,function(){var e,t;return n(this,function(n){switch(n.label){case 0:n.label=1;case 1:return n.trys.push([1,3,,4]),[4,r.createSocket(r)];case 2:return e=n.sent(),this.setSocket(e),[3,4];case 3:return(t=n.sent())===s?this.fireEvent("reconnect-error",t):i(o+1),[3,4];case 4:return[2]}})})},1e3*Math.min(o,5))};i(0)}},e.prototype._genCmdId=function(){return++this.commandId},e}();function u(e,t,n,r){n+=(n.includes("?")?"&":"?")+"auth_callback=1",document.location.href=function(e,t,n,r){var s=e+"/auth/authorize?response_type=code&client_id="+encodeURIComponent(t)+"&redirect_uri="+encodeURIComponent(n);return r&&(s+="&state="+encodeURIComponent(r)),s}(e,t,n,r)}function h(e,r,i){return t(this,void 0,void 0,function(){var t,o,c;return n(this,function(n){switch(n.label){case 0:return(t=new FormData).append("client_id",r),Object.keys(i).forEach(function(e){t.append(e,i[e])}),[4,fetch(e+"/auth/token",{method:"POST",credentials:"same-origin",body:t})];case 1:if(!(o=n.sent()).ok)throw 400===o.status||403===o.status?s:new Error("Unable to fetch tokens");return[4,o.json()];case 2:return(c=n.sent()).hassUrl=e,c.clientId=r,c.expires=1e3*c.expires_in+Date.now(),[2,c]}})})}var d=function(){function e(e,t){this.data=e,this._saveTokens=t}return Object.defineProperty(e.prototype,"wsUrl",{get:function(){return"ws"+this.data.hassUrl.substr(4)+"/api/websocket"},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"accessToken",{get:function(){return this.data.access_token},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"expired",{get:function(){return Date.now()>this.data.expires},enumerable:!0,configurable:!0}),e.prototype.refreshAccessToken=function(){return t(this,void 0,void 0,function(){var e;return n(this,function(t){switch(t.label){case 0:return[4,h(this.data.hassUrl,this.data.clientId,{grant_type:"refresh_token",refresh_token:this.data.refresh_token})];case 1:return(e=t.sent()).refresh_token=this.data.refresh_token,this.data=e,this._saveTokens&&this._saveTokens(e),[2]}})})},e.prototype.revoke=function(){return t(this,void 0,void 0,function(){var e;return n(this,function(t){switch(t.label){case 0:return(e=new FormData).append("action","revoke"),e.append("token",this.data.refresh_token),[4,fetch(this.data.hassUrl+"/auth/token",{method:"POST",credentials:"same-origin",body:e})];case 1:return t.sent(),this._saveTokens&&this._saveTokens(null),[2]}})})},e}();var f=function(){function e(e){this._noSub=e,this.listeners=[]}return e.prototype.action=function(e){var t=this,n=function(e){return t.setState(e,!1)};return function(){for(var r=[],s=0;s<arguments.length;s++)r[s]=arguments[s];var i=e.apply(void 0,[t.state].concat(r));if(null!=i)return"then"in i?i.then(n):n(i)}},e.prototype.setState=function(e,t){this.state=t?e:Object.assign({},this.state,e);for(var n=this.listeners,r=0;r<n.length;r++)n[r](this.state)},e.prototype.subscribe=function(e){var t=this;return this.listeners.push(e),void 0!==this.state&&e(this.state),function(){t.unsubscribe(e)}},e.prototype.unsubscribe=function(e){for(var t=e,n=[],r=this.listeners,s=0;s<r.length;s++)r[s]===t?t=null:n.push(r[s]);this.listeners=n,0===n.length&&this._noSub()},e}();function l(e,r,s,i,o){if(e in i)return i[e](o);var c,a=new f(function(){c&&c.then(function(e){return e()}),i.removeEventListener("ready",u),delete i[e]});function u(){return t(this,void 0,void 0,function(){var e,t;return n(this,function(n){switch(n.label){case 0:return t=(e=a).setState,[4,r(i)];case 1:return t.apply(e,[n.sent(),!0]),[2]}})})}return i[e]=function(e){return a.subscribe(e)},s&&(c=s(i,a)),i.addEventListener("ready",u),u(),a.subscribe(o)}var v=function(e){return e.sendMessagePromise({type:"get_states"})},p=function(e){return e.sendMessagePromise({type:"get_services"})},b=function(e){return e.sendMessagePromise({type:"get_config"})};function m(e,t){return void 0===e?null:{components:e.components.concat(t.data.component)}}var y=function(e){return b(e)},g=function(e,t){return e.subscribeEvents(t.action(m),"component_loaded")};function _(e,t){var n,r;if(void 0===e)return null;var s=t.data,i=s.domain,o=Object.assign({},e[i],((n={})[s.service]={description:"",fields:{}},n));return(r={})[i]=o,r}function k(e,t){var n;if(void 0===e)return null;var r=t.data,s=r.domain,i=r.service,o=e[s];if(!(o&&i in o))return null;var c={};return Object.keys(o).forEach(function(e){e!==i&&(c[e]=o[e])}),(n={})[s]=c,n}var w=function(e){return p(e)},E=function(e,t){return Promise.all([e.subscribeEvents(t.action(_),"service_registered"),e.subscribeEvents(t.action(k),"service_removed")]).then(function(e){return function(){return e.forEach(function(e){return e()})}})};function S(e){return t(this,void 0,void 0,function(){var t,r,s,i;return n(this,function(n){switch(n.label){case 0:return[4,v(e)];case 1:for(t=n.sent(),r={},s=0;s<t.length;s++)r[(i=t[s]).entity_id]=i;return[2,r]}})})}var C=function(e,t){return e.subscribeEvents(function(e){return function(e,t){var n,r=e.state;if(void 0!==r){var s=t.data,i=s.entity_id,o=s.new_state;if(o)e.setState(((n={})[o.entity_id]=o,n));else{var c=Object.assign({},r);delete c[i],e.setState(c,!0)}}}(t,e)},"state_changed")},O={setupRetry:0,createSocket:function(e){if(!e.auth)throw i;var a=e.auth,u=a.wsUrl;return new Promise(function(i,h){return function e(i,h,d){var f=this,l=new WebSocket(u),v=!1,p=function(){if(l.removeEventListener("close",p),v)d(s);else if(0!==i){var t=-1===i?-1:i-1;setTimeout(function(){return e(t,h,d)},1e3)}else d(r)},b=function(e){return t(f,void 0,void 0,function(){var e;return n(this,function(t){switch(t.label){case 0:return t.trys.push([0,3,,4]),a.expired?[4,a.refreshAccessToken()]:[3,2];case 1:t.sent(),t.label=2;case 2:return l.send(JSON.stringify({type:"auth",access_token:a.accessToken})),[3,4];case 3:return e=t.sent(),v=e===s,l.close(),[3,4];case 4:return[2]}})})},m=function(e){return t(f,void 0,void 0,function(){return n(this,function(t){switch(JSON.parse(e.data).type){case o:v=!0,l.close();break;case c:l.removeEventListener("open",b),l.removeEventListener("message",m),l.removeEventListener("close",p),l.removeEventListener("error",p),h(l)}return[2]})})};l.addEventListener("open",b),l.addEventListener("message",m),l.addEventListener("close",p),l.addEventListener("error",p)}(e.setupRetry,i,h)})}};e.createConnection=function(e){return t(this,void 0,void 0,function(){var t,r;return n(this,function(n){switch(n.label){case 0:return[4,(t=Object.assign({},O,e)).createSocket(t)];case 1:return r=n.sent(),[2,new a(r,t)]}})})},e.Auth=d,e.getAuth=function(e){return void 0===e&&(e={}),t(this,void 0,void 0,function(){var t,r,s,o,c,a,f;return n(this,function(n){switch(n.label){case 0:if(!("auth_callback"in(r=function(e){for(var t={},n=e.split("&"),r=0;r<n.length;r++){var s=n[r].split("="),i=decodeURIComponent(s[0]),o=s.length>1?decodeURIComponent(s[1]):void 0;t[i]=o}return t}(location.search.substr(1)))))return[3,4];s=JSON.parse(atob(r.state)),n.label=1;case 1:return n.trys.push([1,3,,4]),[4,function(e,t,n){return h(e,t,{code:n,grant_type:"authorization_code"})}(s.hassUrl,s.clientId,r.code)];case 2:return t=n.sent(),e.saveTokens&&e.saveTokens(t),[3,4];case 3:return o=n.sent(),console.log("Unable to fetch access token",o),[3,4];case 4:return t||!e.loadTokens?[3,6]:[4,e.loadTokens()];case 5:t=n.sent(),n.label=6;case 6:if(t)return[2,new d(t,e.saveTokens)];if(void 0===(c=e.hassUrl))throw i;return"/"===c[c.length-1]&&(c=c.substr(0,c.length-1)),a=e.clientId||location.protocol+"//"+location.host+"/",f=e.redirectUrl||location.protocol+"//"+location.host+location.pathname+location.search,u(c,a,f,function(e){return btoa(JSON.stringify(e))}({hassUrl:c,clientId:a})),[2,new Promise(function(){})]}})})},e.createCollection=l,e.Connection=a,e.subscribeConfig=function(e,t){return l("_cnf",y,g,e,t)},e.subscribeServices=function(e,t){return l("_srv",w,E,e,t)},e.subscribeEntities=function(e,t){return l("_ent",S,C,e,t)},e.ERR_CANNOT_CONNECT=r,e.ERR_INVALID_AUTH=s,e.ERR_CONNECTION_LOST=3,e.ERR_HASS_HOST_REQUIRED=i,e.getStates=v,e.getServices=p,e.getConfig=b,e.getUser=function(e){return e.sendMessagePromise({type:"auth/current_user"})},e.callService=function(e,t,n,r){return e.sendMessagePromise(function(e,t,n){var r={type:"call_service",domain:e,service:t};return n&&(r.service_data=n),r}(t,n,r))}}); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(e.HAWS={})}(this,function(e){function t(e,t,n,r){return new(n||(n=Promise))(function(s,i){function o(e){try{a(r.next(e))}catch(e){i(e)}}function c(e){try{a(r.throw(e))}catch(e){i(e)}}function a(e){e.done?s(e.value):new n(function(t){t(e.value)}).then(o,c)}a((r=r.apply(e,t||[])).next())})}function n(e,t){var n,r,s,i,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(i){return function(c){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(s=2&i[0]?r.return:i[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,i[1])).done)return s;switch(r=0,s&&(i=[2&i[0],s.value]),i[0]){case 0:case 1:s=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(s=(s=o.trys).length>0&&s[s.length-1])&&(6===i[0]||2===i[0])){o=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){o.label=i[1];break}if(6===i[0]&&o.label<s[1]){o.label=s[1],s=i;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(i);break}s[2]&&o.ops.pop(),o.trys.pop();continue}i=t.call(e,o)}catch(e){i=[6,e],r=0}finally{n=s=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,c])}}}var r=1,s=2,i=4;var o="auth_invalid",c="auth_ok";var a=function(){function e(e,t){this.options=t,this.commandId=1,this.commands={},this.eventListeners={},this.closeRequested=!1,this.setSocket(e)}return e.prototype.setSocket=function(e){var t=this,n=this.socket;if(this.socket=e,e.addEventListener("message",function(e){return t._handleMessage(e)}),e.addEventListener("close",function(e){return t._handleClose(e)}),n){var r=this.commands;this.commandId=1,this.commands={},Object.keys(r).forEach(function(e){var n=r[e];"eventCallback"in n&&t.subscribeEvents(n.eventCallback,n.eventType).then(function(e){n.unsubscribe=e,n.resolve()})}),this.fireEvent("ready")}},e.prototype.addEventListener=function(e,t){var n=this.eventListeners[e];n||(n=this.eventListeners[e]=[]),n.push(t)},e.prototype.removeEventListener=function(e,t){var n=this.eventListeners[e];if(n){var r=n.indexOf(t);-1!==r&&n.splice(r,1)}},e.prototype.fireEvent=function(e,t){var n=this;(this.eventListeners[e]||[]).forEach(function(e){return e(n,t)})},e.prototype.close=function(){this.closeRequested=!0,this.socket.close()},e.prototype.subscribeEvents=function(e,r){return t(this,void 0,void 0,function(){var s,i,o=this;return n(this,function(c){switch(c.label){case 0:return s=this._genCmdId(),[4,new Promise(function(c,a){i=o.commands[s]={resolve:c,reject:a,eventCallback:e,eventType:r,unsubscribe:function(){return t(o,void 0,void 0,function(){return n(this,function(e){switch(e.label){case 0:return[4,this.sendMessagePromise((t=s,{type:"unsubscribe_events",subscription:t}))];case 1:return e.sent(),delete this.commands[s],[2]}var t})})}};try{o.sendMessage(function(e){var t={type:"subscribe_events"};return e&&(t.event_type=e),t}(r),s)}catch(e){}})];case 1:return c.sent(),[2,function(){return i.unsubscribe()}]}})})},e.prototype.ping=function(){return this.sendMessagePromise({type:"ping"})},e.prototype.sendMessage=function(e,t){t||(t=this._genCmdId()),e.id=t,this.socket.send(JSON.stringify(e))},e.prototype.sendMessagePromise=function(e){var t=this;return new Promise(function(n,r){var s=t._genCmdId();t.commands[s]={resolve:n,reject:r},t.sendMessage(e,s)})},e.prototype._handleMessage=function(e){var t=JSON.parse(e.data);switch(t.type){case"event":this.commands[t.id].eventCallback(t.event);break;case"result":if(t.id in this.commands){var n=this.commands[t.id];t.success?(n.resolve(t.result),"eventCallback"in n||delete this.commands[t.id]):(n.reject(t.error),delete this.commands[t.id])}break;case"pong":this.commands[t.id].resolve(),delete this.commands[t.id]}},e.prototype._handleClose=function(e){var r=this;if(Object.keys(this.commands).forEach(function(e){var t=r.commands[e];"reject"in t&&t.reject({type:"result",success:!1,error:{code:3,message:"Connection lost"}})}),!this.closeRequested){this.fireEvent("disconnected");var i=Object.assign({},this.options,{setupRetry:0}),o=function(e){setTimeout(function(){return t(r,void 0,void 0,function(){var t,r;return n(this,function(n){switch(n.label){case 0:n.label=1;case 1:return n.trys.push([1,3,,4]),[4,i.createSocket(i)];case 2:return t=n.sent(),this.setSocket(t),[3,4];case 3:return(r=n.sent())===s?this.fireEvent("reconnect-error",r):o(e+1),[3,4];case 4:return[2]}})})},1e3*Math.min(e,5))};o(0)}},e.prototype._genCmdId=function(){return++this.commandId},e}();function u(e,t,n,r){n+=(n.includes("?")?"&":"?")+"auth_callback=1",document.location.href=function(e,t,n,r){var s=e+"/auth/authorize?response_type=code&client_id="+encodeURIComponent(t)+"&redirect_uri="+encodeURIComponent(n);return r&&(s+="&state="+encodeURIComponent(r)),s}(e,t,n,r)}function f(e,r,i){return t(this,void 0,void 0,function(){var t,o,c;return n(this,function(n){switch(n.label){case 0:return(t=new FormData).append("client_id",r),Object.keys(i).forEach(function(e){t.append(e,i[e])}),[4,fetch(e+"/auth/token",{method:"POST",credentials:"same-origin",body:t})];case 1:if(!(o=n.sent()).ok)throw 400===o.status||403===o.status?s:new Error("Unable to fetch tokens");return[4,o.json()];case 2:return(c=n.sent()).hassUrl=e,c.clientId=r,c.expires=1e3*c.expires_in+Date.now(),[2,c]}})})}var d=function(){function e(e,t){this.data=e,this._saveTokens=t}return Object.defineProperty(e.prototype,"wsUrl",{get:function(){return"ws"+this.data.hassUrl.substr(4)+"/api/websocket"},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"accessToken",{get:function(){return this.data.access_token},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"expired",{get:function(){return Date.now()>this.data.expires},enumerable:!0,configurable:!0}),e.prototype.refreshAccessToken=function(){return t(this,void 0,void 0,function(){var e;return n(this,function(t){switch(t.label){case 0:return[4,f(this.data.hassUrl,this.data.clientId,{grant_type:"refresh_token",refresh_token:this.data.refresh_token})];case 1:return(e=t.sent()).refresh_token=this.data.refresh_token,this.data=e,this._saveTokens&&this._saveTokens(e),[2]}})})},e.prototype.revoke=function(){return t(this,void 0,void 0,function(){var e;return n(this,function(t){switch(t.label){case 0:return(e=new FormData).append("action","revoke"),e.append("token",this.data.refresh_token),[4,fetch(this.data.hassUrl+"/auth/token",{method:"POST",credentials:"same-origin",body:e})];case 1:return t.sent(),this._saveTokens&&this._saveTokens(null),[2]}})})},e}();var h=function(){function e(e){this._noSub=e,this.listeners=[]}return e.prototype.action=function(e){var t=this,n=function(e){return t.setState(e,!1)};return function(){for(var r=[],s=0;s<arguments.length;s++)r[s]=arguments[s];var i=e.apply(void 0,[t.state].concat(r));if(null!=i)return"then"in i?i.then(n):n(i)}},e.prototype.setState=function(e,t){this.state=t?e:Object.assign({},this.state,e);for(var n=this.listeners,r=0;r<n.length;r++)n[r](this.state)},e.prototype.subscribe=function(e){var t=this;return this.listeners.push(e),void 0!==this.state&&e(this.state),function(){t.unsubscribe(e)}},e.prototype.unsubscribe=function(e){for(var t=e,n=[],r=this.listeners,s=0;s<r.length;s++)r[s]===t?t=null:n.push(r[s]);this.listeners=n,0===n.length&&this._noSub()},e}();function l(e,r,s,i,o){var c,a=this;if(e in i)return i[e](o);var u=new h(function(){c&&c.then(function(e){return e()}),i.removeEventListener("ready",f),delete i[e]});i[e]=function(e){return u.subscribe(e)},s&&(c=s(i,u));var f=function(){return t(a,void 0,void 0,function(){var e,t,s;return n(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),t=(e=u).setState,[4,r(i)];case 1:return t.apply(e,[n.sent(),!0]),[3,3];case 2:if(s=n.sent(),i.socket.readyState==i.socket.OPEN)throw s;return[3,3];case 3:return[2]}})})};return i.addEventListener("ready",f),f(),u.subscribe(o)}var v=function(e){return e.sendMessagePromise({type:"get_states"})},p=function(e){return e.sendMessagePromise({type:"get_services"})},b=function(e){return e.sendMessagePromise({type:"get_config"})};function m(e,t){return void 0===e?null:{components:e.components.concat(t.data.component)}}var y=function(e){return b(e)},g=function(e,t){return e.subscribeEvents(t.action(m),"component_loaded")};function _(e,t){var n,r;if(void 0===e)return null;var s=t.data,i=s.domain,o=Object.assign({},e[i],((n={})[s.service]={description:"",fields:{}},n));return(r={})[i]=o,r}function k(e,t){var n;if(void 0===e)return null;var r=t.data,s=r.domain,i=r.service,o=e[s];if(!(o&&i in o))return null;var c={};return Object.keys(o).forEach(function(e){e!==i&&(c[e]=o[e])}),(n={})[s]=c,n}var w=function(e){return p(e)},E=function(e,t){return Promise.all([e.subscribeEvents(t.action(_),"service_registered"),e.subscribeEvents(t.action(k),"service_removed")]).then(function(e){return function(){return e.forEach(function(e){return e()})}})};function S(e){return t(this,void 0,void 0,function(){var t,r,s,i;return n(this,function(n){switch(n.label){case 0:return[4,v(e)];case 1:for(t=n.sent(),r={},s=0;s<t.length;s++)r[(i=t[s]).entity_id]=i;return[2,r]}})})}var O=function(e,t){return e.subscribeEvents(function(e){return function(e,t){var n,r=e.state;if(void 0!==r){var s=t.data,i=s.entity_id,o=s.new_state;if(o)e.setState(((n={})[o.entity_id]=o,n));else{var c=Object.assign({},r);delete c[i],e.setState(c,!0)}}}(t,e)},"state_changed")},C={setupRetry:0,createSocket:function(e){if(!e.auth)throw i;var a=e.auth,u=a.wsUrl;return new Promise(function(i,f){return function e(i,f,d){var h=this,l=new WebSocket(u),v=!1,p=function(){if(l.removeEventListener("close",p),v)d(s);else if(0!==i){var t=-1===i?-1:i-1;setTimeout(function(){return e(t,f,d)},1e3)}else d(r)},b=function(e){return t(h,void 0,void 0,function(){var e;return n(this,function(t){switch(t.label){case 0:return t.trys.push([0,3,,4]),a.expired?[4,a.refreshAccessToken()]:[3,2];case 1:t.sent(),t.label=2;case 2:return l.send(JSON.stringify({type:"auth",access_token:a.accessToken})),[3,4];case 3:return e=t.sent(),v=e===s,l.close(),[3,4];case 4:return[2]}})})},m=function(e){return t(h,void 0,void 0,function(){return n(this,function(t){switch(JSON.parse(e.data).type){case o:v=!0,l.close();break;case c:l.removeEventListener("open",b),l.removeEventListener("message",m),l.removeEventListener("close",p),l.removeEventListener("error",p),f(l)}return[2]})})};l.addEventListener("open",b),l.addEventListener("message",m),l.addEventListener("close",p),l.addEventListener("error",p)}(e.setupRetry,i,f)})}};e.createConnection=function(e){return t(this,void 0,void 0,function(){var t,r;return n(this,function(n){switch(n.label){case 0:return[4,(t=Object.assign({},C,e)).createSocket(t)];case 1:return r=n.sent(),[2,new a(r,t)]}})})},e.Auth=d,e.getAuth=function(e){return void 0===e&&(e={}),t(this,void 0,void 0,function(){var t,r,s,o,c,a,h;return n(this,function(n){switch(n.label){case 0:if(!("auth_callback"in(r=function(e){for(var t={},n=e.split("&"),r=0;r<n.length;r++){var s=n[r].split("="),i=decodeURIComponent(s[0]),o=s.length>1?decodeURIComponent(s[1]):void 0;t[i]=o}return t}(location.search.substr(1)))))return[3,4];s=JSON.parse(atob(r.state)),n.label=1;case 1:return n.trys.push([1,3,,4]),[4,function(e,t,n){return f(e,t,{code:n,grant_type:"authorization_code"})}(s.hassUrl,s.clientId,r.code)];case 2:return t=n.sent(),e.saveTokens&&e.saveTokens(t),[3,4];case 3:return o=n.sent(),console.log("Unable to fetch access token",o),[3,4];case 4:return t||!e.loadTokens?[3,6]:[4,e.loadTokens()];case 5:t=n.sent(),n.label=6;case 6:if(t)return[2,new d(t,e.saveTokens)];if(void 0===(c=e.hassUrl))throw i;return"/"===c[c.length-1]&&(c=c.substr(0,c.length-1)),a=e.clientId||location.protocol+"//"+location.host+"/",h=e.redirectUrl||location.protocol+"//"+location.host+location.pathname+location.search,u(c,a,h,function(e){return btoa(JSON.stringify(e))}({hassUrl:c,clientId:a})),[2,new Promise(function(){})]}})})},e.createCollection=l,e.Connection=a,e.subscribeConfig=function(e,t){return l("_cnf",y,g,e,t)},e.subscribeServices=function(e,t){return l("_srv",w,E,e,t)},e.subscribeEntities=function(e,t){return l("_ent",S,O,e,t)},e.ERR_CANNOT_CONNECT=r,e.ERR_INVALID_AUTH=s,e.ERR_CONNECTION_LOST=3,e.ERR_HASS_HOST_REQUIRED=i,e.getStates=v,e.getServices=p,e.getConfig=b,e.getUser=function(e){return e.sendMessagePromise({type:"auth/current_user"})},e.callService=function(e,t,n,r){return e.sendMessagePromise(function(e,t,n){var r={type:"call_service",domain:e,service:t};return n&&(r.service_data=n),r}(t,n,r))}}); | ||
//# sourceMappingURL=haws.umd.js.map |
@@ -14,5 +14,3 @@ import { Auth } from "./auth"; | ||
}; | ||
export declare type HassEvent = { | ||
event_type: string; | ||
data: object; | ||
export declare type HassEventBase = { | ||
origin: string; | ||
@@ -25,2 +23,16 @@ time_fired: string; | ||
}; | ||
export declare type HassEvent = HassEventBase & { | ||
event_type: string; | ||
data: { | ||
[key: string]: any; | ||
}; | ||
}; | ||
export declare type StateChangedEvent = HassEventBase & { | ||
event_type: "state_changed"; | ||
data: { | ||
entity_id: string; | ||
new_state: HassEntity | null; | ||
old_state: HassEntity | null; | ||
}; | ||
}; | ||
export declare type HassConfig = { | ||
@@ -43,3 +55,3 @@ latitude: number; | ||
}; | ||
export declare type HassEntity = { | ||
export declare type HassEntityBase = { | ||
entity_id: string; | ||
@@ -49,4 +61,16 @@ state: string; | ||
last_updated: string; | ||
attributes: { | ||
[s: string]: any; | ||
}; | ||
export declare type HassEntityAttributeBase = { | ||
friendly_name?: string; | ||
unit_of_measurement?: string; | ||
icon?: string; | ||
entity_picture?: string; | ||
supported_features?: number; | ||
hidden: boolean; | ||
assumed_state?: boolean; | ||
device_class?: string; | ||
}; | ||
export declare type HassEntity = HassEntityBase & { | ||
attributes: HassEntityAttributeBase & { | ||
[key: string]: any; | ||
}; | ||
@@ -53,0 +77,0 @@ }; |
@@ -5,3 +5,3 @@ { | ||
"sideEffects": false, | ||
"version": "3.1.4", | ||
"version": "3.1.5", | ||
"description": "Home Assistant websocket client", | ||
@@ -8,0 +8,0 @@ "source": "lib/index.ts", |
@@ -291,2 +291,28 @@ # :aerial_tramway: JavaScript websocket client for Home Assistant | ||
## Using this with long-lived access tokens | ||
If you are in a browser, you should prefer to use the `getAuth()` flow. This will use the more secure refresh/access token pair. If that is not possible, you can ask the user to create a long-lived access token. | ||
You will need to create your own auth object if you want to use this library with a long-lived access token. | ||
```js | ||
import { | ||
Auth, | ||
createConnection, | ||
subscribeEntities | ||
} from "home-assistant-js-websocket"; | ||
(async () => { | ||
let auth = new Auth({ | ||
access_token: "YOUR ACCESS OTKEN", | ||
// Set expires to very far in the future | ||
expires: new Date(new Date().getTime() + 1e11), | ||
hassUrl: "http://localhost:8123" | ||
}); | ||
const connection = await createConnection({ auth }); | ||
subscribeEntities(connection, entities => console.log(entities)); | ||
})(); | ||
``` | ||
## Using this in NodeJS | ||
@@ -293,0 +319,0 @@ |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
74998
431
336