@milaboratories/pl-client 2.17.7 → 2.17.9

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 (276) hide show
  1. package/dist/_virtual/_rolldown/runtime.cjs +43 -0
  2. package/dist/_virtual/_rolldown/runtime.js +18 -0
  3. package/dist/core/PromiseTracker.cjs +33 -33
  4. package/dist/core/PromiseTracker.cjs.map +1 -1
  5. package/dist/core/PromiseTracker.d.ts +10 -7
  6. package/dist/core/PromiseTracker.js +33 -31
  7. package/dist/core/PromiseTracker.js.map +1 -1
  8. package/dist/core/StatefulPromise.cjs +60 -61
  9. package/dist/core/StatefulPromise.cjs.map +1 -1
  10. package/dist/core/StatefulPromise.js +60 -60
  11. package/dist/core/StatefulPromise.js.map +1 -1
  12. package/dist/core/abstract_stream.d.ts +18 -15
  13. package/dist/core/advisory_locks.cjs +42 -49
  14. package/dist/core/advisory_locks.cjs.map +1 -1
  15. package/dist/core/advisory_locks.js +42 -48
  16. package/dist/core/advisory_locks.js.map +1 -1
  17. package/dist/core/auth.cjs +10 -15
  18. package/dist/core/auth.cjs.map +1 -1
  19. package/dist/core/auth.d.ts +7 -3
  20. package/dist/core/auth.js +10 -13
  21. package/dist/core/auth.js.map +1 -1
  22. package/dist/core/cache.d.ts +11 -7
  23. package/dist/core/client.cjs +255 -306
  24. package/dist/core/client.cjs.map +1 -1
  25. package/dist/core/client.d.ts +72 -68
  26. package/dist/core/client.js +253 -285
  27. package/dist/core/client.js.map +1 -1
  28. package/dist/core/config.cjs +81 -99
  29. package/dist/core/config.cjs.map +1 -1
  30. package/dist/core/config.d.ts +93 -90
  31. package/dist/core/config.js +81 -98
  32. package/dist/core/config.js.map +1 -1
  33. package/dist/core/default_client.cjs +84 -125
  34. package/dist/core/default_client.cjs.map +1 -1
  35. package/dist/core/default_client.d.ts +9 -6
  36. package/dist/core/default_client.js +78 -103
  37. package/dist/core/default_client.js.map +1 -1
  38. package/dist/core/driver.cjs +12 -16
  39. package/dist/core/driver.cjs.map +1 -1
  40. package/dist/core/driver.d.ts +18 -14
  41. package/dist/core/driver.js +12 -15
  42. package/dist/core/driver.js.map +1 -1
  43. package/dist/core/error_resource.cjs +5 -4
  44. package/dist/core/error_resource.cjs.map +1 -1
  45. package/dist/core/error_resource.js +5 -3
  46. package/dist/core/error_resource.js.map +1 -1
  47. package/dist/core/errors.cjs +104 -140
  48. package/dist/core/errors.cjs.map +1 -1
  49. package/dist/core/errors.d.ts +34 -30
  50. package/dist/core/errors.js +102 -137
  51. package/dist/core/errors.js.map +1 -1
  52. package/dist/core/final.cjs +63 -89
  53. package/dist/core/final.cjs.map +1 -1
  54. package/dist/core/final.d.ts +8 -4
  55. package/dist/core/final.js +63 -87
  56. package/dist/core/final.js.map +1 -1
  57. package/dist/core/ll_client.cjs +416 -521
  58. package/dist/core/ll_client.cjs.map +1 -1
  59. package/dist/core/ll_client.d.ts +100 -97
  60. package/dist/core/ll_client.js +415 -519
  61. package/dist/core/ll_client.js.map +1 -1
  62. package/dist/core/ll_transaction.cjs +206 -240
  63. package/dist/core/ll_transaction.cjs.map +1 -1
  64. package/dist/core/ll_transaction.d.ts +50 -52
  65. package/dist/core/ll_transaction.js +205 -238
  66. package/dist/core/ll_transaction.js.map +1 -1
  67. package/dist/core/stat.cjs +64 -63
  68. package/dist/core/stat.cjs.map +1 -1
  69. package/dist/core/stat.d.ts +35 -36
  70. package/dist/core/stat.js +64 -62
  71. package/dist/core/stat.js.map +1 -1
  72. package/dist/core/transaction.cjs +613 -650
  73. package/dist/core/transaction.cjs.map +1 -1
  74. package/dist/core/transaction.d.ts +165 -162
  75. package/dist/core/transaction.js +612 -648
  76. package/dist/core/transaction.js.map +1 -1
  77. package/dist/core/type_conversion.cjs +62 -83
  78. package/dist/core/type_conversion.cjs.map +1 -1
  79. package/dist/core/type_conversion.js +61 -81
  80. package/dist/core/type_conversion.js.map +1 -1
  81. package/dist/core/types.cjs +56 -86
  82. package/dist/core/types.cjs.map +1 -1
  83. package/dist/core/types.d.ts +63 -62
  84. package/dist/core/types.js +54 -83
  85. package/dist/core/types.js.map +1 -1
  86. package/dist/core/unauth_client.cjs +35 -41
  87. package/dist/core/unauth_client.cjs.map +1 -1
  88. package/dist/core/unauth_client.d.ts +18 -14
  89. package/dist/core/unauth_client.js +34 -39
  90. package/dist/core/unauth_client.js.map +1 -1
  91. package/dist/core/websocket_stream.cjs +280 -349
  92. package/dist/core/websocket_stream.cjs.map +1 -1
  93. package/dist/core/websocket_stream.js +278 -347
  94. package/dist/core/websocket_stream.js.map +1 -1
  95. package/dist/core/wire.d.ts +21 -17
  96. package/dist/helpers/pl.cjs +71 -73
  97. package/dist/helpers/pl.cjs.map +1 -1
  98. package/dist/helpers/pl.d.ts +40 -41
  99. package/dist/helpers/pl.js +66 -46
  100. package/dist/helpers/pl.js.map +1 -1
  101. package/dist/helpers/poll.cjs +99 -134
  102. package/dist/helpers/poll.cjs.map +1 -1
  103. package/dist/helpers/poll.d.ts +37 -34
  104. package/dist/helpers/poll.js +97 -113
  105. package/dist/helpers/poll.js.map +1 -1
  106. package/dist/helpers/retry_strategy.cjs +82 -87
  107. package/dist/helpers/retry_strategy.cjs.map +1 -1
  108. package/dist/helpers/retry_strategy.js +83 -86
  109. package/dist/helpers/retry_strategy.js.map +1 -1
  110. package/dist/helpers/tx_helpers.cjs +21 -20
  111. package/dist/helpers/tx_helpers.cjs.map +1 -1
  112. package/dist/helpers/tx_helpers.d.ts +11 -7
  113. package/dist/helpers/tx_helpers.js +20 -18
  114. package/dist/helpers/tx_helpers.js.map +1 -1
  115. package/dist/index.cjs +117 -106
  116. package/dist/index.d.ts +17 -17
  117. package/dist/index.js +17 -19
  118. package/dist/proto-grpc/github.com/googleapis/googleapis/google/rpc/status.cjs +72 -66
  119. package/dist/proto-grpc/github.com/googleapis/googleapis/google/rpc/status.cjs.map +1 -1
  120. package/dist/proto-grpc/github.com/googleapis/googleapis/google/rpc/status.d.ts +35 -37
  121. package/dist/proto-grpc/github.com/googleapis/googleapis/google/rpc/status.js +71 -64
  122. package/dist/proto-grpc/github.com/googleapis/googleapis/google/rpc/status.js.map +1 -1
  123. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.cjs +12611 -12866
  124. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.cjs.map +1 -1
  125. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client.cjs +226 -226
  126. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client.cjs.map +1 -1
  127. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client.d.ts +281 -330
  128. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client.js +225 -224
  129. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client.js.map +1 -1
  130. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.d.ts +2640 -4294
  131. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.js +12608 -12706
  132. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.js.map +1 -1
  133. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api_types.cjs +1230 -1089
  134. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api_types.cjs.map +1 -1
  135. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api_types.d.ts +393 -420
  136. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api_types.js +1228 -1083
  137. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api_types.js.map +1 -1
  138. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/base_types.cjs +142 -143
  139. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/base_types.cjs.map +1 -1
  140. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/base_types.d.ts +62 -64
  141. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/base_types.js +140 -141
  142. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/base_types.js.map +1 -1
  143. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/resource_types.cjs +572 -487
  144. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/resource_types.cjs.map +1 -1
  145. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/resource_types.d.ts +125 -228
  146. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/resource_types.js +572 -485
  147. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/resource_types.js.map +1 -1
  148. package/dist/proto-grpc/google/protobuf/any.cjs +131 -146
  149. package/dist/proto-grpc/google/protobuf/any.cjs.map +1 -1
  150. package/dist/proto-grpc/google/protobuf/any.d.ts +78 -84
  151. package/dist/proto-grpc/google/protobuf/any.js +130 -144
  152. package/dist/proto-grpc/google/protobuf/any.js.map +1 -1
  153. package/dist/proto-grpc/google/protobuf/duration.cjs +92 -100
  154. package/dist/proto-grpc/google/protobuf/duration.cjs.map +1 -1
  155. package/dist/proto-grpc/google/protobuf/duration.d.ts +38 -43
  156. package/dist/proto-grpc/google/protobuf/duration.js +91 -98
  157. package/dist/proto-grpc/google/protobuf/duration.js.map +1 -1
  158. package/dist/proto-grpc/google/protobuf/timestamp.cjs +117 -128
  159. package/dist/proto-grpc/google/protobuf/timestamp.cjs.map +1 -1
  160. package/dist/proto-grpc/google/protobuf/timestamp.d.ts +50 -55
  161. package/dist/proto-grpc/google/protobuf/timestamp.js +116 -126
  162. package/dist/proto-grpc/google/protobuf/timestamp.js.map +1 -1
  163. package/dist/proto-grpc/google/rpc/code.cjs +223 -238
  164. package/dist/proto-grpc/google/rpc/code.cjs.map +1 -1
  165. package/dist/proto-grpc/google/rpc/code.d.ts +209 -206
  166. package/dist/proto-grpc/google/rpc/code.js +221 -237
  167. package/dist/proto-grpc/google/rpc/code.js.map +1 -1
  168. package/dist/proto-rest/index.cjs +67 -66
  169. package/dist/proto-rest/index.cjs.map +1 -1
  170. package/dist/proto-rest/index.d.ts +24 -18
  171. package/dist/proto-rest/index.js +61 -65
  172. package/dist/proto-rest/index.js.map +1 -1
  173. package/dist/proto-rest/plapi.d.ts +1400 -1477
  174. package/dist/test/tcp-proxy.cjs +100 -126
  175. package/dist/test/tcp-proxy.cjs.map +1 -1
  176. package/dist/test/tcp-proxy.d.ts +17 -13
  177. package/dist/test/tcp-proxy.js +97 -104
  178. package/dist/test/tcp-proxy.js.map +1 -1
  179. package/dist/test/test_config.cjs +145 -194
  180. package/dist/test/test_config.cjs.map +1 -1
  181. package/dist/test/test_config.d.ts +34 -30
  182. package/dist/test/test_config.js +138 -166
  183. package/dist/test/test_config.js.map +1 -1
  184. package/dist/util/pl.cjs +4 -3
  185. package/dist/util/pl.cjs.map +1 -1
  186. package/dist/util/pl.js +4 -2
  187. package/dist/util/pl.js.map +1 -1
  188. package/dist/util/util.cjs +7 -10
  189. package/dist/util/util.cjs.map +1 -1
  190. package/dist/util/util.js +7 -9
  191. package/dist/util/util.js.map +1 -1
  192. package/package.json +8 -8
  193. package/src/core/errors.ts +1 -1
  194. package/src/core/transaction.ts +123 -133
  195. package/src/core/websocket_stream.ts +10 -1
  196. package/dist/__external/.pnpm/@rollup_plugin-typescript@12.3.0_rollup@4.52.4_tslib@2.8.1_typescript@5.6.3/__external/tslib/tslib.es6.cjs +0 -61
  197. package/dist/__external/.pnpm/@rollup_plugin-typescript@12.3.0_rollup@4.52.4_tslib@2.8.1_typescript@5.6.3/__external/tslib/tslib.es6.cjs.map +0 -1
  198. package/dist/__external/.pnpm/@rollup_plugin-typescript@12.3.0_rollup@4.52.4_tslib@2.8.1_typescript@5.6.3/__external/tslib/tslib.es6.js +0 -58
  199. package/dist/__external/.pnpm/@rollup_plugin-typescript@12.3.0_rollup@4.52.4_tslib@2.8.1_typescript@5.6.3/__external/tslib/tslib.es6.js.map +0 -1
  200. package/dist/core/PromiseTracker.d.ts.map +0 -1
  201. package/dist/core/StatefulPromise.d.ts +0 -39
  202. package/dist/core/StatefulPromise.d.ts.map +0 -1
  203. package/dist/core/abstract_stream.d.ts.map +0 -1
  204. package/dist/core/advisory_locks.d.ts +0 -10
  205. package/dist/core/advisory_locks.d.ts.map +0 -1
  206. package/dist/core/auth.d.ts.map +0 -1
  207. package/dist/core/cache.d.ts.map +0 -1
  208. package/dist/core/client.d.ts.map +0 -1
  209. package/dist/core/config.d.ts.map +0 -1
  210. package/dist/core/default_client.d.ts.map +0 -1
  211. package/dist/core/driver.d.ts.map +0 -1
  212. package/dist/core/error_resource.d.ts +0 -6
  213. package/dist/core/error_resource.d.ts.map +0 -1
  214. package/dist/core/errors.d.ts.map +0 -1
  215. package/dist/core/final.d.ts.map +0 -1
  216. package/dist/core/ll_client.d.ts.map +0 -1
  217. package/dist/core/ll_transaction.d.ts.map +0 -1
  218. package/dist/core/stat.d.ts.map +0 -1
  219. package/dist/core/transaction.d.ts.map +0 -1
  220. package/dist/core/type_conversion.d.ts +0 -8
  221. package/dist/core/type_conversion.d.ts.map +0 -1
  222. package/dist/core/types.d.ts.map +0 -1
  223. package/dist/core/unauth_client.d.ts.map +0 -1
  224. package/dist/core/websocket_stream.d.ts +0 -67
  225. package/dist/core/websocket_stream.d.ts.map +0 -1
  226. package/dist/core/wire.d.ts.map +0 -1
  227. package/dist/helpers/pl.d.ts.map +0 -1
  228. package/dist/helpers/poll.d.ts.map +0 -1
  229. package/dist/helpers/retry_strategy.d.ts +0 -24
  230. package/dist/helpers/retry_strategy.d.ts.map +0 -1
  231. package/dist/helpers/state_helpers.d.ts +0 -3
  232. package/dist/helpers/state_helpers.d.ts.map +0 -1
  233. package/dist/helpers/tx_helpers.d.ts.map +0 -1
  234. package/dist/index.cjs.map +0 -1
  235. package/dist/index.d.ts.map +0 -1
  236. package/dist/index.js.map +0 -1
  237. package/dist/proto-grpc/github.com/googleapis/googleapis/google/rpc/status.d.ts.map +0 -1
  238. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client.d.ts.map +0 -1
  239. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.d.ts.map +0 -1
  240. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api_types.d.ts.map +0 -1
  241. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/base_types.d.ts.map +0 -1
  242. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/import.d.ts +0 -106
  243. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/import.d.ts.map +0 -1
  244. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/resource_types.d.ts.map +0 -1
  245. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/ws-test.d.ts +0 -73
  246. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/ws-test.d.ts.map +0 -1
  247. package/dist/proto-grpc/google/api/http.d.ts +0 -456
  248. package/dist/proto-grpc/google/api/http.d.ts.map +0 -1
  249. package/dist/proto-grpc/google/protobuf/any.d.ts.map +0 -1
  250. package/dist/proto-grpc/google/protobuf/descriptor.d.ts +0 -2340
  251. package/dist/proto-grpc/google/protobuf/descriptor.d.ts.map +0 -1
  252. package/dist/proto-grpc/google/protobuf/duration.d.ts.map +0 -1
  253. package/dist/proto-grpc/google/protobuf/empty.d.ts +0 -32
  254. package/dist/proto-grpc/google/protobuf/empty.d.ts.map +0 -1
  255. package/dist/proto-grpc/google/protobuf/struct.d.ts +0 -187
  256. package/dist/proto-grpc/google/protobuf/struct.d.ts.map +0 -1
  257. package/dist/proto-grpc/google/protobuf/timestamp.d.ts.map +0 -1
  258. package/dist/proto-grpc/google/protobuf/wrappers.d.ts +0 -308
  259. package/dist/proto-grpc/google/protobuf/wrappers.d.ts.map +0 -1
  260. package/dist/proto-grpc/google/rpc/code.d.ts.map +0 -1
  261. package/dist/proto-grpc/google/rpc/error_details.d.ts +0 -654
  262. package/dist/proto-grpc/google/rpc/error_details.d.ts.map +0 -1
  263. package/dist/proto-grpc/google/rpc/http.d.ts +0 -121
  264. package/dist/proto-grpc/google/rpc/http.d.ts.map +0 -1
  265. package/dist/proto-grpc/google/rpc/status.d.ts +0 -55
  266. package/dist/proto-grpc/google/rpc/status.d.ts.map +0 -1
  267. package/dist/proto-rest/index.d.ts.map +0 -1
  268. package/dist/proto-rest/plapi.d.ts.map +0 -1
  269. package/dist/test/tcp-proxy.d.ts.map +0 -1
  270. package/dist/test/test_config.d.ts.map +0 -1
  271. package/dist/util/branding.d.ts +0 -7
  272. package/dist/util/branding.d.ts.map +0 -1
  273. package/dist/util/pl.d.ts +0 -9
  274. package/dist/util/pl.d.ts.map +0 -1
  275. package/dist/util/util.d.ts +0 -2
  276. package/dist/util/util.d.ts.map +0 -1
