wspromisify 2.4.1 → 2.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bundle.cjs +1 -0
- package/dist/bundle.d.ts +77 -0
- package/dist/bundle.mjs +1 -0
- package/package.json +94 -92
- package/rollup.config.js +19 -12
- package/src/WS.ts +16 -17
- package/src/connectLib.ts +1 -4
- package/src/types.ts +2 -2
- package/test/mock/{WS.ts → WS.js} +5 -8
- package/test/mock/index.js +52 -0
- package/test/specs/{close.ts → close.js} +3 -6
- package/test/specs/{drops.ts → drops.js} +3 -6
- package/test/specs/{echo.ts → echo.js} +3 -6
- package/test/specs/{existing_socket.ts → existing_socket.js} +5 -10
- package/test/specs/{lazy.ts → lazy.js} +3 -7
- package/test/specs/{ready.ts → ready.js} +3 -7
- package/test/specs/{reconnect.ts → reconnect.js} +3 -8
- package/test/specs/{sendBeforeOpen.ts → sendBeforeOpen.js} +3 -6
- package/test/specs/{socket.ts → socket.js} +3 -6
- package/test/specs/{utils_once.ts → utils_once.js} +3 -4
- package/test/utils.js +27 -0
- package/tsconfig.json +10 -13
- package/dist/src/SHA1.d.ts +0 -2
- package/dist/src/WS.d.ts +0 -23
- package/dist/src/config.d.ts +0 -3
- package/dist/src/connectLib.d.ts +0 -3
- package/dist/src/packNumber.d.ts +0 -2
- package/dist/src/types.d.ts +0 -48
- package/dist/src/utils.d.ts +0 -9
- package/dist/ws.esm.js +0 -15
- package/dist/ws.esm.js.map +0 -1
- package/dist/ws.js +0 -15
- package/dist/ws.js.map +0 -1
- package/src/packNumber.ts +0 -12
- package/test/_register.js +0 -5
- package/test/mock/index.ts +0 -41
- package/test/utils.ts +0 -31
- /package/test/specs/{encode-decode.ts → encode-decode.js} +0 -0
package/dist/bundle.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";const e=Symbol("Placeholder"),t=t=>{let n=0;for(const s of t)s!==e&&n++;return n},n=(t,n)=>{const s=t.length,o=t.slice(),r=n.length;let i=r,c=0;for(;i&&c<s;c++)o[c]===e&&(o[c]=n[r-i],i--);for(c=s;i;c++,i--)o[c]=n[r-i];return o},s=(e,o,r)=>{const i=e.length-o.length-t(r);if(i<1)return e(...n(o,r));{const t=(...t)=>s(e,n(o,r),t);return t.$args_left=i,t}},o=e=>(...n)=>e.length>t(n)?s(e,[],n):e(...n),r=t=>function(n){return n===e?t:t(n)};function i(t){return function(n,s){const o=n===e,i=arguments.length;if(1===i&&o)throw new Error("Senseless placeholder usage.");return arguments.length>1?o?r((e=>t(e,s))):t(n,s):e=>t(n,e)}}function c(e){return o(e)}const l=void 0,u=1/0,a=e=>typeof e,h=e=>null===e,f={u:"U",b:"B",n:"N",s:"S",f:"F"},d=e=>{const t=a(e);return"object"===t?h(e)?"Null":e.constructor.name:f[t[0]]+t.slice(1)},g=i(((e,t)=>(t.push(e),t))),p=c(((e,t,n)=>n.reduce(e,t))),m=c(((e,t,n)=>{for(let s in n)switch(d(n[s])){case"Array":if(e>1&&"Array"===d(t[s]))switch(e){case 2:const o=t[s],r=n[s];for(const t in r)o[t]?m(e,o[t],r[t]):o[t]=r[t];break;case 3:t[s].push(...n[s])}else t[s]=n[s];break;case"Object":if("Object"===d(t[s])){m(e,t[s],n[s]);break}default:t[s]=n[s]}return t}));m(1),m(2),m(3);const y=i(((e,t)=>{const n=d(e);if(n===d(t)&&("Object"===n||"Array"==n)){if(h(e)||h(t))return e===t;if(e===t)return!0;for(const n of[e,t])for(const s in n)if(!(n===t&&s in e||n===e&&s in t&&y(e[s],t[s])))return!1;return!0}return e===t})),w=o(((e,t,n,s)=>e(s)?t(s):n(s))),b=(...t)=>(...n)=>{let s,o=!0;for(let r=j(t)-1;r>-1;r--)o?(o=!1,s=t[r](...n)):s=s===e?t[r]():t[r](s);return s},_=i(((e,t)=>t[e])),k=i(((e,t)=>{if((e=>"string"===a(e))(t))return t.includes(e);for(const n of t)if(y(n,e))return!0;return!1})),S=c(((e,t,n)=>n.slice(e,(e=>"number"==a(e))(t)?t:u))),v=_(0);S(1,u);const E=e=>h(e)||(e=>e===l)(e),j=e=>e.length,N=e=>()=>e,O=i(((e,t)=>t.split(e))),A=e=>p(((e,t)=>k(t,e)?e:g(t,e)),[],e),P=c(((e,t,n)=>({...n,[e]:t}))),q=i(((e,t)=>t[e])),Q=c(((e,t,n)=>w(j,(()=>E(n)?e:b(w(E,N(e),(n=>Q(e,S(1,u,t),n))),(e=>i(((t,n)=>e(n,t))))(q)(n),v)(t)),N(n),t)));Q(l);const $=/^(.*?)(8|16|32|64)(Clamped)?Array$/,W=(e,t=!1)=>{const n=d(e);switch(n){case"Null":case"String":case"Number":case"Boolean":case"Symbol":return e;case"Array":return t?[...e]:R(b(W,((...e)=>e[0])),e);case"Object":if(t)return{...e};const s={};for(let t in e)s[t]=W(e[t]);return s;default:return $.test(n)?e.constructor.from(e):e}},C=c(((e,t,n)=>p(e,W(t),n))),R=i(((e,t)=>t.map(e))),{floor:z}=Math;let B,D;const I=b((e=>C(((e,t)=>P(...t,e)),{},e)),R(((e,t)=>[e,t])),O(""));(e=>{if(!(e=>b(y(j(e)),j,A,O(""))(e))(e))throw new Error("Not all chars are unique!");B=e,D=B.length,I(B)})("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");const T=(e,t,n)=>e.addEventListener(t,n),U=e=>{let t=!1,n=null;return(...s)=>t?n:(t=!0,n=e(...s))},x=(e,t)=>setTimeout(t,e),F=function(e){const t=this.config;this.open=!0,this.onReadyQueue.forEach((e=>e())),this.onReadyQueue.splice(0);const{id_key:n,data_key:s}=t.server;if(this.handlers.open.forEach((e=>e())),this.messages.forEach((e=>e.send())),null!==this.reconnect_timeout&&(clearInterval(this.reconnect_timeout),this.reconnect_timeout=null),t.ping){const e=setInterval((()=>{this.open&&this.send(t.ping.content),this.forcibly_closed&&clearInterval(e)}),1e3*t.ping.interval)}T(e,"close",(async()=>{this.log("close"),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=async()=>{this.log("reconnect"),null!==this.ws&&(this.ws.close(),this.ws=null);null!==await this.connect()&&(this.reconnect_timeout=setTimeout(t,1e3*e))};t()}this.forcibly_closed=!1})),T(e,"message",(e=>{try{const o=t.decode(e.data);if(this.handlers.message.forEach((t=>t({...e,data:o}))),o[n]){const e=this.queue[o[n]];if(e){const t=e.sent_time?Date.now()-e.sent_time:null;this.log("message",o[s],t),e.ff(o[s]),clearTimeout(e.timeout),delete this.queue[o[n]]}}}catch(t){console.error(t,`WSP: Decode error. Got: ${e.data}`)}}))};var J=function(e){if(!0===this.open)return e(null);const t=this.config,n=t.socket||t.adapter(t.url,t.protocols);if(this.ws=n,!n||n.readyState>1)return this.ws=null,this.log("error","ready() on closing or closed state! status 2."),e(2);T(n,"error",U((t=>(this.log("error","status 3."),this.handlers.error.forEach((e=>e(t))),this.ws=null,e(3))))),n.readyState?(F.call(this,n),e(null)):T(n,"open",U((()=>(this.log("open"),F.call(this,n),e(null)))))};const L={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"},ping:{interval:55,content:{}}},M=Symbol("Placeholder"),G=e=>{let t=0;for(const n of e)n!==M&&t++;return t},H=(e,t)=>{const n=e.length,s=e.slice(),o=t.length;let r=o,i=0;for(;r&&i<n;i++)s[i]===M&&(s[i]=t[o-r],r--);for(i=n;r;i++,r--)s[i]=t[o-r];return s},K=(e,t,n)=>{const s=e.length-t.length-G(n);if(s<1)return e(...H(t,n));{const o=(...s)=>K(e,H(t,n),s);return o.$args_left=s,o}},V=e=>(...t)=>e.length>G(t)?K(e,[],t):e(...t),X=e=>function(t){return t===M?e:e(t)};function Y(e){return function(t,n){const s=t===M,o=arguments.length;if(1===o&&s)throw new Error("Senseless placeholder usage.");return arguments.length>1?s?X((t=>e(t,n))):e(t,n):n=>e(t,n)}}function Z(e){return V(e)}const ee=void 0,te=1/0,ne=e=>typeof e,se=e=>null===e,oe={u:"U",b:"B",n:"N",s:"S",f:"F"},re=e=>{const t=ne(e);return"object"===t?se(e)?"Null":e.constructor.name:oe[t[0]]+t.slice(1)},ie=Z(((e,t,n)=>{for(let s in n)switch(re(n[s])){case"Array":if(e>1&&"Array"===re(t[s]))switch(e){case 2:const o=t[s],r=n[s];for(const t in r)o[t]?ie(e,o[t],r[t]):o[t]=r[t];break;case 3:t[s].push(...n[s])}else t[s]=n[s];break;case"Object":if("Object"===re(t[s])){ie(e,t[s],n[s]);break}default:t[s]=n[s]}return t}));ie(1),ie(2),ie(3);const ce=V(((e,t,n,s)=>e(s)?t(s):n(s))),le=(...e)=>(...t)=>{let n,s=!0;for(let o=de(e)-1;o>-1;o--)s?(s=!1,n=e[o](...t)):n=n===M?e[o]():e[o](n);return n},ue=Y(((e,t)=>t[e])),ae=Z(((e,t,n)=>n.slice(e,(e=>"number"==ne(e))(t)?t:te))),he=ue(0);ae(1,te);const fe=e=>se(e)||(e=>e===ee)(e),de=e=>e.length,ge=e=>()=>e,pe=ge(!0),me=Y(((e,t)=>t[e])),ye=Z(((e,t,n)=>ce(de,(()=>fe(n)?e:le(ce(fe,ge(e),(n=>ye(e,ae(1,te,t),n))),(e=>Y(((t,n)=>e(n,t))))(me)(n),he)(t)),ge(n),t)));ye(ee);module.exports=class{open=!1;ws=null;forcibly_closed=!1;reconnect_timeout=null;queue={};messages=[];onReadyQueue=[];onCloseQueue=[];handlers={open:[],message:[],close:[],error:[]};config={};init_flush(){this.queue={},this.messages=[]}log(e,t=null,n=null){const s=this.config;null!==n?s.log(e,n,t):s.timer?s.log(e,null,t):s.log(e,t)}async connect(){return new Promise((e=>{J.call(this,e)}))}get socket(){return this.ws}async ready(){return new Promise((e=>{this.open?e():this.onReadyQueue.push(e)}))}on(e,t,n=pe,s=!1){const o=e=>n(e)&&t(e);return s?T(this.ws,e,o):this.handlers[e].push(o)}async close(){return new Promise(((e,t)=>{null===this.ws?t("WSP: closing a non-inited socket!"):(this.open=!1,this.onCloseQueue.push((()=>{this.init_flush(),this.ws=null,this.forcibly_closed=!0,e(null)})),this.ws.close())}))}async send(e,t={}){this.log("send",e);const n=this.config,s={},o=n.server.data_key,r=n.lazy&&!this.open,i=(e=>{let t="";for(;e>0;)t=B[e%D]+t,e=z(e/D);return t||"0"})(2147483637*Math.random()|0);if("object"==typeof t.top){if(t.top[o])throw new Error("Attempting to set data key/token via send() options!");Object.assign(s,t.top)}if(n.pipes.forEach((t=>e=t(e))),!0===this.open)this.ws.send(n.encode(i,e,n));else if(!1===this.open||r)this.messages.push({send:()=>this.ws.send(n.encode(i,e,n))}),r&&this.connect();else if(null===this.open)throw new Error("Attempting to send via closed WebSocket connection!");return new Promise(((t,s)=>{this.queue[i]={ff:t,data_type:n.data_type,sent_time:n.timer?Date.now():null,timeout:x(n.timeout,(()=>{this.queue[i]&&(s({"Websocket timeout expired: ":n.timeout,"for the message ":e}),delete this.queue[i])}))}}))}constructor(e={}){this.config=(e=>{const t=Object.assign({},L,e),n=t.url;if("/"==n[0])try{const e=location.protocol.includes("s:")?"wss":"ws";t.url=`${e}://${location.hostname}:${location.port}${n}`}catch(e){throw new Error("WSP: URL starting with / in non-browser environment!")}return t})(e),this.init_flush(),this.open=!1,this.reconnect_timeout=null,this.forcibly_closed=!1,this.config.lazy||this.connect()}};
|
package/dist/bundle.d.ts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// Generated by dts-bundle-generator v7.1.0
|
|
2
|
+
|
|
3
|
+
export declare namespace wsc {
|
|
4
|
+
interface DataObject {
|
|
5
|
+
[key: string]: any;
|
|
6
|
+
}
|
|
7
|
+
type WSEvent = "open" | "message" | "close" | "error";
|
|
8
|
+
/** Minimal socket-like interface. */
|
|
9
|
+
interface Socket {
|
|
10
|
+
readyState: number;
|
|
11
|
+
send(...any: any[]): void;
|
|
12
|
+
close(): void;
|
|
13
|
+
addEventListener(event: string, handler: ((event: any) => any), ...any: any[]): void;
|
|
14
|
+
}
|
|
15
|
+
type AsyncErrCode = Promise<number | null | {}>;
|
|
16
|
+
type EventHandler = (e: any) => void;
|
|
17
|
+
type DataPipe = (message: any) => any;
|
|
18
|
+
type DataType = "json" | "string";
|
|
19
|
+
interface Config {
|
|
20
|
+
data_type: DataType;
|
|
21
|
+
log(event: string, time?: number | null, message?: any): void;
|
|
22
|
+
log(event: string, message?: any): void;
|
|
23
|
+
timer: boolean;
|
|
24
|
+
url: string;
|
|
25
|
+
timeout: number;
|
|
26
|
+
reconnect: number;
|
|
27
|
+
lazy: boolean;
|
|
28
|
+
socket: Socket | null;
|
|
29
|
+
adapter: (host: string, protocols?: string[]) => Socket;
|
|
30
|
+
encode: (key: string, message: any, config: Config) => any;
|
|
31
|
+
decode: (rawMessage: any) => {
|
|
32
|
+
[id_or_data_key: string]: string;
|
|
33
|
+
};
|
|
34
|
+
protocols: string[];
|
|
35
|
+
pipes: DataPipe[];
|
|
36
|
+
server: {
|
|
37
|
+
id_key: string;
|
|
38
|
+
data_key: string;
|
|
39
|
+
};
|
|
40
|
+
ping: {
|
|
41
|
+
interval: number;
|
|
42
|
+
content: any;
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
type UserConfig = Partial<Config>;
|
|
46
|
+
interface SendOptions {
|
|
47
|
+
top: any;
|
|
48
|
+
data_type: DataType;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
declare class WebSocketClient {
|
|
52
|
+
private open;
|
|
53
|
+
private ws;
|
|
54
|
+
private forcibly_closed;
|
|
55
|
+
private reconnect_timeout;
|
|
56
|
+
private queue;
|
|
57
|
+
private messages;
|
|
58
|
+
private onReadyQueue;
|
|
59
|
+
private onCloseQueue;
|
|
60
|
+
private handlers;
|
|
61
|
+
private config;
|
|
62
|
+
private init_flush;
|
|
63
|
+
private log;
|
|
64
|
+
private connect;
|
|
65
|
+
get socket(): wsc.Socket | null;
|
|
66
|
+
ready(): Promise<void>;
|
|
67
|
+
on(event_name: wsc.WSEvent, handler: (data: any) => any, predicate?: (data: any) => boolean, raw?: boolean): number | void;
|
|
68
|
+
close(): wsc.AsyncErrCode;
|
|
69
|
+
send<RequestDataType = any, ResponseDataType = any>(message_data: RequestDataType, opts?: wsc.SendOptions): Promise<ResponseDataType>;
|
|
70
|
+
constructor(user_config?: wsc.UserConfig);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export {
|
|
74
|
+
WebSocketClient as default,
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
export {};
|
package/dist/bundle.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=Symbol("Placeholder"),t=t=>{let n=0;for(const s of t)s!==e&&n++;return n},n=(t,n)=>{const s=t.length,o=t.slice(),r=n.length;let i=r,c=0;for(;i&&c<s;c++)o[c]===e&&(o[c]=n[r-i],i--);for(c=s;i;c++,i--)o[c]=n[r-i];return o},s=(e,o,r)=>{const i=e.length-o.length-t(r);if(i<1)return e(...n(o,r));{const t=(...t)=>s(e,n(o,r),t);return t.$args_left=i,t}},o=e=>(...n)=>e.length>t(n)?s(e,[],n):e(...n),r=t=>function(n){return n===e?t:t(n)};function i(t){return function(n,s){const o=n===e,i=arguments.length;if(1===i&&o)throw new Error("Senseless placeholder usage.");return arguments.length>1?o?r((e=>t(e,s))):t(n,s):e=>t(n,e)}}function c(e){return o(e)}const l=void 0,u=1/0,a=e=>typeof e,h=e=>null===e,f={u:"U",b:"B",n:"N",s:"S",f:"F"},d=e=>{const t=a(e);return"object"===t?h(e)?"Null":e.constructor.name:f[t[0]]+t.slice(1)},g=i(((e,t)=>(t.push(e),t))),p=c(((e,t,n)=>n.reduce(e,t))),m=c(((e,t,n)=>{for(let s in n)switch(d(n[s])){case"Array":if(e>1&&"Array"===d(t[s]))switch(e){case 2:const o=t[s],r=n[s];for(const t in r)o[t]?m(e,o[t],r[t]):o[t]=r[t];break;case 3:t[s].push(...n[s])}else t[s]=n[s];break;case"Object":if("Object"===d(t[s])){m(e,t[s],n[s]);break}default:t[s]=n[s]}return t}));m(1),m(2),m(3);const y=i(((e,t)=>{const n=d(e);if(n===d(t)&&("Object"===n||"Array"==n)){if(h(e)||h(t))return e===t;if(e===t)return!0;for(const n of[e,t])for(const s in n)if(!(n===t&&s in e||n===e&&s in t&&y(e[s],t[s])))return!1;return!0}return e===t})),w=o(((e,t,n,s)=>e(s)?t(s):n(s))),b=(...t)=>(...n)=>{let s,o=!0;for(let r=j(t)-1;r>-1;r--)o?(o=!1,s=t[r](...n)):s=s===e?t[r]():t[r](s);return s},_=i(((e,t)=>t[e])),k=i(((e,t)=>{if((e=>"string"===a(e))(t))return t.includes(e);for(const n of t)if(y(n,e))return!0;return!1})),S=c(((e,t,n)=>n.slice(e,(e=>"number"==a(e))(t)?t:u))),v=_(0);S(1,u);const E=e=>h(e)||(e=>e===l)(e),j=e=>e.length,N=e=>()=>e,O=i(((e,t)=>t.split(e))),A=e=>p(((e,t)=>k(t,e)?e:g(t,e)),[],e),P=c(((e,t,n)=>({...n,[e]:t}))),q=i(((e,t)=>t[e])),Q=c(((e,t,n)=>w(j,(()=>E(n)?e:b(w(E,N(e),(n=>Q(e,S(1,u,t),n))),(e=>i(((t,n)=>e(n,t))))(q)(n),v)(t)),N(n),t)));Q(l);const $=/^(.*?)(8|16|32|64)(Clamped)?Array$/,W=(e,t=!1)=>{const n=d(e);switch(n){case"Null":case"String":case"Number":case"Boolean":case"Symbol":return e;case"Array":return t?[...e]:R(b(W,((...e)=>e[0])),e);case"Object":if(t)return{...e};const s={};for(let t in e)s[t]=W(e[t]);return s;default:return $.test(n)?e.constructor.from(e):e}},C=c(((e,t,n)=>p(e,W(t),n))),R=i(((e,t)=>t.map(e))),{floor:z}=Math;let B,D;const I=b((e=>C(((e,t)=>P(...t,e)),{},e)),R(((e,t)=>[e,t])),O(""));(e=>{if(!(e=>b(y(j(e)),j,A,O(""))(e))(e))throw new Error("Not all chars are unique!");B=e,D=B.length,I(B)})("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");const T=(e,t,n)=>e.addEventListener(t,n),U=e=>{let t=!1,n=null;return(...s)=>t?n:(t=!0,n=e(...s))},x=(e,t)=>setTimeout(t,e),F=function(e){const t=this.config;this.open=!0,this.onReadyQueue.forEach((e=>e())),this.onReadyQueue.splice(0);const{id_key:n,data_key:s}=t.server;if(this.handlers.open.forEach((e=>e())),this.messages.forEach((e=>e.send())),null!==this.reconnect_timeout&&(clearInterval(this.reconnect_timeout),this.reconnect_timeout=null),t.ping){const e=setInterval((()=>{this.open&&this.send(t.ping.content),this.forcibly_closed&&clearInterval(e)}),1e3*t.ping.interval)}T(e,"close",(async()=>{this.log("close"),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=async()=>{this.log("reconnect"),null!==this.ws&&(this.ws.close(),this.ws=null);null!==await this.connect()&&(this.reconnect_timeout=setTimeout(t,1e3*e))};t()}this.forcibly_closed=!1})),T(e,"message",(e=>{try{const o=t.decode(e.data);if(this.handlers.message.forEach((t=>t({...e,data:o}))),o[n]){const e=this.queue[o[n]];if(e){const t=e.sent_time?Date.now()-e.sent_time:null;this.log("message",o[s],t),e.ff(o[s]),clearTimeout(e.timeout),delete this.queue[o[n]]}}}catch(t){console.error(t,`WSP: Decode error. Got: ${e.data}`)}}))};var J=function(e){if(!0===this.open)return e(null);const t=this.config,n=t.socket||t.adapter(t.url,t.protocols);if(this.ws=n,!n||n.readyState>1)return this.ws=null,this.log("error","ready() on closing or closed state! status 2."),e(2);T(n,"error",U((t=>(this.log("error","status 3."),this.handlers.error.forEach((e=>e(t))),this.ws=null,e(3))))),n.readyState?(F.call(this,n),e(null)):T(n,"open",U((()=>(this.log("open"),F.call(this,n),e(null)))))};const L={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"},ping:{interval:55,content:{}}},M=Symbol("Placeholder"),G=e=>{let t=0;for(const n of e)n!==M&&t++;return t},H=(e,t)=>{const n=e.length,s=e.slice(),o=t.length;let r=o,i=0;for(;r&&i<n;i++)s[i]===M&&(s[i]=t[o-r],r--);for(i=n;r;i++,r--)s[i]=t[o-r];return s},K=(e,t,n)=>{const s=e.length-t.length-G(n);if(s<1)return e(...H(t,n));{const o=(...s)=>K(e,H(t,n),s);return o.$args_left=s,o}},V=e=>(...t)=>e.length>G(t)?K(e,[],t):e(...t),X=e=>function(t){return t===M?e:e(t)};function Y(e){return function(t,n){const s=t===M,o=arguments.length;if(1===o&&s)throw new Error("Senseless placeholder usage.");return arguments.length>1?s?X((t=>e(t,n))):e(t,n):n=>e(t,n)}}function Z(e){return V(e)}const ee=void 0,te=1/0,ne=e=>typeof e,se=e=>null===e,oe={u:"U",b:"B",n:"N",s:"S",f:"F"},re=e=>{const t=ne(e);return"object"===t?se(e)?"Null":e.constructor.name:oe[t[0]]+t.slice(1)},ie=Z(((e,t,n)=>{for(let s in n)switch(re(n[s])){case"Array":if(e>1&&"Array"===re(t[s]))switch(e){case 2:const o=t[s],r=n[s];for(const t in r)o[t]?ie(e,o[t],r[t]):o[t]=r[t];break;case 3:t[s].push(...n[s])}else t[s]=n[s];break;case"Object":if("Object"===re(t[s])){ie(e,t[s],n[s]);break}default:t[s]=n[s]}return t}));ie(1),ie(2),ie(3);const ce=V(((e,t,n,s)=>e(s)?t(s):n(s))),le=(...e)=>(...t)=>{let n,s=!0;for(let o=de(e)-1;o>-1;o--)s?(s=!1,n=e[o](...t)):n=n===M?e[o]():e[o](n);return n},ue=Y(((e,t)=>t[e])),ae=Z(((e,t,n)=>n.slice(e,(e=>"number"==ne(e))(t)?t:te))),he=ue(0);ae(1,te);const fe=e=>se(e)||(e=>e===ee)(e),de=e=>e.length,ge=e=>()=>e,pe=ge(!0),me=Y(((e,t)=>t[e])),ye=Z(((e,t,n)=>ce(de,(()=>fe(n)?e:le(ce(fe,ge(e),(n=>ye(e,ae(1,te,t),n))),(e=>Y(((t,n)=>e(n,t))))(me)(n),he)(t)),ge(n),t)));ye(ee);class we{open=!1;ws=null;forcibly_closed=!1;reconnect_timeout=null;queue={};messages=[];onReadyQueue=[];onCloseQueue=[];handlers={open:[],message:[],close:[],error:[]};config={};init_flush(){this.queue={},this.messages=[]}log(e,t=null,n=null){const s=this.config;null!==n?s.log(e,n,t):s.timer?s.log(e,null,t):s.log(e,t)}async connect(){return new Promise((e=>{J.call(this,e)}))}get socket(){return this.ws}async ready(){return new Promise((e=>{this.open?e():this.onReadyQueue.push(e)}))}on(e,t,n=pe,s=!1){const o=e=>n(e)&&t(e);return s?T(this.ws,e,o):this.handlers[e].push(o)}async close(){return new Promise(((e,t)=>{null===this.ws?t("WSP: closing a non-inited socket!"):(this.open=!1,this.onCloseQueue.push((()=>{this.init_flush(),this.ws=null,this.forcibly_closed=!0,e(null)})),this.ws.close())}))}async send(e,t={}){this.log("send",e);const n=this.config,s={},o=n.server.data_key,r=n.lazy&&!this.open,i=(e=>{let t="";for(;e>0;)t=B[e%D]+t,e=z(e/D);return t||"0"})(2147483637*Math.random()|0);if("object"==typeof t.top){if(t.top[o])throw new Error("Attempting to set data key/token via send() options!");Object.assign(s,t.top)}if(n.pipes.forEach((t=>e=t(e))),!0===this.open)this.ws.send(n.encode(i,e,n));else if(!1===this.open||r)this.messages.push({send:()=>this.ws.send(n.encode(i,e,n))}),r&&this.connect();else if(null===this.open)throw new Error("Attempting to send via closed WebSocket connection!");return new Promise(((t,s)=>{this.queue[i]={ff:t,data_type:n.data_type,sent_time:n.timer?Date.now():null,timeout:x(n.timeout,(()=>{this.queue[i]&&(s({"Websocket timeout expired: ":n.timeout,"for the message ":e}),delete this.queue[i])}))}}))}constructor(e={}){this.config=(e=>{const t=Object.assign({},L,e),n=t.url;if("/"==n[0])try{const e=location.protocol.includes("s:")?"wss":"ws";t.url=`${e}://${location.hostname}:${location.port}${n}`}catch(e){throw new Error("WSP: URL starting with / in non-browser environment!")}return t})(e),this.init_flush(),this.open=!1,this.reconnect_timeout=null,this.forcibly_closed=!1,this.config.lazy||this.connect()}}export{we as default};
|
package/package.json
CHANGED
|
@@ -1,92 +1,94 @@
|
|
|
1
|
-
{
|
|
2
|
-
"author": {
|
|
3
|
-
"name": "Michael Akiliev"
|
|
4
|
-
},
|
|
5
|
-
"bugs": {
|
|
6
|
-
"url": "https://github.com/houd1ni/WebsocketPromisify/issues"
|
|
7
|
-
},
|
|
8
|
-
"bundleDependencies": [],
|
|
9
|
-
"deprecated": false,
|
|
10
|
-
"description": "Wraps your WebSockets into Promise-based class with full d.ts typings on client & server",
|
|
11
|
-
"homepage": "https://github.com/houd1ni/WebsocketPromisify#readme",
|
|
12
|
-
"keywords": [
|
|
13
|
-
"WebSockets",
|
|
14
|
-
"WS",
|
|
15
|
-
"Promise",
|
|
16
|
-
"Socket",
|
|
17
|
-
"REST",
|
|
18
|
-
"Ajax",
|
|
19
|
-
"Easy",
|
|
20
|
-
"realtime",
|
|
21
|
-
"Middleware",
|
|
22
|
-
"JSON",
|
|
23
|
-
"Data",
|
|
24
|
-
"transport",
|
|
25
|
-
"API",
|
|
26
|
-
"async"
|
|
27
|
-
],
|
|
28
|
-
"license": "MIT",
|
|
29
|
-
"
|
|
30
|
-
"
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
"
|
|
38
|
-
"test": "
|
|
39
|
-
"
|
|
40
|
-
"
|
|
41
|
-
"
|
|
42
|
-
"prod:
|
|
43
|
-
"prod
|
|
44
|
-
"
|
|
45
|
-
},
|
|
46
|
-
"version": "2.4.
|
|
47
|
-
"
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
"
|
|
56
|
-
"
|
|
57
|
-
],
|
|
58
|
-
"
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
"@babel/
|
|
66
|
-
"@babel/
|
|
67
|
-
"@
|
|
68
|
-
"@
|
|
69
|
-
"@
|
|
70
|
-
"
|
|
71
|
-
"
|
|
72
|
-
"
|
|
73
|
-
"
|
|
74
|
-
"
|
|
75
|
-
"
|
|
76
|
-
"
|
|
77
|
-
"
|
|
78
|
-
"
|
|
79
|
-
"
|
|
80
|
-
"
|
|
81
|
-
"
|
|
82
|
-
"rollup
|
|
83
|
-
"rollup-plugin-
|
|
84
|
-
"
|
|
85
|
-
"
|
|
86
|
-
"
|
|
87
|
-
"
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
1
|
+
{
|
|
2
|
+
"author": {
|
|
3
|
+
"name": "Michael Akiliev"
|
|
4
|
+
},
|
|
5
|
+
"bugs": {
|
|
6
|
+
"url": "https://github.com/houd1ni/WebsocketPromisify/issues"
|
|
7
|
+
},
|
|
8
|
+
"bundleDependencies": [],
|
|
9
|
+
"deprecated": false,
|
|
10
|
+
"description": "Wraps your WebSockets into Promise-based class with full d.ts typings on client & server",
|
|
11
|
+
"homepage": "https://github.com/houd1ni/WebsocketPromisify#readme",
|
|
12
|
+
"keywords": [
|
|
13
|
+
"WebSockets",
|
|
14
|
+
"WS",
|
|
15
|
+
"Promise",
|
|
16
|
+
"Socket",
|
|
17
|
+
"REST",
|
|
18
|
+
"Ajax",
|
|
19
|
+
"Easy",
|
|
20
|
+
"realtime",
|
|
21
|
+
"Middleware",
|
|
22
|
+
"JSON",
|
|
23
|
+
"Data",
|
|
24
|
+
"transport",
|
|
25
|
+
"API",
|
|
26
|
+
"async"
|
|
27
|
+
],
|
|
28
|
+
"license": "MIT",
|
|
29
|
+
"name": "wspromisify",
|
|
30
|
+
"repository": {
|
|
31
|
+
"type": "git",
|
|
32
|
+
"url": "git+https://github.com/houd1ni/WebsocketPromisify.git"
|
|
33
|
+
},
|
|
34
|
+
"scripts": {
|
|
35
|
+
"lint": "tslint src/*.ts",
|
|
36
|
+
"test": "npm run gentypes && npm run prod:es && ava",
|
|
37
|
+
"test:report": "nyc npm test && nyc report --reporter=text-lcov > coverage.lcov && codecov",
|
|
38
|
+
"test:lazy": "ava",
|
|
39
|
+
"gentypes": "dts-bundle-generator --no-check -o dist/bundle.d.ts src/WS.ts",
|
|
40
|
+
"dev": "cross-env NODE_ENV=development BUILD=es rollup -c",
|
|
41
|
+
"prod:cjs": "cross-env NODE_ENV=production BUILD=cjs rollup -c",
|
|
42
|
+
"prod:es": "cross-env NODE_ENV=production BUILD=es rollup -c",
|
|
43
|
+
"prod": "npm run gentypes && npm run prod:es && npm run prod:cjs",
|
|
44
|
+
"all": "npm run dev && npm run prod"
|
|
45
|
+
},
|
|
46
|
+
"version": "2.4.3",
|
|
47
|
+
"type": "module",
|
|
48
|
+
"exports": {
|
|
49
|
+
".": {
|
|
50
|
+
"import": "./dist/bundle.mjs",
|
|
51
|
+
"require": "./dist/bundle.cjs"
|
|
52
|
+
}
|
|
53
|
+
},
|
|
54
|
+
"ava": {
|
|
55
|
+
"files": [
|
|
56
|
+
"./test/specs/*.js"
|
|
57
|
+
],
|
|
58
|
+
"failFast": true,
|
|
59
|
+
"timeout": "2m",
|
|
60
|
+
"nodeArguments": [
|
|
61
|
+
"--experimental-specifier-resolution=node"
|
|
62
|
+
]
|
|
63
|
+
},
|
|
64
|
+
"devDependencies": {
|
|
65
|
+
"@babel/core": "^7.20.12",
|
|
66
|
+
"@babel/polyfill": "^7.12.1",
|
|
67
|
+
"@babel/register": "^7.18.9",
|
|
68
|
+
"@rollup/plugin-commonjs": "^23.0.3",
|
|
69
|
+
"@rollup/plugin-node-resolve": "^15.0.1",
|
|
70
|
+
"@rollup/plugin-replace": "^5.0.1",
|
|
71
|
+
"@rollup/plugin-terser": "^0.1.0",
|
|
72
|
+
"@types/node": "^18.11.18",
|
|
73
|
+
"@types/ws": "^8.5.4",
|
|
74
|
+
"ava": "^5.1.1",
|
|
75
|
+
"axios": "^1.2.2",
|
|
76
|
+
"codecov": "^3.8.3",
|
|
77
|
+
"cross-env": "^7.0.3",
|
|
78
|
+
"dts-bundle-generator": "^7.1.0",
|
|
79
|
+
"express": "^4.18.2",
|
|
80
|
+
"nyc": "^15.1.0",
|
|
81
|
+
"randomatic": "^3.1.1",
|
|
82
|
+
"rollup": "^3.10.0",
|
|
83
|
+
"rollup-plugin-typescript2": "^0.34.1",
|
|
84
|
+
"ts-node": "^10.9.1",
|
|
85
|
+
"tslint": "^6.1.3",
|
|
86
|
+
"typescript": "^4.9.4",
|
|
87
|
+
"ws": "^8.12.0"
|
|
88
|
+
},
|
|
89
|
+
"types": "./dist/bundle.d.ts",
|
|
90
|
+
"dependencies": {
|
|
91
|
+
"pepka": "^1.0.0-beta.1",
|
|
92
|
+
"zipnum": "^1.0.0"
|
|
93
|
+
}
|
|
94
|
+
}
|
package/rollup.config.js
CHANGED
|
@@ -1,33 +1,40 @@
|
|
|
1
|
-
import commonjs from 'rollup
|
|
2
|
-
import resolve from 'rollup
|
|
1
|
+
import commonjs from '@rollup/plugin-commonjs'
|
|
2
|
+
import resolve from '@rollup/plugin-node-resolve'
|
|
3
3
|
import typescript from 'rollup-plugin-typescript2'
|
|
4
|
-
import
|
|
5
|
-
import replace from 'rollup
|
|
4
|
+
import terser from '@rollup/plugin-terser'
|
|
5
|
+
import replace from '@rollup/plugin-replace'
|
|
6
|
+
import tsc from 'typescript'
|
|
6
7
|
|
|
7
8
|
export default {
|
|
8
9
|
input: 'src/WS.ts',
|
|
9
10
|
output: {
|
|
10
|
-
file: process.env.
|
|
11
|
-
|
|
12
|
-
|
|
11
|
+
file: process.env.NODE_ENV=='development'
|
|
12
|
+
? 'dist/bundle.dev.js'
|
|
13
|
+
: process.env.BUILD == 'cjs' ? 'dist/bundle.cjs' : 'dist/bundle.mjs',
|
|
14
|
+
format: process.env.BUILD == 'cjs' ? 'cjs' : 'es',
|
|
15
|
+
name: 'wspromisify'
|
|
13
16
|
},
|
|
14
|
-
|
|
17
|
+
treeshake: { moduleSideEffects: false },
|
|
15
18
|
plugins: [
|
|
16
19
|
resolve(),
|
|
17
20
|
commonjs(),
|
|
18
21
|
typescript({
|
|
19
|
-
typescript:
|
|
22
|
+
typescript: tsc,
|
|
20
23
|
tsconfig: "./tsconfig.json",
|
|
21
24
|
tsconfigOverride: {
|
|
22
25
|
compilerOptions: {
|
|
23
26
|
sourceMap: false,
|
|
24
|
-
inlineSourceMap: process.env.NODE_ENV
|
|
27
|
+
inlineSourceMap: process.env.NODE_ENV=='development',
|
|
28
|
+
module: 'esnext'
|
|
25
29
|
}
|
|
26
30
|
}
|
|
27
31
|
}),
|
|
28
|
-
terser(),
|
|
32
|
+
process.env.NODE_ENV!='development' && terser(),
|
|
29
33
|
replace({
|
|
30
|
-
|
|
34
|
+
preventAssignment: true,
|
|
35
|
+
values: {
|
|
36
|
+
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
|
|
37
|
+
}
|
|
31
38
|
})
|
|
32
39
|
]
|
|
33
40
|
}
|
package/src/WS.ts
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
|
|
2
|
-
import packNumber from './packNumber'
|
|
1
|
+
import { zipnum } from 'zipnum'
|
|
3
2
|
import connectLib from './connectLib'
|
|
4
3
|
import { add_event, sett } from './utils'
|
|
5
4
|
import { enrichConfig } from './config'
|
|
6
5
|
import './types'
|
|
7
|
-
import { T } from '
|
|
6
|
+
import { AnyFunc, T } from 'pepka'
|
|
8
7
|
|
|
9
8
|
const MAX_32 = 2**31 - 1
|
|
10
9
|
|
|
@@ -14,15 +13,15 @@ const MAX_32 = 2**31 - 1
|
|
|
14
13
|
*/
|
|
15
14
|
class WebSocketClient {
|
|
16
15
|
|
|
17
|
-
private open =
|
|
18
|
-
private ws = null
|
|
16
|
+
private open = false
|
|
17
|
+
private ws: wsc.Socket|null = null
|
|
19
18
|
// in use by side functions.
|
|
20
19
|
private forcibly_closed = false
|
|
21
|
-
private reconnect_timeout: NodeJS.Timer = null
|
|
20
|
+
private reconnect_timeout: NodeJS.Timer|null = null
|
|
22
21
|
private queue = {}
|
|
23
|
-
private messages = []
|
|
24
|
-
private onReadyQueue = []
|
|
25
|
-
private onCloseQueue = []
|
|
22
|
+
private messages: any[] = []
|
|
23
|
+
private onReadyQueue: AnyFunc[] = []
|
|
24
|
+
private onCloseQueue: AnyFunc[] = []
|
|
26
25
|
private handlers = <{[event: string]: ((e: any) => void)[]}>{
|
|
27
26
|
open: [], message: [], close: [], error: []
|
|
28
27
|
}
|
|
@@ -33,7 +32,7 @@ class WebSocketClient {
|
|
|
33
32
|
this.messages = [] // send() queue
|
|
34
33
|
}
|
|
35
34
|
|
|
36
|
-
private log(event: string, message: any = null, time: number = null): void {
|
|
35
|
+
private log(event: string, message: any = null, time: number|null = null): void {
|
|
37
36
|
const config = this.config
|
|
38
37
|
if(time !== null) {
|
|
39
38
|
config.log(event, time, message)
|
|
@@ -75,7 +74,7 @@ class WebSocketClient {
|
|
|
75
74
|
const _handler: wsc.EventHandler = (event) =>
|
|
76
75
|
predicate(event) && handler(event)
|
|
77
76
|
return raw
|
|
78
|
-
? add_event(this.ws, event_name, _handler)
|
|
77
|
+
? add_event(this.ws as wsc.Socket, event_name, _handler)
|
|
79
78
|
: this.handlers[event_name].push(_handler)
|
|
80
79
|
}
|
|
81
80
|
|
|
@@ -84,7 +83,7 @@ class WebSocketClient {
|
|
|
84
83
|
if(this.ws === null) {
|
|
85
84
|
rj('WSP: closing a non-inited socket!')
|
|
86
85
|
} else {
|
|
87
|
-
this.open =
|
|
86
|
+
this.open = false
|
|
88
87
|
this.onCloseQueue.push(() => {
|
|
89
88
|
this.init_flush()
|
|
90
89
|
this.ws = null
|
|
@@ -106,7 +105,7 @@ class WebSocketClient {
|
|
|
106
105
|
const data_key = config.server.data_key
|
|
107
106
|
const first_time_lazy = config.lazy && !this.open
|
|
108
107
|
|
|
109
|
-
const message_id =
|
|
108
|
+
const message_id = zipnum((Math.random()*(MAX_32-10))|0)
|
|
110
109
|
if(typeof opts.top === 'object') {
|
|
111
110
|
if(opts.top[data_key]) {
|
|
112
111
|
throw new Error('Attempting to set data key/token via send() options!')
|
|
@@ -119,10 +118,10 @@ class WebSocketClient {
|
|
|
119
118
|
)
|
|
120
119
|
|
|
121
120
|
if(this.open === true) {
|
|
122
|
-
this.ws.send(config.encode(message_id, message_data, config))
|
|
121
|
+
(this.ws as wsc.Socket).send(config.encode(message_id, message_data, config))
|
|
123
122
|
} else if(this.open === false || first_time_lazy) {
|
|
124
123
|
this.messages.push({
|
|
125
|
-
send: () => this.ws.send(config.encode(message_id, message_data, config))
|
|
124
|
+
send: () => (this.ws as wsc.Socket).send(config.encode(message_id, message_data, config))
|
|
126
125
|
})
|
|
127
126
|
if(first_time_lazy) {
|
|
128
127
|
this.connect()
|
|
@@ -140,7 +139,7 @@ class WebSocketClient {
|
|
|
140
139
|
if(this.queue[message_id]) {
|
|
141
140
|
rj({
|
|
142
141
|
'Websocket timeout expired: ': config.timeout,
|
|
143
|
-
'for the message':
|
|
142
|
+
'for the message ': message_data
|
|
144
143
|
})
|
|
145
144
|
delete this.queue[message_id]
|
|
146
145
|
}
|
|
@@ -164,4 +163,4 @@ class WebSocketClient {
|
|
|
164
163
|
}
|
|
165
164
|
}
|
|
166
165
|
|
|
167
|
-
export default WebSocketClient
|
|
166
|
+
export default WebSocketClient
|
package/src/connectLib.ts
CHANGED
package/src/types.ts
CHANGED
|
@@ -24,14 +24,14 @@ declare namespace wsc {
|
|
|
24
24
|
|
|
25
25
|
export interface Config {
|
|
26
26
|
data_type: DataType
|
|
27
|
-
log (event: string, time?: number, message?: any): void
|
|
27
|
+
log (event: string, time?: number|null, message?: any): void
|
|
28
28
|
log (event: string, message?: any): void
|
|
29
29
|
timer: boolean
|
|
30
30
|
url: string
|
|
31
31
|
timeout: number
|
|
32
32
|
reconnect: number
|
|
33
33
|
lazy: boolean
|
|
34
|
-
socket: Socket
|
|
34
|
+
socket: Socket | null
|
|
35
35
|
adapter: (host: string, protocols?: string[]) => Socket
|
|
36
36
|
encode: (key: string, message: any, config: Config) => any
|
|
37
37
|
decode: (rawMessage: any) => {
|
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
|
|
2
|
-
import
|
|
2
|
+
import { WebSocketServer } from 'ws'
|
|
3
3
|
|
|
4
|
-
let mockServer
|
|
4
|
+
let mockServer = {}
|
|
5
5
|
|
|
6
6
|
const createServer = (port = 40510) => {
|
|
7
7
|
return new Promise((ff) => {
|
|
8
8
|
if(mockServer[port] === undefined) {
|
|
9
|
-
mockServer[port] = new (
|
|
9
|
+
mockServer[port] = new WebSocketServer({ port }, () => {
|
|
10
10
|
mockServer[port].on('connection', (socket) => {
|
|
11
|
-
socket.on('message', (rawMessage
|
|
11
|
+
socket.on('message', (rawMessage) => {
|
|
12
12
|
const {id, data} = JSON.parse(rawMessage)
|
|
13
13
|
let response = ''
|
|
14
14
|
if(data.shut) {
|
|
@@ -48,7 +48,4 @@ const killServer = async (port = 40510) => {
|
|
|
48
48
|
})
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
-
export {
|
|
52
|
-
createServer,
|
|
53
|
-
killServer
|
|
54
|
-
}
|
|
51
|
+
export { createServer, killServer }
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
|
|
2
|
+
import express from 'express'
|
|
3
|
+
import { createServer, killServer } from './WS.js'
|
|
4
|
+
import net from 'net';
|
|
5
|
+
|
|
6
|
+
var portInUse = (port) => new Promise((ff) => {
|
|
7
|
+
var server = net.createServer(function(socket) {
|
|
8
|
+
socket.write('Echo server\r\n');
|
|
9
|
+
socket.pipe(socket);
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
server.on('error', function (e) {
|
|
13
|
+
ff(true);
|
|
14
|
+
});
|
|
15
|
+
server.on('listening', function (e) {
|
|
16
|
+
server.close();
|
|
17
|
+
ff(false);
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
server.listen(port, '127.0.0.1');
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
const ports = {}
|
|
24
|
+
|
|
25
|
+
export default async () => {
|
|
26
|
+
const app = express()
|
|
27
|
+
const getPort = (req) => +req.originalUrl.split('/')[2] || 8095
|
|
28
|
+
|
|
29
|
+
app.get(/\/on\/.*/, async (req, res) => {
|
|
30
|
+
const port = getPort(req)
|
|
31
|
+
if(!ports[port]) {
|
|
32
|
+
await createServer(getPort(req))
|
|
33
|
+
ports[port] = true
|
|
34
|
+
} else {
|
|
35
|
+
}
|
|
36
|
+
res.send('on')
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
app.get(/\/off\/.*/, async (req, res) => {
|
|
40
|
+
const port = getPort(req)
|
|
41
|
+
if(ports[port]) {
|
|
42
|
+
await killServer(port)
|
|
43
|
+
delete ports[port]
|
|
44
|
+
} else {
|
|
45
|
+
}
|
|
46
|
+
res.send('off')
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
const port = 8000 + Math.ceil(Math.random()*500)
|
|
50
|
+
app.listen(port, () => {});
|
|
51
|
+
return port
|
|
52
|
+
}
|
|
@@ -1,12 +1,9 @@
|
|
|
1
1
|
import test from 'ava'
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
shutDown
|
|
5
|
-
} from '../utils'
|
|
6
|
-
import mockServer from '../mock'
|
|
2
|
+
import { createNew, shutDown } from '../utils.js'
|
|
3
|
+
import mockServer from '../mock/index.js'
|
|
7
4
|
|
|
8
5
|
/** Closes the connenction. */
|
|
9
|
-
test('close', (t) => {
|
|
6
|
+
test.serial('close', (t) => {
|
|
10
7
|
return new Promise(async (ff) => {
|
|
11
8
|
await mockServer()
|
|
12
9
|
const port = 40513
|
|
@@ -1,12 +1,9 @@
|
|
|
1
1
|
import test from 'ava'
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
shutDown
|
|
5
|
-
} from '../utils'
|
|
6
|
-
import mockServer from '../mock'
|
|
2
|
+
import { createNew, shutDown } from '../utils.js'
|
|
3
|
+
import mockServer from '../mock/index.js'
|
|
7
4
|
|
|
8
5
|
/** Rejects messages by timout */
|
|
9
|
-
test('drops', (t) => {
|
|
6
|
+
test.serial('drops', (t) => {
|
|
10
7
|
return new Promise(async (ff) => {
|
|
11
8
|
await mockServer()
|
|
12
9
|
const ws = await createNew({
|
|
@@ -1,12 +1,9 @@
|
|
|
1
1
|
import test from 'ava'
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
shutDown
|
|
5
|
-
} from '../utils'
|
|
6
|
-
import mockServer from '../mock'
|
|
2
|
+
import { createNew, shutDown } from '../utils.js'
|
|
3
|
+
import mockServer from '../mock/index.js'
|
|
7
4
|
|
|
8
5
|
/** Proof of work */
|
|
9
|
-
test('echo', (t) => {
|
|
6
|
+
test.serial('echo', (t) => {
|
|
10
7
|
t.timeout(5000)
|
|
11
8
|
return new Promise(async (ff, rj) => {
|
|
12
9
|
await mockServer()
|
|
@@ -1,15 +1,11 @@
|
|
|
1
1
|
import test from 'ava'
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
shutDown,
|
|
5
|
-
turnOn
|
|
6
|
-
} from '../utils'
|
|
7
|
-
import mockServer from '../mock'
|
|
2
|
+
import { createNew, shutDown, turnOn } from '../utils.js'
|
|
3
|
+
import mockServer from '../mock/index.js'
|
|
8
4
|
|
|
9
5
|
import * as WS from 'ws'
|
|
10
6
|
|
|
11
7
|
/** If an existing socket connection is provided via config. */
|
|
12
|
-
test('existing_socket', (t) => {
|
|
8
|
+
test.serial('existing_socket', (t) => {
|
|
13
9
|
const existing_port = 8095
|
|
14
10
|
const existing_addr = 'ws://localhost:' + existing_port
|
|
15
11
|
return new Promise(async (ff) => {
|
|
@@ -21,7 +17,7 @@ test('existing_socket', (t) => {
|
|
|
21
17
|
// This one CANNOT connect as fast as we send to it,
|
|
22
18
|
// So readyState is 0.
|
|
23
19
|
const ws1 = await createNew({
|
|
24
|
-
socket: new
|
|
20
|
+
socket: new WS(existing_addr)
|
|
25
21
|
})
|
|
26
22
|
|
|
27
23
|
t.is(ws1.socket.readyState, 0)
|
|
@@ -33,10 +29,9 @@ test('existing_socket', (t) => {
|
|
|
33
29
|
t.deepEqual(response1, msg1)
|
|
34
30
|
await ws1.close()
|
|
35
31
|
|
|
36
|
-
|
|
37
32
|
// This one DO CAN connect as fast as we send to it,
|
|
38
33
|
// So readyState should be 1.
|
|
39
|
-
const ws2_0 = new
|
|
34
|
+
const ws2_0 = new WS(existing_addr)
|
|
40
35
|
|
|
41
36
|
ws2_0.addEventListener('open', async () => {
|
|
42
37
|
const ws2 = await createNew({
|
|
@@ -1,13 +1,9 @@
|
|
|
1
1
|
import test from 'ava'
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
} from '../utils'
|
|
5
|
-
import mockServer from '../mock'
|
|
6
|
-
|
|
7
|
-
|
|
2
|
+
import { createNew, shutDown } from '../utils.js'
|
|
3
|
+
import mockServer from '../mock/index.js'
|
|
8
4
|
|
|
9
5
|
/** Lazy connect */
|
|
10
|
-
test('lazy', (t) => {
|
|
6
|
+
test.serial('lazy', (t) => {
|
|
11
7
|
t.timeout(2000)
|
|
12
8
|
return new Promise(async (ff) => {
|
|
13
9
|
await mockServer()
|
|
@@ -1,13 +1,9 @@
|
|
|
1
1
|
import test from 'ava'
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
shutDown
|
|
5
|
-
} from '../utils'
|
|
6
|
-
import mockServer from '../mock'
|
|
7
|
-
|
|
2
|
+
import { createNew, shutDown } from '../utils.js'
|
|
3
|
+
import mockServer from '../mock/index.js'
|
|
8
4
|
|
|
9
5
|
/** Ready method. */
|
|
10
|
-
test('ready', async (t) => {
|
|
6
|
+
test.serial('ready', async (t) => {
|
|
11
7
|
await mockServer()
|
|
12
8
|
t.timeout(4e3)
|
|
13
9
|
|
|
@@ -1,14 +1,9 @@
|
|
|
1
1
|
import test from 'ava'
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
shutDown,
|
|
5
|
-
turnOn
|
|
6
|
-
} from '../utils'
|
|
7
|
-
import mockServer from '../mock'
|
|
8
|
-
|
|
2
|
+
import { createNew, shutDown, turnOn } from '../utils.js'
|
|
3
|
+
import mockServer from '../mock/index.js'
|
|
9
4
|
|
|
10
5
|
/** Reconnects if connection is broken. */
|
|
11
|
-
test('reconnect', (t
|
|
6
|
+
test.serial('reconnect', (t) => {
|
|
12
7
|
const port = 8116
|
|
13
8
|
return new Promise(async (ff) => {
|
|
14
9
|
await mockServer()
|
|
@@ -1,12 +1,9 @@
|
|
|
1
1
|
import test from 'ava'
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
shutDown
|
|
5
|
-
} from '../utils'
|
|
6
|
-
import mockServer from '../mock'
|
|
2
|
+
import { createNew, shutDown } from '../utils.js'
|
|
3
|
+
import mockServer from '../mock/index.js'
|
|
7
4
|
|
|
8
5
|
/** Sends massages if they were .send() before connection is estabilished. */
|
|
9
|
-
test('sendBeforeOpen', (t) => {
|
|
6
|
+
test.serial('sendBeforeOpen', (t) => {
|
|
10
7
|
return new Promise(async (ff, rj) => {
|
|
11
8
|
await mockServer()
|
|
12
9
|
let to = setTimeout(() => rj(t.fail('cannot create')), 2e2)
|
|
@@ -1,12 +1,9 @@
|
|
|
1
1
|
import test from 'ava'
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
shutDown
|
|
5
|
-
} from '../utils'
|
|
6
|
-
import mockServer from '../mock'
|
|
2
|
+
import { createNew, shutDown } from '../utils.js'
|
|
3
|
+
import mockServer from '../mock/index.js'
|
|
7
4
|
|
|
8
5
|
/** Socket property check. */
|
|
9
|
-
test('sockets', (t) => {
|
|
6
|
+
test.serial('sockets', (t) => {
|
|
10
7
|
return new Promise(async ff => {
|
|
11
8
|
await mockServer()
|
|
12
9
|
const to = setTimeout(() => ff(t.fail()), 4e4)
|
|
@@ -1,13 +1,12 @@
|
|
|
1
1
|
import test from 'ava'
|
|
2
|
-
import mockServer from '../mock'
|
|
2
|
+
import mockServer from '../mock/index.js'
|
|
3
3
|
import { once as onceTest } from '../../src/utils'
|
|
4
4
|
|
|
5
|
-
|
|
6
5
|
/** Utils::once should cache a result and call a func just once. */
|
|
7
|
-
test('once', (t) => {
|
|
6
|
+
test.serial('once', (t) => {
|
|
8
7
|
return new Promise(async (ff) => {
|
|
9
8
|
await mockServer()
|
|
10
|
-
const fn = (a
|
|
9
|
+
const fn = (a) => a*2
|
|
11
10
|
const cached = onceTest(fn)
|
|
12
11
|
|
|
13
12
|
t.is(cached(5), cached(10))
|
package/test/utils.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
|
|
2
|
+
import WSP from '../dist/bundle.mjs'
|
|
3
|
+
import axios from 'axios'
|
|
4
|
+
import WS from 'ws'
|
|
5
|
+
|
|
6
|
+
const turnOn = async (port = 8095) => {
|
|
7
|
+
await axios.get('http://127.0.0.1:8085/on/' + port)
|
|
8
|
+
return true
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const shutDown = async (port = 8095) => {
|
|
12
|
+
await axios.get('http://127.0.0.1:8085/off/' + port)
|
|
13
|
+
return true
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const createNew = async (config = {}, port = 8095) => {
|
|
17
|
+
await turnOn(port)
|
|
18
|
+
const ws = new WSP(Object.assign({
|
|
19
|
+
url: '127.0.0.1:' + port,
|
|
20
|
+
// log: (...a) => console.log(...a),
|
|
21
|
+
adapter: (host, protocols) => new WS(host, protocols)
|
|
22
|
+
}, config))
|
|
23
|
+
|
|
24
|
+
return ws
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export { createNew, turnOn, shutDown }
|
package/tsconfig.json
CHANGED
|
@@ -1,22 +1,19 @@
|
|
|
1
1
|
{
|
|
2
2
|
"compilerOptions": {
|
|
3
|
-
"
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
"
|
|
3
|
+
"moduleResolution": "Node",
|
|
4
|
+
"lib": [ "esnext", "DOM" ],
|
|
5
|
+
"strictNullChecks": true,
|
|
6
|
+
"target": "esnext",
|
|
7
|
+
"module": "esnext",
|
|
8
8
|
"allowJs": false,
|
|
9
|
-
"sourceMap":
|
|
9
|
+
"sourceMap": false,
|
|
10
10
|
"emitDecoratorMetadata": true,
|
|
11
11
|
"experimentalDecorators": true,
|
|
12
12
|
"noUnusedParameters": true,
|
|
13
13
|
"noUnusedLocals": false,
|
|
14
|
-
"
|
|
15
|
-
"
|
|
16
|
-
"
|
|
17
|
-
"baseUrl": "."
|
|
14
|
+
"rootDir": "src",
|
|
15
|
+
"baseUrl": ".",
|
|
16
|
+
"outDir": "dist/ts"
|
|
18
17
|
},
|
|
19
|
-
"include": [
|
|
20
|
-
"./src/WS.ts"
|
|
21
|
-
]
|
|
18
|
+
"include": [ "src/**/*" ]
|
|
22
19
|
}
|
package/dist/src/SHA1.d.ts
DELETED
package/dist/src/WS.d.ts
DELETED
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import './types';
|
|
2
|
-
declare class WebSocketClient {
|
|
3
|
-
private open;
|
|
4
|
-
private ws;
|
|
5
|
-
private forcibly_closed;
|
|
6
|
-
private reconnect_timeout;
|
|
7
|
-
private queue;
|
|
8
|
-
private messages;
|
|
9
|
-
private onReadyQueue;
|
|
10
|
-
private onCloseQueue;
|
|
11
|
-
private handlers;
|
|
12
|
-
private config;
|
|
13
|
-
private init_flush;
|
|
14
|
-
private log;
|
|
15
|
-
private connect;
|
|
16
|
-
get socket(): any;
|
|
17
|
-
ready(): Promise<void>;
|
|
18
|
-
on(event_name: wsc.WSEvent, handler: (data: any) => any, predicate?: (data: any) => boolean, raw?: boolean): number | void;
|
|
19
|
-
close(): wsc.AsyncErrCode;
|
|
20
|
-
send<RequestDataType = any, ResponseDataType = any>(message_data: RequestDataType, opts?: wsc.SendOptions): Promise<ResponseDataType>;
|
|
21
|
-
constructor(user_config?: wsc.UserConfig);
|
|
22
|
-
}
|
|
23
|
-
export default WebSocketClient;
|
package/dist/src/config.d.ts
DELETED
package/dist/src/connectLib.d.ts
DELETED
package/dist/src/packNumber.d.ts
DELETED
package/dist/src/types.d.ts
DELETED
|
@@ -1,48 +0,0 @@
|
|
|
1
|
-
declare namespace wsc {
|
|
2
|
-
interface DataObject {
|
|
3
|
-
[key: string]: any;
|
|
4
|
-
}
|
|
5
|
-
type WSEvent = 'open' | 'message' | 'close' | 'error';
|
|
6
|
-
/** Minimal socket-like interface. */
|
|
7
|
-
interface Socket {
|
|
8
|
-
readyState: number;
|
|
9
|
-
send(...any: any[]): void;
|
|
10
|
-
close(): void;
|
|
11
|
-
addEventListener(event: string, handler: ((event: any) => any), ...any: any[]): void;
|
|
12
|
-
}
|
|
13
|
-
type AsyncErrCode = Promise<number | null | {}>;
|
|
14
|
-
type EventHandler = (e: any) => void;
|
|
15
|
-
type DataPipe = (message: any) => any;
|
|
16
|
-
type DataType = 'json' | 'string';
|
|
17
|
-
interface Config {
|
|
18
|
-
data_type: DataType;
|
|
19
|
-
log(event: string, time?: number, message?: any): void;
|
|
20
|
-
log(event: string, message?: any): void;
|
|
21
|
-
timer: boolean;
|
|
22
|
-
url: string;
|
|
23
|
-
timeout: number;
|
|
24
|
-
reconnect: number;
|
|
25
|
-
lazy: boolean;
|
|
26
|
-
socket: Socket;
|
|
27
|
-
adapter: (host: string, protocols?: string[]) => Socket;
|
|
28
|
-
encode: (key: string, message: any, config: Config) => any;
|
|
29
|
-
decode: (rawMessage: any) => {
|
|
30
|
-
[id_or_data_key: string]: string;
|
|
31
|
-
};
|
|
32
|
-
protocols: string[];
|
|
33
|
-
pipes: DataPipe[];
|
|
34
|
-
server: {
|
|
35
|
-
id_key: string;
|
|
36
|
-
data_key: string;
|
|
37
|
-
};
|
|
38
|
-
ping: {
|
|
39
|
-
interval: number;
|
|
40
|
-
content: any;
|
|
41
|
-
};
|
|
42
|
-
}
|
|
43
|
-
type UserConfig = Partial<Config>;
|
|
44
|
-
interface SendOptions {
|
|
45
|
-
top: any;
|
|
46
|
-
data_type: DataType;
|
|
47
|
-
}
|
|
48
|
-
}
|
package/dist/src/utils.d.ts
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
/// <reference types="node" />
|
|
2
|
-
import './types';
|
|
3
|
-
declare const add_event: (o: wsc.Socket, e: string, handler: wsc.EventHandler) => void;
|
|
4
|
-
declare const once: (fn: Function) => (...args: any) => any;
|
|
5
|
-
declare const sett: (a: number, b: {
|
|
6
|
-
(): void;
|
|
7
|
-
(...args: any[]): void;
|
|
8
|
-
}) => NodeJS.Timeout;
|
|
9
|
-
export { add_event, once, sett };
|
package/dist/ws.esm.js
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
/*! *****************************************************************************
|
|
2
|
-
Copyright (c) Microsoft Corporation.
|
|
3
|
-
|
|
4
|
-
Permission to use, copy, modify, and/or distribute this software for any
|
|
5
|
-
purpose with or without fee is hereby granted.
|
|
6
|
-
|
|
7
|
-
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
8
|
-
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
|
9
|
-
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
10
|
-
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
11
|
-
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
12
|
-
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
13
|
-
PERFORMANCE OF THIS SOFTWARE.
|
|
14
|
-
***************************************************************************** */
|
|
15
|
-
function t(t,e,s,n){return new(s||(s=Promise))((function(o,i){function r(t){try{c(n.next(t))}catch(t){i(t)}}function l(t){try{c(n.throw(t))}catch(t){i(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof s?e:new s((function(t){t(e)}))).then(r,l)}c((n=n.apply(t,e||[])).next())}))}const e="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",s=e.length-1;const n=(t,e,s)=>t.addEventListener(e,s),o=t=>{let e=!1,s=null;return(...n)=>e?s:(e=!0,s=t(...n))},i=function(e){const s=this.config;this.open=!0,this.onReadyQueue.forEach((t=>t())),this.onReadyQueue.splice(0);const{id_key:o,data_key:i}=s.server;if(this.handlers.open.forEach((t=>t())),this.messages.forEach((t=>t.send())),null!==this.reconnect_timeout&&(clearInterval(this.reconnect_timeout),this.reconnect_timeout=null),s.ping){const t=setInterval((()=>{this.open&&this.send(s.ping.content),this.forcibly_closed&&clearInterval(t)}),1e3*s.ping.interval)}n(e,"close",(()=>t(this,void 0,void 0,(function*(){this.log("close"),this.open=!1,this.onCloseQueue.forEach((t=>t())),this.onCloseQueue=[];const e=s.reconnect;if("number"!=typeof e||isNaN(e)||this.forcibly_closed)this.ws=null,this.open=null;else{const s=()=>t(this,void 0,void 0,(function*(){this.log("reconnect"),null!==this.ws&&(this.ws.close(),this.ws=null);null!==(yield this.connect())&&(this.reconnect_timeout=setTimeout(s,1e3*e))}));s()}this.forcibly_closed=!1})))),n(e,"message",(t=>{try{const e=s.decode(t.data);if(this.handlers.message.forEach((s=>s(Object.assign(Object.assign({},t),{data:e})))),e[o]){const t=this.queue[e[o]];if(t){const s=t.sent_time?Date.now()-t.sent_time:null;this.log("message",e[i],s),t.ff(e[i]),clearTimeout(t.timeout),delete this.queue[e[o]]}}}catch(e){console.error(e,`WSP: Decode error. Got: ${t.data}`)}}))},r=function(t){if(!0===this.open)return t(null);const e=this.config,s=e.socket||e.adapter(e.url,e.protocols);if(this.ws=s,!s||s.readyState>1)return this.ws=null,this.log("error","ready() on closing or closed state! status 2."),t(2);n(s,"error",o((e=>(this.log("error","status 3."),this.handlers.error.forEach((t=>t(e))),this.ws=null,t(3))))),s.readyState?(i.call(this,s),t(null)):n(s,"open",o((()=>(this.log("open"),i.call(this,s),t(null)))))},l={data_type:"json",log:()=>null,timer:!1,url:"localhost",timeout:1400,reconnect:2,lazy:!1,socket:null,adapter:(t,e)=>new WebSocket(t,e),encode:(t,e,{server:s})=>JSON.stringify({[s.id_key]:t,[s.data_key]:e}),decode:t=>JSON.parse(t),protocols:[],pipes:[],server:{id_key:"id",data_key:"data"},ping:{interval:55,content:{}}};var c=function(){return!0};const h=Math.pow(2,31)-1;export default class{constructor(t={}){this.open=null,this.ws=null,this.forcibly_closed=!1,this.reconnect_timeout=null,this.queue={},this.messages=[],this.onReadyQueue=[],this.onCloseQueue=[],this.handlers={open:[],message:[],close:[],error:[]},this.config={},this.config=(t=>{const e=Object.assign({},l,t),s=e.url;if("/"==s[0])try{const t=location.protocol.includes("s:")?"wss":"ws";e.url=`${t}://${location.hostname}:${location.port}${s}`}catch(t){throw new Error("WSP: URL starting with / in non-browser environment!")}return e})(t),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(t,e=null,s=null){const n=this.config;null!==s?n.log(t,s,e):n.timer?n.log(t,null,e):n.log(t,e)}connect(){return t(this,void 0,void 0,(function*(){return new Promise((t=>{r.call(this,t)}))}))}get socket(){return this.ws}ready(){return t(this,void 0,void 0,(function*(){return new Promise((t=>{this.open?t():this.onReadyQueue.push(t)}))}))}on(t,e,s=c,o=!1){const i=t=>s(t)&&e(t);return o?n(this.ws,t,i):this.handlers[t].push(i)}close(){return t(this,void 0,void 0,(function*(){return new Promise(((t,e)=>{null===this.ws?e("WSP: closing a non-inited socket!"):(this.open=null,this.onCloseQueue.push((()=>{this.init_flush(),this.ws=null,this.forcibly_closed=!0,t(null)})),this.ws.close())}))}))}send(n,o={}){return t(this,void 0,void 0,(function*(){this.log("send",n);const t=this.config,i={},r=t.server.data_key,l=t.lazy&&!this.open,c=(t=>{const n=[];for(;t>=1;)n.push(e[t%(s+1)]),t=t/s|0;return n.join("")})(Math.random()*(h-10)|0);if("object"==typeof o.top){if(o.top[r])throw new Error("Attempting to set data key/token via send() options!");Object.assign(i,o.top)}if(t.pipes.forEach((t=>n=t(n))),!0===this.open)this.ws.send(t.encode(c,n,t));else if(!1===this.open||l)this.messages.push({send:()=>this.ws.send(t.encode(c,n,t))}),l&&this.connect();else if(null===this.open)throw new Error("Attempting to send via closed WebSocket connection!");return new Promise(((e,s)=>{var n,o;this.queue[c]={ff:e,data_type:t.data_type,sent_time:t.timer?Date.now():null,timeout:(n=t.timeout,o=()=>{this.queue[c]&&(s({"Websocket timeout expired: ":t.timeout,"for the message":i}),delete this.queue[c])},setTimeout(o,n))}}))}))}}
|
package/dist/ws.esm.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ws.esm.js","sources":["../node_modules/tslib/tslib.es6.js"],"sourcesContent":["/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation. All rights reserved.\r\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\r\nthis file except in compliance with the License. You may obtain a copy of the\r\nLicense at http://www.apache.org/licenses/LICENSE-2.0\r\n\r\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\r\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\r\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\r\nMERCHANTABLITY OR NON-INFRINGEMENT.\r\n\r\nSee the Apache Version 2.0 License for specific language governing permissions\r\nand limitations under the License.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\r\n t[p[i]] = s[p[i]];\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [0, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\r\n if (m) return m.call(o);\r\n return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator];\r\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n"],"names":["__awaiter","thisArg","_arguments","P","generator","Promise","resolve","reject","fulfilled","value","step","next","e","rejected","result","done","then","apply"],"mappings":"AA2DA,SAAgBA,UAAUC,EAASC,EAAYC,EAAGC,GAC9C,OAAO,IAAKD,IAAMA,EAAIE,UAAU,SAAUC,EAASC,GAC/C,SAASC,EAAUC,GAAS,IAAMC,EAAKN,EAAUO,KAAKF,IAAW,MAAOG,GAAKL,EAAOK,IACpF,SAASC,EAASJ,GAAS,IAAMC,EAAKN,EAAiB,MAAEK,IAAW,MAAOG,GAAKL,EAAOK,IACvF,SAASF,EAAKI,GAAUA,EAAOC,KAAOT,EAAQQ,EAAOL,OAAS,IAAIN,EAAE,SAAUG,GAAWA,EAAQQ,EAAOL,SAAWO,KAAKR,EAAWK,GACnIH,GAAMN,EAAYA,EAAUa,MAAMhB,EAASC,QAAmBS"}
|
package/dist/ws.js
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/*! *****************************************************************************
|
|
3
|
-
Copyright (c) Microsoft Corporation.
|
|
4
|
-
|
|
5
|
-
Permission to use, copy, modify, and/or distribute this software for any
|
|
6
|
-
purpose with or without fee is hereby granted.
|
|
7
|
-
|
|
8
|
-
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
9
|
-
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
|
10
|
-
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
11
|
-
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
12
|
-
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
13
|
-
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
14
|
-
PERFORMANCE OF THIS SOFTWARE.
|
|
15
|
-
***************************************************************************** */function t(t,e,s,n){return new(s||(s=Promise))((function(o,i){function r(t){try{c(n.next(t))}catch(t){i(t)}}function l(t){try{c(n.throw(t))}catch(t){i(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof s?e:new s((function(t){t(e)}))).then(r,l)}c((n=n.apply(t,e||[])).next())}))}const e="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",s=e.length-1;const n=(t,e,s)=>t.addEventListener(e,s),o=t=>{let e=!1,s=null;return(...n)=>e?s:(e=!0,s=t(...n))},i=function(e){const s=this.config;this.open=!0,this.onReadyQueue.forEach((t=>t())),this.onReadyQueue.splice(0);const{id_key:o,data_key:i}=s.server;if(this.handlers.open.forEach((t=>t())),this.messages.forEach((t=>t.send())),null!==this.reconnect_timeout&&(clearInterval(this.reconnect_timeout),this.reconnect_timeout=null),s.ping){const t=setInterval((()=>{this.open&&this.send(s.ping.content),this.forcibly_closed&&clearInterval(t)}),1e3*s.ping.interval)}n(e,"close",(()=>t(this,void 0,void 0,(function*(){this.log("close"),this.open=!1,this.onCloseQueue.forEach((t=>t())),this.onCloseQueue=[];const e=s.reconnect;if("number"!=typeof e||isNaN(e)||this.forcibly_closed)this.ws=null,this.open=null;else{const s=()=>t(this,void 0,void 0,(function*(){this.log("reconnect"),null!==this.ws&&(this.ws.close(),this.ws=null);null!==(yield this.connect())&&(this.reconnect_timeout=setTimeout(s,1e3*e))}));s()}this.forcibly_closed=!1})))),n(e,"message",(t=>{try{const e=s.decode(t.data);if(this.handlers.message.forEach((s=>s(Object.assign(Object.assign({},t),{data:e})))),e[o]){const t=this.queue[e[o]];if(t){const s=t.sent_time?Date.now()-t.sent_time:null;this.log("message",e[i],s),t.ff(e[i]),clearTimeout(t.timeout),delete this.queue[e[o]]}}}catch(e){console.error(e,`WSP: Decode error. Got: ${t.data}`)}}))},r=function(t){if(!0===this.open)return t(null);const e=this.config,s=e.socket||e.adapter(e.url,e.protocols);if(this.ws=s,!s||s.readyState>1)return this.ws=null,this.log("error","ready() on closing or closed state! status 2."),t(2);n(s,"error",o((e=>(this.log("error","status 3."),this.handlers.error.forEach((t=>t(e))),this.ws=null,t(3))))),s.readyState?(i.call(this,s),t(null)):n(s,"open",o((()=>(this.log("open"),i.call(this,s),t(null)))))},l={data_type:"json",log:()=>null,timer:!1,url:"localhost",timeout:1400,reconnect:2,lazy:!1,socket:null,adapter:(t,e)=>new WebSocket(t,e),encode:(t,e,{server:s})=>JSON.stringify({[s.id_key]:t,[s.data_key]:e}),decode:t=>JSON.parse(t),protocols:[],pipes:[],server:{id_key:"id",data_key:"data"},ping:{interval:55,content:{}}};var c=function(){return!0};const h=Math.pow(2,31)-1;module.exports=class{constructor(t={}){this.open=null,this.ws=null,this.forcibly_closed=!1,this.reconnect_timeout=null,this.queue={},this.messages=[],this.onReadyQueue=[],this.onCloseQueue=[],this.handlers={open:[],message:[],close:[],error:[]},this.config={},this.config=(t=>{const e=Object.assign({},l,t),s=e.url;if("/"==s[0])try{const t=location.protocol.includes("s:")?"wss":"ws";e.url=`${t}://${location.hostname}:${location.port}${s}`}catch(t){throw new Error("WSP: URL starting with / in non-browser environment!")}return e})(t),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(t,e=null,s=null){const n=this.config;null!==s?n.log(t,s,e):n.timer?n.log(t,null,e):n.log(t,e)}connect(){return t(this,void 0,void 0,(function*(){return new Promise((t=>{r.call(this,t)}))}))}get socket(){return this.ws}ready(){return t(this,void 0,void 0,(function*(){return new Promise((t=>{this.open?t():this.onReadyQueue.push(t)}))}))}on(t,e,s=c,o=!1){const i=t=>s(t)&&e(t);return o?n(this.ws,t,i):this.handlers[t].push(i)}close(){return t(this,void 0,void 0,(function*(){return new Promise(((t,e)=>{null===this.ws?e("WSP: closing a non-inited socket!"):(this.open=null,this.onCloseQueue.push((()=>{this.init_flush(),this.ws=null,this.forcibly_closed=!0,t(null)})),this.ws.close())}))}))}send(n,o={}){return t(this,void 0,void 0,(function*(){this.log("send",n);const t=this.config,i={},r=t.server.data_key,l=t.lazy&&!this.open,c=(t=>{const n=[];for(;t>=1;)n.push(e[t%(s+1)]),t=t/s|0;return n.join("")})(Math.random()*(h-10)|0);if("object"==typeof o.top){if(o.top[r])throw new Error("Attempting to set data key/token via send() options!");Object.assign(i,o.top)}if(t.pipes.forEach((t=>n=t(n))),!0===this.open)this.ws.send(t.encode(c,n,t));else if(!1===this.open||l)this.messages.push({send:()=>this.ws.send(t.encode(c,n,t))}),l&&this.connect();else if(null===this.open)throw new Error("Attempting to send via closed WebSocket connection!");return new Promise(((e,s)=>{var n,o;this.queue[c]={ff:e,data_type:t.data_type,sent_time:t.timer?Date.now():null,timeout:(n=t.timeout,o=()=>{this.queue[c]&&(s({"Websocket timeout expired: ":t.timeout,"for the message":i}),delete this.queue[c])},setTimeout(o,n))}}))}))}};
|
package/dist/ws.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ws.js","sources":["../node_modules/tslib/tslib.es6.js"],"sourcesContent":["/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation. All rights reserved.\r\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\r\nthis file except in compliance with the License. You may obtain a copy of the\r\nLicense at http://www.apache.org/licenses/LICENSE-2.0\r\n\r\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\r\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\r\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\r\nMERCHANTABLITY OR NON-INFRINGEMENT.\r\n\r\nSee the Apache Version 2.0 License for specific language governing permissions\r\nand limitations under the License.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\r\n t[p[i]] = s[p[i]];\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [0, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\r\n if (m) return m.call(o);\r\n return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator];\r\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n"],"names":["__awaiter","thisArg","_arguments","P","generator","Promise","resolve","reject","fulfilled","value","step","next","e","rejected","result","done","then","apply"],"mappings":"aA2DA,SAAgBA,UAAUC,EAASC,EAAYC,EAAGC,GAC9C,OAAO,IAAKD,IAAMA,EAAIE,UAAU,SAAUC,EAASC,GAC/C,SAASC,EAAUC,GAAS,IAAMC,EAAKN,EAAUO,KAAKF,IAAW,MAAOG,GAAKL,EAAOK,IACpF,SAASC,EAASJ,GAAS,IAAMC,EAAKN,EAAiB,MAAEK,IAAW,MAAOG,GAAKL,EAAOK,IACvF,SAASF,EAAKI,GAAUA,EAAOC,KAAOT,EAAQQ,EAAOL,OAAS,IAAIN,EAAE,SAAUG,GAAWA,EAAQQ,EAAOL,SAAWO,KAAKR,EAAWK,GACnIH,GAAMN,EAAYA,EAAUa,MAAMhB,EAASC,QAAmBS"}
|
package/src/packNumber.ts
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
|
|
2
|
-
const abc = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
|
|
3
|
-
const ln = abc.length-1
|
|
4
|
-
|
|
5
|
-
export default (n: number): string => {
|
|
6
|
-
const s: string[] = []
|
|
7
|
-
while(n >= 1) {
|
|
8
|
-
s.push(abc[n%(ln+1)])
|
|
9
|
-
n = (n/ln)|0
|
|
10
|
-
}
|
|
11
|
-
return s.join('')
|
|
12
|
-
}
|
package/test/_register.js
DELETED
package/test/mock/index.ts
DELETED
|
@@ -1,41 +0,0 @@
|
|
|
1
|
-
|
|
2
|
-
import * as express from 'express'
|
|
3
|
-
import {
|
|
4
|
-
createServer,
|
|
5
|
-
killServer
|
|
6
|
-
} from './WS'
|
|
7
|
-
|
|
8
|
-
const ports = {}
|
|
9
|
-
|
|
10
|
-
export default async () => {
|
|
11
|
-
const app = express()
|
|
12
|
-
const getPort = (req) => +req.originalUrl.split('/')[2] || 8095
|
|
13
|
-
|
|
14
|
-
app.get(/\/on\/.*/, async (req, res) => {
|
|
15
|
-
const port = getPort(req)
|
|
16
|
-
if(!ports[port]) {
|
|
17
|
-
await createServer(getPort(req))
|
|
18
|
-
ports[port] = true
|
|
19
|
-
} else {
|
|
20
|
-
}
|
|
21
|
-
res.send('on')
|
|
22
|
-
})
|
|
23
|
-
|
|
24
|
-
app.get(/\/off\/.*/, async (req, res) => {
|
|
25
|
-
const port = getPort(req)
|
|
26
|
-
if(ports[port]) {
|
|
27
|
-
await killServer(port)
|
|
28
|
-
delete ports[port]
|
|
29
|
-
} else {
|
|
30
|
-
}
|
|
31
|
-
res.send('off')
|
|
32
|
-
})
|
|
33
|
-
|
|
34
|
-
try {
|
|
35
|
-
app.listen(8085);
|
|
36
|
-
} catch(e) {
|
|
37
|
-
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
return true
|
|
41
|
-
}
|
package/test/utils.ts
DELETED
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
|
|
2
|
-
const WSP = require('../dist/ws')
|
|
3
|
-
import axios from 'axios'
|
|
4
|
-
import * as WS from 'ws'
|
|
5
|
-
|
|
6
|
-
const turnOn = async (port: number = 8095) => {
|
|
7
|
-
await axios.get('http://127.0.0.1:8085/on/' + port)
|
|
8
|
-
return true
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
const shutDown = async (port: number = 8095) => {
|
|
12
|
-
await axios.get('http://127.0.0.1:8085/off/' + port)
|
|
13
|
-
return true
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
const createNew = async (config = {}, port = 8095): Promise<any> => {
|
|
17
|
-
await turnOn(port)
|
|
18
|
-
const ws = new WSP(Object.assign({
|
|
19
|
-
url: '127.0.0.1:' + port,
|
|
20
|
-
// log: (...a) => console.log(...a),
|
|
21
|
-
adapter: (host, protocols) => new (WS as any)(host, protocols)
|
|
22
|
-
}, config))
|
|
23
|
-
|
|
24
|
-
return ws
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
export {
|
|
28
|
-
createNew,
|
|
29
|
-
turnOn,
|
|
30
|
-
shutDown
|
|
31
|
-
}
|
|
File without changes
|