libshv-js 3.6.6 → 3.8.0

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "libshv-js",
3
- "version": "3.6.6",
3
+ "version": "3.8.0",
4
4
  "description": "Typescript implementation of libshv",
5
5
  "scripts": {
6
6
  "test": "echo \"Error: no test specified\" && exit 1",
package/src/rpcmessage.ts CHANGED
@@ -37,6 +37,7 @@ const ErrorMapZod = z.imap({
37
37
  export type ErrorMap = z.infer<typeof ErrorMapZod>;
38
38
 
39
39
  const RpcRequestMetaZod = z.metamap({
40
+ [RPC_MESSAGE_CALLER_IDS]: z.int().or(z.array(z.int())).optional(),
40
41
  [RPC_MESSAGE_REQUEST_ID]: z.number(),
41
42
  [RPC_MESSAGE_METHOD]: z.string(),
42
43
  [RPC_MESSAGE_SHV_PATH]: z.string(),
@@ -47,6 +48,7 @@ const RpcRequestValueZod = z.imap({
47
48
  });
48
49
 
49
50
  const RpcResponseMetaZod = z.metamap({
51
+ [RPC_MESSAGE_CALLER_IDS]: z.int().or(z.array(z.int())).optional(),
50
52
  [RPC_MESSAGE_REQUEST_ID]: z.number(),
51
53
  });
52
54
  const RpcResponseValueZod = z.imap({
@@ -69,6 +71,7 @@ const RpcSignalZod = z.withMeta(RpcSignalMetaZod, RpcSignalValueZod);
69
71
  const RpcMessageZod = z.union([RpcRequestZod, RpcResponseZod, RpcSignalZod]);
70
72
  export type RpcRequest = z.infer<typeof RpcRequestZod>;
71
73
  export type RpcResponse = z.infer<typeof RpcResponseZod>;
74
+ export type RpcResponseValue = z.infer<typeof RpcResponseValueZod>;
72
75
  export type RpcSignal = z.infer<typeof RpcSignalZod>;
73
76
  export type RpcMessage = z.infer<typeof RpcMessageZod>;
74
77
 
package/src/ws-client.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import {ChainPackReader, CHAINPACK_PROTOCOL_TYPE, ChainPackWriter, toChainPack} from './chainpack';
2
2
  import {type CponReader, CPON_PROTOCOL_TYPE, toCpon} from './cpon';
3
- import {ERROR_MESSAGE, ErrorCode, ERROR_CODE, RpcMessageZod, type RpcMessage, isSignal, isRequest, type RpcRequest, isResponse, ERROR_DATA, type ErrorMap, RPC_MESSAGE_METHOD, RPC_MESSAGE_SHV_PATH, RPC_MESSAGE_REQUEST_ID, RPC_MESSAGE_PARAMS, RPC_MESSAGE_ERROR, RPC_MESSAGE_RESULT} from './rpcmessage';
3
+ import {ERROR_MESSAGE, ErrorCode, ERROR_CODE, RpcMessageZod, type RpcMessage, isSignal, isRequest, type RpcRequest, isResponse, ERROR_DATA, type ErrorMap, RPC_MESSAGE_METHOD, RPC_MESSAGE_SHV_PATH, RPC_MESSAGE_REQUEST_ID, RPC_MESSAGE_PARAMS, RPC_MESSAGE_ERROR, RPC_MESSAGE_RESULT, RPC_MESSAGE_CALLER_IDS, RpcResponseValue} from './rpcmessage';
4
4
  import {type RpcValue, type Null, type Int, type IMap, type ShvMap, makeMap, makeIMap, RpcValueWithMetaData, makeMetaMap} from './rpcvalue';
5
5
 
6
6
  const DEFAULT_TIMEOUT = 5000;
@@ -58,7 +58,7 @@ type WsClientOptionsLogin = WsClientOptionsCommon & {
58
58
  onConnected: () => void;
59
59
  onConnectionFailure: (error: Error) => void;
60
60
  onDisconnected: () => void;
61
- onRequest: (rpc_msg: RpcRequest) => void;
61
+ onRequest: (shvPath: string, method: string, param?: RpcValue) => Promise<RpcValue>;
62
62
  };
63
63
 
64
64
  type WsClientOptionsWorkflows = WsClientOptionsCommon & {
@@ -95,7 +95,7 @@ type DirResult = Array<IMap<{
95
95
  }>>;
96
96
 
97
97
  class RpcError extends Error {
98
- constructor(private readonly err_info: ErrorMap) {
98
+ constructor(readonly err_info: ErrorMap) {
99
99
  super(err_info[ERROR_MESSAGE] ?? 'Unknown RpcError');
100
100
  }
101
101
 
@@ -104,18 +104,38 @@ class RpcError extends Error {
104
104
  }
105
105
  }
106
106
 
107
- class InvalidRequest extends RpcError {}
108
- class MethodNotFound extends RpcError {}
109
- class InvalidParams extends RpcError {}
110
- class InternalError extends RpcError {}
111
- class ParseError extends RpcError {}
112
- class MethodCallTimeout extends RpcError {}
113
- class MethodCallCancelled extends RpcError {}
114
- class MethodCallException extends RpcError {}
115
- class Unknown extends RpcError {}
116
- class LoginRequired extends RpcError {}
117
- class UserIDRequired extends RpcError {}
118
- class NotImplemented extends RpcError {}
107
+ const makeErrInfo = (errInfoOrMsg: ErrorMap | string, code: ErrorCode) => {
108
+ if (typeof errInfoOrMsg === 'object') {
109
+ return errInfoOrMsg;
110
+ }
111
+
112
+ return makeIMap({
113
+ [ERROR_CODE]: code,
114
+ [ERROR_MESSAGE]: errInfoOrMsg,
115
+ [ERROR_DATA]: undefined,
116
+ });
117
+ };
118
+
119
+ const createErrorClass = (code: ErrorCode) => class extends RpcError {
120
+ constructor(errInfoOrMsg: ErrorMap | string) {
121
+ super(makeErrInfo(errInfoOrMsg, code));
122
+ }
123
+ };
124
+
125
+ /* eslint-disable @typescript-eslint/naming-convention */
126
+ export const InvalidRequest = createErrorClass(ErrorCode.InvalidRequest);
127
+ export const MethodNotFound = createErrorClass(ErrorCode.MethodNotFound);
128
+ export const InvalidParams = createErrorClass(ErrorCode.InvalidParams);
129
+ export const InternalError = createErrorClass(ErrorCode.InternalError);
130
+ export const ParseError = createErrorClass(ErrorCode.ParseError);
131
+ export const MethodCallTimeout = createErrorClass(ErrorCode.MethodCallTimeout);
132
+ export const MethodCallCancelled = createErrorClass(ErrorCode.MethodCallCancelled);
133
+ export const MethodCallException = createErrorClass(ErrorCode.MethodCallException);
134
+ export const Unknown = createErrorClass(ErrorCode.Unknown);
135
+ export const LoginRequired = createErrorClass(ErrorCode.LoginRequired);
136
+ export const UserIDRequired = createErrorClass(ErrorCode.UserIDRequired);
137
+ export const NotImplemented = createErrorClass(ErrorCode.NotImplemented);
138
+ /* eslint-enable @typescript-eslint/naming-convention */
119
139
 
120
140
  class WsClient {
121
141
  private requestId = 1;
@@ -140,7 +160,7 @@ class WsClient {
140
160
  this.websocket = new WebSocket(options.wsUri);
141
161
  this.websocket.binaryType = 'arraybuffer';
142
162
 
143
- this.websocket.addEventListener('message', (evt: MessageEvent<ArrayBuffer>) => {
163
+ this.websocket.addEventListener('message', async (evt: MessageEvent<ArrayBuffer>) => {
144
164
  const rpcVal = dataToRpcValue(evt.data);
145
165
  const rpcMsg = RpcMessageZod.parse(rpcVal);
146
166
  this.logDebug(`message received: ${toCpon(rpcMsg)}`);
@@ -156,7 +176,37 @@ class WsClient {
156
176
  }
157
177
  } else if (isRequest(rpcMsg)) {
158
178
  if ('onRequest' in this.options) {
159
- this.options.onRequest(rpcMsg);
179
+ const respond = (value: RpcResponseValue) => {
180
+ this.sendRpcMessage(new RpcValueWithMetaData(
181
+ makeMetaMap({
182
+ [RPC_MESSAGE_CALLER_IDS]: rpcMsg.meta[RPC_MESSAGE_CALLER_IDS],
183
+ [RPC_MESSAGE_REQUEST_ID]: rpcMsg.meta[RPC_MESSAGE_REQUEST_ID],
184
+ }),
185
+ value,
186
+ ));
187
+ };
188
+
189
+ try {
190
+ respond(makeIMap({
191
+ [RPC_MESSAGE_RESULT]: await this.options.onRequest(rpcMsg.meta[RPC_MESSAGE_SHV_PATH], rpcMsg.meta[RPC_MESSAGE_METHOD], rpcMsg.value[RPC_MESSAGE_PARAMS]),
192
+ }));
193
+ } catch (error: unknown) {
194
+ const sendError = (error: RpcError) => {
195
+ respond(error.err_info);
196
+ };
197
+
198
+ switch (true) {
199
+ case error instanceof RpcError:
200
+ sendError(error);
201
+ break;
202
+ case error instanceof Error:
203
+ sendError(new InternalError(error.message));
204
+ break;
205
+ default:
206
+ sendError(new InternalError('Unknown error'));
207
+ break;
208
+ }
209
+ }
160
210
  }
161
211
  } else if (isResponse(rpcMsg)) {
162
212
  const requestId = rpcMsg.meta[RPC_MESSAGE_REQUEST_ID];
@@ -221,6 +271,7 @@ class WsClient {
221
271
  callRpcMethod(shvPath: string | undefined, method: string, params?: RpcValue): Promise<ResultOrError> {
222
272
  const rqId = this.requestId++;
223
273
  const rq: RpcRequest = new RpcValueWithMetaData(makeMetaMap({
274
+ [RPC_MESSAGE_CALLER_IDS]: undefined,
224
275
  [RPC_MESSAGE_REQUEST_ID]: rqId,
225
276
  [RPC_MESSAGE_METHOD]: method ?? '',
226
277
  [RPC_MESSAGE_SHV_PATH]: shvPath ?? '',