index.d.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  1. /*!
  2. * TSRPC Base Client v2.1.15
  3. * -----------------------------------------
  4. * Copyright (c) Kingworks Corporation.
  5. * MIT License
  6. * https://github.com/k8w/tsrpc-base-client
  7. */
  8. import { ApiReturn } from 'tsrpc-proto';
  9. import { ApiServiceDef } from 'tsrpc-proto';
  10. import { BaseServiceType } from 'tsrpc-proto';
  11. import { CustomTypeSchema } from 'tsbuffer-schema';
  12. import { Logger } from 'tsrpc-proto';
  13. import { LogLevel } from 'tsrpc-proto';
  14. import { MsgServiceDef } from 'tsrpc-proto';
  15. import { ServiceProto } from 'tsrpc-proto';
  16. import { TSBuffer } from 'tsbuffer';
  17. import { TsrpcError } from 'tsrpc-proto';
  18. export declare type ApiReturnFlowData<ServiceType extends BaseServiceType> = {
  19. [K in keyof ServiceType['api']]: {
  20. apiName: K & string;
  21. req: ServiceType['api'][K]['req'];
  22. options?: TransportOptions;
  23. return: ApiReturn<ServiceType['api'][K]['res']>;
  24. };
  25. }[keyof ServiceType['api']];
  26. export declare interface ApiService extends ApiServiceDef {
  27. reqSchemaId: string;
  28. resSchemaId: string;
  29. }
  30. /**
  31. * An abstract base class for TSRPC Client,
  32. * which includes some common buffer process flows.
  33. *
  34. * @remarks
  35. * You can implement a client on a specific transportation protocol (like HTTP, WebSocket, QUIP) by extend this.
  36. *
  37. * @typeParam ServiceType - `ServiceType` from generated `proto.ts`
  38. *
  39. * @see
  40. * {@link https://github.com/k8w/tsrpc}
  41. * {@link https://github.com/k8w/tsrpc-browser}
  42. * {@link https://github.com/k8w/tsrpc-miniapp}
  43. */
  44. export declare abstract class BaseClient<ServiceType extends BaseServiceType> {
  45. /** The connection is long connection or short connection */
  46. abstract readonly type: 'SHORT' | 'LONG';
  47. readonly dataType: 'json' | 'text' | 'buffer';
  48. readonly options: Readonly<BaseClientOptions>;
  49. /** The map of all services */
  50. readonly serviceMap: ServiceMap;
  51. /** The `TSBuffer` instance for encoding, decoding, and type checking */
  52. readonly tsbuffer: TSBuffer;
  53. /**
  54. * `Logger` to process API Request/Response, send message, send buffer...
  55. * @defaultValue `console`
  56. */
  57. readonly logger?: Logger;
  58. protected _msgHandlers: MsgHandlerManager;
  59. /**
  60. * {@link Flow} to process `callApi`, `sendMsg`, buffer input/output, etc...
  61. */
  62. readonly flows: {
  63. readonly preCallApiFlow: Flow<CallApiFlowData<ServiceType>>;
  64. readonly preApiReturnFlow: Flow<ApiReturnFlowData<ServiceType>>;
  65. readonly postApiReturnFlow: Flow<ApiReturnFlowData<ServiceType>>;
  66. readonly preSendMsgFlow: Flow<SendMsgFlowData<ServiceType>>;
  67. readonly postSendMsgFlow: Flow<SendMsgFlowData<ServiceType>>;
  68. readonly preRecvMsgFlow: Flow<RecvMsgFlowData<ServiceType>>;
  69. readonly postRecvMsgFlow: Flow<RecvMsgFlowData<ServiceType>>;
  70. readonly preSendDataFlow: Flow<{
  71. data: Uint8Array | string | object;
  72. sn?: number | undefined;
  73. }>;
  74. readonly preRecvDataFlow: Flow<{
  75. data: Uint8Array | string | object;
  76. sn?: number | undefined;
  77. }>;
  78. /**
  79. * @deprecated Please use `preSendDataFlow` instead
  80. */
  81. readonly preSendBufferFlow: Flow<{
  82. buf: Uint8Array;
  83. sn?: number | undefined;
  84. }>;
  85. /**
  86. * @deprecated Please use `preRecvDataFlow` instead
  87. */
  88. readonly preRecvBufferFlow: Flow<{
  89. buf: Uint8Array;
  90. sn?: number | undefined;
  91. }>;
  92. /** Before connect to WebSocket server */
  93. readonly preConnectFlow: Flow<{
  94. /** Return `res` to `client.connect()`, without latter connect procedure */
  95. return?: {
  96. isSucc: true;
  97. errMsg?: undefined;
  98. } | {
  99. isSucc: false;
  100. errMsg: string;
  101. } | undefined;
  102. }>;
  103. /** After WebSocket connect successfully */
  104. readonly postConnectFlow: Flow<{}>;
  105. /** After WebSocket disconnected (from connected status) */
  106. readonly postDisconnectFlow: Flow<{
  107. /** reason parameter from server-side `conn.close(reason)` */
  108. reason?: string | undefined;
  109. /**
  110. * Whether is is disconnected manually by `client.disconnect()`,
  111. * otherwise by accident. (e.g. network error, server closed...)
  112. */
  113. isManual?: boolean | undefined;
  114. }>;
  115. };
  116. protected _apiSnCounter: Counter;
  117. /**
  118. * The `SN` number of the last `callApi()`,
  119. * which can be passed to `abort()` to abort an API request.
  120. * @example
  121. * ```ts
  122. * client.callApi('xxx', { value: 'xxx' })
  123. * .then(ret=>{ console.log('succ', ret) });
  124. * let lastSN = client.lastSN;
  125. * client.abort(lastSN);
  126. * ```
  127. */
  128. get lastSN(): number;
  129. /**
  130. * The `SN` number of the next `callApi()`,
  131. * which can be passed to `abort()` to abort an API request.
  132. * @example
  133. * ```ts
  134. * let nextSN = client.nextSN;
  135. * client.callApi('xxx', { value: 'xxx' })
  136. * ```
  137. */
  138. get nextSN(): number;
  139. /**
  140. * Pending API Requests
  141. */
  142. protected _pendingApis: PendingApiItem[];
  143. constructor(proto: ServiceProto<ServiceType>, options: BaseClientOptions);
  144. /**
  145. * Send request and wait for the return
  146. * @param apiName
  147. * @param req - Request body
  148. * @param options - Transport options
  149. * @returns return a `ApiReturn`, all error (network error, business error, code exception...) is unified as `TsrpcError`.
  150. * The promise is never rejected, so you just need to process all error in one place.
  151. */
  152. callApi<T extends string & keyof ServiceType['api']>(apiName: T, req: ServiceType['api'][T]['req'], options?: TransportOptions): Promise<ApiReturn<ServiceType['api'][T]['res']>>;
  153. protected _doCallApi<T extends string & keyof ServiceType['api']>(apiName: T, req: ServiceType['api'][T]['req'], options: TransportOptions | undefined, pendingItem: PendingApiItem): Promise<ApiReturn<ServiceType['api'][T]['res']>>;
  154. /**
  155. * Send message, without response, not ensuring the server is received and processed correctly.
  156. * @param msgName
  157. * @param msg - Message body
  158. * @param options - Transport options
  159. * @returns If the promise is resolved, it means the request is sent to system kernel successfully.
  160. * Notice that not means the server received and processed the message correctly.
  161. */
  162. sendMsg<T extends string & keyof ServiceType['msg']>(msgName: T, msg: ServiceType['msg'][T], options?: TransportOptions): Promise<{
  163. isSucc: true;
  164. } | {
  165. isSucc: false;
  166. err: TsrpcError;
  167. }>;
  168. /**
  169. * Add a message handler,
  170. * duplicate handlers to the same `msgName` would be ignored.
  171. * @param msgName
  172. * @param handler
  173. * @returns
  174. */
  175. listenMsg<T extends keyof ServiceType['msg']>(msgName: T | RegExp, handler: ClientMsgHandler<ServiceType, T>): ClientMsgHandler<ServiceType, T>;
  176. /**
  177. * Remove a message handler
  178. */
  179. unlistenMsg<T extends keyof ServiceType['msg']>(msgName: T | RegExp, handler: Function): void;
  180. /**
  181. * Remove all handlers from a message
  182. */
  183. unlistenMsgAll<T extends keyof ServiceType['msg']>(msgName: T | RegExp): void;
  184. /**
  185. * Abort a pending API request, it makes the promise returned by `callApi()` neither resolved nor rejected forever.
  186. * @param sn - Every api request has a unique `sn` number, you can get it by `this.lastSN`
  187. */
  188. abort(sn: number): void;
  189. /**
  190. * Abort all API requests that has the `abortKey`.
  191. * It makes the promise returned by `callApi` neither resolved nor rejected forever.
  192. * @param abortKey - The `abortKey` of options when `callApi()`, see {@link TransportOptions.abortKey}.
  193. * @example
  194. * ```ts
  195. * // Send API request many times
  196. * client.callApi('SendData', { data: 'AAA' }, { abortKey: 'Session#123' });
  197. * client.callApi('SendData', { data: 'BBB' }, { abortKey: 'Session#123' });
  198. * client.callApi('SendData', { data: 'CCC' }, { abortKey: 'Session#123' });
  199. *
  200. * // And abort the at once
  201. * client.abortByKey('Session#123');
  202. * ```
  203. */
  204. abortByKey(abortKey: string): void;
  205. /**
  206. * Abort all pending API requests.
  207. * It makes the promise returned by `callApi` neither resolved nor rejected forever.
  208. */
  209. abortAll(): void;
  210. /**
  211. * Send data (binary or text)
  212. * @remarks
  213. * Long connection: wait res by listenning `conn.onmessage`
  214. * Short connection: wait res by waitting response
  215. * @param data
  216. * @param options
  217. * @param sn
  218. */
  219. sendData(data: Uint8Array | string | object, options: TransportOptions, serviceId: number, pendingApiItem?: PendingApiItem): Promise<{
  220. err?: TsrpcError;
  221. }>;
  222. protected abstract _sendData(data: Uint8Array | string | object, options: TransportOptions, serviceId: number, pendingApiItem?: PendingApiItem): Promise<{
  223. err?: TsrpcError;
  224. }>;
  225. protected _onRecvData(data: Uint8Array | string | object, pendingApiItem?: PendingApiItem): Promise<void>;
  226. /** @deprecated Please use `_onRecvData` instead */
  227. protected _onRecvBuf: (buf: Uint8Array, pendingApiItem?: PendingApiItem) => Promise<void>;
  228. /**
  229. * @param sn
  230. * @param timeout
  231. * @returns `undefined` 代表 canceled
  232. */
  233. protected _waitApiReturn(pendingItem: PendingApiItem, timeout?: number): Promise<ApiReturn<any>>;
  234. }
  235. export declare interface BaseClientOptions {
  236. /**
  237. * `Logger` to process API Request/Response, send message, send buffer...
  238. * If it is assigned to `undefined`, all log would be hidden. (It may be useful when you want to encrypt the transportation)
  239. * @defaultValue `console`
  240. */
  241. logger?: Logger;
  242. /**
  243. * The minimum log level of `logger`
  244. * @defaultValue `debug`
  245. */
  246. logLevel: LogLevel;
  247. /**
  248. * Whether to log [ApiReq] and [ApiRes] by the `logger`.
  249. * NOTICE: if `logger` is `undefined`, no log would be printed.
  250. * @defaultValue `true`
  251. */
  252. logApi: boolean;
  253. /**
  254. * Whether to log [SendMsg] and [RecvMsg] by the `logger`.
  255. * NOTICE: if `logger` is `undefined`, no log would be printed.
  256. * @defaultValue `true`
  257. */
  258. logMsg: boolean;
  259. /**
  260. * Use JSON instead of binary as transfering format.
  261. * JSON transportation also support ArrayBuffer / Date / ObjectId.
  262. * @defaultValue `false`
  263. */
  264. json: boolean;
  265. /**
  266. * Timeout time for `callApi` (ms)
  267. * `undefined` or `0` means unlimited
  268. * @defaultValue `15000`
  269. */
  270. timeout: number;
  271. /**
  272. * If `true`, all sent and received raw buffer would be print into the log.
  273. * It may be useful when you do something for buffer encryption/decryption, and want to debug them.
  274. * @defaultValue `false`
  275. */
  276. debugBuf: boolean;
  277. /**
  278. * 自定义 mongodb/ObjectId 的反序列化类型
  279. * 传入 `String`,则会反序列化为字符串
  280. * 传入 `ObjectId`, 则会反序列化为 `ObjectId` 实例
  281. * 若为 `false`,则不会自动对 ObjectId 进行额外处理
  282. * 将会针对 'mongodb/ObjectId' 'bson/ObjectId' 进行处理
  283. */
  284. customObjectIdClass?: {
  285. new (id?: any): any;
  286. } | false;
  287. }
  288. /**
  289. * Base HTTP Client
  290. */
  291. export declare class BaseHttpClient<ServiceType extends BaseServiceType> extends BaseClient<ServiceType> {
  292. readonly type = "SHORT";
  293. private _http;
  294. private _jsonServer;
  295. readonly options: Readonly<BaseHttpClientOptions>;
  296. constructor(proto: ServiceProto<ServiceType>, http: IHttpProxy, options?: Partial<BaseHttpClientOptions>);
  297. protected _sendData(data: Uint8Array | string, options: TransportOptions, serviceId: number, pendingApiItem?: PendingApiItem): Promise<{
  298. err?: TsrpcError | undefined;
  299. }>;
  300. }
  301. export declare interface BaseHttpClientOptions extends BaseClientOptions {
  302. /** Server URL, starts with `http://` or `https://`. */
  303. server: string;
  304. /**
  305. * Whether to automatically delete excess properties that not defined in the protocol.
  306. * @defaultValue `true`
  307. */
  308. jsonPrune: boolean;
  309. }
  310. /**
  311. * WebSocket Client for TSRPC.
  312. * It uses native `WebSocket` of browser.
  313. * @typeParam ServiceType - `ServiceType` from generated `proto.ts`
  314. */
  315. export declare class BaseWsClient<ServiceType extends BaseServiceType> extends BaseClient<ServiceType> {
  316. readonly type = "LONG";
  317. protected _wsp: IWebSocketProxy;
  318. readonly options: Readonly<BaseWsClientOptions>;
  319. constructor(proto: ServiceProto<ServiceType>, wsp: IWebSocketProxy, options?: Partial<BaseWsClientOptions>);
  320. protected _onWsOpen: () => void;
  321. protected _onWsClose: (code: number, reason: string) => void;
  322. protected _onWsError: (e: unknown) => void;
  323. protected _onWsMessage: (data: Uint8Array | string) => void;
  324. protected _sendData(data: string | Uint8Array): Promise<{
  325. err?: TsrpcError;
  326. }>;
  327. /**
  328. * Last latency time (ms) of heartbeat test
  329. */
  330. lastHeartbeatLatency: number;
  331. private _pendingHeartbeat?;
  332. private _nextHeartbeatTimer?;
  333. /**
  334. * Send a heartbeat packet
  335. */
  336. private _heartbeat;
  337. private _onHeartbeatAnswer;
  338. private _status;
  339. get status(): WsClientStatus;
  340. get isConnected(): boolean;
  341. private _connecting?;
  342. /**
  343. * Start connecting, you must connect first before `callApi()` and `sendMsg()`.
  344. * @throws never
  345. */
  346. connect(): Promise<{
  347. isSucc: true;
  348. errMsg?: undefined;
  349. } | {
  350. isSucc: false;
  351. errMsg: string;
  352. }>;
  353. private _rsDisconnecting?;
  354. /**
  355. * Disconnect immediately
  356. * @throws never
  357. */
  358. disconnect(code?: number, reason?: string): Promise<void>;
  359. private _wsClose;
  360. }
  361. export declare interface BaseWsClientOptions extends BaseClientOptions {
  362. /** Server URL, starts with `ws://` or `wss://`. */
  363. server: string;
  364. /**
  365. * Heartbeat test
  366. * `undefined` represent disable heartbeat test
  367. * @defaultValue `undefined`
  368. */
  369. heartbeat?: {
  370. /** Interval time between 2 heartbeat packet (unit: ms) */
  371. interval: number;
  372. /** If a heartbeat packet not got reply during this time, the connection would be closed (unit: ms) */
  373. timeout: number;
  374. };
  375. }
  376. export declare type CallApiFlowData<ServiceType extends BaseServiceType> = {
  377. [K in keyof ServiceType['api']]: {
  378. apiName: K & string;
  379. req: ServiceType['api'][K]['req'];
  380. options?: TransportOptions;
  381. return?: ApiReturn<ServiceType['api'][K]['res']>;
  382. };
  383. }[keyof ServiceType['api']];
  384. export declare type ClientMsgHandler<ServiceType extends BaseServiceType, MsgName extends keyof ServiceType['msg']> = (msg: ServiceType['msg'][MsgName], msgName: MsgName) => void | Promise<void>;
  385. /**
  386. * An auto-increment counter
  387. */
  388. export declare class Counter {
  389. private _min;
  390. private _max;
  391. private _last;
  392. constructor(min?: number, max?: number);
  393. /**
  394. * Reset the counter, makes `getNext()` restart from `0`
  395. */
  396. reset(): void;
  397. /**
  398. * Get next counter value, and auto increment `1`
  399. * @param notInc - Just get the next possible value, not actually increasing the sequence
  400. */
  401. getNext(notInc?: boolean): number;
  402. /**
  403. * Last return of `getNext()`
  404. */
  405. get last(): number;
  406. }
  407. export declare const defaultBaseClientOptions: BaseClientOptions;
  408. export declare const defaultBaseHttpClientOptions: BaseHttpClientOptions;
  409. export declare const defaultBaseWsClientOptions: BaseWsClientOptions;
  410. export declare type EncodeOutput<T> = {
  411. isSucc: true;
  412. /** Encoded binary buffer */
  413. output: T;
  414. errMsg?: undefined;
  415. } | {
  416. isSucc: false;
  417. /** Error message */
  418. errMsg: string;
  419. output?: undefined;
  420. };
  421. /**
  422. * A `Flow` is consists of many `FlowNode`, which is function with the same input and output (like pipeline).
  423. *
  424. * @remarks
  425. * `Flow` is like a hook or event, executed at a specific time.
  426. * The difference to event is it can be used to **interrupt** an action, by return `undefined` or `null` in a node.
  427. */
  428. export declare class Flow<T> {
  429. /**
  430. * All node functions, if you want to adjust the sort you can modify this.
  431. */
  432. nodes: FlowNode<T>[];
  433. /**
  434. * Event when error throwed from a `FlowNode` function.
  435. * By default, it does nothing except print a `Uncaught FlowError` error log.
  436. * @param e
  437. * @param last
  438. * @param input
  439. * @param logger
  440. */
  441. onError: (e: Error | TsrpcError, last: T, input: T, logger: Logger | undefined) => void;
  442. /**
  443. * Execute all node function one by one, the previous output is the next input,
  444. * until the last output would be return to the caller.
  445. *
  446. * @remarks
  447. * If any node function return `null | undefined`, or throws an error,
  448. * the latter node functions would not be executed.
  449. * And it would return `null | undefined` immediately to the caller,
  450. * which tell the caller it means a interruption,
  451. * to let the caller stop latter behaviours.
  452. *
  453. * @param input The input of the first `FlowNode`
  454. * @param logger Logger to print log, `undefined` means to hide all log.
  455. * @returns
  456. */
  457. exec(input: T, logger: Logger | undefined): Promise<FlowNodeReturn<T>>;
  458. /**
  459. * Append a node function to the last
  460. * @param node
  461. * @returns
  462. */
  463. push<K extends T>(node: FlowNode<K>): FlowNode<K>;
  464. /**
  465. * Remove a node function
  466. * @param node
  467. * @returns
  468. */
  469. remove<K extends T>(node: FlowNode<K>): FlowNode<T>[];
  470. }
  471. export declare type FlowData<T extends Flow<any>> = T extends Flow<infer R> ? R : unknown;
  472. export declare type FlowNode<T> = (item: T) => FlowNodeReturn<T> | Promise<FlowNodeReturn<T>>;
  473. /**
  474. * @returns
  475. * `T` represents succ & continue,
  476. * `null | undefined` represents interrupt.
  477. * If error is throwed, `Flow.onError` would be called.
  478. */
  479. export declare type FlowNodeReturn<T> = T | null | undefined;
  480. export declare function getCustomObjectIdTypes(classObjectId: {
  481. new (id?: any): any;
  482. }): {
  483. [schemaId: string]: CustomTypeSchema;
  484. };
  485. export declare interface IHttpProxy {
  486. fetch(options: {
  487. url: string;
  488. data: string | Uint8Array;
  489. method: string;
  490. /** ms */
  491. timeout?: number;
  492. headers?: {
  493. [key: string]: string;
  494. };
  495. transportOptions: TransportOptions;
  496. responseType: 'text' | 'arraybuffer';
  497. }): {
  498. abort: () => void;
  499. promise: Promise<{
  500. isSucc: true;
  501. res: string | Uint8Array;
  502. } | {
  503. isSucc: false;
  504. err: TsrpcError;
  505. }>;
  506. };
  507. }
  508. export declare interface IWebSocketProxy {
  509. options: {
  510. onOpen: () => void;
  511. onClose: (code: number, reason: string) => void;
  512. onError: (e: unknown) => void;
  513. onMessage: (data: Uint8Array | string) => void;
  514. logger?: Logger;
  515. };
  516. connect(server: string, protocols?: string[]): void;
  517. close(code?: number, reason?: string): void;
  518. send(data: Uint8Array | string): Promise<{
  519. err?: TsrpcError;
  520. }>;
  521. }
  522. /**
  523. * A manager for TSRPC receiving messages
  524. */
  525. export declare class MsgHandlerManager {
  526. private _handlers;
  527. /**
  528. * Execute all handlers parallelly
  529. * @returns handlers count
  530. */
  531. forEachHandler(msgName: string, logger: Logger | undefined, ...args: any[]): (any | Promise<any>)[];
  532. /**
  533. * Add message handler, duplicate handlers to the same `msgName` would be ignored.
  534. * @param msgName
  535. * @param handler
  536. * @returns
  537. */
  538. addHandler(msgName: string, handler: Function): void;
  539. /**
  540. * Remove handler from the specific `msgName`
  541. * @param msgName
  542. * @param handler
  543. * @returns
  544. */
  545. removeHandler(msgName: string, handler: Function): void;
  546. /**
  547. * Remove all handlers for the specific `msgName`
  548. * @param msgName
  549. */
  550. removeAllHandlers(msgName: string): void;
  551. }
  552. export declare interface MsgService extends MsgServiceDef {
  553. msgSchemaId: string;
  554. }
  555. export declare type ParsedServerInput = {
  556. type: 'api';
  557. service: ApiService;
  558. req: any;
  559. sn?: number;
  560. } | {
  561. type: 'msg';
  562. service: MsgService;
  563. msg: any;
  564. };
  565. export declare type ParsedServerOutput = {
  566. type: 'api';
  567. service: ApiService;
  568. sn?: number;
  569. ret: ApiReturn<any>;
  570. } | {
  571. type: 'msg';
  572. service: MsgService;
  573. msg: any;
  574. };
  575. export declare interface PendingApiItem {
  576. sn: number;
  577. abortKey: string | undefined;
  578. service: ApiService;
  579. isAborted?: boolean;
  580. onAbort?: () => void;
  581. onReturn?: (ret: ApiReturn<any>) => void;
  582. }
  583. export declare type RecvMsgFlowData<ServiceType extends BaseServiceType> = {
  584. [K in keyof ServiceType['msg']]: {
  585. msgName: K & string;
  586. msg: ServiceType['msg'][K];
  587. };
  588. }[keyof ServiceType['msg']];
  589. export declare type SendMsgFlowData<ServiceType extends BaseServiceType> = {
  590. [K in keyof ServiceType['msg']]: {
  591. msgName: K & string;
  592. msg: ServiceType['msg'][K];
  593. options?: TransportOptions;
  594. };
  595. }[keyof ServiceType['msg']];
  596. export declare interface ServiceMap {
  597. id2Service: {
  598. [serviceId: number]: ApiService | MsgService;
  599. };
  600. apiName2Service: {
  601. [apiName: string]: ApiService | undefined;
  602. };
  603. msgName2Service: {
  604. [msgName: string]: MsgService | undefined;
  605. };
  606. }
  607. /** A utility for generate `ServiceMap` */
  608. export declare class ServiceMapUtil {
  609. static getServiceMap(proto: ServiceProto): ServiceMap;
  610. }
  611. export declare class TransportDataUtil {
  612. static readonly HeartbeatPacket: Readonly<Uint8Array>;
  613. private static _tsbuffer?;
  614. static get tsbuffer(): TSBuffer;
  615. static encodeClientMsg(tsbuffer: TSBuffer, service: MsgService, msg: any, type: 'buffer', connType: BaseClient<any>['type']): EncodeOutput<Uint8Array>;
  616. static encodeClientMsg(tsbuffer: TSBuffer, service: MsgService, msg: any, type: 'text', connType: BaseClient<any>['type']): EncodeOutput<string>;
  617. static encodeClientMsg(tsbuffer: TSBuffer, service: MsgService, msg: any, type: 'json', connType: BaseClient<any>['type']): EncodeOutput<object>;
  618. static encodeClientMsg(tsbuffer: TSBuffer, service: MsgService, msg: any, type: 'text' | 'buffer' | 'json', connType: BaseClient<any>['type']): EncodeOutput<Uint8Array> | EncodeOutput<string> | EncodeOutput<object>;
  619. static encodeApiReq(tsbuffer: TSBuffer, service: ApiService, req: any, type: 'buffer', sn?: number): EncodeOutput<Uint8Array>;
  620. static encodeApiReq(tsbuffer: TSBuffer, service: ApiService, req: any, type: 'text', sn?: number): EncodeOutput<string>;
  621. static encodeApiReq(tsbuffer: TSBuffer, service: ApiService, req: any, type: 'json', sn?: number): EncodeOutput<object>;
  622. static encodeApiReq(tsbuffer: TSBuffer, service: ApiService, req: any, type: 'text' | 'buffer' | 'json', sn?: number): EncodeOutput<Uint8Array> | EncodeOutput<string> | EncodeOutput<object>;
  623. static encodeServerMsg(tsbuffer: TSBuffer, service: MsgService, msg: any, type: 'buffer', connType: BaseClient<any>['type']): EncodeOutput<Uint8Array>;
  624. static encodeServerMsg(tsbuffer: TSBuffer, service: MsgService, msg: any, type: 'text', connType: BaseClient<any>['type']): EncodeOutput<string>;
  625. static encodeServerMsg(tsbuffer: TSBuffer, service: MsgService, msg: any, type: 'json', connType: BaseClient<any>['type']): EncodeOutput<object>;
  626. static encodeServerMsg(tsbuffer: TSBuffer, service: MsgService, msg: any, type: 'text' | 'buffer' | 'json', connType: BaseClient<any>['type']): EncodeOutput<Uint8Array> | EncodeOutput<string> | EncodeOutput<object>;
  627. static parseServerOutout(tsbuffer: TSBuffer, serviceMap: ServiceMap, data: Uint8Array | string | object, serviceId?: number): {
  628. isSucc: true;
  629. result: ParsedServerOutput;
  630. } | {
  631. isSucc: false;
  632. errMsg: string;
  633. };
  634. }
  635. export declare interface TransportOptions {
  636. /**
  637. * Timeout of this request(ms)
  638. * `undefined` represents no timeout
  639. * @defaultValue `undefined`
  640. */
  641. timeout?: number;
  642. /**
  643. * Which can be passed to `client.abortByKey(abortKey)`.
  644. * Many requests can share the same `abortKey`, so that they can be aborted at once.
  645. * @remarks
  646. * This may be useful in frontend within React or VueJS.
  647. * You can specify a unified `abortKey` to requests in a component, and abort them when the component is destroying.
  648. * @example
  649. * ```ts
  650. * // Send API request many times
  651. * client.callApi('SendData', { data: 'AAA' }, { abortKey: 'Session#123' });
  652. * client.callApi('SendData', { data: 'BBB' }, { abortKey: 'Session#123' });
  653. * client.callApi('SendData', { data: 'CCC' }, { abortKey: 'Session#123' });
  654. *
  655. * // And abort the at once
  656. * client.abortByKey('Session#123');
  657. * ```
  658. */
  659. abortKey?: string;
  660. }
  661. export declare enum WsClientStatus {
  662. Opening = "OPENING",
  663. Opened = "OPENED",
  664. Closing = "CLOSING",
  665. Closed = "CLOSED"
  666. }
  667. export { }