Browse Source

stuff

master
Daniel Hübleitner 5 years ago
parent
commit
ea18b22463

+ 0
- 20
lib/src/Client.d.ts View File

@@ -1,20 +0,0 @@
1
-import { Socket } from './interfaces/Socket';
2
-export declare class Client implements Socket {
3
-    port: number;
4
-    private server;
5
-    private tls;
6
-    private socket;
7
-    constructor(port: number, server: string, tls?: boolean);
8
-    hook(name: any, args: any): Socket;
9
-    unhook(name: any): Socket;
10
-    on(type: "error" | "close", f: (e?: any) => void): Socket;
11
-    destroy(): void;
12
-    close(): void;
13
-    call(rpcname: string, ...args: any[]): Promise<any>;
14
-    fire(rpcname: string, ...args: any[]): Promise<any>;
15
-    connect(): Promise<void>;
16
-    info(): Promise<any>;
17
-    private callGenerator;
18
-    private hookGenerator;
19
-    private unhookGenerator;
20
-}

+ 0
- 88
lib/src/Client.js View File

@@ -1,88 +0,0 @@
1
-"use strict";
2
-Object.defineProperty(exports, "__esModule", { value: true });
3
-var bsock = require('bsock');
4
-//fix args with defaults like "force = true" -> "force"
5
-function stripAfterEquals(str) {
6
-    return str.split("=")[0];
7
-}
8
-class Client {
9
-    constructor(port, server, tls = false) {
10
-        this.port = port;
11
-        this.server = server;
12
-        this.tls = tls;
13
-    }
14
-    hook(name, args) {
15
-        return this.socket.hook(name, args);
16
-    }
17
-    unhook(name) {
18
-        return this.socket.unhook(name);
19
-    }
20
-    on(type, f) {
21
-        return this.socket.on(type, name);
22
-    }
23
-    destroy() {
24
-        return this.socket.destroy();
25
-    }
26
-    close() {
27
-        return this.socket.close();
28
-    }
29
-    async call(rpcname, ...args) {
30
-        return await this.socket.call.apply(this.socket, [rpcname, ...args]);
31
-    }
32
-    async fire(rpcname, ...args) {
33
-        return await this.socket.fire.apply(this.socket, [rpcname, ...args]);
34
-    }
35
-    async connect() {
36
-        this.socket = await bsock.connect(this.port, this.server, this.tls);
37
-        const info = await this.info();
38
-        info.forEach(i => {
39
-            let f;
40
-            switch (i.type) {
41
-                case 'Call':
42
-                    f = this.callGenerator(i.uniqueName, i.argNames);
43
-                    break;
44
-                case 'Hook':
45
-                    f = this.hookGenerator(i.uniqueName, i.argNames);
46
-                    break;
47
-                case 'Unhook':
48
-                    f = this.unhookGenerator(i.uniqueName, i.argNames);
49
-                    break;
50
-            }
51
-            if (this[i.owner] == null)
52
-                this[i.owner] = {};
53
-            this[i.owner][i.name] = f;
54
-            this[i.owner][i.name].bind(this);
55
-        });
56
-    }
57
-    async info() {
58
-        return await this.socket.call('info');
59
-    }
60
-    callGenerator(fnName, fnArgs) {
61
-        const headerArgs = fnArgs.join(",");
62
-        const argParams = fnArgs.map(stripAfterEquals).join(",");
63
-        return eval('( () => async (' + headerArgs + ') => { return await this.socket.call("' + fnName + '", ' + argParams + ')} )()');
64
-    }
65
-    hookGenerator(fnName, fnArgs) {
66
-        const headerArgs = fnArgs.join(",");
67
-        const argParams = fnArgs.map(stripAfterEquals).join(",");
68
-        return eval(`( () => async (` + headerArgs + (headerArgs.length !== 0 ? "," : "") + ` callback) => {
69
-                            const r = await this.socket.call("` + fnName + `", ` + argParams + `)
70
-                            if(r.uid != null){
71
-                                this.socket.hook(res.uid, callback)
72
-                            }
73
-                            return res
74
-                        } )()`);
75
-    }
76
-    unhookGenerator(fnName, fnArgs) {
77
-        const headerArgs = fnArgs.join(",");
78
-        const argParams = fnArgs.map(stripAfterEquals).join(",");
79
-        if (fnArgs.length != 1)
80
-            console.error("UnhookFunction", fnName, "specified more than one argument: (" + headerArgs + ")");
81
-        return eval(`( () => async (` + headerArgs + `) => {
82
-                            const r = await this.socket.call("` + fnName + `", ` + argParams + `)
83
-                            this.socket.unhook(` + argParams + `)
84
-                            return res
85
-                        } )()`);
86
-    }
87
-}
88
-exports.Client = Client;

+ 0
- 17
lib/src/Response.d.ts View File

@@ -1,17 +0,0 @@
1
-export declare type Outcome = "Success" | "Error";
2
-export declare class Response {
3
-    message?: string | undefined;
4
-    constructor(message?: string | undefined);
5
-}
6
-export declare class SuccessResponse extends Response {
7
-    result: Outcome;
8
-    constructor(message?: string);
9
-}
10
-export declare class ErrorResponse extends Response {
11
-    result: Outcome;
12
-    constructor(message?: string);
13
-}
14
-export declare class SubscriptionResponse extends SuccessResponse {
15
-    uid: string;
16
-    constructor(uid: string, message?: string);
17
-}

+ 0
- 30
lib/src/Response.js View File

@@ -1,30 +0,0 @@
1
-"use strict";
2
-Object.defineProperty(exports, "__esModule", { value: true });
3
-/* Responses */
4
-class Response {
5
-    constructor(message) {
6
-        this.message = message;
7
-    }
8
-}
9
-exports.Response = Response;
10
-class SuccessResponse extends Response {
11
-    constructor(message) {
12
-        super(message);
13
-        this.result = "Success";
14
-    }
15
-}
16
-exports.SuccessResponse = SuccessResponse;
17
-class ErrorResponse extends Response {
18
-    constructor(message = "Unknown error") {
19
-        super(message);
20
-        this.result = "Error";
21
-    }
22
-}
23
-exports.ErrorResponse = ErrorResponse;
24
-class SubscriptionResponse extends SuccessResponse {
25
-    constructor(uid, message) {
26
-        super(message);
27
-        this.uid = uid;
28
-    }
29
-}
30
-exports.SubscriptionResponse = SubscriptionResponse;

+ 0
- 14
lib/src/Server.d.ts View File

@@ -1,14 +0,0 @@
1
-import { SocketConf } from './Types';
2
-import { Exporter } from './interfaces/Exporter';
3
-import { Socket } from "./interfaces/Socket";
4
-export declare class Server {
5
-    private port;
6
-    private rpcExporters;
7
-    private conf;
8
-    private io;
9
-    private wsServer;
10
-    constructor(port: number, rpcExporters?: Exporter[], conf?: SocketConf);
11
-    private startWebsocket;
12
-    protected initRPCs(socket: Socket): void;
13
-    protected initPublicRPCs(socket: Socket): void;
14
-}

+ 0
- 58
lib/src/Server.js View File

