Skip to content

Commit 3092f0c

Browse files
[feat] adding typescript to the package
1 parent c499f8a commit 3092f0c

12 files changed

+398
-0
lines changed

index.d.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import RPCClient from "./lib/client";
2+
import RPCServer from "./lib/server";
3+
export { createRPCError } from "./lib/util";
4+
export { createValidator } from "./lib/validator";
5+
export { NOREPLY } from "./lib/symbols";
6+
export { RPCError, RPCFormatViolationError, RPCFormationViolationError, RPCFrameworkError, RPCGenericError, RPCInternalError, RPCMessageTypeNotSupportedError, RPCNotImplementedError, RPCNotSupportedError, RPCOccurenceConstraintViolationError, RPCOccurrenceConstraintViolationError, RPCPropertyConstraintViolationError, RPCProtocolError, RPCSecurityError, RPCTypeConstraintViolationError, TimeoutError, UnexpectedHttpResponse, WebsocketUpgradeError, } from "./lib/errors";
7+
export { RPCServer, RPCClient };

lib/client.d.ts

Lines changed: 161 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
1+
/// <reference types="node" />
2+
/// <reference types="node" />
3+
/// <reference types="node" />
4+
import EventEmitter from "events";
5+
import { Validator } from "./validator";
6+
import Queue from "./queue";
7+
import WebSocket from "ws";
8+
import { ExponentialStrategy } from "backoff";
9+
import EventBuffer from "./event-buffer";
10+
export interface RPC_ClientOptions {
11+
identity: string;
12+
reconnect: boolean;
13+
callTimeoutMs: number;
14+
pingIntervalMs: number;
15+
deferPingsOnActivity: boolean;
16+
respondWithDetailedErrors: boolean;
17+
callConcurrency: number;
18+
strictMode: boolean | string[];
19+
strictModeValidators: Validator[];
20+
maxBadMessages: number;
21+
protocols: string[];
22+
endpoint?: string;
23+
password: string | null;
24+
wsOpts: any;
25+
headers: any;
26+
maxReconnects: number;
27+
query?: string | Record<string, any>;
28+
backoff: {
29+
initialDelay: number;
30+
maxDelay: number;
31+
factor: number;
32+
randomisationFactor: number;
33+
};
34+
}
35+
declare class RPC_Client extends EventEmitter {
36+
_identity?: string;
37+
_wildcardHandler: Function | null;
38+
_handlers: Map<string, Function>;
39+
_state: number;
40+
_callQueue: Queue;
41+
_ws?: WebSocket;
42+
_wsAbortController?: AbortController;
43+
_keepAliveAbortController?: AbortController;
44+
_pendingPingResponse: boolean;
45+
_lastPingTime: number;
46+
_closePromise?: Promise<{
47+
code: number;
48+
reason: string;
49+
}>;
50+
_protocolOptions: string[];
51+
_protocol?: string;
52+
_strictProtocols: string[];
53+
_strictValidators?: Map<string, Validator>;
54+
_pendingCalls: Map<string, Record<string, any>>;
55+
_pendingResponses: Map<string, {
56+
abort: {
57+
(reason?: any): void;
58+
(reason?: any): void;
59+
};
60+
promise: Promise<any>;
61+
}>;
62+
_outboundMsgBuffer: string[];
63+
_connectedOnce: boolean;
64+
_backoffStrategy?: ExponentialStrategy;
65+
_badMessagesCount: number;
66+
_reconnectAttempt: number;
67+
_options: RPC_ClientOptions;
68+
_connectionUrl: string;
69+
_connectPromise: Promise<{
70+
response: any;
71+
}>;
72+
_nextPingTimeout: NodeJS.Timeout;
73+
static OPEN: number;
74+
static CONNECTING: number;
75+
static CLOSING: number;
76+
static CLOSED: number;
77+
constructor({ ...options }: RPC_ClientOptions);
78+
get identity(): string | undefined;
79+
get protocol(): string | undefined;
80+
get state(): number;
81+
reconfigure(options: RPC_ClientOptions): void;
82+
/**
83+
* Attempt to connect to the RPCServer.
84+
* @returns {Promise<undefined>} Resolves when connected, rejects on failure
85+
*/
86+
connect(): Promise<any>;
87+
_keepAlive(): Promise<void>;
88+
_tryReconnect(): Promise<void>;
89+
_beginConnect(): Promise<{
90+
response: any;
91+
}>;
92+
/**
93+
* Start consuming from a WebSocket
94+
* @param {WebSocket} ws - A WebSocket instance
95+
* @param {EventBuffer} leadMsgBuffer - A buffer which traps all 'message' events
96+
*/
97+
_attachWebsocket(ws: WebSocket, leadMsgBuffer?: EventBuffer): void;
98+
_handleDisconnect({ code, reason }: {
99+
code: number;
100+
reason: Buffer;
101+
}): void;
102+
_rejectPendingCalls(abortReason: string): void;
103+
/**
104+
* Call a method on a remote RPCClient or RPCServerClient.
105+
* @param {string} method - The RPC method to call.
106+
* @param {*} params - A value to be passed as params to the remote handler.
107+
* @param {Object} options - Call options
108+
* @param {number} options.callTimeoutMs - Call timeout (in milliseconds)
109+
* @param {AbortSignal} options.signal - AbortSignal to cancel the call.
110+
* @param {boolean} options.noReply - If set to true, the call will return immediately.
111+
* @returns Promise<*> - Response value from the remote handler.
112+
*/
113+
call(method: any, params?: any, options?: Record<string, any>): Promise<unknown>;
114+
_call(method: any, params: any, options?: Record<string, any>): Promise<any>;
115+
/**
116+
* Closes the RPCClient.
117+
* @param {Object} options - Close options
118+
* @param {number} options.code - The websocket CloseEvent code.
119+
* @param {string} options.reason - The websocket CloseEvent reason.
120+
* @param {boolean} options.awaitPending - Wait for in-flight calls & responses to complete before closing.
121+
* @param {boolean} options.force - Terminate websocket immediately without passing code, reason, or waiting.
122+
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent/code CloseEvent codes}
123+
* @returns Promise<Object> - The CloseEvent (code & reason) for closure. May be different from requested code & reason.
124+
*/
125+
close({ code, reason, awaitPending, force, }: {
126+
code?: number;
127+
reason?: string;
128+
awaitPending?: any;
129+
force?: any;
130+
}): Promise<{
131+
code: number | undefined;
132+
reason: string | undefined;
133+
} | undefined>;
134+
_awaitUntilPendingSettled(): Promise<PromiseSettledResult<any>[]>;
135+
_deferNextPing(): void;
136+
_onMessage(buffer: Buffer): void;
137+
_onCall(msgId: string, method: string, params: any): Promise<void>;
138+
_onCallResult(msgId: string, result: any): any;
139+
_onCallError(msgId: string, errorCode: string, errorDescription: string, errorDetails: Record<string, any>): void;
140+
/**
141+
* Send a message to the RPCServer. While socket is connecting, the message is queued and send when open.
142+
* @param {Buffer|String} message - String to send via websocket
143+
*/
144+
sendRaw(message: string): void;
145+
/**
146+
*
147+
* @param {string} [method] - The name of the handled method.
148+
*/
149+
removeHandler(method: string): void;
150+
removeAllHandlers(): void;
151+
/**
152+
*
153+
* @param {string} [method] - The name of the RPC method to handle.
154+
* @param {Function} handler - A function that can handle incoming calls for this method.
155+
*/
156+
handle(method: string | Function, handler?: ({ params, signal }: {
157+
params: any;
158+
signal: any;
159+
}) => void): void;
160+
}
161+
export default RPC_Client;

