@pezkuwi/rpc-provider 16.5.20 → 16.5.22

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.
Files changed (210) hide show
  1. package/package.json +9 -9
  2. package/build/LICENSE +0 -201
  3. package/build/README.md +0 -68
  4. package/build/bizinikiwi-connect/Health.js +0 -259
  5. package/build/bizinikiwi-connect/index.js +0 -319
  6. package/build/bizinikiwi-connect/types.js +0 -1
  7. package/build/bundle.js +0 -5
  8. package/build/cjs/bizinikiwi-connect/Health.d.ts +0 -7
  9. package/build/cjs/bizinikiwi-connect/Health.js +0 -264
  10. package/build/cjs/bizinikiwi-connect/index.d.ts +0 -22
  11. package/build/cjs/bizinikiwi-connect/index.js +0 -323
  12. package/build/cjs/bizinikiwi-connect/types.d.ts +0 -12
  13. package/build/cjs/bizinikiwi-connect/types.js +0 -2
  14. package/build/cjs/bundle.d.ts +0 -5
  15. package/build/cjs/bundle.js +0 -14
  16. package/build/cjs/coder/error.js +0 -53
  17. package/build/cjs/coder/index.js +0 -63
  18. package/build/cjs/defaults.js +0 -8
  19. package/build/cjs/http/index.js +0 -196
  20. package/build/cjs/http/types.js +0 -2
  21. package/build/cjs/index.js +0 -5
  22. package/build/cjs/lru.js +0 -150
  23. package/build/cjs/mock/index.js +0 -196
  24. package/build/cjs/mock/mockHttp.js +0 -17
  25. package/build/cjs/mock/mockWs.js +0 -47
  26. package/build/cjs/mock/types.js +0 -2
  27. package/build/cjs/packageInfo.js +0 -4
  28. package/build/cjs/types.js +0 -2
  29. package/build/cjs/ws/errors.js +0 -41
  30. package/build/cjs/ws/index.js +0 -529
  31. package/build/coder/error.d.ts +0 -29
  32. package/build/coder/error.js +0 -50
  33. package/build/coder/index.d.ts +0 -8
  34. package/build/coder/index.js +0 -58
  35. package/build/defaults.d.ts +0 -5
  36. package/build/defaults.js +0 -6
  37. package/build/http/index.d.ts +0 -81
  38. package/build/http/index.js +0 -191
  39. package/build/http/types.d.ts +0 -7
  40. package/build/http/types.js +0 -1
  41. package/build/index.d.ts +0 -2
  42. package/build/index.js +0 -2
  43. package/build/lru.d.ts +0 -15
  44. package/build/lru.js +0 -146
  45. package/build/mock/index.d.ts +0 -35
  46. package/build/mock/index.js +0 -191
  47. package/build/mock/mockHttp.d.ts +0 -9
  48. package/build/mock/mockHttp.js +0 -12
  49. package/build/mock/mockWs.d.ts +0 -26
  50. package/build/mock/mockWs.js +0 -43
  51. package/build/mock/types.d.ts +0 -23
  52. package/build/mock/types.js +0 -1
  53. package/build/package.json +0 -344
  54. package/build/packageDetect.d.ts +0 -1
  55. package/build/packageDetect.js +0 -4
  56. package/build/packageInfo.d.ts +0 -6
  57. package/build/packageInfo.js +0 -1
  58. package/build/types.d.ts +0 -85
  59. package/build/types.js +0 -1
  60. package/build/ws/errors.d.ts +0 -1
  61. package/build/ws/errors.js +0 -38
  62. package/build/ws/index.d.ts +0 -121
  63. package/build/ws/index.js +0 -524
  64. package/build-deno/README.md +0 -66
  65. package/build-deno/bizinikiwi-connect/Health.ts +0 -323
  66. package/build-deno/bizinikiwi-connect/index.ts +0 -417
  67. package/build-deno/bizinikiwi-connect/types.ts +0 -14
  68. package/build-deno/bundle.ts +0 -6
  69. package/build-deno/coder/error.ts +0 -64
  70. package/build-deno/coder/index.ts +0 -86
  71. package/build-deno/defaults.ts +0 -8
  72. package/build-deno/http/index.ts +0 -236
  73. package/build-deno/http/types.ts +0 -9
  74. package/build-deno/index.ts +0 -4
  75. package/build-deno/lru.ts +0 -189
  76. package/build-deno/mock/index.ts +0 -257
  77. package/build-deno/mock/mockHttp.ts +0 -33
  78. package/build-deno/mock/mockWs.ts +0 -87
  79. package/build-deno/mock/types.ts +0 -34
  80. package/build-deno/mod.ts +0 -2
  81. package/build-deno/packageDetect.ts +0 -8
  82. package/build-deno/packageInfo.ts +0 -3
  83. package/build-deno/types.ts +0 -99
  84. package/build-deno/ws/errors.ts +0 -38
  85. package/build-deno/ws/index.ts +0 -650
  86. package/build-tsc-cjs/packageDetect.js +0 -6
  87. package/src/bizinikiwi-connect/Health.ts +0 -325
  88. package/src/bizinikiwi-connect/index.spec.ts +0 -675
  89. package/src/bizinikiwi-connect/index.ts +0 -427
  90. package/src/bizinikiwi-connect/types.ts +0 -16
  91. package/src/bundle.ts +0 -8
  92. package/src/coder/decodeResponse.spec.ts +0 -70
  93. package/src/coder/encodeJson.spec.ts +0 -20
  94. package/src/coder/encodeObject.spec.ts +0 -25
  95. package/src/coder/error.spec.ts +0 -111
  96. package/src/coder/error.ts +0 -66
  97. package/src/coder/index.ts +0 -88
  98. package/src/defaults.ts +0 -10
  99. package/src/http/index.spec.ts +0 -72
  100. package/src/http/index.ts +0 -238
  101. package/src/http/send.spec.ts +0 -61
  102. package/src/http/types.ts +0 -11
  103. package/src/index.ts +0 -6
  104. package/src/lru.spec.ts +0 -74
  105. package/src/lru.ts +0 -197
  106. package/src/mock/index.ts +0 -259
  107. package/src/mock/mockHttp.ts +0 -35
  108. package/src/mock/mockWs.ts +0 -92
  109. package/src/mock/on.spec.ts +0 -43
  110. package/src/mock/send.spec.ts +0 -38
  111. package/src/mock/subscribe.spec.ts +0 -81
  112. package/src/mock/types.ts +0 -36
  113. package/src/mock/unsubscribe.spec.ts +0 -57
  114. package/src/mod.ts +0 -4
  115. package/src/packageDetect.ts +0 -12
  116. package/src/packageInfo.ts +0 -6
  117. package/src/types.ts +0 -101
  118. package/src/ws/connect.spec.ts +0 -167
  119. package/src/ws/errors.ts +0 -41
  120. package/src/ws/index.spec.ts +0 -97
  121. package/src/ws/index.ts +0 -652
  122. package/src/ws/send.spec.ts +0 -126
  123. package/src/ws/state.spec.ts +0 -20
  124. package/src/ws/subscribe.spec.ts +0 -68
  125. package/src/ws/unsubscribe.spec.ts +0 -100
  126. package/tsconfig.build.json +0 -17
  127. package/tsconfig.build.tsbuildinfo +0 -1
  128. package/tsconfig.spec.json +0 -18
  129. package/tsconfig.spec.tsbuildinfo +0 -1
  130. /package/{build-tsc/bizinikiwi-connect → bizinikiwi-connect}/Health.d.ts +0 -0
  131. /package/{build-tsc-esm/bizinikiwi-connect → bizinikiwi-connect}/Health.js +0 -0
  132. /package/{build-tsc/bizinikiwi-connect → bizinikiwi-connect}/index.d.ts +0 -0
  133. /package/{build-tsc-esm/bizinikiwi-connect → bizinikiwi-connect}/index.js +0 -0
  134. /package/{build-tsc/bizinikiwi-connect → bizinikiwi-connect}/types.d.ts +0 -0
  135. /package/{build-tsc-esm/bizinikiwi-connect → bizinikiwi-connect}/types.js +0 -0
  136. /package/{build-tsc/bundle.d.ts → bundle.d.ts} +0 -0
  137. /package/{build-tsc-esm/bundle.js → bundle.js} +0 -0
  138. /package/{build → cjs}/bizinikiwi-connect/Health.d.ts +0 -0
  139. /package/{build-tsc-cjs → cjs}/bizinikiwi-connect/Health.js +0 -0
  140. /package/{build → cjs}/bizinikiwi-connect/index.d.ts +0 -0
  141. /package/{build-tsc-cjs → cjs}/bizinikiwi-connect/index.js +0 -0
  142. /package/{build → cjs}/bizinikiwi-connect/types.d.ts +0 -0
  143. /package/{build-tsc-cjs → cjs}/bizinikiwi-connect/types.js +0 -0
  144. /package/{build → cjs}/bundle.d.ts +0 -0
  145. /package/{build-tsc-cjs → cjs}/bundle.js +0 -0
  146. /package/{build-tsc → cjs}/coder/error.d.ts +0 -0
  147. /package/{build-tsc-cjs → cjs}/coder/error.js +0 -0
  148. /package/{build-tsc → cjs}/coder/index.d.ts +0 -0
  149. /package/{build-tsc-cjs → cjs}/coder/index.js +0 -0
  150. /package/{build-tsc → cjs}/defaults.d.ts +0 -0
  151. /package/{build-tsc-cjs → cjs}/defaults.js +0 -0
  152. /package/{build-tsc → cjs}/http/index.d.ts +0 -0
  153. /package/{build-tsc-cjs → cjs}/http/index.js +0 -0
  154. /package/{build-tsc → cjs}/http/types.d.ts +0 -0
  155. /package/{build-tsc-cjs → cjs}/http/types.js +0 -0
  156. /package/{build-tsc → cjs}/index.d.ts +0 -0
  157. /package/{build-tsc-cjs → cjs}/index.js +0 -0
  158. /package/{build-tsc → cjs}/lru.d.ts +0 -0
  159. /package/{build-tsc-cjs → cjs}/lru.js +0 -0
  160. /package/{build-tsc → cjs}/mock/index.d.ts +0 -0
  161. /package/{build-tsc-cjs → cjs}/mock/index.js +0 -0
  162. /package/{build-tsc → cjs}/mock/mockHttp.d.ts +0 -0
  163. /package/{build-tsc-cjs → cjs}/mock/mockHttp.js +0 -0
  164. /package/{build-tsc → cjs}/mock/mockWs.d.ts +0 -0
  165. /package/{build-tsc-cjs → cjs}/mock/mockWs.js +0 -0
  166. /package/{build-tsc → cjs}/mock/types.d.ts +0 -0
  167. /package/{build-tsc-cjs → cjs}/mock/types.js +0 -0
  168. /package/{build/cjs → cjs}/package.json +0 -0
  169. /package/{build-tsc → cjs}/packageDetect.d.ts +0 -0
  170. /package/{build/cjs → cjs}/packageDetect.js +0 -0
  171. /package/{build-tsc → cjs}/packageInfo.d.ts +0 -0
  172. /package/{build-tsc-cjs → cjs}/packageInfo.js +0 -0
  173. /package/{build-tsc → cjs}/types.d.ts +0 -0
  174. /package/{build-tsc-cjs → cjs}/types.js +0 -0
  175. /package/{build-tsc → cjs}/ws/errors.d.ts +0 -0
  176. /package/{build-tsc-cjs → cjs}/ws/errors.js +0 -0
  177. /package/{build-tsc → cjs}/ws/index.d.ts +0 -0
  178. /package/{build-tsc-cjs → cjs}/ws/index.js +0 -0
  179. /package/{build/cjs/coder → coder}/error.d.ts +0 -0
  180. /package/{build-tsc-esm/coder → coder}/error.js +0 -0
  181. /package/{build/cjs/coder → coder}/index.d.ts +0 -0
  182. /package/{build-tsc-esm/coder → coder}/index.js +0 -0
  183. /package/{build/cjs/defaults.d.ts → defaults.d.ts} +0 -0
  184. /package/{build-tsc-esm/defaults.js → defaults.js} +0 -0
  185. /package/{build/cjs/http → http}/index.d.ts +0 -0
  186. /package/{build-tsc-esm/http → http}/index.js +0 -0
  187. /package/{build/cjs/http → http}/types.d.ts +0 -0
  188. /package/{build-tsc-esm/http → http}/types.js +0 -0
  189. /package/{build/cjs/index.d.ts → index.d.ts} +0 -0
  190. /package/{build-tsc-esm/index.js → index.js} +0 -0
  191. /package/{build/cjs/lru.d.ts → lru.d.ts} +0 -0
  192. /package/{build-tsc-esm/lru.js → lru.js} +0 -0
  193. /package/{build/cjs/mock → mock}/index.d.ts +0 -0
  194. /package/{build-tsc-esm/mock → mock}/index.js +0 -0
  195. /package/{build/cjs/mock → mock}/mockHttp.d.ts +0 -0
  196. /package/{build-tsc-esm/mock → mock}/mockHttp.js +0 -0
  197. /package/{build/cjs/mock → mock}/mockWs.d.ts +0 -0
  198. /package/{build-tsc-esm/mock → mock}/mockWs.js +0 -0
  199. /package/{build/cjs/mock → mock}/types.d.ts +0 -0
  200. /package/{build-tsc-esm/mock → mock}/types.js +0 -0
  201. /package/{build/cjs/packageDetect.d.ts → packageDetect.d.ts} +0 -0
  202. /package/{build-tsc-esm/packageDetect.js → packageDetect.js} +0 -0
  203. /package/{build/cjs/packageInfo.d.ts → packageInfo.d.ts} +0 -0
  204. /package/{build-tsc-esm/packageInfo.js → packageInfo.js} +0 -0
  205. /package/{build/cjs/types.d.ts → types.d.ts} +0 -0
  206. /package/{build-tsc-esm/types.js → types.js} +0 -0
  207. /package/{build/cjs/ws → ws}/errors.d.ts +0 -0
  208. /package/{build-tsc-esm/ws → ws}/errors.js +0 -0
  209. /package/{build/cjs/ws → ws}/index.d.ts +0 -0
  210. /package/{build-tsc-esm/ws → ws}/index.js +0 -0