@@ -1,523 +1,419 @@
1
- import { PlatformClient } from '../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client.js';
2
- import { compressionAlgorithms, ChannelCredentials, InterceptingCall, status } from '@grpc/grpc-js';
3
- import { plAddressToConfig, SUPPORTED_WIRE_PROTOCOLS } from './config.js';
4
- import { GrpcTransport } from '@protobuf-ts/grpc-transport';
5
- import { LLPlTransaction } from './ll_transaction.js';
6
- import { parsePlJwt } from '../util/pl.js';
7
- import { interceptors } from 'undici';
8
- import { inferAuthRefreshTime } from './auth.js';
9
- import { defaultHttpDispatcher } from '@milaboratories/pl-http';
10
- import { parseHttpAuth } from '@milaboratories/pl-model-common';
11
- import { createClient, parseResponseError } from '../proto-rest/index.js';
12
- import { notEmpty, retry, withTimeout } from '@milaboratories/ts-helpers';
13
- import { Code } from '../proto-grpc/google/rpc/code.js';
14
- import { WebSocketBiDiStream } from './websocket_stream.js';
15
- import { TxAPI_ClientMessage, TxAPI_ServerMessage } from '../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.js';
16
- import { isAbortedError } from './errors.js';
1
+ import { TxAPI_ClientMessage, TxAPI_ServerMessage } from "../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.js";
2
+ import { Code } from "../proto-grpc/google/rpc/code.js";
3
+ import { isAbortedError } from "./errors.js";
4
+ import { SUPPORTED_WIRE_PROTOCOLS, plAddressToConfig } from "./config.js";
5
+ import { PlatformClient } from "../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client.js";
6
+ import { LLPlTransaction } from "./ll_transaction.js";
7
+ import { parsePlJwt } from "../util/pl.js";
8
+ import { inferAuthRefreshTime } from "./auth.js";
9
+ import { createClient, parseResponseError } from "../proto-rest/index.js";
10
+ import { WebSocketBiDiStream } from "./websocket_stream.js";
11
+ import { notEmpty, retry, withTimeout } from "@milaboratories/ts-helpers";
12
+ import { ChannelCredentials, InterceptingCall, compressionAlgorithms, status } from "@grpc/grpc-js";
13
+ import { GrpcTransport } from "@protobuf-ts/grpc-transport";
14
+ import { interceptors } from "undici";
15
+ import { defaultHttpDispatcher } from "@milaboratories/pl-http";
16
+ import { parseHttpAuth } from "@milaboratories/pl-model-common";
17
17
 
