home-assistant-js-websocket
Advanced tools
Comparing version 3.0.0-rc4 to 3.0.0-rc5
@@ -1,2 +0,2 @@ | ||
declare type AuthData = { | ||
export declare type AuthData = { | ||
hassUrl: string; | ||
@@ -9,5 +9,5 @@ clientId: string; | ||
}; | ||
declare type SaveTokensFunc = (data: AuthData) => void; | ||
declare type LoadTokensFunc = () => Promise<AuthData | undefined>; | ||
declare type getAuthOptions = { | ||
export declare type SaveTokensFunc = (data: AuthData) => void; | ||
export declare type LoadTokensFunc = () => Promise<AuthData | undefined>; | ||
export declare type getAuthOptions = { | ||
hassUrl?: string; | ||
@@ -28,3 +28,2 @@ clientId?: string; | ||
} | ||
export default function getAuth(options?: getAuthOptions): Promise<Auth>; | ||
export {}; | ||
export declare function getAuth(options?: getAuthOptions): Promise<Auth>; |
@@ -1,4 +0,4 @@ | ||
import Store from "./store"; | ||
import { Store } from "./store"; | ||
import { Connection } from "./connection"; | ||
import { UnsubscribeFunc } from "./types"; | ||
export default function createCollection<State>(key: string, fetchCollection: (conn: Connection) => Promise<State>, subscribeUpdates: (conn: Connection, store: Store<State>) => Promise<UnsubscribeFunc>, conn: Connection, onChange: (state: State) => void): UnsubscribeFunc; | ||
export declare function createCollection<State>(key: string, fetchCollection: (conn: Connection) => Promise<State>, subscribeUpdates: (conn: Connection, store: Store<State>) => Promise<UnsubscribeFunc>, conn: Connection, onChange: (state: State) => void): UnsubscribeFunc; |
import { HassConfig, UnsubscribeFunc } from "./types"; | ||
import { Connection } from "./connection"; | ||
declare const _default: (conn: Connection, onChange: (state: HassConfig) => void) => UnsubscribeFunc; | ||
export default _default; | ||
export declare const subscribeConfig: (conn: Connection, onChange: (state: HassConfig) => void) => UnsubscribeFunc; |
@@ -1,3 +0,3 @@ | ||
import { ConnectionOptions, HassServices, HassConfig, MessageBase, HassEntity } from "./types"; | ||
declare type EventListener = (conn: Connection, eventData?: any) => void; | ||
import { ConnectionOptions, MessageBase } from "./types"; | ||
export declare type ConnectionEventListener = (conn: Connection, eventData?: any) => void; | ||
declare type Events = "ready" | "disconnected" | "reconnect-error"; | ||
@@ -11,3 +11,3 @@ export declare class Connection { | ||
eventListeners: { | ||
[eventType: string]: EventListener[]; | ||
[eventType: string]: ConnectionEventListener[]; | ||
}; | ||
@@ -18,10 +18,6 @@ closeRequested: boolean; | ||
setSocket(socket: WebSocket): void; | ||
addEventListener(eventType: Events, callback: EventListener): void; | ||
removeEventListener(eventType: Events, callback: EventListener): void; | ||
addEventListener(eventType: Events, callback: ConnectionEventListener): void; | ||
removeEventListener(eventType: Events, callback: ConnectionEventListener): void; | ||
fireEvent(eventType: Events, eventData?: any): void; | ||
close(): void; | ||
getStates(): Promise<HassEntity[]>; | ||
getServices(): Promise<HassServices>; | ||
getConfig(): Promise<HassConfig>; | ||
callService(domain: string, service: string, serviceData?: object): Promise<{}>; | ||
subscribeEvents<EventType>(eventCallback: (ev: EventType) => void, eventType: string): Promise<() => Promise<void>>; | ||
@@ -35,3 +31,2 @@ ping(): Promise<{}>; | ||
} | ||
export default function createConnection(options?: Partial<ConnectionOptions>): Promise<Connection>; | ||
export {}; |
@@ -5,4 +5,1 @@ export declare const ERR_CANNOT_CONNECT = 1; | ||
export declare const ERR_HASS_HOST_REQUIRED = 4; | ||
export declare const MSG_TYPE_AUTH_REQUIRED = "auth_required"; | ||
export declare const MSG_TYPE_AUTH_INVALID = "auth_invalid"; | ||
export declare const MSG_TYPE_AUTH_OK = "auth_ok"; |
import { HassEntities, UnsubscribeFunc } from "./types"; | ||
import { Connection } from "./connection"; | ||
declare const _default: (conn: Connection, onChange: (state: HassEntities) => void) => UnsubscribeFunc; | ||
export default _default; | ||
export declare const subscribeEntities: (conn: Connection, onChange: (state: HassEntities) => void) => UnsubscribeFunc; |
@@ -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,o="auth_required",c="auth_invalid",a="auth_ok",u="auth_callback";function h(e,t,n,r){n+=n.includes("?")?"&":"?",n+=u+"=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 l(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",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 f=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 n;return t(this,function(r){switch(r.label){case 0:return n=this,[4,function(n,r,s){return e(this,void 0,void 0,function(){var e;return t(this,function(t){switch(t.label){case 0:return[4,l(n,r,{grant_type:"refresh_token",refresh_token:s})];case 1:return(e=t.sent()).refresh_token=s,[2,e]}})})}(this.data.hassUrl,this.data.clientId,this.data.refresh_token)];case 1:return n.data=r.sent(),this._saveTokens&&this._saveTokens(this.data),[2]}})})},n}();function d(n){return void 0===n&&(n={}),e(this,void 0,void 0,function(){var e,r,s,o,c,a,u,d,v;return t(this,function(t){switch(t.label){case 0:if(e=n.loadTokens,r=n.saveTokens,!("auth_callback"in(s=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];c=JSON.parse(atob(s.state)),t.label=1;case 1:return t.trys.push([1,3,,4]),[4,function(e,t,n){return l(e,t,{code:n,grant_type:"authorization_code"})}(c.hassUrl,c.clientId,s.code)];case 2:return o=t.sent(),r&&r(o),[3,4];case 3:return a=t.sent(),console.log("Unable to fetch access token",a),[3,4];case 4:return o||!e?[3,6]:[4,e()];case 5:o=t.sent(),t.label=6;case 6:if(o)return[2,new f(o,r)];if(void 0===(u=n.hassUrl))throw i;return"/"===u[u.length-1]&&(u=u.substr(0,u.length-1)),d=n.clientId||location.protocol+"//"+location.host+"/",v=n.redirectUrl||location.protocol+"//"+location.host+location.pathname+location.search,h(u,d,v,function(e){return btoa(JSON.stringify(e))}({hassUrl:u,clientId:d})),[2,new Promise(function(){})]}})})}var v=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 p(n,r,s,i,o){if(n in i)return i[n](o);var c,a=new v(function(){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]=a.subscribe,c=s(i,a),i.addEventListener("ready",u),u(),a.subscribe(o)}var b=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.eventType&&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.getStates=function(){return this.sendMessagePromise({type:"get_states"})},n.prototype.getServices=function(){return this.sendMessagePromise({type:"get_services"})},n.prototype.getConfig=function(){return this.sendMessagePromise({type:"get_config"})},n.prototype.callService=function(e,t,n){return this.sendMessagePromise(function(e,t,n){var r={type:"call_service",domain:e,service:t};return n&&(r.service_data=n),r}(e,t,n))},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])}},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+=1,this.commandId},n}(),m={setupRetry:0,createSocket:function(s){if(!s.auth)throw i;var u=s.auth,h=u.wsUrl;return new Promise(function(i,l){return function s(i,l,f){var d=this,v=new WebSocket(h),p=!1,b=function(){if(v.removeEventListener("close",b),p)f(r);else if(0!==i){var e=-1===i?-1:i-1;setTimeout(function(){return s(e,l,f)},1e3)}else f(n)},m=function(n){return e(d,void 0,void 0,function(){var e;return t(this,function(t){switch(t.label){case 0:switch(JSON.parse(n.data).type){case o:return[3,1];case c:return[3,6];case a:return[3,7]}return[3,8];case 1:return t.trys.push([1,4,,5]),u.expired?[4,u.refreshAccessToken()]:[3,3];case 2:t.sent(),t.label=3;case 3:return v.send(JSON.stringify({type:"auth",access_token:u.accessToken})),[3,5];case 4:return e=t.sent(),p=e===r,v.close(),[3,5];case 5:return[3,9];case 6:return p=!0,v.close(),[3,9];case 7:return v.removeEventListener("message",m),v.removeEventListener("close",b),v.removeEventListener("error",b),l(v),[3,9];case 8:t.label=9;case 9:return[2]}})})};v.addEventListener("message",m),v.addEventListener("close",b),v.addEventListener("error",b)}(s.setupRetry,i,l)})}};function y(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({},m,n)).createSocket(e)];case 1:return r=t.sent(),[2,new b(r,e)]}})})}function g(e,t){return void 0===e?null:{components:e.components.concat(t.data.component)}}var _=function(e){return e.getConfig()},k=function(e,t){return e.subscribeEvents(t.action(g),"component_loaded")};function w(e,t){return p("_cnf",_,k,e,t)}function E(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 S(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 C=function(e){return e.getServices()},O=function(e,t){return Promise.all([e.subscribeEvents(t.action(E),"service_registered"),e.subscribeEvents(t.action(S),"service_removed")]).then(function(e){return function(){return e.forEach(function(e){return e()})}})};function I(e,t){return p("_srv",C,O,e,t)}function L(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,n.getStates()];case 1:for(e=t.sent(),r={},s=0;s<e.length;s++)r[(i=e[s]).entity_id]=i;return[2,r]}})})}var P=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")};function j(e,t){return p("_ent",L,P,e,t)}export{n as ERR_CANNOT_CONNECT,r as ERR_INVALID_AUTH,s as ERR_CONNECTION_LOST,i as ERR_HASS_HOST_REQUIRED,d as getAuth,p as createCollection,y as createConnection,w as subscribeConfig,I as subscribeServices,j as subscribeEntities}; | ||
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_required",c="auth_invalid",a="auth_ok";var u=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.eventType&&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 h(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 l(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",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 n;return t(this,function(r){switch(r.label){case 0:return n=this,[4,function(n,r,s){return e(this,void 0,void 0,function(){var e;return t(this,function(t){switch(t.label){case 0:return[4,l(n,r,{grant_type:"refresh_token",refresh_token:s})];case 1:return(e=t.sent()).refresh_token=s,[2,e]}})})}(this.data.hassUrl,this.data.clientId,this.data.refresh_token)];case 1:return n.data=r.sent(),this._saveTokens&&this._saveTokens(this.data),[2]}})})},n}();function f(n){return void 0===n&&(n={}),e(this,void 0,void 0,function(){var e,r,s,o,c,a,u;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 l(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+"/",u=n.redirectUrl||location.protocol+"//"+location.host+location.pathname+location.search,h(c,a,u,function(e){return btoa(JSON.stringify(e))}({hassUrl:c,clientId:a})),[2,new Promise(function(){})]}})})}var v=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 p(n,r,s,i,o){if(n in i)return i[n](o);var c,a=new v(function(){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]=a.subscribe,c=s(i,a),i.addEventListener("ready",u),u(),a.subscribe(o)}var b=function(e){return e.sendMessagePromise({type:"get_states"})},m=function(e){return e.sendMessagePromise({type:"get_services"})},y=function(e){return e.sendMessagePromise({type:"get_config"})},g=function(e){return e.sendMessagePromise({type:"auth/current_user"})},_=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 w=function(e){return y(e)},E=function(e,t){return e.subscribeEvents(t.action(k),"component_loaded")},S=function(e,t){return p("_cnf",w,E,e,t)};function O(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 T(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 L=function(e){return m(e)},P=function(e,t){return Promise.all([e.subscribeEvents(t.action(O),"service_registered"),e.subscribeEvents(t.action(T),"service_removed")]).then(function(e){return function(){return e.forEach(function(e){return e()})}})},C=function(e,t){return p("_srv",L,P,e,t)};function I(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,b(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 j=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 p("_ent",I,j,e,t)},M={setupRetry:0,createSocket:function(s){if(!s.auth)throw i;var u=s.auth,h=u.wsUrl;return new Promise(function(i,l){return function s(i,l,d){var f=this,v=new WebSocket(h),p=!1,b=function(){if(v.removeEventListener("close",b),p)d(r);else if(0!==i){var e=-1===i?-1:i-1;setTimeout(function(){return s(e,l,d)},1e3)}else d(n)},m=function(n){return e(f,void 0,void 0,function(){var e;return t(this,function(t){switch(t.label){case 0:switch(JSON.parse(n.data).type){case o:return[3,1];case c:return[3,6];case a:return[3,7]}return[3,8];case 1:return t.trys.push([1,4,,5]),u.expired?[4,u.refreshAccessToken()]:[3,3];case 2:t.sent(),t.label=3;case 3:return v.send(JSON.stringify({type:"auth",access_token:u.accessToken})),[3,5];case 4:return e=t.sent(),p=e===r,v.close(),[3,5];case 5:return[3,9];case 6:return p=!0,v.close(),[3,9];case 7:return v.removeEventListener("message",m),v.removeEventListener("close",b),v.removeEventListener("error",b),l(v),[3,9];case 8:t.label=9;case 9:return[2]}})})};v.addEventListener("message",m),v.addEventListener("close",b),v.addEventListener("error",b)}(s.setupRetry,i,l)})}};function x(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({},M,n)).createSocket(e)];case 1:return r=t.sent(),[2,new u(r,e)]}})})}export{x as createConnection,d as Auth,f as getAuth,p as createCollection,u as Connection,S as subscribeConfig,C 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,b as getStates,m as getServices,y as getConfig,g as getUser,_ 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,i="auth_required",o="auth_invalid",c="auth_ok",a="auth_callback";function u(e,t,n,r){n+=n.includes("?")?"&":"?",n+=a+"=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",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 n;return t(this,function(r){switch(r.label){case 0:return n=this,[4,function(n,r,s){return e(this,void 0,void 0,function(){var e;return t(this,function(t){switch(t.label){case 0:return[4,h(n,r,{grant_type:"refresh_token",refresh_token:s})];case 1:return(e=t.sent()).refresh_token=s,[2,e]}})})}(this.data.hassUrl,this.data.clientId,this.data.refresh_token)];case 1:return n.data=r.sent(),this._saveTokens&&this._saveTokens(this.data),[2]}})})},n}();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 d(n,r,s,i,o){if(n in i)return i[n](o);var c,a=new f(function(){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]=a.subscribe,c=s(i,a),i.addEventListener("ready",u),u(),a.subscribe(o)}var v=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.eventType&&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.getStates=function(){return this.sendMessagePromise({type:"get_states"})},n.prototype.getServices=function(){return this.sendMessagePromise({type:"get_services"})},n.prototype.getConfig=function(){return this.sendMessagePromise({type:"get_config"})},n.prototype.callService=function(e,t,n){return this.sendMessagePromise(function(e,t,n){var r={type:"call_service",domain:e,service:t};return n&&(r.service_data=n),r}(e,t,n))},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])}},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+=1,this.commandId},n}(),p={setupRetry:0,createSocket:function(a){if(!a.auth)throw s;var u=a.auth,h=u.wsUrl;return new Promise(function(s,l){return function s(a,l,f){var d=this,v=new WebSocket(h),p=!1,b=function(){if(v.removeEventListener("close",b),p)f(r);else if(0!==a){var e=-1===a?-1:a-1;setTimeout(function(){return s(e,l,f)},1e3)}else f(n)},m=function(n){return e(d,void 0,void 0,function(){var e;return t(this,function(t){switch(t.label){case 0:switch(JSON.parse(n.data).type){case i:return[3,1];case o:return[3,6];case c:return[3,7]}return[3,8];case 1:return t.trys.push([1,4,,5]),u.expired?[4,u.refreshAccessToken()]:[3,3];case 2:t.sent(),t.label=3;case 3:return v.send(JSON.stringify({type:"auth",access_token:u.accessToken})),[3,5];case 4:return e=t.sent(),p=e===r,v.close(),[3,5];case 5:return[3,9];case 6:return p=!0,v.close(),[3,9];case 7:return v.removeEventListener("message",m),v.removeEventListener("close",b),v.removeEventListener("error",b),l(v),[3,9];case 8:t.label=9;case 9:return[2]}})})};v.addEventListener("message",m),v.addEventListener("close",b),v.addEventListener("error",b)}(a.setupRetry,s,l)})}};function b(e,t){return void 0===e?null:{components:e.components.concat(t.data.component)}}var m=function(e){return e.getConfig()},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 e.getServices()},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,n.getStates()];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")};exports.ERR_CANNOT_CONNECT=n,exports.ERR_INVALID_AUTH=r,exports.ERR_CONNECTION_LOST=3,exports.ERR_HASS_HOST_REQUIRED=s,exports.getAuth=function(n){return void 0===n&&(n={}),e(this,void 0,void 0,function(){var e,r,i,o,c,a,f,d,v;return t(this,function(t){switch(t.label){case 0:if(e=n.loadTokens,r=n.saveTokens,!("auth_callback"in(i=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];c=JSON.parse(atob(i.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"})}(c.hassUrl,c.clientId,i.code)];case 2:return o=t.sent(),r&&r(o),[3,4];case 3:return a=t.sent(),console.log("Unable to fetch access token",a),[3,4];case 4:return o||!e?[3,6]:[4,e()];case 5:o=t.sent(),t.label=6;case 6:if(o)return[2,new l(o,r)];if(void 0===(f=n.hassUrl))throw s;return"/"===f[f.length-1]&&(f=f.substr(0,f.length-1)),d=n.clientId||location.protocol+"//"+location.host+"/",v=n.redirectUrl||location.protocol+"//"+location.host+location.pathname+location.search,u(f,d,v,function(e){return btoa(JSON.stringify(e))}({hassUrl:f,clientId:d})),[2,new Promise(function(){})]}})})},exports.createCollection=d,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({},p,n)).createSocket(e)];case 1:return r=t.sent(),[2,new v(r,e)]}})})},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)}; | ||
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_required",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.eventType&&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",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 n;return t(this,function(r){switch(r.label){case 0:return n=this,[4,function(n,r,s){return e(this,void 0,void 0,function(){var e;return t(this,function(t){switch(t.label){case 0:return[4,h(n,r,{grant_type:"refresh_token",refresh_token:s})];case 1:return(e=t.sent()).refresh_token=s,[2,e]}})})}(this.data.hassUrl,this.data.clientId,this.data.refresh_token)];case 1:return n.data=r.sent(),this._saveTokens&&this._saveTokens(this.data),[2]}})})},n}();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 d(n,r,s,i,o){if(n in i)return i[n](o);var c,a=new f(function(){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]=a.subscribe,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(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,v(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 x=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(a){if(!a.auth)throw s;var u=a.auth,h=u.wsUrl;return new Promise(function(s,l){return function s(a,l,f){var d=this,v=new WebSocket(h),p=!1,b=function(){if(v.removeEventListener("close",b),p)f(r);else if(0!==a){var e=-1===a?-1:a-1;setTimeout(function(){return s(e,l,f)},1e3)}else f(n)},m=function(n){return e(d,void 0,void 0,function(){var e;return t(this,function(t){switch(t.label){case 0:switch(JSON.parse(n.data).type){case i:return[3,1];case o:return[3,6];case c:return[3,7]}return[3,8];case 1:return t.trys.push([1,4,,5]),u.expired?[4,u.refreshAccessToken()]:[3,3];case 2:t.sent(),t.label=3;case 3:return v.send(JSON.stringify({type:"auth",access_token:u.accessToken})),[3,5];case 4:return e=t.sent(),p=e===r,v.close(),[3,5];case 5:return[3,9];case 6:return p=!0,v.close(),[3,9];case 7:return v.removeEventListener("message",m),v.removeEventListener("close",b),v.removeEventListener("error",b),l(v),[3,9];case 8:t.label=9;case 9:return[2]}})})};v.addEventListener("message",m),v.addEventListener("close",b),v.addEventListener("error",b)}(a.setupRetry,s,l)})}};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({},C,n)).createSocket(e)];case 1:return r=t.sent(),[2,new a(r,e)]}})})},exports.Auth=l,exports.getAuth=function(n){return void 0===n&&(n={}),e(this,void 0,void 0,function(){var e,r,i,o,c,a,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("="),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 h(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 l(e,n.saveTokens)];if(void 0===(c=n.hassUrl))throw s;return"/"===c[c.length-1]&&(c=c.substr(0,c.length-1)),a=n.clientId||location.protocol+"//"+location.host+"/",f=n.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(){})]}})})},exports.createCollection=d,exports.Connection=a,exports.subscribeConfig=function(e,t){return d("_cnf",y,g,e,t)},exports.subscribeServices=function(e,t){return d("_srv",w,E,e,t)},exports.subscribeEntities=function(e,t){return d("_ent",S,x,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=v,exports.getServices=p,exports.getConfig=b,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,o="auth_required",c="auth_invalid",a="auth_ok",u="auth_callback";function f(e,t,n,r){n+=n.includes("?")?"&":"?",n+=u+"=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",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 l=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(r){switch(r.label){case 0:return e=this,[4,function(e,r,s){return t(this,void 0,void 0,function(){var t;return n(this,function(n){switch(n.label){case 0:return[4,h(e,r,{grant_type:"refresh_token",refresh_token:s})];case 1:return(t=n.sent()).refresh_token=s,[2,t]}})})}(this.data.hassUrl,this.data.clientId,this.data.refresh_token)];case 1:return e.data=r.sent(),this._saveTokens&&this._saveTokens(this.data),[2]}})})},e}();var d=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(e,r,s,i,o){if(e in i)return i[e](o);var c,a=new d(function(){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]=a.subscribe,c=s(i,a),i.addEventListener("ready",u),u(),a.subscribe(o)}var p=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.eventType&&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.getStates=function(){return this.sendMessagePromise({type:"get_states"})},e.prototype.getServices=function(){return this.sendMessagePromise({type:"get_services"})},e.prototype.getConfig=function(){return this.sendMessagePromise({type:"get_config"})},e.prototype.callService=function(e,t,n){return this.sendMessagePromise(function(e,t,n){var r={type:"call_service",domain:e,service:t};return n&&(r.service_data=n),r}(e,t,n))},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])}},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+=1,this.commandId},e}(),b={setupRetry:0,createSocket:function(e){if(!e.auth)throw i;var u=e.auth,f=u.wsUrl;return new Promise(function(i,h){return function e(i,h,l){var d=this,v=new WebSocket(f),p=!1,b=function(){if(v.removeEventListener("close",b),p)l(s);else if(0!==i){var t=-1===i?-1:i-1;setTimeout(function(){return e(t,h,l)},1e3)}else l(r)},m=function(e){return t(d,void 0,void 0,function(){var t;return n(this,function(n){switch(n.label){case 0:switch(JSON.parse(e.data).type){case o:return[3,1];case c:return[3,6];case a:return[3,7]}return[3,8];case 1:return n.trys.push([1,4,,5]),u.expired?[4,u.refreshAccessToken()]:[3,3];case 2:n.sent(),n.label=3;case 3:return v.send(JSON.stringify({type:"auth",access_token:u.accessToken})),[3,5];case 4:return t=n.sent(),p=t===s,v.close(),[3,5];case 5:return[3,9];case 6:return p=!0,v.close(),[3,9];case 7:return v.removeEventListener("message",m),v.removeEventListener("close",b),v.removeEventListener("error",b),h(v),[3,9];case 8:n.label=9;case 9:return[2]}})})};v.addEventListener("message",m),v.addEventListener("close",b),v.addEventListener("error",b)}(e.setupRetry,i,h)})}};function m(e,t){return void 0===e?null:{components:e.components.concat(t.data.component)}}var y=function(e){return e.getConfig()},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 e.getServices()},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,e.getStates()];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")};e.ERR_CANNOT_CONNECT=r,e.ERR_INVALID_AUTH=s,e.ERR_CONNECTION_LOST=3,e.ERR_HASS_HOST_REQUIRED=i,e.getAuth=function(e){return void 0===e&&(e={}),t(this,void 0,void 0,function(){var t,r,s,o,c,a,u,d,v;return n(this,function(n){switch(n.label){case 0:if(t=e.loadTokens,r=e.saveTokens,!("auth_callback"in(s=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];c=JSON.parse(atob(s.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"})}(c.hassUrl,c.clientId,s.code)];case 2:return o=n.sent(),r&&r(o),[3,4];case 3:return a=n.sent(),console.log("Unable to fetch access token",a),[3,4];case 4:return o||!t?[3,6]:[4,t()];case 5:o=n.sent(),n.label=6;case 6:if(o)return[2,new l(o,r)];if(void 0===(u=e.hassUrl))throw i;return"/"===u[u.length-1]&&(u=u.substr(0,u.length-1)),d=e.clientId||location.protocol+"//"+location.host+"/",v=e.redirectUrl||location.protocol+"//"+location.host+location.pathname+location.search,f(u,d,v,function(e){return btoa(JSON.stringify(e))}({hassUrl:u,clientId:d})),[2,new Promise(function(){})]}})})},e.createCollection=v,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({},b,e)).createSocket(t)];case 1:return r=n.sent(),[2,new p(r,t)]}})})},e.subscribeConfig=function(e,t){return v("_cnf",y,g,e,t)},e.subscribeServices=function(e,t){return v("_srv",w,E,e,t)},e.subscribeEntities=function(e,t){return v("_ent",S,C,e,t)}}); | ||
!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_required",c="auth_invalid",a="auth_ok";var u=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.eventType&&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 f(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",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 l=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(r){switch(r.label){case 0:return e=this,[4,function(e,r,s){return t(this,void 0,void 0,function(){var t;return n(this,function(n){switch(n.label){case 0:return[4,h(e,r,{grant_type:"refresh_token",refresh_token:s})];case 1:return(t=n.sent()).refresh_token=s,[2,t]}})})}(this.data.hassUrl,this.data.clientId,this.data.refresh_token)];case 1:return e.data=r.sent(),this._saveTokens&&this._saveTokens(this.data),[2]}})})},e}();var d=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(e,r,s,i,o){if(e in i)return i[e](o);var c,a=new d(function(){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]=a.subscribe,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"})};function y(e,t){return void 0===e?null:{components:e.components.concat(t.data.component)}}var g=function(e){return m(e)},_=function(e,t){return e.subscribeEvents(t.action(y),"component_loaded")};function k(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 w(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 E=function(e){return b(e)},S=function(e,t){return Promise.all([e.subscribeEvents(t.action(k),"service_registered"),e.subscribeEvents(t.action(w),"service_removed")]).then(function(e){return function(){return e.forEach(function(e){return e()})}})};function C(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,p(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")},T={setupRetry:0,createSocket:function(e){if(!e.auth)throw i;var u=e.auth,f=u.wsUrl;return new Promise(function(i,h){return function e(i,h,l){var d=this,v=new WebSocket(f),p=!1,b=function(){if(v.removeEventListener("close",b),p)l(s);else if(0!==i){var t=-1===i?-1:i-1;setTimeout(function(){return e(t,h,l)},1e3)}else l(r)},m=function(e){return t(d,void 0,void 0,function(){var t;return n(this,function(n){switch(n.label){case 0:switch(JSON.parse(e.data).type){case o:return[3,1];case c:return[3,6];case a:return[3,7]}return[3,8];case 1:return n.trys.push([1,4,,5]),u.expired?[4,u.refreshAccessToken()]:[3,3];case 2:n.sent(),n.label=3;case 3:return v.send(JSON.stringify({type:"auth",access_token:u.accessToken})),[3,5];case 4:return t=n.sent(),p=t===s,v.close(),[3,5];case 5:return[3,9];case 6:return p=!0,v.close(),[3,9];case 7:return v.removeEventListener("message",m),v.removeEventListener("close",b),v.removeEventListener("error",b),h(v),[3,9];case 8:n.label=9;case 9:return[2]}})})};v.addEventListener("message",m),v.addEventListener("close",b),v.addEventListener("error",b)}(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({},T,e)).createSocket(t)];case 1:return r=n.sent(),[2,new u(r,t)]}})})},e.Auth=l,e.getAuth=function(e){return void 0===e&&(e={}),t(this,void 0,void 0,function(){var t,r,s,o,c,a,u;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 l(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+"/",u=e.redirectUrl||location.protocol+"//"+location.host+location.pathname+location.search,f(c,a,u,function(e){return btoa(JSON.stringify(e))}({hassUrl:c,clientId:a})),[2,new Promise(function(){})]}})})},e.createCollection=v,e.Connection=u,e.subscribeConfig=function(e,t){return v("_cnf",g,_,e,t)},e.subscribeServices=function(e,t){return v("_srv",E,S,e,t)},e.subscribeEntities=function(e,t){return v("_ent",C,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=p,e.getServices=b,e.getConfig=m,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 |
@@ -1,8 +0,12 @@ | ||
import getAuth from "./auth"; | ||
import createCollection from "./collection"; | ||
import createConnection from "./connection"; | ||
import subscribeConfig from "./config"; | ||
import subscribeServices from "./services"; | ||
import subscribeEntities from "./entities"; | ||
import { ERR_CANNOT_CONNECT, ERR_INVALID_AUTH, ERR_CONNECTION_LOST, ERR_HASS_HOST_REQUIRED } from "./const"; | ||
export { ERR_CANNOT_CONNECT, ERR_INVALID_AUTH, ERR_CONNECTION_LOST, ERR_HASS_HOST_REQUIRED, getAuth, createCollection, createConnection, subscribeConfig, subscribeServices, subscribeEntities }; | ||
import { ConnectionOptions } from "./types"; | ||
import { Connection } from "./connection"; | ||
export * from "./auth"; | ||
export * from "./collection"; | ||
export * from "./connection"; | ||
export * from "./config"; | ||
export * from "./services"; | ||
export * from "./entities"; | ||
export * from "./errors"; | ||
export * from "./types"; | ||
export * from "./commands"; | ||
export declare function createConnection(options?: Partial<ConnectionOptions>): Promise<Connection>; |
import { Error } from "./types"; | ||
export declare function authAccessToken(accessToken: string): { | ||
export declare function auth(accessToken: string): { | ||
type: string; | ||
@@ -15,2 +15,5 @@ access_token: string; | ||
}; | ||
export declare function user(): { | ||
type: string; | ||
}; | ||
declare type ServiceCallMessage = { | ||
@@ -17,0 +20,0 @@ type: "call_service"; |
import { HassServices, UnsubscribeFunc } from "./types"; | ||
import { Connection } from "./connection"; | ||
declare const _default: (conn: Connection, onChange: (state: HassServices) => void) => UnsubscribeFunc; | ||
export default _default; | ||
export declare const subscribeServices: (conn: Connection, onChange: (state: HassServices) => void) => UnsubscribeFunc; |
import { ConnectionOptions } from "./types"; | ||
export default function createSocket(options: ConnectionOptions): Promise<WebSocket>; | ||
export declare function createSocket(options: ConnectionOptions): Promise<WebSocket>; |
import { UnsubscribeFunc } from "./types"; | ||
declare type Listener<State> = (state: State) => void; | ||
declare type NoSubscribersCallback = () => void; | ||
export default class Store<State> { | ||
export declare class Store<State> { | ||
private _noSub; | ||
@@ -6,0 +6,0 @@ listeners: Listener<State>[]; |
@@ -5,3 +5,3 @@ { | ||
"sideEffects": false, | ||
"version": "3.0.0-rc4", | ||
"version": "3.0.0-rc5", | ||
"description": "Home Assistant websocket client", | ||
@@ -8,0 +8,0 @@ "source": "lib/index.ts", |
@@ -244,18 +244,4 @@ # :aerial_tramway: JavaScript websocket client for Home Assistant | ||
##### `conn.getStates()` | ||
A connection object is obtained by calling [`createConnection()`](#createconnection). | ||
Get the state of all entities. Returns a promise that will resolve to the result of querying the server for all the states. | ||
##### `conn.getServices()` | ||
Get all available services. Returns a promise that will resolve to the result of querying the server for all the services. | ||
##### `conn.getConfig()` | ||
Get the Home Assistant server config. Returns a promise that will resolve to the result of querying the server for all the config. | ||
##### `conn.callService(domain, service[, serviceData])` | ||
Call a service within Home Assistant. Returns a promise that will resolve when the service has been called successfully. | ||
##### `conn.subscribeEvents(eventCallback[, eventType])` | ||
@@ -275,2 +261,15 @@ | ||
## Other methods | ||
The library also contains a few helper method that you can use to ineract with the API. | ||
- `getUser(connection) -> Promise<HassEntity[]>` | ||
- `callService(connection, domain, service, serviceData?) -> Promise` | ||
The following are also available, but it's recommended that you use the subscribe methods documented above. | ||
- `getStates(connection) -> Promise<HassEntity[]>` | ||
- `getServices(connection) -> Promise<HassEntity[]>` | ||
- `getConfig(connection) -> Promise<HassEntity[]>` | ||
## Using this in NodeJS | ||
@@ -277,0 +276,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
70558
24
386
292