lib/errors.d.ts

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
export declare class TimeoutError extends Error {
2+
}
3+
export declare class UnexpectedHttpResponse extends Error {
4+
code: any;
5+
request: any;
6+
response: any;
7+
}
8+
export declare class RPCError extends Error {
9+
rpcErrorMessage: string;
10+
rpcErrorCode: string;
11+
}
12+
export declare class RPCGenericError extends RPCError {
13+
rpcErrorMessage: string;
14+
rpcErrorCode: string;
15+
}
16+
export declare class RPCNotImplementedError extends RPCError {
17+
rpcErrorMessage: string;
18+
rpcErrorCode: string;
19+
}
20+
export declare class RPCNotSupportedError extends RPCError {
21+
rpcErrorMessage: string;
22+
rpcErrorCode: string;
23+
}
24+
export declare class RPCInternalError extends RPCError {
25+
rpcErrorMessage: string;
26+
rpcErrorCode: string;
27+
}
28+
export declare class RPCProtocolError extends RPCError {
29+
rpcErrorMessage: string;
30+
rpcErrorCode: string;
31+
}
32+
export declare class RPCSecurityError extends RPCError {
33+
rpcErrorMessage: string;
34+
rpcErrorCode: string;
35+
}
36+
export declare class RPCFormatViolationError extends RPCError {
37+
rpcErrorMessage: string;
38+
rpcErrorCode: string;
39+
}
40+
export declare class RPCFormationViolationError extends RPCError {
41+
rpcErrorMessage: string;
42+
rpcErrorCode: string;
43+
}
44+
export declare class RPCPropertyConstraintViolationError extends RPCError {
45+
rpcErrorMessage: string;
46+
rpcErrorCode: string;
47+
}
48+
export declare class RPCOccurenceConstraintViolationError extends RPCError {
49+
rpcErrorMessage: string;
50+
rpcErrorCode: string;
51+
}
52+
export declare class RPCOccurrenceConstraintViolationError extends RPCError {
53+
rpcErrorMessage: string;
54+
rpcErrorCode: string;
55+
}
56+
export declare class RPCTypeConstraintViolationError extends RPCError {
57+
rpcErrorMessage: string;
58+
rpcErrorCode: string;
59+
}
60+
export declare class RPCMessageTypeNotSupportedError extends RPCError {
61+
rpcErrorMessage: string;
62+
rpcErrorCode: string;
63+
}
64+
export declare class RPCFrameworkError extends RPCError {
65+
rpcErrorMessage: string;
66+
rpcErrorCode: string;
67+
}
68+
export declare class WebsocketUpgradeError extends Error {
69+
code: any;
70+
constructor(code: any, message: string | undefined);
71+
}
72+
declare const _default: {
73+
WebsocketUpgradeError: typeof WebsocketUpgradeError;
74+
TimeoutError: typeof TimeoutError;
75+
UnexpectedHttpResponse: typeof UnexpectedHttpResponse;
76+
RPCError: typeof RPCError;
77+
RPCGenericError: typeof RPCGenericError;
78+
RPCNotImplementedError: typeof RPCNotImplementedError;
79+
RPCNotSupportedError: typeof RPCNotSupportedError;
80+
RPCInternalError: typeof RPCInternalError;
81+
RPCProtocolError: typeof RPCProtocolError;
82+
RPCSecurityError: typeof RPCSecurityError;
83+
RPCFormatViolationError: typeof RPCFormatViolationError;
84+
RPCFormationViolationError: typeof RPCFormationViolationError;
85+
RPCPropertyConstraintViolationError: typeof RPCPropertyConstraintViolationError;
86+
RPCOccurrenceConstraintViolationError: typeof RPCOccurrenceConstraintViolationError;
87+
RPCOccurenceConstraintViolationError: typeof RPCOccurenceConstraintViolationError;
88+
RPCTypeConstraintViolationError: typeof RPCTypeConstraintViolationError;
89+
RPCMessageTypeNotSupportedError: typeof RPCMessageTypeNotSupportedError;
90+
RPCFrameworkError: typeof RPCFrameworkError;
91+
};
92+
export default _default;