@@ -1,58 +0,0 @@
1
-"use strict";
2
-Object.defineProperty(exports, "__esModule", { value: true });
3
-const http = require("http");
4
-const bsock = require("bsock");
5
-const Util_1 = require("./Util");
6
-class Server {
7
-    constructor(port, rpcExporters = [], conf = {
8
-        errorHandler: (socket) => (error) => { socket.destroy(); console.error(error); },
9
-        closeHandler: (socket) => () => { console.log("Socket closing"); },
10
-        connectionHandler: (socket) => { console.log("New websocket connection in port " + socket.port); },
11
-        visibility: "127.0.0.1"
12
-    }) {
13
-        this.port = port;
14
-        this.rpcExporters = rpcExporters;
15
-        this.conf = conf;
16
-        this.io = bsock.createServer();
17
-        this.wsServer = http.createServer();
18
-        this.startWebsocket();
19
-    }
20
-    startWebsocket() {
21
-        try {
22
-            this.io.attach(this.wsServer);
23
-            this.io.on('socket', (socket) => {
24
-                socket.on('error', this.conf.errorHandler(socket));
25
-                socket.on('close', this.conf.closeHandler(socket));
26
-                if (this.conf.visibility === "127.0.0.1")
27
-                    this.initRPCs(socket);
28
-                else
29
-                    this.initPublicRPCs(socket);
30
-            });
31
-            this.wsServer.listen(this.port, this.conf.visibility);
32
-        }
33
-        catch (e) {
34
-            //@ts-ignore
35
-            this.errorHandler(undefined)("Unable to connect to socket");
36
-        }
37
-    }
38
-    initRPCs(socket) {
39
-        const infoRPC = [
40
-            {
41
-                name: 'info',
42
-                type: 'Call',
43
-                func: async () => rpcInfos
44
-            }
45
-        ];
46
-        const rpcInfos = [
47
-            ...Util_1.rpcHooker(socket, "RPC", infoRPC, false),
48
-            ...this.rpcExporters.flatMap(exporter => Util_1.rpcHooker(socket, exporter.name, [...exporter.exportPublicRPCs(), ...exporter.exportRPCs()]))
49
-        ];
50
-    }
51
-    initPublicRPCs(socket) {
52
-        const rpcInfos = [
53
-            ...Util_1.rpcHooker(socket, "Admin", adminRPCs, false),
54
-            ...this.rpcExporters.flatMap(exporter => Util_1.rpcHooker(socket, exporter.name, exporter.exportPublicRPCs()))
55
-        ];
56
-    }
57
-}
58
-exports.Server = Server;

+ 0
- 54
lib/src/Types.d.ts View File

@@ -1,54 +0,0 @@
1
-import { SuccessResponse, ErrorResponse, SubscriptionResponse } from "./Response";
2
-import { Socket } from "./interfaces/Socket";
3
-export declare type Visibility = "127.0.0.1" | "0.0.0.0";
4
-export declare type Name = string;
5
-export declare type SocketConf = {
6
-    connectionHandler: (socket: Socket) => void;
7
-    errorHandler: (socket: Socket) => (error: any) => void;
8
-    closeHandler: (socket: Socket) => () => void;
9
-    visibility: Visibility;
10
-};
11
-export declare type rpcType = 'Hook' | 'Unhook' | 'Call';
12
-export declare type BaseRPC = {
13
-    type: rpcType;
14
-    name: string;
15
-};
16
-export declare type HookRPC = BaseRPC & {
17
-    type: 'Hook';
18
-    func: CallbackFunction;
19
-    unhook: UnhookFunction;
20
-};
21
-export declare type UnhookRPC = BaseRPC & {
22
-    type: 'Unhook';
23
-    func: UnhookFunction;
24
-};
25
-export declare type CallRPC = BaseRPC & {
26
-    type: 'Call';
27
-    func: (...args: any[]) => Promise<any>;
28
-};
29
-export declare type SocketioRPC = CallRPC | UnhookRPC | HookRPC;
30
-export declare type BaseInfo = {
31
-    owner: string;
32
-    argNames: string[];
33
-};
34
-export declare type HookInfo = BaseRPC & BaseInfo & {
35
-    type: 'Hook';
36
-    generator: (socket: any) => CallbackFunction;
37
-    unhook: UnhookFunction;
38
-};
39
-export declare type UnhookInfo = BaseRPC & BaseInfo & {
40
-    type: 'Unhook';
41
-    func: UnhookFunction;
42
-};
43
-export declare type CallInfo = BaseRPC & BaseInfo & {
44
-    type: 'Call';
45
-    func: AsyncFunction;
46
-};
47
-export declare type RpcInfo = HookInfo | UnhookInfo | CallInfo;
48
-export declare type ExtendedRpcInfo = RpcInfo & {
49
-    uniqueName: string;
50
-};
51
-export declare type OnFunction = (type: 'error' | 'close', f: (e?: any) => void) => Socket;
52
-export declare type UnhookFunction = (uid: string) => Promise<SuccessResponse | ErrorResponse>;
53
-export declare type CallbackFunction = (...args: any[]) => Promise<SubscriptionResponse | ErrorResponse>;
54
-export declare type AsyncFunction = (...args: any[]) => Promise<any>;

+ 0
- 2
lib/src/Types.js View File

@@ -1,2 +0,0 @@
1
-"use strict";
2
-Object.defineProperty(exports, "__esModule", { value: true });

+ 0
- 4
lib/src/Util.d.ts View File

@@ -1,4 +0,0 @@
1
-import { SocketioRPC, RpcInfo, ExtendedRpcInfo } from "./Types";
2
-import { Socket } from "./interfaces/Socket";
3
-export declare const rpcToRpcinfo: (rpc: SocketioRPC, owner: string) => RpcInfo;
4
-export declare const rpcHooker: (socket: Socket, owner: string, RPCs: SocketioRPC[], makeUnique?: boolean) => ExtendedRpcInfo[];

+ 0
- 75
lib/src/Util.js View File

@@ -1,75 +0,0 @@
1
-"use strict";
2
-Object.defineProperty(exports, "__esModule", { value: true });
3
-const uuid = require("uuid/v4");
4
-exports.rpcToRpcinfo = (rpc, owner) => {
5
-    switch (rpc.type) {
6
-        case "Call":
7
-            return {
8
-                owner: owner,
9
-                argNames: extractArgs(rpc.func),
10
-                type: rpc.type,
11
-                name: rpc.name,
12
-                func: rpc.func,
13
-            };
14
-        case "Unhook":
15
-            return {
16
-                owner: owner,
17
-                argNames: extractArgs(rpc.func),
18
-                type: rpc.type,
19
-                name: rpc.name,
20
-                func: rpc.func,
21
-            };
22
-        case "Hook":
23
-            const generator = hookGenerator(rpc);
24
-            return {
25
-                owner: owner,
26
-                argNames: extractArgs(generator(undefined)),
27
-                type: rpc.type,
28
-                name: rpc.name,
29
-                unhook: rpc.unhook,
30
-                generator: generator,
31
-            };
32
-    }
33
-};
34
-exports.rpcHooker = (socket, owner, RPCs, makeUnique = true) => {
35
-    const suffix = makeUnique ? "-" + uuid().substr(0, 4) : "";
36
-    return RPCs.map(rpc => exports.rpcToRpcinfo(rpc, owner))
37
-        .map(info => {
38
-        const ret = info;
39
-        ret.uniqueName = info.name + suffix;
40
-        switch (info.type) {
41
-            case "Hook":
42
-                socket.hook(ret.uniqueName, info.generator(socket));
43
-                break;
44
-            default:
45
-                socket.hook(ret.uniqueName, info.func);
46
-        }
47
-        socket.on('close', () => socket.unhook(info.name));
48
-        return ret;
49
-    });
50
-};
51
-const hookGenerator = (rpc) => {
52
-    const argsArr = extractArgs(rpc.func);
53
-    argsArr.pop();
54
-    const args = argsArr.join(',');
55
-    return eval(`(socket) => async (` + args + `) => { 
56
-        const res = await rpc.func(` + args + (args.length !== 0 ? ',' : '') + ` (x) => {
57
-            socket.call(res.uid, x)
58
-        })
59
-        if(res.result == 'Success'){
60
-            socket.on('close', async () => {
61
-                const unhookRes = await rpc.unhook(res.uid)
62
-                console.log("Specific close handler for", rpc.name, res.uid, unhookRes)
63
-            })
64
-
65
-        }
66
-        return res
67
-    }`);
68
-};
69
-const extractArgs = (f) => {
70
-    let fn = String(f);
71
-    let args = fn.substr(0, fn.indexOf(")"));
72
-    args = args.substr(fn.indexOf("(") + 1);
73
-    let ret = args.split(",");
74
-    return ret;
75
-};