18
- class WireClientProviderImpl {
19
- wireOpts;
20
- clientConstructor;
21
- client = undefined;
22
- constructor(wireOpts, clientConstructor) {
23
- this.wireOpts = wireOpts;
24
- this.clientConstructor = clientConstructor;
25
- }
26
- reset() {
27
- this.client = undefined;
28
- }
29
- get() {
30
- if (this.client === undefined)
31
- this.client = this.clientConstructor(this.wireOpts());
32
- return this.client;
33
- }
34
- }
18
+ //#region src/core/ll_client.ts
19
+ var WireClientProviderImpl = class {
20
+ client = void 0;
21
+ constructor(wireOpts, clientConstructor) {
22
+ this.wireOpts = wireOpts;
23
+ this.clientConstructor = clientConstructor;
24
+ }
25
+ reset() {
26
+ this.client = void 0;
27
+ }
28
+ get() {
29
+ if (this.client === void 0) this.client = this.clientConstructor(this.wireOpts());
30
+ return this.client;
31
+ }
32
+ };
35
33
  /** Abstract out low level networking and authorization details */
36
- class LLPlClient {
37
- conf;
38
- ops;
39
- /** Initial authorization information */
40
- authInformation;
41
- /** Will be executed by the client when it is required */
42
- onAuthUpdate;
43
- /** Will be executed if auth-related error happens during normal client operation */
44
- onAuthError;
45
- /** Will be executed by the client when it is required */
46
- onAuthRefreshProblem;
47
- /** Threshold after which auth info refresh is required */
48
- refreshTimestamp;
49
- _status = "OK";
50
- statusListener;
51
- _wireProto = "grpc";
52
- _wireConn;
53
- _restInterceptors;
54
- _restMiddlewares;
55
- _grpcInterceptors;
56
- providers = [];
57
- clientProvider;
58
- httpDispatcher;
59
- static async build(configOrAddress, ops = {}) {
60
- const conf = typeof configOrAddress === "string" ? plAddressToConfig(configOrAddress) : configOrAddress;
61
- const pl = new LLPlClient(conf, ops);
62
- // FIXME(rfiskov)[MILAB-5275]: Investigate why autodetect randomly fails; temporary turn it off.
63
- if (ops.useAutoDetectWireProtocol) {
64
- await pl.detectOptimalWireProtocol();
65
- }
66
- return pl;
67
- }
68
- constructor(conf, ops = {}) {
69
- this.conf = conf;
70
- this.ops = ops;
71
- const { auth, statusListener } = ops;
72
- if (auth !== undefined) {
73
- this.refreshTimestamp = inferAuthRefreshTime(auth.authInformation, this.conf.authMaxRefreshSeconds);
74
- this.authInformation = auth.authInformation;
75
- this.onAuthUpdate = auth.onUpdate;
76
- this.onAuthRefreshProblem = auth.onUpdateError;
77
- this.onAuthError = auth.onAuthError;
78
- }
79
- this._restInterceptors = [];
80
- this._restMiddlewares = [];
81
- this._grpcInterceptors = [];
82
- if (auth !== undefined) {
83
- this._restInterceptors.push(this.createRestAuthInterceptor());
84
- this._grpcInterceptors.push(this.createGrpcAuthInterceptor());
85
- }
86
- this._restInterceptors.push(interceptors.retry({ statusCodes: [] })); // Handle errors with openapi-fetch middleware.
87
- this._restMiddlewares.push(this.createRestErrorMiddleware());
88
- this._grpcInterceptors.push(this.createGrpcErrorInterceptor());
89
- this.httpDispatcher = defaultHttpDispatcher(this.conf.httpProxy);
90
- if (this.conf.wireProtocol) {
91
- this._wireProto = this.conf.wireProtocol;
92
- }
93
- this.initWireConnection(this._wireProto);
94
- if (statusListener !== undefined) {
95
- this.statusListener = statusListener;
96
- statusListener(this._status);
97
- }
98
- this.clientProvider = this.createWireClientProvider((wireConn) => {
99
- if (wireConn.type === "grpc") {
100
- return new PlatformClient(wireConn.Transport);
101
- }
102
- else {
103
- return createClient({
104
- hostAndPort: wireConn.Config.hostAndPort,
105
- ssl: wireConn.Config.ssl,
106
- dispatcher: wireConn.Dispatcher,
107
- middlewares: wireConn.Middlewares,
108
- });
109
- }
110
- });
111
- }
112
- initWireConnection(protocol) {
113
- switch (protocol) {
114
- case "rest":
115
- this.initRestConnection();
116
- return;
117
- case "grpc":
118
- this.initGrpcConnection(this.ops.shouldUseGzip ?? false);
119
- return;
120
- default:
121
- ((v) => {
122
- throw new Error(`Unsupported wire protocol '${v}'. Use one of: ${SUPPORTED_WIRE_PROTOCOLS.join(", ")}`);
123
- })(protocol);
124
- }
125
- }
126
- initRestConnection() {
127
- const dispatcher = defaultHttpDispatcher(this.conf.grpcProxy, this._restInterceptors);
128
- this._replaceWireConnection({
129
- type: "rest",
130
- Config: this.conf,
131
- Dispatcher: dispatcher,
132
- Middlewares: this._restMiddlewares,
133
- });
134
- }
135
- /**
136
- * Initializes (or reinitializes) _grpcTransport
137
- * @param gzip - whether to enable gzip compression
138
- */
139
- initGrpcConnection(gzip) {
140
- const clientOptions = {
141
- "grpc.keepalive_time_ms": 30_000, // 30 seconds
142
- "grpc.service_config_disable_resolution": 1, // Disable DNS TXT lookups for service config
143
- interceptors: this._grpcInterceptors,
144
- };
145
- if (gzip)
146
- clientOptions["grpc.default_compression_algorithm"] = compressionAlgorithms.gzip;
147
- //
148
- // Leaving it here for now
149
- // https://github.com/grpc/grpc-node/issues/2788
150
- //
151
- // We should implement message pooling algorithm to overcome hardcoded NO_DELAY behaviour
152
- // of HTTP/2 and allow our small messages to batch together.
153
- //
154
- const grpcOptions = {
155
- host: this.conf.hostAndPort,
156
- timeout: this.conf.defaultRequestTimeout,
157
- channelCredentials: this.conf.ssl
158
- ? ChannelCredentials.createSsl()
159
- : ChannelCredentials.createInsecure(),
160
- clientOptions,
161
- };
162
- const grpcProxy = typeof this.conf.grpcProxy === "string" ? { url: this.conf.grpcProxy } : this.conf.grpcProxy;
163
- if (grpcProxy?.url) {
164
- const url = new URL(grpcProxy.url);
165
- if (grpcProxy.auth) {
166
- const parsed = parseHttpAuth(grpcProxy.auth);
167
- if (parsed.scheme !== "Basic") {
168
- throw new Error(`Unsupported auth scheme: ${parsed.scheme}.`);
169
- }
170
- url.username = parsed.username;
171
- url.password = parsed.password;
172
- }
173
- process.env.grpc_proxy = url.toString();
174
- }
175
- else {
176
- delete process.env.grpc_proxy;
177
- }
178
- this._replaceWireConnection({ type: "grpc", Transport: new GrpcTransport(grpcOptions) });
179
- }
180
- _replaceWireConnection(newConn) {
181
- const oldConn = this._wireConn;
182
- this._wireConn = newConn;
183
- this._wireProto = newConn.type;
184
- // Reset all providers to let them reinitialize their clients
185
- for (let i = 0; i < this.providers.length; i++) {
186
- const provider = this.providers[i].deref();
187
- if (provider === undefined) {
188
- // at the same time we need to remove providers that are no longer valid
189
- this.providers.splice(i, 1);
190
- i--;
191
- }
192
- else {
193
- provider.reset();
194
- }
195
- }
196
- if (oldConn !== undefined && oldConn.type === "grpc")
197
- oldConn.Transport.close();
198
- }
199
- providerCleanupCounter = 0;
200
- /**
201
- * Creates a provider for a grpc client. Returned provider will create fresh client whenever the underlying transport is reset.
202
- *
203
- * @param clientConstructor - a factory function that creates a grpc client
204
- */
205
- createWireClientProvider(clientConstructor) {
206
- // We need to cleanup providers periodically to avoid memory leaks.
207
- // This is a simple heuristic to avoid memory leaks.
208
- // We could use a more sophisticated algorithm, but this is good enough for now.
209
- this.providerCleanupCounter++;
210
- if (this.providerCleanupCounter >= 16) {
211
- for (let i = 0; i < this.providers.length; i++) {
212
- const provider = this.providers[i].deref();
213
- if (provider === undefined) {
214
- this.providers.splice(i, 1);
215
- i--;
216
- }
217
- }
218
- this.providerCleanupCounter = 0;
219
- }
220
- const provider = new WireClientProviderImpl(() => this._wireConn, clientConstructor);
221
- this.providers.push(new WeakRef(provider));
222
- return provider;
223
- }
224
- get wireConnection() {
225
- return this._wireConn;
226
- }
227
- get wireProtocol() {
228
- return this._wireProto;
229
- }
230
- /** Returns true if client is authenticated. Even with anonymous auth information
231
- * connection is considered authenticated. Unauthenticated clients are used for
232
- * login and similar tasks, see {@link UnauthenticatedPlClient}. */
233
- get authenticated() {
234
- return this.authInformation !== undefined;
235
- }
236
- /** null means anonymous connection */
237
- get authUser() {
238
- if (!this.authenticated)
239
- throw new Error("Client is not authenticated");
240
- if (this.authInformation?.jwtToken)
241
- return parsePlJwt(this.authInformation?.jwtToken).user.login;
242
- else
243
- return null;
244
- }
245
- updateStatus(newStatus) {
246
- process.nextTick(() => {
247
- if (this._status !== newStatus) {
248
- this._status = newStatus;
249
- if (this.statusListener !== undefined)
250
- this.statusListener(this._status);
251
- if (newStatus === "Unauthenticated" && this.onAuthError !== undefined)
252
- this.onAuthError();
253
- }
254
- });
255
- }
256
- get status() {
257
- return this._status;
258
- }
259
- authRefreshInProgress = false;
260
- refreshAuthInformationIfNeeded() {
261
- if (this.refreshTimestamp === undefined ||
262
- Date.now() < this.refreshTimestamp ||
263
- this.authRefreshInProgress ||
264
- this._status === "Unauthenticated")
265
- return;
266
- // Running refresh in background`
267
- this.authRefreshInProgress = true;
268
- void (async () => {
269
- try {
270
- const token = await this.getJwtToken(BigInt(this.conf.authTTLSeconds));
271
- this.authInformation = { jwtToken: token };
272
- this.refreshTimestamp = inferAuthRefreshTime(this.authInformation, this.conf.authMaxRefreshSeconds);
273
- if (this.onAuthUpdate)
274
- this.onAuthUpdate(this.authInformation);
275
- }
276
- catch (e) {
277
- if (this.onAuthRefreshProblem)
278
- this.onAuthRefreshProblem(e);
279
- }
280
- finally {
281
- this.authRefreshInProgress = false;
282
- }
283
- })();
284
- }
285
- /**
286
- * Creates middleware that parses error responses and handles them centrally.
287
- * This middleware runs before openapi-fetch parses the response, so we need to
288
- * manually parse the response body for error responses.
289
- */
290
- createRestErrorMiddleware() {
291
- return {
292
- onResponse: async ({ request: _request, response, options: _options }) => {
293
- const { body, ...resOptions } = response;
294
- if ([502, 503, 504].includes(response.status)) {
295
- // Service unavailable, bad gateway, gateway timeout
296
- this.updateStatus("Disconnected");
297
- return new Response(body, { ...resOptions, status: response.status });
298
- }
299
- const respErr = await parseResponseError(response);
300
- if (!respErr.error) {
301
- // No error: nice!
302
- return new Response(respErr.origBody ?? body, { ...resOptions, status: response.status });
303
- }
304
- if (typeof respErr.error === "string") {
305
- // Non-standard error or normal response: let later middleware to deal wit it.
306
- return new Response(respErr.error, { ...resOptions, status: response.status });
307
- }
308
- if (respErr.error.code === Code.UNAUTHENTICATED) {
309
- this.updateStatus("Unauthenticated");
310
- }
311
- // Let later middleware to deal with standard gRPC error.
312
- return new Response(respErr.origBody, { ...resOptions, status: response.status });
313
- },
314
- };
315
- }
316
- /** Detects certain errors and update client status accordingly when using GRPC wire connection */
317
- createGrpcErrorInterceptor() {
318
- return (options, nextCall) => {
319
- return new InterceptingCall(nextCall(options), {
320
- start: (metadata, listener, next) => {
321
- next(metadata, {
322
- onReceiveStatus: (status$1, next) => {
323
- if (status$1.code == status.UNAUTHENTICATED)
324
- // (!!!) don't change to "==="
325
- this.updateStatus("Unauthenticated");
326
- if (status$1.code == status.UNAVAILABLE)
327
- // (!!!) don't change to "==="
328
- this.updateStatus("Disconnected");
329
- next(status$1);
330
- },
331
- });
332
- },
333
- });
334
- };
335
- }
336
- createRestAuthInterceptor() {
337
- return (dispatch) => {
338
- return (options, handler) => {
339
- if (this.authInformation?.jwtToken !== undefined) {
340
- // TODO: check this magic really works and gets called
341
- options.headers = {
342
- ...options.headers,
343
- authorization: "Bearer " + this.authInformation.jwtToken,
344
- };
345
- this.refreshAuthInformationIfNeeded();
346
- }
347
- return dispatch(options, handler);
348
- };
349
- };
350
- }
351
- /** Injects authentication information if needed */
352
- createGrpcAuthInterceptor() {
353
- return (options, nextCall) => {
354
- return new InterceptingCall(nextCall(options), {
355
- start: (metadata, listener, next) => {
356
- if (this.authInformation?.jwtToken !== undefined) {
357
- metadata.set("authorization", "Bearer " + this.authInformation.jwtToken);
358
- this.refreshAuthInformationIfNeeded();
359
- next(metadata, listener);
360
- }
361
- else {
362
- next(metadata, listener);
363
- }
364
- },
365
- });
366
- };
367
- }
368
- async getJwtToken(ttlSeconds, options) {
369
- const cl = this.clientProvider.get();
370
- if (cl instanceof PlatformClient) {
371
- const meta = {};
372
- if (options?.authorization)
373
- meta.authorization = options.authorization;
374
- return (await cl.getJWTToken({ expiration: { seconds: ttlSeconds, nanos: 0 } }, { meta }).response).token;
375
- }
376
- else {
377
- const headers = {};
378
- if (options?.authorization)
379
- headers.authorization = options.authorization;
380
- const resp = cl.POST("/v1/auth/jwt-token", {
381
- body: { expiration: `${ttlSeconds}s` },
382
- headers,
383
- });
384
- return notEmpty((await resp).data, "REST: empty response for JWT token request").token;
385
- }
386
- }
387
- async ping() {
388
- const cl = this.clientProvider.get();
389
- if (cl instanceof PlatformClient) {
390
- return (await cl.ping({})).response;
391
- }
392
- else {
393
- return notEmpty((await cl.GET("/v1/ping")).data, "REST: empty response for ping request");
394
- }
395
- }
396
- /**
397
- * Detects the best available wire protocol.
398
- * If wireProtocol is explicitly configured, does nothing.
399
- * Otherwise probes the current protocol via ping; if it fails, switches to the alternative.
400
- */
401
- async detectOptimalWireProtocol() {
402
- if (this.conf.wireProtocol) {
403
- return;
404
- }
405
- // Each retry is:
406
- // - ping request timeout (100 to 3_000ms)
407
- // - backoff delay (30 to 500ms)
408
- //
409
- // 30 attempts are ~43 seconds of overall waiting time.
410
- // Think twice on overall time this thing takes to complete when changing these parameters.
411
- // It may block UI when connecting to the server and loading projects list.
412
- const pingTimeoutFactor = 1.3;
413
- const maxPingTimeoutMs = 3_000;
414
- const retryOptions = {
415
- type: "exponentialBackoff",
416
- maxAttempts: 30,
417
- initialDelay: 30,
418
- backoffMultiplier: 1.3,
419
- jitter: 0.2,
420
- maxDelay: 500,
421
- };
422
- let attempt = 1;
423
- let pingTimeoutMs = 100;
424
- await retry(() => withTimeout(this.ping(), pingTimeoutMs), retryOptions, (e) => {
425
- if (isAbortedError(e)) {
426
- this.ops.logger?.info(`Wire proto autodetect: ping timed out after ${pingTimeoutMs}ms: attempt=${attempt}, wire=${this._wireProto}`);
427
- if (attempt % 2 === 0) {
428
- // We have 2 wire protocols to check. Increase timeout each 2 attempts.
429
- pingTimeoutMs = Math.min(Math.round(pingTimeoutMs * pingTimeoutFactor), maxPingTimeoutMs);
430
- }
431
- }
432
- else {
433
- this.ops.logger?.info(`Wire proto autodetect: ping failed: attempt=${attempt}, wire=${this._wireProto}, err=${String(e)}`);
434
- }
435
- attempt++;
436
- const protocol = this._wireProto === "grpc" ? "rest" : "grpc";
437
- this.ops.logger?.info(`Wire protocol autodetect next attempt: will try wire '${protocol}' with timeout ${pingTimeoutMs}ms`);
438
- this.initWireConnection(protocol);
439
- return true;
440
- });
441
- }
442
- async license() {
443
- const cl = this.clientProvider.get();
444
- if (cl instanceof PlatformClient) {
445
- return (await cl.license({})).response;
446
- }
447
- else {
448
- const resp = notEmpty((await cl.GET("/v1/license")).data, "REST: empty response for license request");
449
- return {
450
- status: resp.status,
451
- isOk: resp.isOk,
452
- responseBody: Uint8Array.from(Buffer.from(resp.responseBody)),
453
- };
454
- }
455
- }
456
- async authMethods() {
457
- const cl = this.clientProvider.get();
458
- if (cl instanceof PlatformClient) {
459
- return (await cl.authMethods({})).response;
460
- }
461
- else {
462
- return notEmpty((await cl.GET("/v1/auth/methods")).data, "REST: empty response for auth methods request");
463
- }
464
- }
465
- async txSync(txId) {
466
- const cl = this.clientProvider.get();
467
- if (cl instanceof PlatformClient) {
468
- await cl.txSync({ txId: BigInt(txId) });
469
- }
470
- else {
471
- await cl.POST("/v1/tx-sync", { body: { txId: txId.toString() } });
472
- }
473
- }
474
- createTx(rw, ops = {}) {
475
- return new LLPlTransaction((abortSignal) => {
476
- let totalAbortSignal = abortSignal;
477
- if (ops.abortSignal)
478
- totalAbortSignal = AbortSignal.any([totalAbortSignal, ops.abortSignal]);
479
- const timeout = ops.timeout ??
480
- (rw ? this.conf.defaultRWTransactionTimeout : this.conf.defaultROTransactionTimeout);
481
- const cl = this.clientProvider.get();
482
- if (cl instanceof PlatformClient) {
483
- return cl.tx({
484
- abort: totalAbortSignal,
485
- timeout,
486
- });
487
- }
488
- const wireConn = this.wireConnection;
489
- if (wireConn.type === "rest") {
490
- // For REST/WebSocket protocol, timeout needs to be converted to AbortSignal
491
- if (timeout !== undefined) {
492
- totalAbortSignal = AbortSignal.any([totalAbortSignal, AbortSignal.timeout(timeout)]);
493
- }
494
- // The gRPC transport has the auth interceptor that already handles it, but here we need to refresh the auth information to be safe.
495
- this.refreshAuthInformationIfNeeded();
496
- const wsUrl = this.conf.ssl
497
- ? `wss://${this.conf.hostAndPort}/v1/ws/tx`
498
- : `ws://${this.conf.hostAndPort}/v1/ws/tx`;
499
- return new WebSocketBiDiStream(wsUrl, (msg) => TxAPI_ClientMessage.toBinary(msg), (data) => TxAPI_ServerMessage.fromBinary(new Uint8Array(data)), {
500
- abortSignal: totalAbortSignal,
501
- jwtToken: this.authInformation?.jwtToken,
502
- dispatcher: wireConn.Dispatcher,
503
- onComplete: async (stream) => stream.requests.send({
504
- // Ask server to gracefully close the stream on its side, if not done yet.
505
- requestId: 0,
506
- request: { oneofKind: "streamClose", streamClose: {} },
507
- }),
508
- });
509
- }
510
- throw new Error(`transactions are not supported for wire protocol ${this._wireProto}`);
511
- });
512
- }
513
- /** Closes underlying transport */
514
- async close() {
515
- if (this.wireConnection.type === "grpc") {
516
- this.wireConnection.Transport.close();
517
- }
518
- await this.httpDispatcher.destroy();
519
- }
520
- }
34
+ var LLPlClient = class LLPlClient {
35
+ /** Initial authorization information */
36
+ authInformation;
37
+ /** Will be executed by the client when it is required */
38
+ onAuthUpdate;
39
+ /** Will be executed if auth-related error happens during normal client operation */
40
+ onAuthError;
41
+ /** Will be executed by the client when it is required */
42
+ onAuthRefreshProblem;
43
+ /** Threshold after which auth info refresh is required */
44
+ refreshTimestamp;
45
+ _status = "OK";
46
+ statusListener;
47
+ _wireProto = "grpc";
48
+ _wireConn;
49
+ _restInterceptors;
50
+ _restMiddlewares;
51
+ _grpcInterceptors;
52
+ providers = [];
53
+ clientProvider;
54
+ httpDispatcher;
55
+ static async build(configOrAddress, ops = {}) {
56
+ const pl = new LLPlClient(typeof configOrAddress === "string" ? plAddressToConfig(configOrAddress) : configOrAddress, ops);
57
+ if (ops.useAutoDetectWireProtocol) await pl.detectOptimalWireProtocol();
58
+ return pl;
59
+ }
60
+ constructor(conf, ops = {}) {
61
+ this.conf = conf;
62
+ this.ops = ops;
63
+ const { auth, statusListener } = ops;
64
+ if (auth !== void 0) {
65
+ this.refreshTimestamp = inferAuthRefreshTime(auth.authInformation, this.conf.authMaxRefreshSeconds);
66
+ this.authInformation = auth.authInformation;
67
+ this.onAuthUpdate = auth.onUpdate;
68
+ this.onAuthRefreshProblem = auth.onUpdateError;
69
+ this.onAuthError = auth.onAuthError;
70
+ }
71
+ this._restInterceptors = [];
72
+ this._restMiddlewares = [];
73
+ this._grpcInterceptors = [];
74
+ if (auth !== void 0) {
75
+ this._restInterceptors.push(this.createRestAuthInterceptor());
76
+ this._grpcInterceptors.push(this.createGrpcAuthInterceptor());
77
+ }
78
+ this._restInterceptors.push(interceptors.retry({ statusCodes: [] }));
79
+ this._restMiddlewares.push(this.createRestErrorMiddleware());
80
+ this._grpcInterceptors.push(this.createGrpcErrorInterceptor());
81
+ this.httpDispatcher = defaultHttpDispatcher(this.conf.httpProxy);
82
+ if (this.conf.wireProtocol) this._wireProto = this.conf.wireProtocol;
83
+ this.initWireConnection(this._wireProto);
84
+ if (statusListener !== void 0) {
85
+ this.statusListener = statusListener;
86
+ statusListener(this._status);
87
+ }
88
+ this.clientProvider = this.createWireClientProvider((wireConn) => {
89
+ if (wireConn.type === "grpc") return new PlatformClient(wireConn.Transport);
90
+ else return createClient({
91
+ hostAndPort: wireConn.Config.hostAndPort,
92
+ ssl: wireConn.Config.ssl,
93
+ dispatcher: wireConn.Dispatcher,
94
+ middlewares: wireConn.Middlewares
95
+ });
96
+ });
97
+ }
98
+ initWireConnection(protocol) {
99
+ switch (protocol) {
100
+ case "rest":
101
+ this.initRestConnection();
102
+ return;
103
+ case "grpc":
104
+ this.initGrpcConnection(this.ops.shouldUseGzip ?? false);
105
+ return;
106
+ default: ((v) => {
107
+ throw new Error(`Unsupported wire protocol '${v}'. Use one of: ${SUPPORTED_WIRE_PROTOCOLS.join(", ")}`);
108
+ })(protocol);
109
+ }
110
+ }
111
+ initRestConnection() {
112
+ const dispatcher = defaultHttpDispatcher(this.conf.grpcProxy, this._restInterceptors);
113
+ this._replaceWireConnection({
114
+ type: "rest",
115
+ Config: this.conf,
116
+ Dispatcher: dispatcher,
117
+ Middlewares: this._restMiddlewares
118
+ });
119
+ }
120
+ /**
121
+ * Initializes (or reinitializes) _grpcTransport
122
+ * @param gzip - whether to enable gzip compression
123
+ */
124
+ initGrpcConnection(gzip) {
125
+ const clientOptions = {
126
+ "grpc.keepalive_time_ms": 3e4,
127
+ "grpc.service_config_disable_resolution": 1,
128
+ interceptors: this._grpcInterceptors
129
+ };
130
+ if (gzip) clientOptions["grpc.default_compression_algorithm"] = compressionAlgorithms.gzip;
131
+ const grpcOptions = {
132
+ host: this.conf.hostAndPort,
133
+ timeout: this.conf.defaultRequestTimeout,
134
+ channelCredentials: this.conf.ssl ? ChannelCredentials.createSsl() : ChannelCredentials.createInsecure(),
135
+ clientOptions
136
+ };
137
+ const grpcProxy = typeof this.conf.grpcProxy === "string" ? { url: this.conf.grpcProxy } : this.conf.grpcProxy;
138
+ if (grpcProxy?.url) {
139
+ const url = new URL(grpcProxy.url);
140
+ if (grpcProxy.auth) {
141
+ const parsed = parseHttpAuth(grpcProxy.auth);
142
+ if (parsed.scheme !== "Basic") throw new Error(`Unsupported auth scheme: ${parsed.scheme}.`);
143
+ url.username = parsed.username;
144
+ url.password = parsed.password;
145
+ }
146
+ process.env.grpc_proxy = url.toString();
147
+ } else delete process.env.grpc_proxy;
148
+ this._replaceWireConnection({
149
+ type: "grpc",
150
+ Transport: new GrpcTransport(grpcOptions)
151
+ });
152
+ }
153
+ _replaceWireConnection(newConn) {
154
+ const oldConn = this._wireConn;
155
+ this._wireConn = newConn;
156
+ this._wireProto = newConn.type;
157
+ for (let i = 0; i < this.providers.length; i++) {
158
+ const provider = this.providers[i].deref();
159
+ if (provider === void 0) {
160
+ this.providers.splice(i, 1);
161
+ i--;
162
+ } else provider.reset();
163
+ }
164
+ if (oldConn !== void 0 && oldConn.type === "grpc") oldConn.Transport.close();
165
+ }
166
+ providerCleanupCounter = 0;
167
+ /**
168
+ * Creates a provider for a grpc client. Returned provider will create fresh client whenever the underlying transport is reset.
169
+ *
170
+ * @param clientConstructor - a factory function that creates a grpc client
171
+ */
172
+ createWireClientProvider(clientConstructor) {
173
+ this.providerCleanupCounter++;
174
+ if (this.providerCleanupCounter >= 16) {
175
+ for (let i = 0; i < this.providers.length; i++) if (this.providers[i].deref() === void 0) {
176
+ this.providers.splice(i, 1);
177
+ i--;
178
+ }
179
+ this.providerCleanupCounter = 0;
180
+ }
181
+ const provider = new WireClientProviderImpl(() => this._wireConn, clientConstructor);
182
+ this.providers.push(new WeakRef(provider));
183
+ return provider;
184
+ }
185
+ get wireConnection() {
186
+ return this._wireConn;
187
+ }
188
+ get wireProtocol() {
189
+ return this._wireProto;
190
+ }
191
+ /** Returns true if client is authenticated. Even with anonymous auth information
192
+ * connection is considered authenticated. Unauthenticated clients are used for
193
+ * login and similar tasks, see {@link UnauthenticatedPlClient}. */
194
+ get authenticated() {
195
+ return this.authInformation !== void 0;
196
+ }
197
+ /** null means anonymous connection */
198
+ get authUser() {
199
+ if (!this.authenticated) throw new Error("Client is not authenticated");
200
+ if (this.authInformation?.jwtToken) return parsePlJwt(this.authInformation?.jwtToken).user.login;
201
+ else return null;
202
+ }
203
+ updateStatus(newStatus) {
204
+ process.nextTick(() => {
205
+ if (this._status !== newStatus) {
206
+ this._status = newStatus;
207
+ if (this.statusListener !== void 0) this.statusListener(this._status);
208
+ if (newStatus === "Unauthenticated" && this.onAuthError !== void 0) this.onAuthError();
209
+ }
210
+ });
211
+ }
212
+ get status() {
213
+ return this._status;
214
+ }
215
+ authRefreshInProgress = false;
216
+ refreshAuthInformationIfNeeded() {
217
+ if (this.refreshTimestamp === void 0 || Date.now() < this.refreshTimestamp || this.authRefreshInProgress || this._status === "Unauthenticated") return;
218
+ this.authRefreshInProgress = true;
219
+ (async () => {
220
+ try {
221
+ this.authInformation = { jwtToken: await this.getJwtToken(BigInt(this.conf.authTTLSeconds)) };
222
+ this.refreshTimestamp = inferAuthRefreshTime(this.authInformation, this.conf.authMaxRefreshSeconds);
223
+ if (this.onAuthUpdate) this.onAuthUpdate(this.authInformation);
224
+ } catch (e) {
225
+ if (this.onAuthRefreshProblem) this.onAuthRefreshProblem(e);
226
+ } finally {
227
+ this.authRefreshInProgress = false;
228
+ }
229
+ })();
230
+ }
231
+ /**
232
+ * Creates middleware that parses error responses and handles them centrally.
233
+ * This middleware runs before openapi-fetch parses the response, so we need to
234
+ * manually parse the response body for error responses.
235
+ */
236
+ createRestErrorMiddleware() {
237
+ return { onResponse: async ({ request: _request, response, options: _options }) => {
238
+ const { body, ...resOptions } = response;
239
+ if ([
240
+ 502,
241
+ 503,
242
+ 504
243
+ ].includes(response.status)) {
244
+ this.updateStatus("Disconnected");
245
+ return new Response(body, {
246
+ ...resOptions,
247
+ status: response.status
248
+ });
249
+ }
250
+ const respErr = await parseResponseError(response);
251
+ if (!respErr.error) return new Response(respErr.origBody ?? body, {
252
+ ...resOptions,
253
+ status: response.status
254
+ });
255
+ if (typeof respErr.error === "string") return new Response(respErr.error, {
256
+ ...resOptions,
257
+ status: response.status
258
+ });
259
+ if (respErr.error.code === Code.UNAUTHENTICATED) this.updateStatus("Unauthenticated");
260
+ return new Response(respErr.origBody, {
261
+ ...resOptions,
262
+ status: response.status
263
+ });
264
+ } };
265
+ }
266
+ /** Detects certain errors and update client status accordingly when using GRPC wire connection */
267
+ createGrpcErrorInterceptor() {
268
+ return (options, nextCall) => {
269
+ return new InterceptingCall(nextCall(options), { start: (metadata, listener, next) => {
270
+ next(metadata, { onReceiveStatus: (status$1, next) => {
271
+ if (status$1.code == status.UNAUTHENTICATED) this.updateStatus("Unauthenticated");
272
+ if (status$1.code == status.UNAVAILABLE) this.updateStatus("Disconnected");
273
+ next(status$1);
274
+ } });
275
+ } });
276
+ };
277
+ }
278
+ createRestAuthInterceptor() {
279
+ return (dispatch) => {
280
+ return (options, handler) => {
281
+ if (this.authInformation?.jwtToken !== void 0) {
282
+ options.headers = {
283
+ ...options.headers,
284
+ authorization: "Bearer " + this.authInformation.jwtToken
285
+ };
286
+ this.refreshAuthInformationIfNeeded();
287
+ }
288
+ return dispatch(options, handler);
289
+ };
290
+ };
291
+ }
292
+ /** Injects authentication information if needed */
293
+ createGrpcAuthInterceptor() {
294
+ return (options, nextCall) => {
295
+ return new InterceptingCall(nextCall(options), { start: (metadata, listener, next) => {
296
+ if (this.authInformation?.jwtToken !== void 0) {
297
+ metadata.set("authorization", "Bearer " + this.authInformation.jwtToken);
298
+ this.refreshAuthInformationIfNeeded();
299
+ next(metadata, listener);
300
+ } else next(metadata, listener);
301
+ } });
302
+ };
303
+ }
304
+ async getJwtToken(ttlSeconds, options) {
305
+ const cl = this.clientProvider.get();
306
+ if (cl instanceof PlatformClient) {
307
+ const meta = {};
308
+ if (options?.authorization) meta.authorization = options.authorization;
309
+ return (await cl.getJWTToken({ expiration: {
310
+ seconds: ttlSeconds,
311
+ nanos: 0
312
+ } }, { meta }).response).token;
313
+ } else {
314
+ const headers = {};
315
+ if (options?.authorization) headers.authorization = options.authorization;
316
+ return notEmpty((await cl.POST("/v1/auth/jwt-token", {
317
+ body: { expiration: `${ttlSeconds}s` },
318
+ headers
319
+ })).data, "REST: empty response for JWT token request").token;
320
+ }
321
+ }
322
+ async ping() {
323
+ const cl = this.clientProvider.get();
324
+ if (cl instanceof PlatformClient) return (await cl.ping({})).response;
325
+ else return notEmpty((await cl.GET("/v1/ping")).data, "REST: empty response for ping request");
326
+ }
327
+ /**
328
+ * Detects the best available wire protocol.
329
+ * If wireProtocol is explicitly configured, does nothing.
330
+ * Otherwise probes the current protocol via ping; if it fails, switches to the alternative.
331
+ */
332
+ async detectOptimalWireProtocol() {
333
+ if (this.conf.wireProtocol) return;
334
+ const pingTimeoutFactor = 1.3;
335
+ const maxPingTimeoutMs = 3e3;
336
+ const retryOptions = {
337
+ type: "exponentialBackoff",
338
+ maxAttempts: 30,
339
+ initialDelay: 30,
340
+ backoffMultiplier: 1.3,
341
+ jitter: .2,
342
+ maxDelay: 500
343
+ };
344
+ let attempt = 1;
345
+ let pingTimeoutMs = 100;
346
+ await retry(() => withTimeout(this.ping(), pingTimeoutMs), retryOptions, (e) => {
347
+ if (isAbortedError(e)) {
348
+ this.ops.logger?.info(`Wire proto autodetect: ping timed out after ${pingTimeoutMs}ms: attempt=${attempt}, wire=${this._wireProto}`);
349
+ if (attempt % 2 === 0) pingTimeoutMs = Math.min(Math.round(pingTimeoutMs * pingTimeoutFactor), maxPingTimeoutMs);
350
+ } else this.ops.logger?.info(`Wire proto autodetect: ping failed: attempt=${attempt}, wire=${this._wireProto}, err=${String(e)}`);
351
+ attempt++;
352
+ const protocol = this._wireProto === "grpc" ? "rest" : "grpc";
353
+ this.ops.logger?.info(`Wire protocol autodetect next attempt: will try wire '${protocol}' with timeout ${pingTimeoutMs}ms`);
354
+ this.initWireConnection(protocol);
355
+ return true;
356
+ });
357
+ }
358
+ async license() {
359
+ const cl = this.clientProvider.get();
360
+ if (cl instanceof PlatformClient) return (await cl.license({})).response;
361
+ else {
362
+ const resp = notEmpty((await cl.GET("/v1/license")).data, "REST: empty response for license request");
363
+ return {
364
+ status: resp.status,
365
+ isOk: resp.isOk,
366
+ responseBody: Uint8Array.from(Buffer.from(resp.responseBody))
367
+ };
368
+ }
369
+ }
370
+ async authMethods() {
371
+ const cl = this.clientProvider.get();
372
+ if (cl instanceof PlatformClient) return (await cl.authMethods({})).response;
373
+ else return notEmpty((await cl.GET("/v1/auth/methods")).data, "REST: empty response for auth methods request");
374
+ }
375
+ async txSync(txId) {
376
+ const cl = this.clientProvider.get();
377
+ if (cl instanceof PlatformClient) await cl.txSync({ txId: BigInt(txId) });
378
+ else await cl.POST("/v1/tx-sync", { body: { txId: txId.toString() } });
379
+ }
380
+ createTx(rw, ops = {}) {
381
+ return new LLPlTransaction((abortSignal) => {
382
+ let totalAbortSignal = abortSignal;
383
+ if (ops.abortSignal) totalAbortSignal = AbortSignal.any([totalAbortSignal, ops.abortSignal]);
384
+ const timeout = ops.timeout ?? (rw ? this.conf.defaultRWTransactionTimeout : this.conf.defaultROTransactionTimeout);
385
+ const cl = this.clientProvider.get();
386
+ if (cl instanceof PlatformClient) return cl.tx({
387
+ abort: totalAbortSignal,
388
+ timeout
389
+ });
390
+ const wireConn = this.wireConnection;
391
+ if (wireConn.type === "rest") {
392
+ if (timeout !== void 0) totalAbortSignal = AbortSignal.any([totalAbortSignal, AbortSignal.timeout(timeout)]);
393
+ this.refreshAuthInformationIfNeeded();
394
+ return new WebSocketBiDiStream(this.conf.ssl ? `wss://${this.conf.hostAndPort}/v1/ws/tx` : `ws://${this.conf.hostAndPort}/v1/ws/tx`, (msg) => TxAPI_ClientMessage.toBinary(msg), (data) => TxAPI_ServerMessage.fromBinary(new Uint8Array(data)), {
395
+ abortSignal: totalAbortSignal,
396
+ jwtToken: this.authInformation?.jwtToken,
397
+ dispatcher: wireConn.Dispatcher,
398
+ onComplete: async (stream) => stream.requests.send({
399
+ requestId: 0,
400
+ request: {
401
+ oneofKind: "streamClose",
402
+ streamClose: {}
403
+ }
404
+ })
405
+ });
406
+ }
407
+ throw new Error(`transactions are not supported for wire protocol ${this._wireProto}`);
408
+ });
409
+ }
410
+ /** Closes underlying transport */
411
+ async close() {
412
+ if (this.wireConnection.type === "grpc") this.wireConnection.Transport.close();
413
+ await this.httpDispatcher.destroy();
414
+ }
415
+ };
521
416
 
417
+ //#endregion
522
418
  export { LLPlClient };
523
- //# sourceMappingURL=ll_client.js.map
419
+ //# sourceMappingURL=ll_client.js.map