Socket
Socket
Sign inDemoInstall

wspromisify

Package Overview
Dependencies
Maintainers
1
Versions
49
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

wspromisify - npm Package Compare versions

Comparing version 2.0.1 to 2.1.1

dist/src/config.d.ts

4

dist/src/connectLib.d.ts

@@ -1,3 +0,3 @@

import "./types";
declare const connectLib: (ff: any) => any;
import './types';
declare const connectLib: (ff: Function) => any;
export default connectLib;

@@ -1,4 +0,9 @@

import "./types";
/// <reference types="node" />
import './types';
declare const add_event: (o: wsc.Socket, e: string, handler: wsc.EventHandler) => void;
declare const once: (fn: Function) => (...args: any) => any;
export { add_event, once, };
declare const sett: (a: number, b: {
(): void;
(...args: any[]): void;
}) => NodeJS.Timeout;
export { add_event, once, sett };

@@ -1,2 +0,2 @@

import "./types";
import './types';
declare class WebSocketClient implements wsc.WebSocketClient {

@@ -3,0 +3,0 @@ private open;

@@ -1,2 +0,1 @@

function __awaiter(e,t,n,o){return new(n||(n=Promise))(function(s,i){function c(e){try{r(o.next(e))}catch(e){i(e)}}function l(e){try{r(o.throw(e))}catch(e){i(e)}}function r(e){e.done?s(e.value):new n(function(t){t(e.value)}).then(c,l)}r((o=o.apply(e,t||[])).next())})}var SHA1=e=>{for(var t,n,o,s,i,c,l,r=0,u=0,h=[],a=[t=1732584193,n=4023233417,~t,~n,3285377520],d=[],f=unescape(encodeURI(e)),_=f.length;u<=_;)d[u>>2]|=(f.charCodeAt(u)||128)<<8*(3-u++%4);for(d[l=_+8>>2|15]=_<<3;r<=l;r+=16){for(t=a,u=0;u<80;t=[0|[(c=((f=t[0])<<5|f>>>27)+t[4]+(h[u]=u<16?~~d[r+u]:c<<1|c>>>31)+1518500249)+((n=t[1])&(o=t[2])|~n&(s=t[3])),i=c+(n^o^s)+341275144,c+(n&o|n&s|o&s)+882459459,i+1535694389][0|u++/20],f,n<<30|n>>>2,o,s])c=h[u-3]^h[u-8]^h[u-14]^h[u-16];for(u=5;u;)a[--u]=a[u]+t[u]|0}for(e="";u<40;)e+=(a[u>>3]>>4*(7-u++%8)&15).toString(16);return e};const add_event=(e,t,n)=>e.addEventListener(t,n),once=e=>{let t=!1,n=null;return(...o)=>t?n:(t=!0,n=e(...o))},init=function(e){const t=this.config;this.open=!0,this.onReadyQueue.forEach(e=>e()),this.onReadyQueue=[];const{id_key:n,data_key:o}=t.server;this.messages.forEach(e=>e.send()),null!==this.reconnect_timeout&&(clearInterval(this.reconnect_timeout),this.reconnect_timeout=null),add_event(e,"close",e=>__awaiter(this,void 0,void 0,function*(){this.log("Closed."),this.open=!1,this.onCloseQueue.forEach(e=>e()),this.onCloseQueue=[];const e=t.reconnect;if("number"!=typeof e||isNaN(e)||this.forcibly_closed)this.ws=null,this.open=null;else{const t=()=>__awaiter(this,void 0,void 0,function*(){this.log("Trying to reconnect..."),null!==this.ws&&(this.ws.close(),this.ws=null),null!==(yield this.connect())&&(this.reconnect_timeout=setTimeout(t,1e3*e))});t()}this.forcibly_closed=!1})),add_event(e,"message",e=>{try{const s=t.decode(e.data);if(s[n]){const e=this.queue[s[n]];if(e){const t=e.sent_time?Date.now()-e.sent_time:null;this.log("Message.",s[o],t),e.ff(s[o]),clearTimeout(e.timeout),delete this.queue[s[n]]}}}catch(t){console.error(t,`Decode error. Got: ${e.data}`)}})},connectLib=function(e){if(!0===this.open)return e(1);const t=this.config,n=t.socket||t.adapter(`ws://${t.url}`,t.protocols);this.ws=n,add_event(n,"error",once(t=>(this.ws=null,this.log("Error status 3."),e(3)))),t.socket&&1===n.readyState?(init.call(this,n),e(null)):add_event(n,"open",once(t=>(this.log("Opened."),init.call(this,n),e(null))))},sett=(e,t)=>setTimeout(t,e),default_config={data_type:"json",log:(e="",t=0,n="")=>null,timer:!1,url:"localhost",timeout:1400,reconnect:2,lazy:!1,socket:null,adapter:(e,t)=>new WebSocket(e,t),encode:(e,t,{server:n})=>JSON.stringify({[n.id_key]:e,[n.data_key]:t}),decode:e=>JSON.parse(e),protocols:[],pipes:[],server:{id_key:"id",data_key:"data"}};class WebSocketClient{constructor(e={}){this.open=null,this.ws=null,this.forcibly_closed=!1,this.reconnect_timeout=null,this.queue={},this.messages=[],this.onReadyQueue=[],this.onCloseQueue=[],this.config={};const t={};Object.assign(t,default_config),Object.assign(t,e),this.config=t,this.init_flush(),this.open=!1,this.reconnect_timeout=null,this.forcibly_closed=!1,t.lazy||this.connect()}init_flush(){this.queue={},this.messages=[]}log(e,t=null,n=null){const o=this.config;e=`WSP: ${e}`,null!==n?o.log(e,n,t):o.timer?o.log(e,null,t):o.log(e,t)}connect(){return __awaiter(this,void 0,void 0,function*(){return new Promise((e,t)=>{connectLib.call(this,e)})})}get socket(){return this.ws}ready(){return __awaiter(this,void 0,void 0,function*(){return new Promise((e,t)=>{this.open?e():this.onReadyQueue.push(e)})})}on(e,t,n){return add_event(this.ws,e,e=>{n&&!n(e)||t(e)})}close(){return __awaiter(this,void 0,void 0,function*(){return new Promise((e,t)=>{null===this.ws?t("WSP: closing a non-inited socket!"):(this.open=null,this.onCloseQueue.push(()=>{this.init_flush(),this.ws=null,this.forcibly_closed=!0,e()}),this.ws.close())})})}send(e,t={}){return __awaiter(this,void 0,void 0,function*(){this.log("Send.",e);const n=this.config,o={},s=(n.server.id_key,n.server.data_key),i=n.lazy&&!this.open,c=SHA1(""+(1e5*Math.random()|0)).slice(0,20);if("object"==typeof t.top){if(t.top[s])throw new Error("Attempting to set data key/token via send() options!");Object.assign(o,t.top)}if(n.pipes.forEach(t=>e=t(e)),!0===this.open)this.ws.send(n.encode(c,e,n));else if(!1===this.open||i)this.messages.push({send:()=>this.ws.send(n.encode(c,e,n))}),i&&this.connect();else if(null===this.open)throw new Error("Attempting to send via closed WebSocket connection!");return new Promise((e,t)=>{this.queue[c]={ff:e,data_type:n.data_type,sent_time:n.timer?Date.now():null,timeout:sett(n.timeout,()=>{this.queue[c]&&(t({"Websocket timeout expired: ":n.timeout,"for the message":o}),delete this.queue[c])})}})})}}export default WebSocketClient;
//# sourceMappingURL=ws.esm.js.map
function e(e,t,o,n){return new(o||(o=Promise))(function(s,i){function r(e){try{c(n.next(e))}catch(e){i(e)}}function l(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){e.done?s(e.value):new o(function(t){t(e.value)}).then(r,l)}c((n=n.apply(e,t||[])).next())})}const t="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",o=t.length-1;var n=e=>{const n=[];for(;e>=1;)n.push(t[e%(o+1)]),e=e/o|0;return n.join("")};const s=(e,t,o)=>e.addEventListener(t,o),i=e=>{let t=!1,o=null;return(...n)=>t?o:(t=!0,o=e(...n))},r=(e,t)=>setTimeout(t,e),l=function(t){const o=this.config;this.open=!0,this.onReadyQueue.forEach(e=>e()),this.onReadyQueue.splice(0);const{id_key:n,data_key:i}=o.server;this.messages.forEach(e=>e.send()),null!==this.reconnect_timeout&&(clearInterval(this.reconnect_timeout),this.reconnect_timeout=null),s(t,"close",()=>e(this,void 0,void 0,function*(){this.log("Closed."),this.open=!1,this.onCloseQueue.forEach(e=>e()),this.onCloseQueue=[];const t=o.reconnect;if("number"!=typeof t||isNaN(t)||this.forcibly_closed)this.ws=null,this.open=null;else{const o=()=>e(this,void 0,void 0,function*(){this.log("Trying to reconnect..."),null!==this.ws&&(this.ws.close(),this.ws=null),null!==(yield this.connect())&&(this.reconnect_timeout=setTimeout(o,1e3*t))});o()}this.forcibly_closed=!1})),s(t,"message",e=>{try{const t=o.decode(e.data);if(t[n]){const e=this.queue[t[n]];if(e){const o=e.sent_time?Date.now()-e.sent_time:null;this.log("Message.",t[i],o),e.ff(t[i]),clearTimeout(e.timeout),delete this.queue[t[n]]}}}catch(t){console.error(t,`Decode error. Got: ${e.data}`)}})},c=function(e){if(!0===this.open)return e(null);const t=this.config,o=t.socket||t.adapter(`ws://${t.url}`,t.protocols);if(this.ws=o,s(o,"error",i(()=>(this.ws=null,this.log("Error status 3."),e(3)))),!o||o.readyState>1)throw new Error("WSP: Error: ready() on closing or closed state!");o.readyState?(l.call(this,o),e(null)):s(o,"open",i(()=>(this.log("Opened."),l.call(this,o),e(null))))},u={data_type:"json",log:()=>null,timer:!1,url:"localhost",timeout:1400,reconnect:2,lazy:!1,socket:null,adapter:(e,t)=>new WebSocket(e,t),encode:(e,t,{server:o})=>JSON.stringify({[o.id_key]:e,[o.data_key]:t}),decode:e=>JSON.parse(e),protocols:[],pipes:[],server:{id_key:"id",data_key:"data"}},h=e=>{const t=Object.assign(u,e),o=t.url;if("/"==o[0])try{t.url=`${location.hostname}:${location.port}${o}`}catch(e){throw new Error("WSP: URL starting with / in non-browser environment!")}return t},a=Math.pow(2,31)-1;export default class{constructor(e={}){this.open=null,this.ws=null,this.forcibly_closed=!1,this.reconnect_timeout=null,this.queue={},this.messages=[],this.onReadyQueue=[],this.onCloseQueue=[],this.config={},this.config=h(e),this.init_flush(),this.open=!1,this.reconnect_timeout=null,this.forcibly_closed=!1,this.config.lazy||this.connect()}init_flush(){this.queue={},this.messages=[]}log(e,t=null,o=null){const n=this.config;e=`WSP: ${e}`,null!==o?n.log(e,o,t):n.timer?n.log(e,null,t):n.log(e,t)}connect(){return e(this,void 0,void 0,function*(){return new Promise(e=>{c.call(this,e)})})}get socket(){return this.ws}ready(){return e(this,void 0,void 0,function*(){return new Promise(e=>{this.open?e():this.onReadyQueue.push(e)})})}on(e,t,o){return s(this.ws,e,e=>{o&&!o(e)||t(e)})}close(){return e(this,void 0,void 0,function*(){return new Promise((e,t)=>{null===this.ws?t("WSP: closing a non-inited socket!"):(this.open=null,this.onCloseQueue.push(()=>{this.init_flush(),this.ws=null,this.forcibly_closed=!0,e()}),this.ws.close())})})}send(t,o={}){return e(this,void 0,void 0,function*(){this.log("Send.",t);const e=this.config,s={},i=e.server.data_key,l=e.lazy&&!this.open,c=n(Math.random()*(a-10)|0);if("object"==typeof o.top){if(o.top[i])throw new Error("Attempting to set data key/token via send() options!");Object.assign(s,o.top)}if(e.pipes.forEach(e=>t=e(t)),console.log({open:this.open,encoded:e.encode(c,t,e)}),!0===this.open)this.ws.send(e.encode(c,t,e));else if(!1===this.open||l)this.messages.push({send:()=>this.ws.send(e.encode(c,t,e))}),l&&this.connect();else if(null===this.open)throw new Error("Attempting to send via closed WebSocket connection!");return new Promise((t,o)=>{this.queue[c]={ff:t,data_type:e.data_type,sent_time:e.timer?Date.now():null,timeout:r(e.timeout,()=>{this.queue[c]&&(o({"Websocket timeout expired: ":e.timeout,"for the message":s}),delete this.queue[c])})}})})}}

@@ -1,2 +0,1 @@

"use strict";function __awaiter(e,t,n,o){return new(n||(n=Promise))(function(s,i){function c(e){try{l(o.next(e))}catch(e){i(e)}}function r(e){try{l(o.throw(e))}catch(e){i(e)}}function l(e){e.done?s(e.value):new n(function(t){t(e.value)}).then(c,r)}l((o=o.apply(e,t||[])).next())})}var SHA1=e=>{for(var t,n,o,s,i,c,r,l=0,u=0,h=[],a=[t=1732584193,n=4023233417,~t,~n,3285377520],d=[],f=unescape(encodeURI(e)),_=f.length;u<=_;)d[u>>2]|=(f.charCodeAt(u)||128)<<8*(3-u++%4);for(d[r=_+8>>2|15]=_<<3;l<=r;l+=16){for(t=a,u=0;u<80;t=[0|[(c=((f=t[0])<<5|f>>>27)+t[4]+(h[u]=u<16?~~d[l+u]:c<<1|c>>>31)+1518500249)+((n=t[1])&(o=t[2])|~n&(s=t[3])),i=c+(n^o^s)+341275144,c+(n&o|n&s|o&s)+882459459,i+1535694389][0|u++/20],f,n<<30|n>>>2,o,s])c=h[u-3]^h[u-8]^h[u-14]^h[u-16];for(u=5;u;)a[--u]=a[u]+t[u]|0}for(e="";u<40;)e+=(a[u>>3]>>4*(7-u++%8)&15).toString(16);return e};const add_event=(e,t,n)=>e.addEventListener(t,n),once=e=>{let t=!1,n=null;return(...o)=>t?n:(t=!0,n=e(...o))},init=function(e){const t=this.config;this.open=!0,this.onReadyQueue.forEach(e=>e()),this.onReadyQueue=[];const{id_key:n,data_key:o}=t.server;this.messages.forEach(e=>e.send()),null!==this.reconnect_timeout&&(clearInterval(this.reconnect_timeout),this.reconnect_timeout=null),add_event(e,"close",e=>__awaiter(this,void 0,void 0,function*(){this.log("Closed."),this.open=!1,this.onCloseQueue.forEach(e=>e()),this.onCloseQueue=[];const e=t.reconnect;if("number"!=typeof e||isNaN(e)||this.forcibly_closed)this.ws=null,this.open=null;else{const t=()=>__awaiter(this,void 0,void 0,function*(){this.log("Trying to reconnect..."),null!==this.ws&&(this.ws.close(),this.ws=null),null!==(yield this.connect())&&(this.reconnect_timeout=setTimeout(t,1e3*e))});t()}this.forcibly_closed=!1})),add_event(e,"message",e=>{try{const s=t.decode(e.data);if(s[n]){const e=this.queue[s[n]];if(e){const t=e.sent_time?Date.now()-e.sent_time:null;this.log("Message.",s[o],t),e.ff(s[o]),clearTimeout(e.timeout),delete this.queue[s[n]]}}}catch(t){console.error(t,`Decode error. Got: ${e.data}`)}})},connectLib=function(e){if(!0===this.open)return e(1);const t=this.config,n=t.socket||t.adapter(`ws://${t.url}`,t.protocols);this.ws=n,add_event(n,"error",once(t=>(this.ws=null,this.log("Error status 3."),e(3)))),t.socket&&1===n.readyState?(init.call(this,n),e(null)):add_event(n,"open",once(t=>(this.log("Opened."),init.call(this,n),e(null))))},sett=(e,t)=>setTimeout(t,e),default_config={data_type:"json",log:(e="",t=0,n="")=>null,timer:!1,url:"localhost",timeout:1400,reconnect:2,lazy:!1,socket:null,adapter:(e,t)=>new WebSocket(e,t),encode:(e,t,{server:n})=>JSON.stringify({[n.id_key]:e,[n.data_key]:t}),decode:e=>JSON.parse(e),protocols:[],pipes:[],server:{id_key:"id",data_key:"data"}};class WebSocketClient{constructor(e={}){this.open=null,this.ws=null,this.forcibly_closed=!1,this.reconnect_timeout=null,this.queue={},this.messages=[],this.onReadyQueue=[],this.onCloseQueue=[],this.config={};const t={};Object.assign(t,default_config),Object.assign(t,e),this.config=t,this.init_flush(),this.open=!1,this.reconnect_timeout=null,this.forcibly_closed=!1,t.lazy||this.connect()}init_flush(){this.queue={},this.messages=[]}log(e,t=null,n=null){const o=this.config;e=`WSP: ${e}`,null!==n?o.log(e,n,t):o.timer?o.log(e,null,t):o.log(e,t)}connect(){return __awaiter(this,void 0,void 0,function*(){return new Promise((e,t)=>{connectLib.call(this,e)})})}get socket(){return this.ws}ready(){return __awaiter(this,void 0,void 0,function*(){return new Promise((e,t)=>{this.open?e():this.onReadyQueue.push(e)})})}on(e,t,n){return add_event(this.ws,e,e=>{n&&!n(e)||t(e)})}close(){return __awaiter(this,void 0,void 0,function*(){return new Promise((e,t)=>{null===this.ws?t("WSP: closing a non-inited socket!"):(this.open=null,this.onCloseQueue.push(()=>{this.init_flush(),this.ws=null,this.forcibly_closed=!0,e()}),this.ws.close())})})}send(e,t={}){return __awaiter(this,void 0,void 0,function*(){this.log("Send.",e);const n=this.config,o={},s=(n.server.id_key,n.server.data_key),i=n.lazy&&!this.open,c=SHA1(""+(1e5*Math.random()|0)).slice(0,20);if("object"==typeof t.top){if(t.top[s])throw new Error("Attempting to set data key/token via send() options!");Object.assign(o,t.top)}if(n.pipes.forEach(t=>e=t(e)),!0===this.open)this.ws.send(n.encode(c,e,n));else if(!1===this.open||i)this.messages.push({send:()=>this.ws.send(n.encode(c,e,n))}),i&&this.connect();else if(null===this.open)throw new Error("Attempting to send via closed WebSocket connection!");return new Promise((e,t)=>{this.queue[c]={ff:e,data_type:n.data_type,sent_time:n.timer?Date.now():null,timeout:sett(n.timeout,()=>{this.queue[c]&&(t({"Websocket timeout expired: ":n.timeout,"for the message":o}),delete this.queue[c])})}})})}}module.exports=WebSocketClient;
//# sourceMappingURL=ws.js.map
"use strict";function __awaiter(e,t,n,o){return new(n||(n=Promise))(function(i,s){function c(e){try{l(o.next(e))}catch(e){s(e)}}function r(e){try{l(o.throw(e))}catch(e){s(e)}}function l(e){e.done?i(e.value):new n(function(t){t(e.value)}).then(c,r)}l((o=o.apply(e,t||[])).next())})}const abc="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",ln=abc.length-1;var packNumber=e=>{const t=[];for(;e>=1;)t.push(abc[e%(ln+1)]),e=e/ln|0;return t.join("")};const add_event=(e,t,n)=>e.addEventListener(t,n),once=e=>{let t=!1,n=null;return(...o)=>t?n:(t=!0,n=e(...o))},sett=(e,t)=>setTimeout(t,e),init=function(e){const t=this.config;this.open=!0,this.onReadyQueue.forEach(e=>e()),this.onReadyQueue.splice(0);const{id_key:n,data_key:o}=t.server;this.messages.forEach(e=>e.send()),null!==this.reconnect_timeout&&(clearInterval(this.reconnect_timeout),this.reconnect_timeout=null),add_event(e,"close",()=>__awaiter(this,void 0,void 0,function*(){this.log("Closed."),this.open=!1,this.onCloseQueue.forEach(e=>e()),this.onCloseQueue=[];const e=t.reconnect;if("number"!=typeof e||isNaN(e)||this.forcibly_closed)this.ws=null,this.open=null;else{const t=()=>__awaiter(this,void 0,void 0,function*(){this.log("Trying to reconnect..."),null!==this.ws&&(this.ws.close(),this.ws=null),null!==(yield this.connect())&&(this.reconnect_timeout=setTimeout(t,1e3*e))});t()}this.forcibly_closed=!1})),add_event(e,"message",e=>{try{const i=t.decode(e.data);if(i[n]){const e=this.queue[i[n]];if(e){const t=e.sent_time?Date.now()-e.sent_time:null;this.log("Message.",i[o],t),e.ff(i[o]),clearTimeout(e.timeout),delete this.queue[i[n]]}}}catch(t){console.error(t,`Decode error. Got: ${e.data}`)}})},connectLib=function(e){if(!0===this.open)return e(null);const t=this.config,n=t.socket||t.adapter(`ws://${t.url}`,t.protocols);if(this.ws=n,add_event(n,"error",once(()=>(this.ws=null,this.log("Error status 3."),e(3)))),!n||n.readyState>1)throw new Error("WSP: Error: ready() on closing or closed state!");n.readyState?(init.call(this,n),e(null)):add_event(n,"open",once(()=>(this.log("Opened."),init.call(this,n),e(null))))},default_config={data_type:"json",log:()=>null,timer:!1,url:"localhost",timeout:1400,reconnect:2,lazy:!1,socket:null,adapter:(e,t)=>new WebSocket(e,t),encode:(e,t,{server:n})=>JSON.stringify({[n.id_key]:e,[n.data_key]:t}),decode:e=>JSON.parse(e),protocols:[],pipes:[],server:{id_key:"id",data_key:"data"}},enrichConfig=e=>{const t=Object.assign(default_config,e),n=t.url;if("/"==n[0])try{t.url=`${location.hostname}:${location.port}${n}`}catch(e){throw new Error("WSP: URL starting with / in non-browser environment!")}return t},MAX_32=Math.pow(2,31)-1;class WebSocketClient{constructor(e={}){this.open=null,this.ws=null,this.forcibly_closed=!1,this.reconnect_timeout=null,this.queue={},this.messages=[],this.onReadyQueue=[],this.onCloseQueue=[],this.config={},this.config=enrichConfig(e),this.init_flush(),this.open=!1,this.reconnect_timeout=null,this.forcibly_closed=!1,this.config.lazy||this.connect()}init_flush(){this.queue={},this.messages=[]}log(e,t=null,n=null){const o=this.config;e=`WSP: ${e}`,null!==n?o.log(e,n,t):o.timer?o.log(e,null,t):o.log(e,t)}connect(){return __awaiter(this,void 0,void 0,function*(){return new Promise(e=>{connectLib.call(this,e)})})}get socket(){return this.ws}ready(){return __awaiter(this,void 0,void 0,function*(){return new Promise(e=>{this.open?e():this.onReadyQueue.push(e)})})}on(e,t,n){return add_event(this.ws,e,e=>{n&&!n(e)||t(e)})}close(){return __awaiter(this,void 0,void 0,function*(){return new Promise((e,t)=>{null===this.ws?t("WSP: closing a non-inited socket!"):(this.open=null,this.onCloseQueue.push(()=>{this.init_flush(),this.ws=null,this.forcibly_closed=!0,e()}),this.ws.close())})})}send(e,t={}){return __awaiter(this,void 0,void 0,function*(){this.log("Send.",e);const n=this.config,o={},i=n.server.data_key,s=n.lazy&&!this.open,c=packNumber(Math.random()*(MAX_32-10)|0);if("object"==typeof t.top){if(t.top[i])throw new Error("Attempting to set data key/token via send() options!");Object.assign(o,t.top)}if(n.pipes.forEach(t=>e=t(e)),console.log({open:this.open,encoded:n.encode(c,e,n)}),!0===this.open)this.ws.send(n.encode(c,e,n));else if(!1===this.open||s)this.messages.push({send:()=>this.ws.send(n.encode(c,e,n))}),s&&this.connect();else if(null===this.open)throw new Error("Attempting to send via closed WebSocket connection!");return new Promise((e,t)=>{this.queue[c]={ff:e,data_type:n.data_type,sent_time:n.timer?Date.now():null,timeout:sett(n.timeout,()=>{this.queue[c]&&(t({"Websocket timeout expired: ":n.timeout,"for the message":o}),delete this.queue[c])})}})})}}module.exports=WebSocketClient;

@@ -37,34 +37,50 @@ {

"scripts": {
"lint": "./node_modules/.bin/tslint 'src/**/*.ts'",
"test": "npm run prod:es && npm run test:compile && npm run test:exec",
"test:compile": "./node_modules/.bin/tsc -p ./test/",
"test:exec": "./node_modules/.bin/ava ./test/dist/test/src/index.js",
"dev": "rollup --watch -c --config rollup.config.js --environment INCLUDE_DEPS,BUILD:development",
"prod:cjs": "rollup -c --config rollup.config.js --environment INCLUDE_DEPS,BUILD:cjs",
"prod:es": "rollup -c --config rollup.config.js --environment INCLUDE_DEPS,BUILD:es",
"lint": "tslint 'src/**/*.ts'",
"test": "npm run prod:cjs && ava",
"test:lazy": "ava",
"dev": "rollup --watch -c",
"prod:cjs": "cross-env BUILD=cjs rollup -c",
"prod:es": "cross-env BUILD=es rollup -c",
"prod": "npm run prod:es && npm run prod:cjs"
},
"version": "2.0.1",
"version": "2.1.1",
"ava": {
"files": [
"./test/specs/*.ts"
],
"serial": true,
"failFast": true,
"timeout": "2m",
"compileEnhancements": false,
"extensions": [
"ts"
],
"require": [
"ts-node/register"
]
},
"devDependencies": {
"@types/node": "^8.0.58",
"@types/ramda": "^0.25.8",
"@types/ws": "^3.2.1",
"ava": "^1.0.0-rc.2",
"axios": "^0.17.1",
"express": "^4.16.2",
"ramda": "^0.25.0",
"@types/node": "^10.12.24",
"@types/ramda": "^0.25.48",
"@types/ws": "^6.0.1",
"ava": "^1.2.1",
"axios": "^0.18.0",
"cross-env": "^5.2.0",
"express": "^4.16.4",
"ramda": "^0.26.1",
"randomatic": "^3.1.1",
"rollup": "^0.52.1",
"rollup-plugin-alias": "^1.4.0",
"rollup-plugin-commonjs": "^8.2.6",
"rollup-plugin-node-resolve": "^3.0.0",
"rollup": "^1.1.2",
"rollup-plugin-alias": "^1.5.1",
"rollup-plugin-commonjs": "^9.2.0",
"rollup-plugin-node-resolve": "^4.0.0",
"rollup-plugin-resolve-aliases": "^0.2.0",
"rollup-plugin-typescript2": "^0.17.2",
"rollup-plugin-uglify": "^4.0.0",
"tslint": "^5.8.0",
"typescript": "^3.1.6",
"rollup-plugin-terser": "4.0.4",
"rollup-plugin-typescript2": "^0.19.2",
"ts-node": "^8.0.2",
"tslint": "^5.12.1",
"typescript": "^3.3.3",
"uglify-es": "^3.3.9",
"ws": "^3.3.2"
"ws": "^6.1.3"
},
"types": "./dist/src/WS.d.ts"
}

@@ -5,3 +5,3 @@ # WebsocketPromisify

a nice this readme version: https://houd1ni.github.io/WebsocketPromisify/
A nice-looking this readme version: https://houd1ni.github.io/WebsocketPromisify/

@@ -22,3 +22,3 @@ Makes websocket's API just like REST with Promise-like API, with native Promises.

- Automatically reconnects.
- You can usEncodere the WebSocket (or your ws-like implementation) further in other stuff (socket property).
- You can use native WebSocket or ws-like implementation (ws npm package) via `socket` property.
- And provide your own socket instance via socket config prop.

@@ -55,3 +55,4 @@ - Any id and data keys to negotiate with your back-end.

// Set up.
// Required. URL to connect.
// Required. URL to connect without a protocol.
// Can start with /, then current page host and port will be used.
url: 'localhost',

@@ -108,5 +109,4 @@ // Timeout after sending a message before it drops with error.

import WSP from 'wspromisify'
import WSP from 'wspromisify' // or const WSP = require('wspromisify') in Node.
const somehost = 'example.com:8080'

@@ -113,0 +113,0 @@

@@ -5,3 +5,3 @@ import commonjs from 'rollup-plugin-commonjs'

import * as uglifyES from 'uglify-es'
import { uglify } from 'rollup-plugin-uglify'
import { terser } from 'rollup-plugin-terser'

@@ -29,4 +29,4 @@ export default {

}),
uglify({}, uglifyES.minify)
terser()
]
}