+ 0
- 97
lib/src/backend/RPCSocketServer.d.ts View File

@@ -1,97 +0,0 @@
1
-import { Socket } from "./RPCSocketServer";
2
-declare type rpcType = 'hook' | 'unhook' | 'call';
3
-export declare type Outcome = "Success" | "Error";
4
-export declare type Visibility = "127.0.0.1" | "0.0.0.0";
5
-export declare class Response {
6
-    message?: string | undefined;
7
-    constructor(message?: string | undefined);
8
-}
9
-export declare class SuccessResponse extends Response {
10
-    result: Outcome;
11
-    constructor(message?: string);
12
-}
13
-export declare class ErrorResponse extends Response {
14
-    result: Outcome;
15
-    constructor(message?: string);
16
-}
17
-export declare class SubscriptionResponse extends SuccessResponse {
18
-    uid: string;
19
-    constructor(uid: string, message?: string);
20
-}
21
-export declare type UnhookFunction = (uid: string) => Promise<SuccessResponse | ErrorResponse>;
22
-export declare type callbackFunction = (...args: any[]) => Promise<SubscriptionResponse | ErrorResponse>;
23
-export declare type AsyncFunction = (...args: any[]) => Promise<any>;
24
-export interface RPCExporter {
25
-    name: string;
26
-    exportRPCs(): socketioRPC[];
27
-    exportPublicRPCs(): socketioRPC[];
28
-}
29
-declare type baseRPC = {
30
-    type: rpcType;
31
-    name: string;
32
-};
33
-declare type hookRPC = baseRPC & {
34
-    type: 'hook';
35
-    func: callbackFunction;
36
-    unhook: UnhookFunction;
37
-};
38
-declare type unhookRPC = baseRPC & {
39
-    type: 'unhook';
40
-    func: UnhookFunction;
41
-};
42
-declare type callRPC = baseRPC & {
43
-    type: 'call';
44
-    func: (...args: any[]) => Promise<any>;
45
-};
46
-export declare type socketioRPC = callRPC | unhookRPC | hookRPC;
47
-export declare type baseInfo = {
48
-    owner: string;
49
-    argNames: string[];
50
-};
51
-declare type HookInfo = baseRPC & baseInfo & {
52
-    type: 'hook';
53
-    generator: (socket: any) => callbackFunction;
54
-    unhook: UnhookFunction;
55
-};
56
-declare type UnhookInfo = baseRPC & baseInfo & {
57
-    type: 'unhook';
58
-    func: UnhookFunction;
59
-};
60
-declare type CallInfo = baseRPC & baseInfo & {
61
-    type: 'call';
62
-    func: AsyncFunction;
63
-};
64
-declare type RpcInfo = HookInfo | UnhookInfo | CallInfo;
65
-export declare type ExtendedRpcInfo = RpcInfo & {
66
-    uniqueName: string;
67
-};
68
-export declare const rpcToRpcinfo: (rpc: socketioRPC, owner: string) => RpcInfo;
69
-declare type OnFunction = (type: 'error' | 'close', f: (e?: any) => void) => Socket;
70
-export interface Socket {
71
-    port: number;
72
-    hook: (rpcname: string, ...args: any[]) => Socket;
73
-    unhook: (rpcname: string) => Socket;
74
-    call: (rpcname: string, ...args: any[]) => Promise<any>;
75
-    fire: (rpcname: string, ...args: any[]) => Promise<any>;
76
-    on: OnFunction;
77
-    destroy: () => void;
78
-    close: () => void;
79
-}
80
-export declare type RPCSocketConf = {
81
-    connectionHandler: (socket: Socket) => void;
82
-    errorHandler: (socket: Socket) => (error: any) => void;
83
-    closeHandler: (socket: Socket) => () => void;
84
-};
85
-export declare class RPCSocketServer {
86
-    private port;
87
-    private rpcExporters;
88
-    private visibility;
89
-    private conf;
90
-    private io;
91
-    private wsServer;
92
-    constructor(port: number, rpcExporters?: RPCExporter[], visibility?: Visibility, conf?: RPCSocketConf);
93
-    private startWebsocket;
94
-    protected initRPCs(socket: Socket): void;
95
-    protected initPublicRPCs(socket: Socket): void;
96
-}
97
-export {};

+ 0
- 153
lib/src/backend/RPCSocketServer.js View File

