Skip to content

Commit 527eefb

Browse files
author
Alex Cheng
committed
feat: add Typescript types (WIP)
1 parent cfd0530 commit 527eefb

File tree

2 files changed

+162
-0
lines changed

2 files changed

+162
-0
lines changed

index.d.ts

Lines changed: 161 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
1+
2+
import Ajv, { ValidateFunction } from 'ajv';
3+
import { WebSocket } from 'ws';
4+
import { ExponentialStrategy } from 'backoff';
5+
import { EventEmitter } from 'events';
6+
import { URLSearchParams } from 'url';
7+
import { IncomingMessage, IncomingHttpHeaders, OutgoingHttpHeaders } from 'http';
8+
import { Duplex } from 'stream';
9+
import errors from './lib/errors';
10+
import symbols from './lib/symbols';
11+
declare module 'ocpp-rpc' {
12+
13+
type OCPPProtocols = 'ocpp2.0.1' | 'ocpp1.6';
14+
enum CONNECTION_STATE {
15+
CONNECTING = 0,
16+
OPEN = 1,
17+
CLOSING = 2,
18+
CLOSED = 3,
19+
}
20+
21+
// ref './lib/validator.js'
22+
class Validator {
23+
constructor(subprotocol: string, ajv: Ajv);
24+
get subprotocol(): string;
25+
validate(schemaId: string, params: unknown): ValidateFunction;
26+
}
27+
28+
29+
type RPCClientConstructorOptions = {
30+
// The RPC server's endpoint (a websocket URL). Required.
31+
endpoint: string,
32+
// The RPC client's identity. Will be automatically encoded. Required.
33+
identity: string,
34+
// Array of subprotocols supported by this server. Can be overridden in an auth callback. Defaults to [].
35+
protocols?: Array<OCPPProtocols>,
36+
// Optional password to use in HTTP Basic auth. (The username will always be the identity).
37+
password?: string,
38+
// Additional HTTP headers to send along with the websocket upgrade request. Defaults to {}.
39+
headers: OutgoingHttpHeaders,
40+
// An optional query string or object to append as the query string of the connection URL. Defaults to ''.
41+
query: Record<string, unknown> | string,
42+
// Milliseconds to wait before unanswered outbound calls are rejected automatically. Defaults to 60000.
43+
callTimeoutMs?: number,
44+
// Milliseconds between WebSocket pings to connected clients. Defaults to 30000.
45+
pingIntervalMs?: number,
46+
// Enable strict validation of calls & responses. Defaults to false. (See Strict Validation to understand how this works.)
47+
strictMode?: boolean,
48+
// Optional additional validators to be used in conjunction with strictMode. (See Strict Validation to understand how this works.)
49+
strictModeValidators?: Array<Validator>,
50+
// Specifies whether to send detailed errors (including stack trace) to remote party upon an error being thrown by a handler. Defaults to false.
51+
respondWithDetailedErrors?: boolean,
52+
// The number of concurrent in-flight outbound calls permitted at any one time. Additional calls are queued. (There is no limit on inbound calls.) Defaults to 1.
53+
callConcurrency?: number,
54+
// If true, the client will attempt to reconnect after losing connection to the
55+
reconnect: boolean,
56+
// If reconnect is true, specifies the number of times to try reconnecting before failing and emitting a close event. Defaults to Infinity.
57+
maxReconnects: number,
58+
// If reconnect is true, specifies the options for an ExponentialStrategy backoff strategy, used for reconnects.
59+
backoff: ConstructorParameters<typeof ExponentialStrategy>,
60+
// he maximum number of non-conforming RPC messages which can be tolerated by the server before the client is automatically closed. Defaults to Infinity.
61+
maxBadMessages?: number,
62+
// Additional WebSocketServer options.
63+
wssOptions?: ConstructorParameters<typeof WebSocket.WebSocketServer>,
64+
}
65+
type ConnectResponse = { response?: IncomingMessage }
66+
67+
export class RPCServerClient extends EventEmitter {
68+
get identity(): string;
69+
get protocol(): OCPPProtocols;
70+
get state(): CONNECTION_STATE;
71+
reconfigure(options: RPCClientConstructorOptions): void;
72+
connect: () => Promise<ConnectResponse | ConnectResponse<ConnectResponse> | undefined>;
73+
close: (options?: {
74+
// The WebSocket close code. Defaults to 1000
75+
code?: Number,
76+
// The reason for closure. Defaults to ''.
77+
reason?: string,
78+
// If true, the connection won't be fully closed until any outstanding in-flight (inbound & outbound) calls are responded to. Additional calls will be rejected in the meantime. Defaults to false.
79+
awaitPending?: boolean,
80+
// If true, terminates the WebSocket connection instantly and uncleanly. Defaults to false.
81+
force?: boolean
82+
}) => Promise<Record<string, unknown>>;
83+
// WIP
84+
sendRaw: (message: Array | Number | Object | String | ArrayBuffer | Buffer | DataView) => void; // TypedArray?
85+
handle(method?: string, handler: Function): void;
86+
call(method: string, params: any, options?: {
87+
callTimeoutMs: number;
88+
signal: AbortSignal;
89+
noReply: boolean;
90+
}): Promise<any>;
91+
}
92+
93+
94+
type RPCServerConstructorOptions = {
95+
// Array of subprotocols supported by this server. Can be overridden in an auth callback. Defaults to [].
96+
protocols?: Array<OCPPProtocols>,
97+
// Milliseconds to wait before unanswered outbound calls are rejected automatically. Defaults to 60000.
98+
callTimeoutMs?: number,
99+
// Milliseconds between WebSocket pings to connected clients. Defaults to 30000.
100+
pingIntervalMs?: number,
101+
// Specifies whether to send detailed errors (including stack trace) to remote party upon an error being thrown by a handler. Defaults to false.
102+
respondWithDetailedErrors?: boolean,
103+
// The number of concurrent in-flight outbound calls permitted at any one time. Additional calls are queued. (There is no limit on inbound calls.) Defaults to 1.
104+
callConcurrency?: number,
105+
// Enable strict validation of calls & responses. Defaults to false. (See Strict Validation to understand how this works.)
106+
strictMode?: boolean,
107+
// Optional additional validators to be used in conjunction with strictMode. (See Strict Validation to understand how this works.)
108+
strictModeValidators?: Array<Validator>,
109+
// he maximum number of non-conforming RPC messages which can be tolerated by the server before the client is automatically closed. Defaults to Infinity.
110+
maxBadMessages?: number,
111+
// Additional WebSocketServer options.
112+
wssOptions?: ConstructorParameters<typeof WebSocket.Server>,
113+
}
114+
115+
type accept = (session?: unknown, protocol?: OCPPProtocols) => void;
116+
type reject = (code: number, message: string) => void;
117+
type handshake = {
118+
// A set of subprotocols purportedly supported by the client.
119+
protocols: Set<OCPPProtocols>,
120+
// The identity portion of the connection URL, decoded.
121+
identity: string,
122+
// If HTTP Basic auth was used in the connection, and the username correctly matches the identity, this field will contain the password (otherwise undefined). Read Security Profile 1 for more details of how this works.
123+
password: string,
124+
// The endpoint path portion of the connection URL. This is the part of the path before the identity.
125+
endpoint: string,
126+
// The query string parsed as URLSearchParams.
127+
query: URLSearchParams,
128+
// The remote IP address of the socket.
129+
remoteAddress: string,
130+
// The HTTP headers sent in the upgrade request.
131+
headers: IncomingHttpHeaders,
132+
// The full HTTP request received by the underlying webserver.
133+
request: IncomingMessage,
134+
};
135+
type authCb = (accept: accept, reject: reject, handshake: handshake) => void;
136+
137+
type clientHandler = (client: RPCServerClient) => void;
138+
type clientEvent = (event: 'client', handler: clientHandler) => void;
139+
140+
export class RPCServer extends EventEmitter {
141+
constructor(options?: RPCServerConstructorOptions)
142+
auth: (cb: authCb) => void;
143+
handleUpgrade(): (request: IncomingMessage, socket: Duplex, head: Buffer) => void
144+
reconfigure: (options: RPCServerConstructorOptions) => void
145+
close(options?: {
146+
//The WebSocket close code to pass to all connected clients. Defaults to 1000.
147+
code?: Number,
148+
//The reason for closure to pass to all connected clients. Defaults to ''.
149+
reason?: string,
150+
//If true, each connected client won't be fully closed until any outstanding in-flight (inbound & outbound) calls are responded to. Additional calls will be rejected in the meantime. Defaults to false.
151+
awaitPending?: boolean,
152+
//If true, terminates all client WebSocket connections instantly and uncleanly. Defaults to false.)
153+
force?: boolean
154+
}): void;
155+
}
156+
157+
export const createRPCError: (type: string, message?: string, details?: Record<string, unknown>) => Error;
158+
export const createValidator: (subprotocol: any, json: any) => Validator;
159+
export { symbols }
160+
export { errors }
161+
}

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
"version": "1.5.1",
44
"description": "A client & server implementation of the WAMP-like RPC-over-websocket system defined in the OCPP protcols (e.g. OCPP1.6-J and OCPP2.0.1).",
55
"main": "index.js",
6+
"types": "index.d.ts",
67
"scripts": {
78
"test": "mocha",
89
"coverage": "nyc --reporter=lcov --reporter=text mocha"

0 commit comments

Comments
 (0)