lib/event-buffer.d.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
/// <reference types="node" />
2+
/// <reference types="node" />
3+
import { EventEmitter } from "stream";
4+
declare class EventBuffer {
5+
_emitter: EventEmitter;
6+
_event: string | symbol;
7+
_collector: (...args: any) => void;
8+
_buffer: any;
9+
constructor(emitter: EventEmitter, event: string | symbol);
10+
condense(): any;
11+
}
12+
export default EventBuffer;

lib/queue.d.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
declare class Queue {
2+
_pending: number;
3+
_concurrency: number;
4+
_queue: any[];
5+
constructor();
6+
setConcurrency(concurrency: number): void;
7+
push(fn: any): Promise<unknown>;
8+
_next(): Promise<false | undefined>;
9+
}
10+
export default Queue;

lib/server.d.ts

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/// <reference types="node" />
2+
/// <reference types="node" />
3+
/// <reference types="node" />
4+
/// <reference types="node" />
5+
/// <reference types="node" />
6+
import { IncomingMessage, Server } from "http";
7+
import { ServerOptions, WebSocket, WebSocketServer } from "ws";
8+
import { EventEmitter } from "stream";
9+
import { Validator } from "./validator";
10+
import RpcServerClient, { IHandshakeInterface } from "./serverClient";
11+
import { Socket } from "net";
12+
interface IOccpServiceOptions {
13+
wssOptions?: ServerOptions;
14+
protocols?: string[];
15+
callTimeoutMs?: number;
16+
pingIntervalMs?: number;
17+
deferPingsOnActivity?: boolean;
18+
respondWithDetailedErrors?: boolean;
19+
callConcurrency?: number;
20+
maxBadMessages?: number;
21+
strictMode?: boolean | string[];
22+
strictModeValidators?: Validator[];
23+
}
24+
interface TPendingUpgrades {
25+
session: Record<string, any>;
26+
protocol: string;
27+
handshake: IHandshakeInterface;
28+
}
29+
declare class RPCServer extends EventEmitter {
30+
_httpServerAbortControllers: Set<AbortController>;
31+
_state: number;
32+
_clients: Set<RpcServerClient>;
33+
_pendingUpgrades: WeakMap<IncomingMessage, TPendingUpgrades>;
34+
_options: IOccpServiceOptions;
35+
_wss: WebSocketServer;
36+
_strictValidators: Map<string, Validator>;
37+
authCallback: (accept: (session?: Record<string, any>, protocol?: string | false) => void, reject: (code: number, message: string) => void, handshake: IHandshakeInterface, signal: AbortSignal) => void;
38+
constructor({ ...options }: IOccpServiceOptions, _callback?: () => void);
39+
reconfigure(options: any): void;
40+
_onConnection(websocket: WebSocket, request: IncomingMessage): Promise<void>;
41+
get handleUpgrade(): (request: IncomingMessage, socket: Socket, head: Buffer) => Promise<void>;
42+
auth(cb: (accept: (session?: Record<string, any>, protocol?: string | false) => void, reject: (code: number, message: string) => void, handshake: IHandshakeInterface, signal?: AbortSignal) => void): void;
43+
listen(port: any, host?: any, options?: Record<string, any>): Promise<Server<typeof IncomingMessage, typeof import("http").ServerResponse>>;
44+
close({ code, reason, awaitPending, force }: Record<string, any>): Promise<void>;
45+
}
46+
export default RPCServer;