@@ -1,153 +0,0 @@
1
-"use strict";
2
-Object.defineProperty(exports, "__esModule", { value: true });
3
-const http = require("http");
4
-const bsock = require("bsock");
5
-const uuid = require("uuid/v4");
6
-/* Responses */
7
-class Response {
8
-    constructor(message) {
9
-        this.message = message;
10
-    }
11
-}
12
-exports.Response = Response;
13
-class SuccessResponse extends Response {
14
-    constructor(message) {
15
-        super(message);
16
-        this.result = "Success";
17
-    }
18
-}
19
-exports.SuccessResponse = SuccessResponse;
20
-class ErrorResponse extends Response {
21
-    constructor(message = "Unknown error") {
22
-        super(message);
23
-        this.result = "Error";
24
-    }
25
-}
26
-exports.ErrorResponse = ErrorResponse;
27
-class SubscriptionResponse extends SuccessResponse {
28
-    constructor(uid, message) {
29
-        super(message);
30
-        this.uid = uid;
31
-    }
32
-}
33
-exports.SubscriptionResponse = SubscriptionResponse;
34
-exports.rpcToRpcinfo = (rpc, owner) => {
35
-    switch (rpc.type) {
36
-        case "call":
37
-            return {
38
-                owner: owner,
39
-                argNames: extractArgs(rpc.func),
40
-                type: rpc.type,
41
-                name: rpc.name,
42
-                func: rpc.func,
43
-            };
44
-        case "unhook":
45
-            return {
46
-                owner: owner,
47
-                argNames: extractArgs(rpc.func),
48
-                type: rpc.type,
49
-                name: rpc.name,
50
-                func: rpc.func,
51
-            };
52
-        case "hook":
53
-            const generator = hookGenerator(rpc);
54
-            return {
55
-                owner: owner,
56
-                argNames: extractArgs(generator(undefined)),
57
-                type: rpc.type,
58
-                name: rpc.name,
59
-                unhook: rpc.unhook,
60
-                generator: generator,
61
-            };
62
-    }
63
-};
64
-function rpcHooker(socket, exporter, makeUnique = true) {
65
-    const owner = exporter.name;
66
-    const RPCs = [...exporter.exportPublicRPCs(), ...exporter.exportRPCs()];
67
-    const suffix = makeUnique ? "-" + uuid().substr(0, 4) : "";
68
-    return RPCs.map(rpc => exports.rpcToRpcinfo(rpc, owner))
69
-        .map(info => {
70
-        const ret = info;
71
-        ret.uniqueName = info.name + suffix;
72
-        switch (info.type) {
73
-            case "hook":
74
-                socket.hook(ret.uniqueName, info.generator(socket));
75
-                break;
76
-            default:
77
-                socket.hook(ret.uniqueName, info.func);
78
-        }
79
-        socket.on('close', () => socket.unhook(info.name));
80
-        return ret;
81
-    });
82
-}
83
-const hookGenerator = (rpc) => {
84
-    const argsArr = extractArgs(rpc.func);
85
-    argsArr.pop();
86
-    const args = argsArr.join(',');
87
-    return eval(`(socket) => async (` + args + `) => { 
88
-        const res = await rpc.func(` + args + (args.length !== 0 ? ',' : '') + ` (x) => {
89
-            socket.call(res.uid, x)
90
-        })
91
-        if(res.result == 'Success'){
92
-            socket.on('close', async () => {
93
-                const unhookRes = await rpc.unhook(res.uid)
94
-                console.log("Specific close handler for", rpc.name, res.uid, unhookRes)
95
-            })
96
-
97
-        }
98
-        return res
99
-    }`);
100
-};
101
-const extractArgs = (f) => {
102
-    let fn = String(f);
103
-    let args = fn.substr(0, fn.indexOf(")"));
104
-    args = args.substr(fn.indexOf("(") + 1);
105
-    let ret = args.split(",");
106
-    return ret;
107
-};
108
-class RPCSocketServer {
109
-    constructor(port, rpcExporters = [], visibility = "127.0.0.1", conf = {
110
-        errorHandler: (socket) => (error) => { socket.destroy(); console.error(error); },
111
-        closeHandler: (socket) => () => { console.log("Socket closing"); },
112
-        connectionHandler: (socket) => { console.log("New websocket connection in port " + socket.port); }
113
-    }) {
114
-        this.port = port;
115
-        this.rpcExporters = rpcExporters;
116
-        this.visibility = visibility;
117
-        this.conf = conf;
118
-        this.io = bsock.createServer();
119
-        this.wsServer = http.createServer();
120
-        this.startWebsocket();
121
-    }
122
-    startWebsocket() {
123
-        try {
124
-            this.io.attach(this.wsServer);
125
-            this.io.on('socket', (socket) => {
126
-                socket.on('error', this.conf.errorHandler(socket));
127
-                socket.on('close', this.conf.closeHandler(socket));
128
-                if (this.visibility === "127.0.0.1")
129
-                    this.initRPCs(socket);
130
-                else
131
-                    this.initPublicRPCs(socket);
132
-            });
133
-            this.wsServer.listen(this.port, this.visibility);
134
-        }
135
-        catch (e) {
136
-            //@ts-ignore
137
-            this.errorHandler(undefined)("Unable to connect to socket");
138
-        }
139
-    }
140
-    initRPCs(socket) {
141
-        socket.hook('info', () => rpcInfos);
142
-        const rpcInfos = [
143
-            ...this.rpcExporters.flatMap(exporter => rpcHooker(socket, exporter))
144
-        ];
145
-    }
146
-    initPublicRPCs(socket) {
147
-        socket.hook('info', () => rpcInfos);
148
-        const rpcInfos = [
149
-            ...this.rpcExporters.flatMap(exporter => rpcHooker(socket, exporter))
150
-        ];
151
-    }
152
-}
153
-exports.RPCSocketServer = RPCSocketServer;

+ 0
- 6
lib/src/interfaces/Exporter.d.ts View File

@@ -1,6 +0,0 @@
1
-import { SocketioRPC, Name } from "../Types";
2
-export interface Exporter {
3
-    name: Name;
4
-    exportRPCs(): SocketioRPC[];
5
-    exportPublicRPCs(): SocketioRPC[];
6
-}

+ 0
- 2
lib/src/interfaces/Exporter.js View File

@@ -1,2 +0,0 @@
1
-"use strict";
2
-Object.defineProperty(exports, "__esModule", { value: true });

+ 0
- 11
lib/src/interfaces/Socket.d.ts View File

@@ -1,11 +0,0 @@
1
-import { OnFunction } from "../Types";
2
-export interface Socket {
3
-    port: number;
4
-    hook: (rpcname: string, ...args: any[]) => Socket;
5
-    unhook: (rpcname: string) => Socket;
6
-    call: (rpcname: string, ...args: any[]) => Promise<any>;
7
-    fire: (rpcname: string, ...args: any[]) => Promise<any>;
8
-    on: OnFunction;
9
-    destroy: () => void;
10
-    close: () => void;
11
-}

+ 0
- 2
lib/src/interfaces/Socket.js View File

@@ -1,2 +0,0 @@
1
-"use strict";
2
-Object.defineProperty(exports, "__esModule", { value: true });

+ 0
- 1
lib/test/test.d.ts View File

@@ -1 +0,0 @@
1
-export {};

+ 0
- 23
lib/test/test.js View File

@@ -1,23 +0,0 @@
1
-"use strict";
2
-Object.defineProperty(exports, "__esModule", { value: true });
3
-const Server_1 = require("../src/Server");
4
-//@ts-ignore
5
-const Client_1 = require("../src/Client");
6
-new Server_1.Server(20000, [{
7
-        name: "HelloWorldRPCGroup",
8
-        exportPublicRPCs: () => [],
9
-        exportRPCs: () => [{
10
-                type: 'call',
11
-                name: 'echo',
12
-                func: async (s) => s,
13
-            }],
14
-    }]);
15
-<<<<<<< HEAD
16
-const caller = new Client_1.Client(20000, 'localhost');
17
-=======
18
-const caller = new RPCSocket_1.RPCSocket(20000, 'localhost');
19
->>>>>>> 17dc58c5b3fd3c76113d592d895400498578affa
20
-caller.connect().then(_ => {
21
-    caller.info().then(console.log);
22
-    caller["HelloWorldRPCGroup"].echo("x").then(console.log);
23
-});

+ 2
- 1
package.json View File

@@ -23,5 +23,6 @@
23 23
   "dependencies": {
24 24
     "bsock": "^0.1.9",
25 25
     "uuid": "^3.3.3"
26
-  }
26
+  },
27
+  "files": []
27 28
 }

+ 24
- 18
src/Client.ts View File

@@ -1,50 +1,56 @@
1
+'use strict'
2
+
1 3
 var bsock = require('bsock')
2 4
 
3
-import { ExtendedRpcInfo, UnhookFunction, CallbackFunction, AsyncFunction } from "./Types";
4
-import { Socket } from './interfaces/Socket'
5
+import * as I from './Interfaces';
6
+import * as T from './Types';
7
+
5 8
 
6 9
 //fix args with defaults like "force = true" -> "force"
7 10
 function stripAfterEquals(str:string){
8 11
     return str.split("=")[0]
9 12
 }
10 13
 
