@milaboratories/pl-client 2.17.6 → 2.17.8

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