lib/serverClient.d.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/// <reference types="node" />
2+
/// <reference types="node" />
3+
import WebSocket from "ws";
4+
import RPC_Client, { RPC_ClientOptions } from "./client";
5+
import { IncomingHttpHeaders, IncomingMessage } from "http";
6+
export interface IHandshakeInterface {
7+
remoteAddress: string | undefined;
8+
headers: IncomingHttpHeaders;
9+
protocols: Set<string>;
10+
endpoint: string;
11+
identity: string;
12+
query: URLSearchParams;
13+
request: IncomingMessage;
14+
password: Buffer | undefined;
15+
}
16+
declare class RpcServerClient extends RPC_Client {
17+
_session: Record<string, any>;
18+
_handshake: IHandshakeInterface;
19+
constructor({ ...options }: RPC_ClientOptions, { ws, handshake, session, }: {
20+
ws: WebSocket;
21+
session: Record<string, any>;
22+
handshake: IHandshakeInterface;
23+
});
24+
get handshake(): IHandshakeInterface;
25+
get session(): Record<string, any>;
26+
connect(): Promise<void>;
27+
}
28+
export default RpcServerClient;

lib/standard-validators.d.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
declare const _default: readonly [import("./validator").Validator, import("./validator").Validator];
2+
export default _default;

lib/symbols.d.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
export declare const NOREPLY: {
2+
NOREPLY: symbol;
3+
};
4+
export default NOREPLY;

lib/util.d.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
export declare function getPackageIdent(): string;
2+
export declare function getErrorPlainObject(err: Error): any;
3+
export declare function createRPCError(type: string, message?: any, details?: {}): Record<string, any>;
4+
declare const _default: {
5+
getErrorPlainObject: typeof getErrorPlainObject;
6+
createRPCError: typeof createRPCError;
7+
getPackageIdent: typeof getPackageIdent;
8+
};
9+
export default _default;

lib/validator.d.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import Ajv, { AnySchema, AsyncSchema, SchemaObject } from "ajv";
2+
export declare class Validator {
3+
_subprotocol: string;
4+
_ajv: Ajv;
5+
constructor(subprotocol: string, ajv: Ajv);
6+
get subprotocol(): string;
7+
validate(schemaId: string, params: any): boolean | Promise<unknown>;
8+
}
9+
export declare function createValidator(subprotocol: string, json: boolean | SchemaObject | AsyncSchema | AnySchema[]): Validator;

0 commit comments

Comments
 (0)