11
-export class Client implements Socket{
12
-    private socket: Socket
14
+export class Client implements I.Socket{
15
+
16
+    private socket: I.Socket
13 17
     constructor(public port:number, private server: string, private tls: boolean = false){
14 18
     }
15 19
 
16
-    hook(name, args){
20
+
21
+
22
+    public hook(name: T.Name, args: T.Arg){
17 23
         return this.socket.hook(name, args)
18 24
     }
19 25
 
20
-    unhook(name){
26
+    public unhook(name: T.Name){
21 27
         return this.socket.unhook(name)
22 28
     }
23 29
 
24
-    on(type: "error" | "close", f: (e?: any) => void){
25
-        return this.socket.on(type, name)
30
+    public on(type: "error" | "close", f: (e?: any) => void){
31
+        return this.socket.on(type, f)
26 32
     }
27 33
 
28
-    destroy(){
34
+    public destroy(){
29 35
         return this.socket.destroy()
30 36
     }
31 37
 
32
-    close(){
38
+    public close(){
33 39
         return this.socket.close()
34 40
     }
35 41
 
36
-    async call (rpcname: string, ...args: any[]) : Promise<any>{
42
+    public async call (rpcname: T.Name, ...args: T.Any[]) : Promise<T.Any>{
37 43
         return await this.socket.call.apply(this.socket, [rpcname, ...args])
38 44
     }
39 45
 
40
-    async fire(rpcname: string, ...args: any[]) : Promise<any>{
46
+    public async fire(rpcname: T.Name, ...args: T.Any[]) : Promise<T.Any>{
41 47
         return await this.socket.fire.apply(this.socket, [rpcname, ...args])
42 48
     }
43 49
     
44
-    async connect(){
50
+    public async connect(){
45 51
         this.socket = await bsock.connect(this.port, this.server, this.tls)
46 52
 
47
-        const info:ExtendedRpcInfo[] = await this.info()
53
+        const info:T.ExtendedRpcInfo[] = await this.info()
48 54
         info.forEach(i => {
49 55
             let f: any
50 56
             switch (i.type) {
@@ -65,17 +71,17 @@ export class Client implements Socket{
65 71
         })
66 72
     }
67 73
 
68
-    async info(){
74
+    public async info(){
69 75
         return await this.socket.call('info')
70 76
     }
71 77
 
72
-    private callGenerator(fnName, fnArgs:string[]): AsyncFunction{
78
+    private callGenerator(fnName: T.Name, fnArgs:T.Arg[]): T.AsyncFunction{
73 79
         const headerArgs = fnArgs.join(",")
74 80
         const argParams = fnArgs.map(stripAfterEquals).join(",")
75 81
         return eval( '( () => async ('+headerArgs+') => { return await this.socket.call("'+fnName+'", '+argParams+')} )()' )
76 82
     }
77 83
 
78
-    private hookGenerator(fnName, fnArgs:string[]): CallbackFunction{
84
+    private hookGenerator(fnName: T.Name, fnArgs:T.Arg[]): T.CallbackFunction{
79 85
         const headerArgs = fnArgs.join(",")
80 86
         const argParams = fnArgs.map(stripAfterEquals).join(",")
81 87
         return eval( `( () => async (`+headerArgs+(headerArgs.length!==0?",":"")+` callback) => {
@@ -87,7 +93,7 @@ export class Client implements Socket{
87 93
                         } )()` )
88 94
     }
89 95
 
90
-    private unhookGenerator(fnName, fnArgs:string[]): UnhookFunction{
96
+    private unhookGenerator(fnName: T.Name, fnArgs:T.Arg[]): T.UnhookFunction{
91 97
         const headerArgs = fnArgs.join(",")
92 98
         const argParams = fnArgs.map(stripAfterEquals).join(",")
93 99
         if(fnArgs.length != 1)

+ 19
- 0
src/Interfaces.ts View File

@@ -0,0 +1,19 @@
1
+import * as T from "./Types";
2
+import * as I from "./Interfaces"
3
+
4
+export interface Exporter{
5
+    name: T.Name
6
+    localRPCs() : T.RPC[]
7
+    publicRPCs() : T.RPC[]
8
+}
9
+
10
+export interface Socket {
11
+    port: number
12
+    hook: (rpcname: T.Name, ...args: T.Any[]) => I.Socket
13
+    unhook: (rpcname:T.Name) => I.Socket
14
+    call: (rpcname:T.Name, ...args: T.Any[]) => Promise<T.Any>
15
+    fire: (rpcname:T.Name, ...args: T.Any[]) => Promise<T.Any>
16
+    on: T.OnFunction
17
+    destroy: ()=>void
18
+    close: ()=>void
19
+}

src/Response.ts → src/Responses.ts View File


+ 26
- 26
src/Server.ts View File

@@ -1,23 +1,23 @@
1
+'use strict'
2
+
1 3
 import http = require('http');
2 4
 import bsock = require('bsock');
3 5
 
4
-import { ExtendedRpcInfo, SocketConf, SocketioRPC } from './Types';
5
-import { rpcHooker } from './Util';
6
-import { Exporter } from './interfaces/Exporter';
7
-import { Socket } from "./interfaces/Socket";
6
+import * as T from './Types'; 
7
+import * as U from './Utils'; 
8
+import * as I from './Interfaces'; 
8 9
 
9 10
 export class Server{
10
-    
11
+    private ws = http.createServer()
11 12
     private io = bsock.createServer()
12
-    private wsServer = http.createServer()
13 13
 
14 14
     constructor(
15 15
         private port:number,
16
-        private rpcExporters: Exporter[] = [],
17
-        private conf: SocketConf = {
18
-            errorHandler: (socket:Socket) => (error:any) => { socket.destroy(); console.error(error) },
19
-            closeHandler: (socket:Socket) => () => { console.log("Socket closing") },
20
-            connectionHandler: (socket:Socket) => { console.log("New websocket connection in port "+socket.port)},
16
+        private exporters: I.Exporter[] = [],
17
+        private conf: T.SocketConf = {
18
+            errorHandler: (socket:I.Socket) => (error:any) => { socket.destroy(); console.error(error) },
19
+            closeHandler: (socket:I.Socket) => () => { console.log("Socket closing") },
20
+            connectionHandler: (socket:I.Socket) => { console.log("New websocket connection in port "+socket.port)},
21 21
             visibility: "127.0.0.1"
22 22
         }
23 23
     ){
@@ -26,8 +26,8 @@ export class Server{
26 26
 
27 27
     private startWebsocket(){
28 28
         try{
29
-            this.io.attach(this.wsServer)
30
-            this.io.on('socket', (socket:Socket) => {
29
+            this.io.attach(this.ws)
30
+            this.io.on('socket', (socket:I.Socket) => {
31 31
                 socket.on('error', this.conf.errorHandler(socket))
32 32
                 socket.on('close', this.conf.closeHandler(socket))
33 33
                 if(this.conf.visibility === "127.0.0.1")
@@ -35,26 +35,26 @@ export class Server{
35 35
                 else
36 36
                     this.initPublicRPCs(socket)
37 37
             })
38
-            this.wsServer.listen(this.port, this.conf.visibility)
38
+            this.ws.listen(this.port, this.conf.visibility)
39 39
         }catch(e){
40 40
             //@ts-ignore
41 41
             this.errorHandler(undefined)("Unable to connect to socket")
42 42
         }
43 43
     }
44 44
 
45
-    protected initRPCs(socket:Socket){
46
-        const infoRPC:SocketioRPC[] = [
47
-            {
48
-                name: 'info',
49
-                type: 'Call',
50
-                func: async () => rpcInfos
51
-            }
52
-        ]
53
-        const rpcInfos:ExtendedRpcInfo[] = [
54
-            ...rpcHooker(socket, "RPC", infoRPC, false),
55
-            ...this.rpcExporters.flatMap(exporter => rpcHooker(socket, exporter.name, [...exporter.exportPublicRPCs(), ...exporter.exportRPCs()]))
45
+    protected initRPCs(socket:I.Socket){
46
+        socket.hook('info', () => rpcInfos)
47
+
48
+        const rpcInfos:T.ExtendedRpcInfo[] = [
49
+            ...this.exporters.flatMap(exporter => U.rpcHooker(socket, exporter))
56 50
         ]
57 51
     }
58 52
 
59
-    protected initPublicRPCs(socket:Socket){}
53
+    protected initPublicRPCs(socket:I.Socket){
54
+        socket.hook('info', () => rpcInfos)
55
+
56
+        const rpcInfos:T.ExtendedRpcInfo[] = [
57
+            ...this.exporters.flatMap(exporter => U.rpcHooker(socket, exporter))
58
+        ]
59
+    }
60 60
 }

+ 23
- 20
src/Types.ts View File

@@ -1,44 +1,47 @@
1
-import { SuccessResponse, ErrorResponse, SubscriptionResponse } from "./Response";
2
-import { Socket } from "./interfaces/Socket";
1
+import * as R from "./Responses";
2
+import * as I from "./Interfaces";
3 3
 
4 4
 export type Visibility = "127.0.0.1" | "0.0.0.0"
5
-export type Name = string
5
+export type Any = any
6
+export type Arg = string
7
+export type Name = Arg
8
+export type Owner = Name
6 9
 
7 10
 export type SocketConf = {
8
-    connectionHandler: (socket:Socket) => void
9
-    errorHandler: (socket:Socket) => (error:any) => void
10
-    closeHandler: (socket:Socket) => () =>  void
11
+    connectionHandler: (socket:I.Socket) => void
12
+    errorHandler: (socket:I.Socket) => (error:any) => void
13
+    closeHandler: (socket:I.Socket) => () =>  void
11 14
     visibility: Visibility
12 15
 }
13 16
 
14
-export type rpcType = 'Hook' | 'Unhook' | 'Call'
17
+export type RPCType = 'Hook' | 'Unhook' | 'Call'
15 18
 
16 19
 export type BaseRPC = { 
17
-    type: rpcType
18
-    name: string
20
+    type: RPCType
21
+    name: Name
19 22
 }
20 23
 
21 24
 export type HookRPC = BaseRPC & {
22 25
     type: 'Hook'
23
-    func: CallbackFunction
26
+    clbk: CallbackFunction
24 27
     unhook: UnhookFunction
25 28
 }
26 29
 
27 30
 export type UnhookRPC = BaseRPC & {
28 31
     type: 'Unhook'
29
-    func: UnhookFunction
32
+    unhook: UnhookFunction
30 33
 }
31 34
 
32 35
 export type CallRPC = BaseRPC & {
33 36
     type: 'Call'
34
-    func: (...args) => Promise<any>
37
+    call: AsyncFunction
35 38
 }
36 39
 
37
-export type SocketioRPC = CallRPC | UnhookRPC | HookRPC
40
+export type RPC = CallRPC | UnhookRPC | HookRPC
38 41
 
39 42
 export type BaseInfo = {
40
-    owner: string,
41
-    argNames: string[],
43
+    owner: Name,
44
+    argNames: Name[],
42 45
 }
43 46
 
44 47
 export type HookInfo = BaseRPC & BaseInfo & { 
@@ -49,18 +52,18 @@ export type HookInfo = BaseRPC & BaseInfo & {
49 52
 
50 53
 export type UnhookInfo = BaseRPC & BaseInfo & {
51 54
     type: 'Unhook',
52
-    func: UnhookFunction
55
+    unhook: UnhookFunction
53 56
 }
54 57
 
55 58
 export type CallInfo = BaseRPC & BaseInfo & {
56 59
     type: 'Call',
57
-    func: AsyncFunction
60
+    call: AsyncFunction
58 61
 }
59 62
 
60 63
 export type RpcInfo = HookInfo | UnhookInfo | CallInfo
61 64
 export type ExtendedRpcInfo = RpcInfo & { uniqueName: string } 
62 65
 
63
-export type OnFunction = (type: 'error' | 'close', f: (e?:any)=>void) => Socket
64
-export type UnhookFunction = (uid:string) => Promise<SuccessResponse | ErrorResponse>
65
-export type CallbackFunction = (...args) => Promise<SubscriptionResponse | ErrorResponse>
66
+export type OnFunction = (type: 'error' | 'close', f: (e?:any)=>void) => I.Socket
67
+export type UnhookFunction = (uid:string) => Promise<R.SuccessResponse | R.ErrorResponse>
68
+export type CallbackFunction = (...args) => Promise<R.SubscriptionResponse | R.ErrorResponse>
66 69
 export type AsyncFunction = (...args) => Promise<any>

src/Util.ts → src/Utils.ts View File

@@ -1,25 +1,25 @@
1 1
 import * as uuid from "uuid/v4"
2 2
 
3
-import { HookRPC, HookInfo, SocketioRPC, RpcInfo, ExtendedRpcInfo } from "./Types";
4
-import { Socket } from "./interfaces/Socket";
3
+import * as T from "./Types";
4
+import * as I from "./Interfaces";
5 5
 
6
-export const rpcToRpcinfo = (rpc : SocketioRPC, owner: string):RpcInfo => {
6
+export const rpcToRpcinfo = (rpc : T.RPC, owner: T.Owner):T.RpcInfo => {
7 7
     switch(rpc.type){
8 8
         case "Call" :
9 9
             return {
10 10
                 owner: owner,
11
-                argNames: extractArgs(rpc.func),
11
+                argNames: extractArgs(rpc.call),
12 12
                 type: rpc.type,
13 13
                 name: rpc.name,
14
-                func: rpc.func,
14
+                call: rpc.call,
15 15
             }
16 16
         case "Unhook" :
17 17
             return {
18 18
                 owner: owner,
19
-                argNames: extractArgs(rpc.func),
19
+                argNames: extractArgs(rpc.unhook),
20 20
                 type: rpc.type,
21 21
                 name: rpc.name,
22
-                func: rpc.func,
22
+                unhook: rpc.unhook,
23 23
             }
24 24
         case "Hook" :
25 25
             const generator = hookGenerator(rpc)
@@ -33,8 +33,9 @@ export const rpcToRpcinfo = (rpc : SocketioRPC, owner: string):RpcInfo => {
33 33
             }
34 34
     }
35 35
 }
36
-
37
-export const rpcHooker = (socket: Socket, owner:string, RPCs: SocketioRPC[], makeUnique = true):ExtendedRpcInfo[] => {
36
+export function rpcHooker(socket: I.Socket, exporter:I.Exporter, makeUnique = true):T.ExtendedRpcInfo[]{
37
+    const owner = exporter.name
38
+    const RPCs = [...exporter.publicRPCs(), ...exporter.localRPCs()]
38 39
     const suffix = makeUnique?"-"+uuid().substr(0,4):""
39 40
     return RPCs.map(rpc => rpcToRpcinfo(rpc, owner))
40 41
     .map(info => {
@@ -45,21 +46,25 @@ export const rpcHooker = (socket: Socket, owner:string, RPCs: SocketioRPC[], mak
45 46
             case "Hook":
46 47
                 socket.hook(ret.uniqueName, info.generator(socket))
47 48
                 break;
48
-            default:
49
-                socket.hook(ret.uniqueName, info.func)
49
+            case "Unhook":
50
+                socket.hook(ret.uniqueName, info.unhook)
51
+                break;
52
+            case "Call":
53
+                socket.hook(ret.uniqueName, info.call)
54
+                break;
50 55
         }
51 56
         socket.on('close', () => socket.unhook(info.name))
52 57
         return ret
53 58
     })
54 59
 }
55 60
 
56
-const hookGenerator = (rpc:HookRPC): HookInfo['generator'] => { 
57
-    const argsArr = extractArgs(rpc.func)
61
+const hookGenerator = (rpc:T.HookRPC): T.HookInfo['generator'] => { 
62
+    const argsArr = extractArgs(rpc.clbk)
58 63
     argsArr.pop()
59 64
     const args = argsArr.join(',')
60 65
 
61 66
     return eval(`(socket) => async (`+args+`) => { 
62
-        const res = await rpc.func(`+args+(args.length!==0?',':'')+` (x) => {
67
+        const res = await rpc.clbk(`+args+(args.length!==0?',':'')+` (x) => {
63 68
             socket.call(res.uid, x)
64 69
         })
65 70
         if(res.result == 'Success'){
@@ -73,7 +78,7 @@ const hookGenerator = (rpc:HookRPC): HookInfo['generator'] => {
73 78
     }`)
74 79
 }
75 80
 
76
-const extractArgs = (f:Function):string[] => {
81
+const extractArgs = (f:Function):T.Arg[] => {
77 82
     let fn = String(f)
78 83
     let args = fn.substr(0, fn.indexOf(")"))
79 84
     args = args.substr(fn.indexOf("(")+1)

+ 0
- 256
src/backend/RPCSocketServer.ts View File

@@ -1,256 +0,0 @@
1
-import http = require('http');
2
-import bsock = require('bsock');
3
-
4
-import * as uuid from "uuid/v4"
5
-import { Socket } from "./RPCSocketServer"
6
-
7
-type rpcType = 'hook' | 'unhook' | 'call'
8
-export type Outcome = "Success" | "Error"
9
-export type Visibility = "127.0.0.1" | "0.0.0.0"
10
-
11
-/* Responses */
12
-export class Response{
13
-    constructor(
14
-        public message?:string
15
-    ){}
16
-}
17
-
18
-export class SuccessResponse extends Response{
19
-    result:Outcome = "Success"
20
-
21
-    constructor(
22
-        message?:string
23
-    ){
24
-        super(message)
25
-    }
26
-}
27
-
28
-export class ErrorResponse extends Response{
29
-    result:Outcome = "Error"
30
-
31
-    constructor(
32
-        message: string = "Unknown error"
33
-    ){
34
-        super(message)
35
-    } 
36
-}
37
-
38
-export class SubscriptionResponse extends SuccessResponse{
39
-    constructor(
40
-        public uid: string,
41
-        message?:string
42
-    ){
43
-        super(message)
44
-    }
45
-}
46
-export type UnhookFunction = (uid:string) => Promise<SuccessResponse | ErrorResponse>
47
-export type callbackFunction = (...args) => Promise<SubscriptionResponse | ErrorResponse>
48
-export type AsyncFunction = (...args) => Promise<any>
49
-
50
-export interface RPCExporter{
51
-    name: string
52
-    exportRPCs() : socketioRPC[]
53
-    exportPublicRPCs() : socketioRPC[]
54
-}
55
-
56
-type baseRPC = { 
57
-    type: rpcType
58
-    name: string
59
-}
60
-
61
-type hookRPC = baseRPC & {
62
-    type: 'hook'
63
-    func: callbackFunction
64
-    unhook: UnhookFunction
65
-}
66
-
67
-type unhookRPC = baseRPC & {
68
-    type: 'unhook'
69
-    func: UnhookFunction
70
-}
71
-
72
-type callRPC = baseRPC & {
73
-    type: 'call'
74
-    func: (...args) => Promise<any>
75
-}
76
-
77
-export type socketioRPC = callRPC | unhookRPC | hookRPC
78
-
79
-export type baseInfo = {
80
-    owner: string,
81
-    argNames: string[],
82
-}
83
-
84
-type HookInfo = baseRPC & baseInfo & { 
85
-    type: 'hook', 
86
-    generator: (socket) => callbackFunction
87
-    unhook: UnhookFunction
88
-}
89
-
90
-type UnhookInfo = baseRPC & baseInfo & {
91
-    type: 'unhook',
92
-    func: UnhookFunction
93
-}
94
-
95
-type CallInfo = baseRPC & baseInfo & {
96
-    type: 'call',
97
-    func: AsyncFunction
98
-}
99
-
100
-type RpcInfo = HookInfo | UnhookInfo | CallInfo
101
-
102
-export type ExtendedRpcInfo = RpcInfo & { uniqueName: string } 
103
-
104
-export const rpcToRpcinfo = (rpc : socketioRPC, owner: string):RpcInfo => {
105
-    switch(rpc.type){
106
-        case "call" :
107
-            return {
108
-                owner: owner,
109
-                argNames: extractArgs(rpc.func),
110
-                type: rpc.type,
111
-                name: rpc.name,
112
-                func: rpc.func,
113
-            }
114
-        case "unhook" :
115
-            return {
116
-                owner: owner,
117
-                argNames: extractArgs(rpc.func),
118
-                type: rpc.type,
119
-                name: rpc.name,
120
-                func: rpc.func,
121
-            }
122
-        case "hook" :
123
-            const generator = hookGenerator(rpc)
124
-            return {
125
-                owner: owner,
126
-                argNames: extractArgs(generator(undefined)),
127
-                type: rpc.type,
128
-                name: rpc.name,
129
-                unhook: rpc.unhook,
130
-                generator: generator,
131
-            }
132
-    }
133
-}
134
-
135
-
136
-function rpcHooker(socket: Socket, exporter:RPCExporter, makeUnique = true):ExtendedRpcInfo[]{
137
-    const owner = exporter.name
138
-    const RPCs = [...exporter.exportPublicRPCs(), ...exporter.exportRPCs()]
139
-    const suffix = makeUnique?"-"+uuid().substr(0,4):""
140
-    return RPCs.map(rpc => rpcToRpcinfo(rpc, owner))
141
-    .map(info => {
142
-        const ret:any = info
143
-        ret.uniqueName = info.name+suffix
144
-
145
-        switch(info.type){
146
-            case "hook":
147
-                socket.hook(ret.uniqueName, info.generator(socket))
148
-                break;
149
-            default:
150
-                socket.hook(ret.uniqueName, info.func)
151
-        }
152
-        socket.on('close', () => socket.unhook(info.name))
153
-        return ret
154
-    })
155
-}
156
-
157
-const hookGenerator = (rpc:hookRPC): HookInfo['generator'] => { 
158
-    const argsArr = extractArgs(rpc.func)
159
-    argsArr.pop()
160
-    const args = argsArr.join(',')
161
-
162
-    return eval(`(socket) => async (`+args+`) => { 
163
-        const res = await rpc.func(`+args+(args.length!==0?',':'')+` (x) => {
164
-            socket.call(res.uid, x)
165
-        })
166
-        if(res.result == 'Success'){
167
-            socket.on('close', async () => {
168
-                const unhookRes = await rpc.unhook(res.uid)
169
-                console.log("Specific close handler for", rpc.name, res.uid, unhookRes)
170
-            })
171
-
172
-        }
173
-        return res
174
-    }`)
175
-}
176
-
177
-const extractArgs = (f:Function):string[] => {
178
-    let fn = String(f)
179
-    let args = fn.substr(0, fn.indexOf(")"))
180
-    args = args.substr(fn.indexOf("(")+1)
181
-    let ret = args.split(",")
182
-    return ret
183
-}
184
-
185
-
186
-type OnFunction = (type: 'error' | 'close', f: (e?:any)=>void) => Socket
187
-
188
-export interface Socket {
189
-    port: number
190
-    hook: (rpcname: string, ...args: any[]) => Socket
191
-    unhook: (rpcname:string) => Socket
192
-    call: (rpcname:string, ...args: any[]) => Promise<any>
193
-    fire: (rpcname:string, ...args: any[]) => Promise<any>
194
-    on: OnFunction
195
-    destroy: ()=>void
196
-    close: ()=>void
197
-}
198
-
199
-export type RPCSocketConf = {
200
-    connectionHandler: (socket:Socket) => void
201
-    errorHandler: (socket:Socket) => (error:any) => void
202
-    closeHandler: (socket:Socket) => () =>  void
203
-}
204
-
205
-export class RPCSocketServer{
206
-    
207
-    private io = bsock.createServer()
208
-    private wsServer = http.createServer()
209
-
210
-    constructor(
211
-        private port:number,
212
-        private rpcExporters: RPCExporter[] = [],
213
-        private visibility: Visibility = "127.0.0.1",
214
-        private conf: RPCSocketConf = {
215
-            errorHandler: (socket:Socket) => (error:any) => { socket.destroy(); console.error(error) },
216
-            closeHandler: (socket:Socket) => () => { console.log("Socket closing") },
217
-            connectionHandler: (socket:Socket) => { console.log("New websocket connection in port "+socket.port) }
218
-        }
219
-    ){
220
-        this.startWebsocket()
221
-    }
222
-
223
-    private startWebsocket(){
224
-        try{
225
-            this.io.attach(this.wsServer)
226
-            this.io.on('socket', (socket:Socket) => {
227
-                socket.on('error', this.conf.errorHandler(socket))
228
-                socket.on('close', this.conf.closeHandler(socket))
229
-                if(this.visibility === "127.0.0.1")
230
-                    this.initRPCs(socket)
231
-                else
232
-                    this.initPublicRPCs(socket)
233
-            })
234
-            this.wsServer.listen(this.port, this.visibility)
235
-        }catch(e){
236
-            //@ts-ignore
237
-            this.errorHandler(undefined)("Unable to connect to socket")
238
-        }
239
-    }
240
-
241
-    protected initRPCs(socket:Socket){
242
-        socket.hook('info', () => rpcInfos)
243
-
244
-        const rpcInfos:ExtendedRpcInfo[] = [
245
-            ...this.rpcExporters.flatMap(exporter => rpcHooker(socket, exporter))
246
-        ]
247
-    }
248
-
249
-    protected initPublicRPCs(socket:Socket){
250
-        socket.hook('info', () => rpcInfos)
251
-
252
-        const rpcInfos:ExtendedRpcInfo[] = [
253
-            ...this.rpcExporters.flatMap(exporter => rpcHooker(socket, exporter))
254
-        ]
255
-    }
256
-}

+ 0
- 7
src/interfaces/Exporter.ts View File

@@ -1,7 +0,0 @@
1
-import { SocketioRPC, Name } from "../Types";
2
-
3
-export interface Exporter{
4
-    name: Name
5
-    exportRPCs() : SocketioRPC[]
6
-    exportPublicRPCs() : SocketioRPC[]
7
-}

+ 0
- 12
src/interfaces/Socket.ts View File

@@ -1,12 +0,0 @@
1
-import { OnFunction } from "../Types";
2
-
3
-export interface Socket {
4
-    port: number
5
-    hook: (rpcname: string, ...args: any[]) => Socket
6
-    unhook: (rpcname:string) => Socket
7
-    call: (rpcname:string, ...args: any[]) => Promise<any>
8
-    fire: (rpcname:string, ...args: any[]) => Promise<any>
9
-    on: OnFunction
10
-    destroy: ()=>void
11
-    close: ()=>void
12
-}

+ 43
- 11
src/webpack.prod.js View File

@@ -1,27 +1,59 @@
1 1
 const path = require('path');
2 2
 const TerserPlugin = require('terser-webpack-plugin');
3 3
 
4
-module.exports = {
4
+const frontendConf = {
5
+    mode: 'production',
6
+    target: "web",
7
+    entry: path.resolve(__dirname, 'Client.ts'),
8
+    output: {
9
+        path: path.resolve(__dirname, '../lib'),
10
+        filename: 'Frontend.js',
11
+        libraryTarget: 'commonjs',
12
+    },
13
+    module: {
14
+      rules: [
15
+        { test: /\.ts?$/, loader: "ts-loader" }
16
+      ]
17
+    },
18
+    resolve: {
19
+      extensions: [".ts", ".tsx", ".js"]
20
+    },
21
+    optimization: {
22
+      minimize: true,
23
+      minimizer: [
24
+        new TerserPlugin({
25
+          parallel: true,
26
+          exclude: [
27
+            /\.\/(.*)\/.ts/,
28
+            /\.\/(.*).ts/,
29
+          ],
30
+        }),
31
+      ],
32
+    },
33
+}
34
+
35
+const backendConf = {
5 36
   mode: 'production',
6
-  target: "web",
7
-  entry: path.resolve(__dirname, 'Client.ts'),
37
+  target: "node",
38
+  entry: path.resolve(__dirname, 'Server.ts'),
8 39
   output: {
9
-      path: path.resolve(__dirname, '../../lib'),
10
-      filename: 'Frontend.min.js',
40
+      path: path.resolve(__dirname, '../lib'),
41
+      filename: 'Backend.js',
11 42
       libraryTarget: 'commonjs',
12 43
   },
13
-  resolve: {
14
-    // Add `.ts` and `.tsx` as a resolvable extension.
15
-    extensions: [".ts", ".tsx", ".js"]
16
-  },
17 44
   module: {
18 45
     rules: [
19 46
       { test: /\.ts?$/, loader: "ts-loader" }
20 47
     ]
21 48
   },
49
+  resolve: {
50
+    extensions: [".ts", ".tsx", ".js"]
51
+  },
22 52
   optimization: {
53
+    minimize: true,
23 54
     minimizer: [
24 55
       new TerserPlugin({
56
+        parallel: true,
25 57
         exclude: [
26 58
           /\.\/(.*)\/.ts/,
27 59
           /\.\/(.*).ts/,
@@ -29,6 +61,6 @@ module.exports = {
29 61
       }),
30 62
     ],
31 63
   },
32
-  externals: {
33
-  }
34 64
 }
65
+
66
+module.exports = [frontendConf, backendConf]

+ 5
- 6
test/test.ts View File

@@ -1,15 +1,14 @@
1 1
 import { Server } from '../src/Server'
2
-//@ts-ignore
3 2
 import {Client} from '../src/Client'
4 3
 
5 4
 new Server(20000, [{
6 5
     name: "HelloWorldRPCGroup",
7
-    exportPublicRPCs: () => [],
8
-    exportRPCs: () => [{
9
-        type: 'call',
6
+    publicRPCs: () => [],
7
+    localRPCs: () => [{
8
+        type: 'Call',
10 9
         name: 'echo',
11
-        func: async (s:string) => s,
12
-    }],
10
+        call: async (s:string) => s,
11
+    }]
13 12
 }])
14 13
 
15 14
 const caller = new Client(20000, 'localhost')

+ 12
- 12
tsconfig.json View File

@@ -1,14 +1,14 @@
1 1
 {
2
-    "compilerOptions": {
3
-      "strictPropertyInitialization": false,
4
-      "noImplicitAny": false,
5
-      "target": "ESnext",
6
-      "module": "commonjs",
7
-      "declaration": true,
8
-      "outDir": "./lib",
9
-      "strict": true,
10
-      "experimentalDecorators": true
11
-    },
12
-    "include": ["src/backend/**/*", "test/**/*"],
13
-    "exclude": ["node_modules", "**/__tests__/*", "src/frontend/**/*"]
2
+  "compilerOptions": {
3
+    "strictPropertyInitialization": false,
4
+    "noImplicitAny": false,
5
+    "target": "ESnext",
6
+    "module": "commonjs",
7
+    "declaration": true,
8
+    "outDir": "./js",
9
+    "strict": true,
10
+    "experimentalDecorators": true
11
+  },
12
+  "include": ["src/**/*.ts", "test/**/*.ts"],
13
+  "exclude": ["node_modules"],
14 14
 }

Loading…
Cancel
Save