@@ -1,66 +0,0 @@
1
- // Copyright 2017-2025 @pezkuwi/rpc-provider authors & contributors
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
- import type { RpcErrorInterface } from '../types.js';
5
-
6
- import { isFunction } from '@pezkuwi/util';
7
-
8
- const UNKNOWN = -99999;
9
-
10
- function extend<Data, K extends keyof RpcError<Data>> (that: RpcError<Data>, name: K, value: RpcError<Data>[K]): void {
11
- Object.defineProperty(that, name, {
12
- configurable: true,
13
- enumerable: false,
14
- value
15
- });
16
- }
17
-
18
- /**
19
- * @name RpcError
20
- * @summary Extension to the basic JS Error.
21
- * @description
22
- * The built-in JavaScript Error class is extended by adding a code to allow for Error categorization. In addition to the normal `stack`, `message`, the numeric `code` and `data` (any types) parameters are available on the object.
23
- * @example
24
- * <BR>
25
- *
26
- * ```javascript
27
- * const { RpcError } from '@pezkuwi/util');
28
- *
29
- * throw new RpcError('some message', RpcError.CODES.METHOD_NOT_FOUND); // => error.code = -32601
30
- * ```
31
- */
32
- export default class RpcError<T = never> extends Error implements RpcErrorInterface<T> {
33
- public code!: number;
34
-
35
- public data?: T;
36
-
37
- public override message!: string;
38
-
39
- public override name!: string;
40
-
41
- public override stack!: string;
42
-
43
- public constructor (message = '', code: number = UNKNOWN, data?: T) {
44
- super();
45
-
46
- extend(this, 'message', String(message));
47
- extend(this, 'name', this.constructor.name);
48
- extend(this, 'data', data);
49
- extend(this, 'code', code);
50
-
51
- if (isFunction(Error.captureStackTrace)) {
52
- Error.captureStackTrace(this, this.constructor);
53
- } else {
54
- const { stack } = new Error(message);
55
-
56
- stack && extend(this, 'stack', stack);
57
- }
58
- }
59
-
60
- public static CODES = {
61
- ASSERT: -90009,
62
- INVALID_JSONRPC: -99998,
63
- METHOD_NOT_FOUND: -32601, // Rust client
64
- UNKNOWN
65
- };
66
- }
@@ -1,88 +0,0 @@
1
- // Copyright 2017-2025 @pezkuwi/rpc-provider authors & contributors
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
- import type { JsonRpcRequest, JsonRpcResponse, JsonRpcResponseBaseError } from '../types.js';
5
-
6
- import { isNumber, isString, isUndefined, stringify } from '@pezkuwi/util';
7
-
8
- import RpcError from './error.js';
9
-
10
- function formatErrorData (data?: string | number): string {
11
- if (isUndefined(data)) {
12
- return '';
13
- }
14
-
15
- const formatted = `: ${isString(data)
16
- ? data.replace(/Error\("/g, '').replace(/\("/g, '(').replace(/"\)/g, ')').replace(/\(/g, ', ').replace(/\)/g, '')
17
- : stringify(data)}`;
18
-
19
- // We need some sort of cut-off here since these can be very large and
20
- // very nested, pick a number and trim the result display to it
21
- return formatted.length <= 256
22
- ? formatted
23
- : `${formatted.substring(0, 255)}…`;
24
- }
25
-
26
- function checkError (error?: JsonRpcResponseBaseError): void {
27
- if (error) {
28
- const { code, data, message } = error;
29
-
30
- throw new RpcError(`${code}: ${message}${formatErrorData(data)}`, code, data);
31
- }
32
- }
33
-
34
- /** @internal */
35
- export class RpcCoder {
36
- #id = 0;
37
-
38
- public decodeResponse <T> (response?: JsonRpcResponse<T>): T {
39
- if (!response || response.jsonrpc !== '2.0') {
40
- throw new Error('Invalid jsonrpc field in decoded object');
41
- }
42
-
43
- const isSubscription = !isUndefined(response.params) && !isUndefined(response.method);
44
-
45
- if (
46
- !isNumber(response.id) &&
47
- (
48
- !isSubscription || (
49
- !isNumber(response.params.subscription) &&
50
- !isString(response.params.subscription)
51
- )
52
- )
53
- ) {
54
- throw new Error('Invalid id field in decoded object');
55
- }
56
-
57
- checkError(response.error);
58
-
59
- if (response.result === undefined && !isSubscription) {
60
- throw new Error('No result found in jsonrpc response');
61
- }
62
-
63
- if (isSubscription) {
64
- checkError(response.params.error);
65
-
66
- return response.params.result;
67
- }
68
-
69
- return response.result;
70
- }
71
-
72
- public encodeJson (method: string, params: unknown[]): [number, string] {
73
- const [id, data] = this.encodeObject(method, params);
74
-
75
- return [id, stringify(data)];
76
- }
77
-
78
- public encodeObject (method: string, params: unknown[]): [number, JsonRpcRequest] {
79
- const id = ++this.#id;
80
-
81
- return [id, {
82
- id,
83
- jsonrpc: '2.0',
84
- method,
85
- params
86
- }];
87
- }
88
- }
package/src/defaults.ts DELETED
@@ -1,10 +0,0 @@
1
- // Copyright 2017-2025 @pezkuwi/rpc-provider authors & contributors
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
- const HTTP_URL = 'http://127.0.0.1:9933';
5
- const WS_URL = 'ws://127.0.0.1:9944';
6
-
7
- export default {
8
- HTTP_URL,
9
- WS_URL
10
- };
@@ -1,72 +0,0 @@
1
- // Copyright 2017-2025 @pezkuwi/rpc-provider authors & contributors
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
- /// <reference types="@pezkuwi/dev-test/globals.d.ts" />
5
-
6
- import { TEST_HTTP_URL } from '../mock/mockHttp.js';
7
- import { HttpProvider } from './index.js';
8
-
9
- describe('Http', (): void => {
10
- let http: HttpProvider;
11
-
12
- beforeEach((): void => {
13
- http = new HttpProvider(TEST_HTTP_URL);
14
- });
15
-
16
- it('requires an http:// prefixed endpoint', (): void => {
17
- expect(
18
- () => new HttpProvider('ws://')
19
- ).toThrow(/with 'http/);
20
- });
21
-
22
- it('allows https:// endpoints', (): void => {
23
- expect(
24
- () => new HttpProvider('https://')
25
- ).not.toThrow();
26
- });
27
-
28
- it('allows custom headers', (): void => {
29
- expect(
30
- () => new HttpProvider('https://', { foo: 'bar' })
31
- ).not.toThrow();
32
- });
33
-
34
- it('should throw error on negative cache capacity or TTL', () => {
35
- expect(() =>
36
- new HttpProvider(TEST_HTTP_URL, {}, -5, 30000)
37
- ).toThrow(/'capacity' must be a non-negative integer/);
38
-
39
- expect(() =>
40
- new HttpProvider(TEST_HTTP_URL, {}, 1024, -1000)
41
- ).toThrow(/'ttl' must be between 0 and 1800000 ms or null to disable/);
42
- });
43
-
44
- it('allow clone', (): void => {
45
- const clone = http.clone();
46
- /* eslint-disable */
47
- expect((clone as any)['#endpoint']).toEqual((http as any)['#endpoint']);
48
- expect((clone as any)['#headers']).toEqual((http as any)['#headers']);
49
- /* eslint-enable */
50
- });
51
-
52
- it('always returns isConnected true', (): void => {
53
- expect(http.isConnected).toEqual(true);
54
- });
55
-
56
- it('does not (yet) support subscribe', async (): Promise<void> => {
57
- await http.subscribe('', '', [], (cb): void => {
58
- // eslint-disable-next-line jest/no-conditional-expect
59
- expect(cb).toEqual(expect.anything());
60
- }).catch((error): void => {
61
- // eslint-disable-next-line jest/no-conditional-expect
62
- expect((error as Error).message).toMatch(/does not have subscriptions/);
63
- });
64
- });
65
-
66
- it('does not (yet) support unsubscribe', async (): Promise<void> => {
67
- await http.unsubscribe('', '', 0).catch((error): void => {
68
- // eslint-disable-next-line jest/no-conditional-expect
69
- expect((error as Error).message).toMatch(/does not have subscriptions/);
70
- });
71
- });
72
- });
package/src/http/index.ts DELETED
@@ -1,238 +0,0 @@
1
- // Copyright 2017-2025 @pezkuwi/rpc-provider authors & contributors
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
- import type RpcError from '../coder/error.js';
5
- import type { JsonRpcResponse, ProviderInterface, ProviderInterfaceCallback, ProviderInterfaceEmitCb, ProviderInterfaceEmitted, ProviderStats } from '../types.js';
6
-
7
- import { logger, noop, stringify } from '@pezkuwi/util';
8
- import { fetch } from '@pezkuwi/x-fetch';
9
-
10
- import { RpcCoder } from '../coder/index.js';
11
- import defaults from '../defaults.js';
12
- import { DEFAULT_CAPACITY, DEFAULT_TTL, LRUCache } from '../lru.js';
13
-
14
- const ERROR_SUBSCRIBE = 'HTTP Provider does not have subscriptions, use WebSockets instead';
15
-
16
- const l = logger('api-http');
17
-
18
- /**
19
- * # @pezkuwi/rpc-provider
20
- *
21
- * @name HttpProvider
22
- *
23
- * @description The HTTP Provider allows sending requests using HTTP to a HTTP RPC server TCP port. It does not support subscriptions so you won't be able to listen to events such as new blocks or balance changes. It is usually preferable using the [[WsProvider]].
24
- *
25
- * @example
26
- * <BR>
27
- *
28
- * ```javascript
29
- * import Api from '@pezkuwi/api/promise';
30
- * import { HttpProvider } from '@pezkuwi/rpc-provider';
31
- *
32
- * const provider = new HttpProvider('http://127.0.0.1:9933');
33
- * const api = new Api(provider);
34
- * ```
35
- *
36
- * @see [[WsProvider]]
37
- */
38
- export class HttpProvider implements ProviderInterface {
39
- readonly #callCache: LRUCache;
40
- readonly #cacheCapacity: number;
41
- readonly #coder: RpcCoder;
42
- readonly #endpoint: string;
43
- readonly #headers: Record<string, string>;
44
- readonly #stats: ProviderStats;
45
- readonly #ttl: number | null | undefined;
46
-
47
- /**
48
- * @param {string} endpoint The endpoint url starting with http://
49
- * @param {Record<string, string>} headers The headers provided to the underlying Http Endpoint
50
- * @param {number} [cacheCapacity] Custom size of the HttpProvider LRUCache. Defaults to `DEFAULT_CAPACITY` (1024)
51
- * @param {number} [cacheTtl] Custom TTL of the HttpProvider LRUCache. Determines how long an object can live in the cache. Defaults to `DEFAULT_TTL` (30000)
52
- */
53
- constructor (endpoint: string = defaults.HTTP_URL, headers: Record<string, string> = {}, cacheCapacity?: number, cacheTtl?: number | null) {
54
- if (!/^(https|http):\/\//.test(endpoint)) {
55
- throw new Error(`Endpoint should start with 'http://' or 'https://', received '${endpoint}'`);
56
- }
57
-
58
- this.#coder = new RpcCoder();
59
- this.#endpoint = endpoint;
60
- this.#headers = headers;
61
- this.#cacheCapacity = cacheCapacity === 0 ? 0 : cacheCapacity || DEFAULT_CAPACITY;
62
-
63
- const ttl = cacheTtl === undefined ? DEFAULT_TTL : cacheTtl;
64
-
65
- this.#callCache = new LRUCache(cacheCapacity === 0 ? 0 : cacheCapacity || DEFAULT_CAPACITY, ttl);
66
- this.#ttl = cacheTtl;
67
-
68
- this.#stats = {
69
- active: { requests: 0, subscriptions: 0 },
70
- total: { bytesRecv: 0, bytesSent: 0, cached: 0, errors: 0, requests: 0, subscriptions: 0, timeout: 0 }
71
- };
72
- }
73
-
74
- /**
75
- * @summary `true` when this provider supports subscriptions
76
- */
77
- public get hasSubscriptions (): boolean {
78
- return !!false;
79
- }
80
-
81
- /**
82
- * @description Returns a clone of the object
83
- */
84
- public clone (): HttpProvider {
85
- return new HttpProvider(this.#endpoint, this.#headers);
86
- }
87
-
88
- /**
89
- * @description Manually connect from the connection
90
- */
91
- public async connect (): Promise<void> {
92
- // noop
93
- }
94
-
95
- /**
96
- * @description Manually disconnect from the connection
97
- */
98
- public async disconnect (): Promise<void> {
99
- // noop
100
- }
101
-
102
- /**
103
- * @description Returns the connection stats
104
- */
105
- public get stats (): ProviderStats {
106
- return this.#stats;
107
- }
108
-
109
- /**
110
- * @description Returns the connection stats
111
- */
112
- public get ttl (): number | null | undefined {
113
- return this.#ttl;
114
- }
115
-
116
- /**
117
- * @summary `true` when this provider supports clone()
118
- */
119
- public get isClonable (): boolean {
120
- return !!true;
121
- }
122
-
123
- /**
124
- * @summary Whether the node is connected or not.
125
- * @return {boolean} true if connected
126
- */
127
- public get isConnected (): boolean {
128
- return !!true;
129
- }
130
-
131
- /**
132
- * @summary Events are not supported with the HttpProvider, see [[WsProvider]].
133
- * @description HTTP Provider does not have 'on' emitters. WebSockets should be used instead.
134
- */
135
- public on (_type: ProviderInterfaceEmitted, _sub: ProviderInterfaceEmitCb): () => void {
136
- l.error('HTTP Provider does not have \'on\' emitters, use WebSockets instead');
137
-
138
- return noop;
139
- }
140
-
141
- /**
142
- * @summary Send HTTP POST Request with Body to configured HTTP Endpoint.
143
- */
144
- public async send <T> (method: string, params: unknown[], isCacheable?: boolean): Promise<T> {
145
- this.#stats.total.requests++;
146
-
147
- const [, body] = this.#coder.encodeJson(method, params);
148
-
149
- if (this.#cacheCapacity === 0) {
150
- return this.#send(body);
151
- }
152
-
153
- const cacheKey = isCacheable ? `${method}::${stringify(params)}` : '';
154
- let resultPromise: Promise<T> | null = isCacheable
155
- ? this.#callCache.get(cacheKey)
156
- : null;
157
-
158
- if (!resultPromise) {
159
- resultPromise = this.#send(body);
160
-
161
- if (isCacheable) {
162
- this.#callCache.set(cacheKey, resultPromise);
163
- }
164
- } else {
165
- this.#stats.total.cached++;
166
- }
167
-
168
- return resultPromise;
169
- }
170
-
171
- async #send <T> (body: string): Promise<T> {
172
- this.#stats.active.requests++;
173
- this.#stats.total.bytesSent += body.length;
174
-
175
- try {
176
- const response = await fetch(this.#endpoint, {
177
- body,
178
- headers: {
179
- Accept: 'application/json',
180
- 'Content-Length': `${body.length}`,
181
- 'Content-Type': 'application/json',
182
- ...this.#headers
183
- },
184
- method: 'POST'
185
- });
186
-
187
- if (!response.ok) {
188
- throw new Error(`[${response.status}]: ${response.statusText}`);
189
- }
190
-
191
- const result = await response.text();
192
-
193
- this.#stats.total.bytesRecv += result.length;
194
-
195
- const decoded = this.#coder.decodeResponse(JSON.parse(result) as JsonRpcResponse<T>);
196
-
197
- this.#stats.active.requests--;
198
-
199
- return decoded;
200
- } catch (e) {
201
- this.#stats.active.requests--;
202
- this.#stats.total.errors++;
203
-
204
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
205
- const { method, params } = JSON.parse(body);
206
-
207
- const rpcError: RpcError = e as RpcError;
208
-
209
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
210
- const failedRequest = `\nFailed HTTP Request: ${JSON.stringify({ method, params })}`;
211
-
212
- // Provide HTTP Request alongside the error
213
- rpcError.message = `${rpcError.message}${failedRequest}`;
214
-
215
- throw rpcError;
216
- }
217
- }
218
-
219
- /**
220
- * @summary Subscriptions are not supported with the HttpProvider, see [[WsProvider]].
221
- */
222
- // eslint-disable-next-line @typescript-eslint/require-await
223
- public async subscribe (_types: string, _method: string, _params: unknown[], _cb: ProviderInterfaceCallback): Promise<number> {
224
- l.error(ERROR_SUBSCRIBE);
225
-
226
- throw new Error(ERROR_SUBSCRIBE);
227
- }
228
-
229
- /**
230
- * @summary Subscriptions are not supported with the HttpProvider, see [[WsProvider]].
231
- */
232
- // eslint-disable-next-line @typescript-eslint/require-await
233
- public async unsubscribe (_type: string, _method: string, _id: number): Promise<boolean> {
234
- l.error(ERROR_SUBSCRIBE);
235
-
236
- throw new Error(ERROR_SUBSCRIBE);
237
- }
238
- }
@@ -1,61 +0,0 @@
1
- // Copyright 2017-2025 @pezkuwi/rpc-provider authors & contributors
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
- /// <reference types="@pezkuwi/dev-test/globals.d.ts" />
5
-
6
- import type { Mock } from '../mock/types.js';
7
-
8
- import { mockHttp, TEST_HTTP_URL } from '../mock/mockHttp.js';
9
- import { HttpProvider } from './index.js';
10
-
11
- // Does not work with Node 18 (native fetch)
12
- // See https://github.com/nock/nock/issues/2397
13
- // eslint-disable-next-line jest/no-disabled-tests
14
- describe.skip('send', (): void => {
15
- let http: HttpProvider;
16
- let mock: Mock;
17
-
18
- beforeEach((): void => {
19
- http = new HttpProvider(TEST_HTTP_URL);
20
- });
21
-
22
- afterEach(async () => {
23
- if (mock) {
24
- await mock.done();
25
- }
26
- });
27
-
28
- it('passes the body through correctly', (): Promise<void> => {
29
- mock = mockHttp([{
30
- method: 'test_body',
31
- reply: {
32
- result: 'ok'
33
- }
34
- }]);
35
-
36
- return http
37
- .send('test_body', ['param'])
38
- .then((): void => {
39
- expect(mock.body['test_body']).toEqual({
40
- id: 1,
41
- jsonrpc: '2.0',
42
- method: 'test_body',
43
- params: ['param']
44
- });
45
- });
46
- });
47
-
48
- it('throws error when !response.ok', async (): Promise<any> => {
49
- mock = mockHttp([{
50
- code: 500,
51
- method: 'test_error'
52
- }]);
53
-
54
- return http
55
- .send('test_error', [])
56
- .catch((error): void => {
57
- // eslint-disable-next-line jest/no-conditional-expect
58
- expect((error as Error).message).toMatch(/\[500\]/);
59
- });
60
- });
61
- });
package/src/http/types.ts DELETED
@@ -1,11 +0,0 @@
1
- // Copyright 2017-2025 @pezkuwi/rpc-provider authors & contributors
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
- import type { Logger } from '@pezkuwi/util/types';
5
- import type { RpcCoder } from '../coder/index.js';
6
-
7
- export interface HttpState {
8
- coder: RpcCoder;
9
- endpoint: string;
10
- l: Logger;
11
- }
package/src/index.ts DELETED
@@ -1,6 +0,0 @@
1
- // Copyright 2017-2025 @pezkuwi/rpc-provider authors & contributors
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
- import './packageDetect.js';
5
-
6
- export * from './bundle.js';
package/src/lru.spec.ts DELETED
@@ -1,74 +0,0 @@
1
- // Copyright 2017-2025 @pezkuwi/rpc-provider authors & contributors
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
- /// <reference types="@pezkuwi/dev-test/globals.d.ts" />
5
-
6
- import { LRUCache } from './lru.js';
7
-
8
- describe('LRUCache', (): void => {
9
- let lru: LRUCache | undefined;
10
-
11
- beforeEach((): void => {
12
- lru = new LRUCache(4, 500);
13
- });
14
-
15
- it('allows getting of items below capacity', (): void => {
16
- const keys = ['1', '2', '3', '4'];
17
-
18
- keys.forEach((k) => lru?.set(k, `${k}${k}${k}`));
19
- const lruKeys = lru?.keys();
20
-
21
- expect(lruKeys?.join(', ')).toBe(keys.reverse().join(', '));
22
- expect(lru?.length === lru?.lengthData && lru?.length === lru?.lengthRefs).toBe(true);
23
-
24
- keys.forEach((k) => expect(lru?.get(k)).toEqual(`${k}${k}${k}`));
25
- });
26
-
27
- it('drops items when at capacity', (): void => {
28
- const keys = ['1', '2', '3', '4', '5', '6'];
29
-
30
- keys.forEach((k) => lru?.set(k, `${k}${k}${k}`));
31
-
32
- expect(lru?.keys().join(', ')).toEqual(keys.slice(2).reverse().join(', '));
33
- expect(lru?.length === lru?.lengthData && lru?.length === lru?.lengthRefs).toBe(true);
34
-
35
- keys.slice(2).forEach((k) => expect(lru?.get(k)).toEqual(`${k}${k}${k}`));
36
- });
37
-
38
- it('adjusts the order as they are used', (): void => {
39
- const keys = ['1', '2', '3', '4', '5'];
40
-
41
- keys.forEach((k) => lru?.set(k, `${k}${k}${k}`));
42
-
43
- expect(lru?.entries()).toEqual([['5', '555'], ['4', '444'], ['3', '333'], ['2', '222']]);
44
- expect(lru?.length === lru?.lengthData && lru?.length === lru?.lengthRefs).toBe(true);
45
-
46
- lru?.get('3');
47
-
48
- expect(lru?.entries()).toEqual([['3', '333'], ['5', '555'], ['4', '444'], ['2', '222']]);
49
- expect(lru?.length === lru?.lengthData && lru?.length === lru?.lengthRefs).toBe(true);
50
-
51
- lru?.set('4', '4433');
52
-
53
- expect(lru?.entries()).toEqual([['4', '4433'], ['3', '333'], ['5', '555'], ['2', '222']]);
54
- expect(lru?.length === lru?.lengthData && lru?.length === lru?.lengthRefs).toBe(true);
55
-
56
- lru?.set('6', '666');
57
-
58
- expect(lru?.entries()).toEqual([['6', '666'], ['4', '4433'], ['3', '333'], ['5', '555']]);
59
- expect(lru?.length === lru?.lengthData && lru?.length === lru?.lengthRefs).toBe(true);
60
- });
61
-
62
- it('evicts items with TTL', (): void => {
63
- const keys = ['1', '2', '3', '4', '5'];
64
-
65
- keys.forEach((k) => lru?.set(k, `${k}${k}${k}`));
66
-
67
- expect(lru?.entries()).toEqual([['5', '555'], ['4', '444'], ['3', '333'], ['2', '222']]);
68
-
69
- setTimeout((): void => {
70
- lru?.get('3');
71
- expect(lru?.entries()).toEqual([['3', '333']]);
72
- }, 800);
73
- });
74
- });