@@ -12,3 +12,3 @@ import './types'

this.onReadyQueue.forEach((fn: Function) => fn())
this.onReadyQueue = []
this.onReadyQueue.splice(0)
const {id_key, data_key} = config.server

@@ -23,6 +23,6 @@ // Send all pending messages.

add_event(ws, 'close', async (e) => {
add_event(ws, 'close', async () => {
this.log('Closed.')
this.open = false
this.onCloseQueue.forEach((fn) => fn())
this.onCloseQueue.forEach((fn: Function) => fn())
this.onCloseQueue = []

@@ -82,5 +82,5 @@ // Auto reconnect.

const connectLib = function(ff) {
const connectLib = function(ff: Function) {
if(this.open === true) {
return ff(1)
return ff(null)
}

@@ -90,4 +90,10 @@ const config = this.config

this.ws = ws
if(!ws || ws.readyState > 1) {
this.ws = null
this.log('Error: ready() on closing or closed state! Status 2.')
return ff(2)
}
add_event(ws, 'error', once((e) => {
add_event(ws, 'error', once(() => {
this.ws = null

@@ -98,9 +104,8 @@ this.log('Error status 3.')

}))
// Because 'open' won't be envoked on opened socket.
if(config.socket && ws.readyState === 1) {
if(ws.readyState) {
init.call(this, ws)
ff(null)
} else {
add_event(ws, 'open', once((e) => {
add_event(ws, 'open', once(() => {
this.log('Opened.')

@@ -107,0 +112,0 @@ init.call(this, ws)

@@ -20,6 +20,12 @@ import './types'

const sett = (
a: number,
b: { (): void; (...args: any[]): void; }
) => setTimeout(b, a)
export {
add_event,
once,
sett
}
import SHA1 from './SHA1'
import packNumber from './packNumber'
import connectLib from './connectLib'
import { add_event } from './utils'
import { add_event, sett } from './utils'
import { enrichConfig } from './config'
import './types'
const MAX_32 = 2**31 - 1
/* .send(your_data) wraps request to server with {id: `hash`, data: `actually your data`},

@@ -11,34 +14,2 @@ returns a Promise, that will be rejected after a timeout or

*/
const sett = (
a: number,
b: { (): void; (...args: any[]): void; }
) => setTimeout(b, a)
const default_config = <wsc.Config>{
data_type: 'json', // ToDo some other stuff maybe.
// Debug features.
log: ((event = '', time = 0, message = '') => null),
timer: false,
// Set up.
url: 'localhost',
timeout: 1400,
reconnect: 2, // Reconnect timeout in seconds or null.
lazy: false,
socket: null,
adapter: ((host, protocols) => new WebSocket(host, protocols)),
encode: (key, data, { server }) => JSON.stringify({
[server.id_key]: key,
[server.data_key]: data
}),
decode: (rawMessage) => JSON.parse(rawMessage),
protocols: [],
pipes: [],
server: {
id_key: 'id',
data_key: 'data'
}
}
class WebSocketClient implements wsc.WebSocketClient {

@@ -48,2 +19,3 @@

private ws = null
// in use by side functions.
private forcibly_closed = false

@@ -77,3 +49,3 @@ private reconnect_timeout: NodeJS.Timer = null

private async connect() { // returns status if won't open or null if ok.
return new Promise((ff, rj) => {
return new Promise((ff) => {
connectLib.call(this, ff)

@@ -88,3 +60,3 @@ })

public async ready() {
return new Promise((ff, rj) => {
return new Promise((ff) => {
if(this.open) {

@@ -131,7 +103,6 @@ ff()

const message = {}
const id_key = config.server.id_key
const data_key = config.server.data_key
const first_time_lazy = config.lazy && !this.open
const message_id = SHA1('' + ((Math.random()*1e5)|0)).slice(0, 20)
const message_id = packNumber((Math.random()*(MAX_32-10))|0)
if(typeof opts.top === 'object') {

@@ -148,2 +119,3 @@ if(opts.top[data_key]) {

console.log({open: this.open, encoded: config.encode(message_id, message_data, config)})
if(this.open === true) {

@@ -182,7 +154,3 @@ this.ws.send(config.encode(message_id, message_data, config))

constructor(user_config: wsc.UserConfig = {}) {
// Config.
const config = {} as wsc.Config
Object.assign(config, default_config)
Object.assign(config, user_config)
this.config = config
this.config = enrichConfig(user_config)
// Init.

@@ -194,3 +162,3 @@ this.init_flush()

this.forcibly_closed = false
if(!config.lazy) {
if(!this.config.lazy) {
this.connect()

@@ -197,0 +165,0 @@ }

@@ -12,2 +12,3 @@ {

"experimentalDecorators": true,
"noUnusedParameters": true,
"noUnusedLocals": false,

@@ -14,0 +15,0 @@ "outDir": "./dist/",

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc