@polyester/sdk 0.36.0-devnet-20261117035807 → 0.36.0-devnet-20261118141710

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 (345) hide show
  1. package/CHANGELOG.md +66 -8
  2. package/dist/catalogs/index.d.ts +2 -2
  3. package/dist/catalogs/snapshot-validation.js +10 -1
  4. package/dist/catalogs/snapshot-validation.js.map +1 -1
  5. package/dist/catalogs/zipper-catalog.d.ts +2 -0
  6. package/dist/catalogs/zipper-catalog.d.ts.map +1 -1
  7. package/dist/catalogs/zipper-catalog.js.map +1 -1
  8. package/dist/catalogs/zipper-supply.d.ts +2 -0
  9. package/dist/catalogs/zipper-supply.d.ts.map +1 -1
  10. package/dist/catalogs/zipper-supply.js +7 -5
  11. package/dist/catalogs/zipper-supply.js.map +1 -1
  12. package/dist/client.d.ts +2 -0
  13. package/dist/client.d.ts.map +1 -1
  14. package/dist/client.js +2 -0
  15. package/dist/client.js.map +1 -1
  16. package/dist/gen/ai/v1/assistant_pb.d.ts +679 -13
  17. package/dist/gen/ai/v1/assistant_pb.d.ts.map +1 -1
  18. package/dist/gen/ai/v1/assistant_pb.js +355 -97
  19. package/dist/gen/ai/v1/assistant_pb.js.map +1 -1
  20. package/dist/gen/alerts/v1/price_alerts_pb.d.ts +33 -4
  21. package/dist/gen/alerts/v1/price_alerts_pb.d.ts.map +1 -1
  22. package/dist/gen/alerts/v1/price_alerts_pb.js +23 -2
  23. package/dist/gen/alerts/v1/price_alerts_pb.js.map +1 -1
  24. package/dist/gen/auth/v1/activity_pb.d.ts +148 -0
  25. package/dist/gen/auth/v1/activity_pb.d.ts.map +1 -0
  26. package/dist/gen/auth/v1/activity_pb.js +40 -0
  27. package/dist/gen/auth/v1/activity_pb.js.map +1 -0
  28. package/dist/gen/auth/v1/api_keys_pb.d.ts +10 -4
  29. package/dist/gen/auth/v1/api_keys_pb.d.ts.map +1 -1
  30. package/dist/gen/auth/v1/api_keys_pb.js +3 -1
  31. package/dist/gen/auth/v1/api_keys_pb.js.map +1 -1
  32. package/dist/gen/auth/v1/auth_pb.d.ts +61 -5
  33. package/dist/gen/auth/v1/auth_pb.d.ts.map +1 -1
  34. package/dist/gen/auth/v1/auth_pb.js +23 -6
  35. package/dist/gen/auth/v1/auth_pb.js.map +1 -1
  36. package/dist/gen/auth/v1/mfa_pb.d.ts +140 -2
  37. package/dist/gen/auth/v1/mfa_pb.d.ts.map +1 -1
  38. package/dist/gen/auth/v1/mfa_pb.js +80 -8
  39. package/dist/gen/auth/v1/mfa_pb.js.map +1 -1
  40. package/dist/gen/auth/v1/policies_pb.d.ts +18 -3
  41. package/dist/gen/auth/v1/policies_pb.d.ts.map +1 -1
  42. package/dist/gen/auth/v1/policies_pb.js +18 -3
  43. package/dist/gen/auth/v1/policies_pb.js.map +1 -1
  44. package/dist/gen/auth/v1/social_verification_pb.d.ts +36 -15
  45. package/dist/gen/auth/v1/social_verification_pb.d.ts.map +1 -1
  46. package/dist/gen/auth/v1/social_verification_pb.js +1 -1
  47. package/dist/gen/auth/v1/social_verification_pb.js.map +1 -1
  48. package/dist/gen/auth/v1/subaccounts_pb.d.ts +15 -1
  49. package/dist/gen/auth/v1/subaccounts_pb.d.ts.map +1 -1
  50. package/dist/gen/auth/v1/subaccounts_pb.js +1 -1
  51. package/dist/gen/auth/v1/subaccounts_pb.js.map +1 -1
  52. package/dist/gen/chain/withdraw/v1/auto_withdraw_pb.d.ts +6 -2
  53. package/dist/gen/chain/withdraw/v1/auto_withdraw_pb.d.ts.map +1 -1
  54. package/dist/gen/chain/withdraw/v1/auto_withdraw_pb.js.map +1 -1
  55. package/dist/gen/chain/withdraw/v1/withdraw_pb.d.ts +104 -6
  56. package/dist/gen/chain/withdraw/v1/withdraw_pb.d.ts.map +1 -1
  57. package/dist/gen/chain/withdraw/v1/withdraw_pb.js +49 -3
  58. package/dist/gen/chain/withdraw/v1/withdraw_pb.js.map +1 -1
  59. package/dist/gen/chain/zipper/v1/zipper_pb.d.ts +76 -3
  60. package/dist/gen/chain/zipper/v1/zipper_pb.d.ts.map +1 -1
  61. package/dist/gen/chain/zipper/v1/zipper_pb.js +46 -2
  62. package/dist/gen/chain/zipper/v1/zipper_pb.js.map +1 -1
  63. package/dist/gen/index.d.ts +3 -1
  64. package/dist/gen/index.js +4 -2
  65. package/dist/gen/ledger/read/v1/ledger_read_pb.d.ts +21 -139
  66. package/dist/gen/ledger/read/v1/ledger_read_pb.d.ts.map +1 -1
  67. package/dist/gen/ledger/read/v1/ledger_read_pb.js +16 -17
  68. package/dist/gen/ledger/read/v1/ledger_read_pb.js.map +1 -1
  69. package/dist/gen/ledger/read/v1/statement_export_pb.d.ts +236 -20
  70. package/dist/gen/ledger/read/v1/statement_export_pb.d.ts.map +1 -1
  71. package/dist/gen/ledger/read/v1/statement_export_pb.js +44 -10
  72. package/dist/gen/ledger/read/v1/statement_export_pb.js.map +1 -1
  73. package/dist/gen/ledger/v1/catalog_pb.d.ts +9 -1
  74. package/dist/gen/ledger/v1/catalog_pb.d.ts.map +1 -1
  75. package/dist/gen/ledger/v1/catalog_pb.js +9 -1
  76. package/dist/gen/ledger/v1/catalog_pb.js.map +1 -1
  77. package/dist/gen/marketdata/v1/asset_info_pb.d.ts +158 -7
  78. package/dist/gen/marketdata/v1/asset_info_pb.d.ts.map +1 -1
  79. package/dist/gen/marketdata/v1/asset_info_pb.js +56 -6
  80. package/dist/gen/marketdata/v1/asset_info_pb.js.map +1 -1
  81. package/dist/gen/notifications/v1/notifications_pb.d.ts +45 -6
  82. package/dist/gen/notifications/v1/notifications_pb.d.ts.map +1 -1
  83. package/dist/gen/notifications/v1/notifications_pb.js +23 -5
  84. package/dist/gen/notifications/v1/notifications_pb.js.map +1 -1
  85. package/dist/gen/orders/v1/orders_pb.d.ts +105 -29
  86. package/dist/gen/orders/v1/orders_pb.d.ts.map +1 -1
  87. package/dist/gen/orders/v1/orders_pb.js +14 -2
  88. package/dist/gen/orders/v1/orders_pb.js.map +1 -1
  89. package/dist/gen/orders/v1/orders_read_pb.d.ts +50 -20
  90. package/dist/gen/orders/v1/orders_read_pb.d.ts.map +1 -1
  91. package/dist/gen/orders/v1/orders_read_pb.js +1 -1
  92. package/dist/gen/orders/v1/orders_read_pb.js.map +1 -1
  93. package/dist/gen/polyester/api/options_pb.d.ts +11 -2
  94. package/dist/gen/polyester/api/options_pb.d.ts.map +1 -1
  95. package/dist/gen/polyester/api/options_pb.js +13 -3
  96. package/dist/gen/polyester/api/options_pb.js.map +1 -1
  97. package/dist/gen/privatews/v1/private_ws_pb.d.ts +13 -3
  98. package/dist/gen/privatews/v1/private_ws_pb.d.ts.map +1 -1
  99. package/dist/gen/privatews/v1/private_ws_pb.js.map +1 -1
  100. package/dist/gen/swap/quickswap/v1/quickswap_broker_pb.d.ts +126 -10
  101. package/dist/gen/swap/quickswap/v1/quickswap_broker_pb.d.ts.map +1 -1
  102. package/dist/gen/swap/quickswap/v1/quickswap_broker_pb.js +14 -6
  103. package/dist/gen/swap/quickswap/v1/quickswap_broker_pb.js.map +1 -1
  104. package/dist/gen/swap/quickswap/v1/quickswap_explorer_pb.d.ts +665 -0
  105. package/dist/gen/swap/quickswap/v1/quickswap_explorer_pb.d.ts.map +1 -0
  106. package/dist/gen/swap/quickswap/v1/quickswap_explorer_pb.js +216 -0
  107. package/dist/gen/swap/quickswap/v1/quickswap_explorer_pb.js.map +1 -0
  108. package/dist/gen/swap/quickswap/v1/quickswap_pb.d.ts +166 -52
  109. package/dist/gen/swap/quickswap/v1/quickswap_pb.d.ts.map +1 -1
  110. package/dist/gen/swap/quickswap/v1/quickswap_pb.js +50 -12
  111. package/dist/gen/swap/quickswap/v1/quickswap_pb.js.map +1 -1
  112. package/dist/gen/system/v1/system_pb.d.ts +49 -2
  113. package/dist/gen/system/v1/system_pb.d.ts.map +1 -1
  114. package/dist/gen/system/v1/system_pb.js +18 -6
  115. package/dist/gen/system/v1/system_pb.js.map +1 -1
  116. package/dist/gen/transfer/v1/internal_transfer_pb.d.ts +150 -71
  117. package/dist/gen/transfer/v1/internal_transfer_pb.d.ts.map +1 -1
  118. package/dist/gen/transfer/v1/internal_transfer_pb.js +56 -34
  119. package/dist/gen/transfer/v1/internal_transfer_pb.js.map +1 -1
  120. package/dist/gen/triggers/v1/triggers_pb.d.ts +117 -16
  121. package/dist/gen/triggers/v1/triggers_pb.d.ts.map +1 -1
  122. package/dist/gen/triggers/v1/triggers_pb.js +45 -2
  123. package/dist/gen/triggers/v1/triggers_pb.js.map +1 -1
  124. package/dist/index.d.ts +13 -9
  125. package/dist/realtime/client.js +5 -1
  126. package/dist/realtime/client.js.map +1 -1
  127. package/dist/realtime/snapshot-then-stream.js +5 -3
  128. package/dist/realtime/snapshot-then-stream.js.map +1 -1
  129. package/dist/services/account-activity/account-activity.d.ts +22 -0
  130. package/dist/services/account-activity/account-activity.d.ts.map +1 -0
  131. package/dist/services/account-activity/account-activity.js +32 -0
  132. package/dist/services/account-activity/account-activity.js.map +1 -0
  133. package/dist/services/account-activity/account-activity.schemas.d.ts +78 -0
  134. package/dist/services/account-activity/account-activity.schemas.d.ts.map +1 -0
  135. package/dist/services/account-activity/account-activity.schemas.js +44 -0
  136. package/dist/services/account-activity/account-activity.schemas.js.map +1 -0
  137. package/dist/services/account-activity/account-activity.types.d.ts +2 -0
  138. package/dist/services/account-activity/service.d.ts +8 -0
  139. package/dist/services/account-activity/service.d.ts.map +1 -0
  140. package/dist/services/account-activity/service.js +9 -0
  141. package/dist/services/account-activity/service.js.map +1 -0
  142. package/dist/services/address-book/address-book.schemas.js +2 -2
  143. package/dist/services/api-keys/api-keys.schemas.js +2 -2
  144. package/dist/services/assistant/assistant-events.schemas.d.ts +81 -81
  145. package/dist/services/assistant/assistant.codecs.d.ts +7 -2
  146. package/dist/services/assistant/assistant.codecs.d.ts.map +1 -1
  147. package/dist/services/assistant/assistant.codecs.js +18 -2
  148. package/dist/services/assistant/assistant.codecs.js.map +1 -1
  149. package/dist/services/assistant/assistant.d.ts +29 -2
  150. package/dist/services/assistant/assistant.d.ts.map +1 -1
  151. package/dist/services/assistant/assistant.js +44 -2
  152. package/dist/services/assistant/assistant.js.map +1 -1
  153. package/dist/services/assistant/assistant.schemas.d.ts +111 -6
  154. package/dist/services/assistant/assistant.schemas.d.ts.map +1 -1
  155. package/dist/services/assistant/assistant.schemas.js +74 -6
  156. package/dist/services/assistant/assistant.schemas.js.map +1 -1
  157. package/dist/services/assistant/assistant.types.d.ts +3 -3
  158. package/dist/services/auto-withdraw/auto-withdraw.codecs.d.ts +3 -1
  159. package/dist/services/auto-withdraw/auto-withdraw.codecs.d.ts.map +1 -1
  160. package/dist/services/auto-withdraw/auto-withdraw.codecs.js.map +1 -1
  161. package/dist/services/auto-withdraw/auto-withdraw.schemas.d.ts +15 -13
  162. package/dist/services/auto-withdraw/auto-withdraw.schemas.d.ts.map +1 -1
  163. package/dist/services/auto-withdraw/auto-withdraw.schemas.js +1 -0
  164. package/dist/services/auto-withdraw/auto-withdraw.schemas.js.map +1 -1
  165. package/dist/services/balances/balances.d.ts +1 -13
  166. package/dist/services/balances/balances.d.ts.map +1 -1
  167. package/dist/services/balances/balances.js +1 -45
  168. package/dist/services/balances/balances.js.map +1 -1
  169. package/dist/services/balances/balances.schemas.d.ts +1 -67
  170. package/dist/services/balances/balances.schemas.d.ts.map +1 -1
  171. package/dist/services/balances/balances.schemas.js +1 -22
  172. package/dist/services/balances/balances.schemas.js.map +1 -1
  173. package/dist/services/balances/balances.types.d.ts +2 -2
  174. package/dist/services/candles/candles.schemas.d.ts +10 -10
  175. package/dist/services/changelog/changelog.schemas.d.ts +38 -38
  176. package/dist/services/checkpoints/checkpoints.schemas.d.ts +3 -3
  177. package/dist/services/dust-conversion/dust-conversion.schemas.d.ts +11 -11
  178. package/dist/services/dust-conversion/dust-conversion.schemas.d.ts.map +1 -1
  179. package/dist/services/dust-conversion/dust-conversion.schemas.js +1 -1
  180. package/dist/services/dust-conversion/dust-conversion.schemas.js.map +1 -1
  181. package/dist/services/heatmap/heatmap.schemas.d.ts +4 -4
  182. package/dist/services/internal-transfers/internal-transfers.codecs.d.ts +11 -6
  183. package/dist/services/internal-transfers/internal-transfers.codecs.d.ts.map +1 -1
  184. package/dist/services/internal-transfers/internal-transfers.codecs.js +6 -6
  185. package/dist/services/internal-transfers/internal-transfers.codecs.js.map +1 -1
  186. package/dist/services/internal-transfers/internal-transfers.d.ts +17 -10
  187. package/dist/services/internal-transfers/internal-transfers.d.ts.map +1 -1
  188. package/dist/services/internal-transfers/internal-transfers.js +21 -10
  189. package/dist/services/internal-transfers/internal-transfers.js.map +1 -1
  190. package/dist/services/internal-transfers/internal-transfers.schemas.d.ts +43 -31
  191. package/dist/services/internal-transfers/internal-transfers.schemas.d.ts.map +1 -1
  192. package/dist/services/internal-transfers/internal-transfers.schemas.js +23 -12
  193. package/dist/services/internal-transfers/internal-transfers.schemas.js.map +1 -1
  194. package/dist/services/internal-transfers/internal-transfers.types.d.ts +2 -2
  195. package/dist/services/lifecycle/lifecycle.d.ts +1 -1
  196. package/dist/services/lifecycle/lifecycle.js +2 -3
  197. package/dist/services/lifecycle/lifecycle.js.map +1 -1
  198. package/dist/services/lifecycle/lifecycle.schemas.d.ts +40 -40
  199. package/dist/services/market-data/market-data.codecs.d.ts +8 -0
  200. package/dist/services/market-data/market-data.codecs.d.ts.map +1 -0
  201. package/dist/services/market-data/market-data.codecs.js +7 -1
  202. package/dist/services/market-data/market-data.codecs.js.map +1 -1
  203. package/dist/services/market-data/market-data.d.ts +3 -2
  204. package/dist/services/market-data/market-data.d.ts.map +1 -1
  205. package/dist/services/market-data/market-data.js +3 -2
  206. package/dist/services/market-data/market-data.js.map +1 -1
  207. package/dist/services/market-data/market-data.schemas.d.ts +332 -4
  208. package/dist/services/market-data/market-data.schemas.d.ts.map +1 -1
  209. package/dist/services/market-data/market-data.schemas.js +56 -8
  210. package/dist/services/market-data/market-data.schemas.js.map +1 -1
  211. package/dist/services/market-data/market-data.types.d.ts +3 -2
  212. package/dist/services/notifications/notifications.codecs.d.ts +1 -1
  213. package/dist/services/notifications/notifications.codecs.d.ts.map +1 -1
  214. package/dist/services/notifications/notifications.codecs.js +2 -1
  215. package/dist/services/notifications/notifications.codecs.js.map +1 -1
  216. package/dist/services/notifications/notifications.d.ts +4 -2
  217. package/dist/services/notifications/notifications.d.ts.map +1 -1
  218. package/dist/services/notifications/notifications.js +4 -2
  219. package/dist/services/notifications/notifications.js.map +1 -1
  220. package/dist/services/notifications/notifications.schemas.d.ts +63 -7
  221. package/dist/services/notifications/notifications.schemas.d.ts.map +1 -1
  222. package/dist/services/notifications/notifications.schemas.js +5 -0
  223. package/dist/services/notifications/notifications.schemas.js.map +1 -1
  224. package/dist/services/orderbook/orderbook.js +3 -2
  225. package/dist/services/orderbook/orderbook.js.map +1 -1
  226. package/dist/services/orders/order-enums.codecs.d.ts +2 -0
  227. package/dist/services/orders/order-errors.schemas.d.ts +50 -5
  228. package/dist/services/orders/order-errors.schemas.d.ts.map +1 -1
  229. package/dist/services/orders/order-errors.schemas.js +13 -3
  230. package/dist/services/orders/order-errors.schemas.js.map +1 -1
  231. package/dist/services/orders/orders-batch.schemas.d.ts +310 -70
  232. package/dist/services/orders/orders-batch.schemas.d.ts.map +1 -1
  233. package/dist/services/orders/orders-input.schemas.d.ts +58 -11
  234. package/dist/services/orders/orders-input.schemas.d.ts.map +1 -1
  235. package/dist/services/orders/orders-input.schemas.js +1 -1
  236. package/dist/services/orders/orders-output.schemas.d.ts +13 -13
  237. package/dist/services/policies/api-key-policies/api-key-policies.schemas.d.ts +15 -15
  238. package/dist/services/policies/api-key-policies/api-key-policies.schemas.js +1 -1
  239. package/dist/services/policies/shared.codecs.js +12 -6
  240. package/dist/services/policies/shared.codecs.js.map +1 -1
  241. package/dist/services/policies/shared.d.ts +1 -1
  242. package/dist/services/policies/shared.js +1 -1
  243. package/dist/services/policies/subaccount-policies/subaccount-policies.schemas.d.ts +9 -9
  244. package/dist/services/policies/subaccount-policies/subaccount-policies.schemas.js +4 -30
  245. package/dist/services/policies/subaccount-policies/subaccount-policies.schemas.js.map +1 -1
  246. package/dist/services/price-alerts/price-alerts.d.ts +5 -2
  247. package/dist/services/price-alerts/price-alerts.d.ts.map +1 -1
  248. package/dist/services/price-alerts/price-alerts.js +5 -2
  249. package/dist/services/price-alerts/price-alerts.js.map +1 -1
  250. package/dist/services/price-alerts/price-alerts.schemas.js +1 -1
  251. package/dist/services/rewards/rewards.schemas.d.ts +4 -4
  252. package/dist/services/social-verification/social-verification.schemas.d.ts +9 -0
  253. package/dist/services/social-verification/social-verification.schemas.d.ts.map +1 -1
  254. package/dist/services/social-verification/social-verification.schemas.js +9 -2
  255. package/dist/services/social-verification/social-verification.schemas.js.map +1 -1
  256. package/dist/services/statement-exports/statement-exports.codecs.d.ts +3 -2
  257. package/dist/services/statement-exports/statement-exports.codecs.d.ts.map +1 -1
  258. package/dist/services/statement-exports/statement-exports.codecs.js +2 -1
  259. package/dist/services/statement-exports/statement-exports.codecs.js.map +1 -1
  260. package/dist/services/statement-exports/statement-exports.d.ts +25 -10
  261. package/dist/services/statement-exports/statement-exports.d.ts.map +1 -1
  262. package/dist/services/statement-exports/statement-exports.js +33 -10
  263. package/dist/services/statement-exports/statement-exports.js.map +1 -1
  264. package/dist/services/statement-exports/statement-exports.schemas.d.ts +38 -10
  265. package/dist/services/statement-exports/statement-exports.schemas.d.ts.map +1 -1
  266. package/dist/services/statement-exports/statement-exports.schemas.js +25 -6
  267. package/dist/services/statement-exports/statement-exports.schemas.js.map +1 -1
  268. package/dist/services/statement-exports/statement-exports.types.d.ts +2 -2
  269. package/dist/services/subaccounts/subaccounts.codecs.js +112 -38
  270. package/dist/services/subaccounts/subaccounts.codecs.js.map +1 -1
  271. package/dist/services/subaccounts/subaccounts.d.ts +2 -1
  272. package/dist/services/subaccounts/subaccounts.d.ts.map +1 -1
  273. package/dist/services/subaccounts/subaccounts.js +3 -3
  274. package/dist/services/subaccounts/subaccounts.js.map +1 -1
  275. package/dist/services/subaccounts/subaccounts.schemas.d.ts +12 -5
  276. package/dist/services/subaccounts/subaccounts.schemas.d.ts.map +1 -1
  277. package/dist/services/subaccounts/subaccounts.schemas.js +10 -3
  278. package/dist/services/subaccounts/subaccounts.schemas.js.map +1 -1
  279. package/dist/services/system/system.d.ts +12 -1
  280. package/dist/services/system/system.d.ts.map +1 -1
  281. package/dist/services/system/system.js +5 -0
  282. package/dist/services/system/system.js.map +1 -1
  283. package/dist/services/system/system.schemas.d.ts +13 -13
  284. package/dist/services/system/system.types.d.ts +2 -2
  285. package/dist/services/trades/trades.schemas.d.ts +2 -2
  286. package/dist/services/trading-withdraws/trading-withdraws.codecs.d.ts +8 -0
  287. package/dist/services/trading-withdraws/trading-withdraws.codecs.d.ts.map +1 -0
  288. package/dist/services/trading-withdraws/trading-withdraws.codecs.js +7 -1
  289. package/dist/services/trading-withdraws/trading-withdraws.codecs.js.map +1 -1
  290. package/dist/services/trading-withdraws/trading-withdraws.d.ts +2 -1
  291. package/dist/services/trading-withdraws/trading-withdraws.d.ts.map +1 -1
  292. package/dist/services/trading-withdraws/trading-withdraws.js +2 -1
  293. package/dist/services/trading-withdraws/trading-withdraws.js.map +1 -1
  294. package/dist/services/trading-withdraws/trading-withdraws.schemas.d.ts +15 -0
  295. package/dist/services/trading-withdraws/trading-withdraws.schemas.d.ts.map +1 -1
  296. package/dist/services/trading-withdraws/trading-withdraws.schemas.js +16 -2
  297. package/dist/services/trading-withdraws/trading-withdraws.schemas.js.map +1 -1
  298. package/dist/services/trading-withdraws/trading-withdraws.types.d.ts +2 -1
  299. package/dist/services/transfers/transfers.schemas.d.ts +4 -4
  300. package/dist/services/triggers/trigger-child-order.schemas.js +1 -1
  301. package/dist/services/triggers/trigger-child-order.schemas.js.map +1 -1
  302. package/dist/services/triggers/trigger-input.schemas.d.ts +10 -10
  303. package/dist/services/triggers/triggers-output.schemas.d.ts +170 -52
  304. package/dist/services/triggers/triggers-output.schemas.d.ts.map +1 -1
  305. package/dist/services/triggers/triggers-output.schemas.js +13 -3
  306. package/dist/services/triggers/triggers-output.schemas.js.map +1 -1
  307. package/dist/services/triggers/triggers.codecs.d.ts +10 -0
  308. package/dist/services/triggers/triggers.codecs.d.ts.map +1 -0
  309. package/dist/services/triggers/triggers.codecs.js +7 -1
  310. package/dist/services/triggers/triggers.codecs.js.map +1 -1
  311. package/dist/services/triggers/triggers.d.ts +2 -2
  312. package/dist/services/triggers/triggers.js +2 -2
  313. package/dist/services/triggers/triggers.js.map +1 -1
  314. package/dist/services/zipper/zipper.d.ts.map +1 -1
  315. package/dist/services/zipper/zipper.js +13 -7
  316. package/dist/services/zipper/zipper.js.map +1 -1
  317. package/dist/services/zipper/zipper.schemas.d.ts +7 -2
  318. package/dist/services/zipper/zipper.schemas.d.ts.map +1 -1
  319. package/dist/services/zipper/zipper.schemas.js +29 -9
  320. package/dist/services/zipper/zipper.schemas.js.map +1 -1
  321. package/dist/services/zipper/zipper.types.d.ts +2 -2
  322. package/dist/shared/catalog-config.d.ts +16 -2
  323. package/dist/shared/catalog-config.d.ts.map +1 -1
  324. package/dist/shared/catalog-config.js.map +1 -1
  325. package/dist/shared/connect-error-mapping.d.ts.map +1 -1
  326. package/dist/shared/connect-error-mapping.js +27 -4
  327. package/dist/shared/connect-error-mapping.js.map +1 -1
  328. package/dist/shared/error-detail.d.ts +10 -0
  329. package/dist/shared/error-detail.d.ts.map +1 -1
  330. package/dist/shared/error-detail.js.map +1 -1
  331. package/dist/shared/error-details/auth.js +6 -0
  332. package/dist/shared/error-details/auth.js.map +1 -1
  333. package/dist/shared/errors.d.ts +5 -1
  334. package/dist/shared/errors.d.ts.map +1 -1
  335. package/dist/shared/errors.js +3 -0
  336. package/dist/shared/errors.js.map +1 -1
  337. package/dist/shared/ledger-codes.d.ts +3 -1
  338. package/dist/shared/ledger-codes.d.ts.map +1 -1
  339. package/dist/shared/ledger-codes.js +6 -3
  340. package/dist/shared/ledger-codes.js.map +1 -1
  341. package/dist/shared/rate-limit.schemas.d.ts +1 -1
  342. package/dist/wired-services.d.ts.map +1 -1
  343. package/dist/wired-services.js +3 -1
  344. package/dist/wired-services.js.map +1 -1
  345. package/package.json +1 -1
package/dist/index.d.ts CHANGED
@@ -2,7 +2,7 @@ import { AccountSigner, AccountSignerConfig, AccountSignerFactory, HexAddress }
2
2
  import { CreatePolyesterEnvironmentParams, POLYESTER_DEVNET_ENVIRONMENT, POLYESTER_TESTNET_ENVIRONMENT, PolyesterAccountAbstractionEnvironment, PolyesterContractsEnvironment, PolyesterEntryPointConfig, PolyesterEnvironment, PolyesterSafeDeploymentConfig, createPolyesterEnvironment } from "./environment.js";
3
3
  import { CreatePolyesterAccountSignerParams } from "./account-signer/create-polyester-account-signer.js";
4
4
  import "./account-signer/index.js";
5
- import { AssetConfig, DepositWithdrawConfig, PairConfig, PairStatus, SpotConfig, ZipperAssetChainVariant, ZipperAssetConfig, ZipperChainConfig, ZipperChainContractConfig, ZipperMemoRequirement, ZipperRouteStatus } from "./shared/catalog-config.js";
5
+ import { AssetConfig, DepositWithdrawConfig, PairConfig, PairStatus, SpotConfig, ZipperAssetChainVariant, ZipperAssetConfig, ZipperChainConfig, ZipperChainContractConfig, ZipperMemoRequirement, ZipperRouteStatus, ZipperSupplyStatus } from "./shared/catalog-config.js";
6
6
  import { OrderErrorCode, OrderErrorDetail } from "./services/orders/order-errors.schemas.js";
7
7
  import { RateLimitDetail, RateLimitFailureReason, RateLimitPolicyClass, RateLimitRefillModel, RateLimitScope } from "./shared/rate-limit.schemas.js";
8
8
  import { PolyesterErrorDetail, loadErrorDetailDecoders } from "./shared/error-detail.js";
@@ -19,11 +19,12 @@ import { ApiKeyPolicy, ApiKeyPolicyApplyInput, ApiKeyPolicyCreateInput, ApiKeyPo
19
19
  import { ApiKey, ApiKeyIdInput, ApiKeyStatus, ApiKeysCreateInput, ApiKeysListInput, ApiKeysUpdateInput, AssistantKeySpecInput, SetAssistantKeysInput } from "./services/api-keys/api-keys.schemas.js";
20
20
  import { SubaccountPolicy, SubaccountPolicyApplyInput, SubaccountPolicyCreateInput, SubaccountPolicyUpdateInput } from "./services/policies/subaccount-policies/subaccount-policies.schemas.js";
21
21
  import { AccountCodeValue, TransferCodeValue } from "./shared/ledger-codes.js";
22
- import { BalanceHistoryInput, BalanceHistoryResponse, BalanceRange, EquityGroupBy, EquityHistoryInput, EquityHistoryResponse, EquitySeries, EquitySeriesGrouping, ExportStatementInput, LedgerBalance, PortfolioEquityHistoryInput, PortfolioEquityHistoryResponse, PortfolioEquitySeries, PortfolioEquitySeriesGrouping, PortfolioEquitySnapshotResponse, Statement, StatementPage, formatLedgerBalance } from "./services/balances/balances.schemas.js";
22
+ import { BalanceHistoryInput, BalanceHistoryResponse, BalanceRange, EquityGroupBy, EquityHistoryInput, EquityHistoryResponse, EquitySeries, EquitySeriesGrouping, LedgerBalance, PortfolioEquityHistoryInput, PortfolioEquityHistoryResponse, PortfolioEquitySeries, PortfolioEquitySeriesGrouping, PortfolioEquitySnapshotResponse, formatLedgerBalance } from "./services/balances/balances.schemas.js";
23
23
  import { CreateSubaccountChallengeInput, CreateSubaccountInput, CreateSubaccountResult as CreateSubaccountResult$1, EffectiveSubaccountPermissions, GetSubaccountInput, InviteSubaccountMemberInput, ListSubaccountInvitesInput, RemoveSubaccountMemberInput, RespondSubaccountInviteInput, SetSubaccountMemberMfaRequirementInput, Subaccount, SubaccountActivityInput, SubaccountChallenge, SubaccountEvent, SubaccountIdInput, SubaccountInvite, SubaccountInviteStatus, SubaccountMember, SubaccountPermission, SubaccountPermissionDefinition, SubaccountRole, SubaccountRoleCatalog, SubaccountRoleDefinition, SubaccountStatus, UpdateSubaccountInput, UpdateSubaccountMemberRoleInput } from "./services/subaccounts/subaccounts.schemas.js";
24
+ import { AccountActivityEvent, ListAccountActivityInput, ListAccountActivityResult } from "./services/account-activity/account-activity.schemas.js";
24
25
  import { Candle, CandleColumnar, CandleColumnarInt, CandleInt, GetCandlesColumnsInput, GetCandlesInput, Timeframe } from "./services/candles/candles.schemas.js";
25
26
  import { ChainAnalyticsRange, GetUnifiedAssetBalancesInput, GetZippedAssetSupplyGroupInput, GetZippedAssetSupplyInput, UnifiedAssetBalancesResponse, ZippedAssetSupplyGroupResponse, ZippedAssetSupplyResponse, ZippedAssetSupplySeries } from "./services/chain-analytics/chain-analytics.schemas.js";
26
- import { AssetEditorialInfo, AssetInfo, GetMarketTradesInput, ListAssetInfoInput, MarketTrade, TradeBackfill } from "./services/market-data/market-data.schemas.js";
27
+ import { AssetEditorialInfo, AssetInfo, AssetMarketStats, AssetMarketValue, GetMarketTradesInput, ListAssetInfoInput, MarketTrade, TradeBackfill } from "./services/market-data/market-data.schemas.js";
27
28
  import { CurrencyConversionConfig, CurrencyConversionRates, CurrencyMetadata, FiatConversionRate, FiatConversionSnapshot, ListMarketOverviewInput, MarketOverview, MarketOverviewOrderBy, MarketOverviewSort, MarketOverviewSparkline, SparklineIntervalName, SpotPairVolumeSeries, SpotVolumeHistoryInput, SpotVolumeHistoryResponse, StablecoinConversionRate } from "./services/market-overview/market-overview.schemas.js";
28
29
  import { GetOrderbookInput, OrderbookData, OrderbookLevel } from "./services/orderbook/orderbook.schemas.js";
29
30
  import { CreateOrderbookSubscriptionInput, OrderbookStreamHandlers, OrderbookSubscription } from "./services/orderbook/orderbook.js";
@@ -43,11 +44,11 @@ import { ListTriggersResult } from "./services/triggers/triggers.js";
43
44
  import { CancelPriceAlertInput, CreatePriceAlertInput, ListPriceAlertsInput, ListPriceAlertsResult, PriceAlert, UpdatePriceAlertInput, UpdatePriceAlertResult } from "./services/price-alerts/price-alerts.schemas.js";
44
45
  import { AccountNotification, AccountNotificationDetail, GetNotificationInput, ListNotificationsInput, ListNotificationsResult, MarkAllNotificationsReadInput, MarkNotificationsInput, NotificationCounts } from "./services/notifications/notifications.schemas.js";
45
46
  import { AssistantApprovalPreview, AssistantOrderPreview, AssistantRunEvent, AssistantView } from "./services/assistant/assistant-events.schemas.js";
46
- import { AssistantAccountSelection, AssistantApprovalDecision, AssistantApprovalStatus, AssistantDisplaySetting, AssistantFailureCategory, AssistantKeyState, AssistantKeyView, AssistantMemoryKind, AssistantMessageRole, AssistantOrderPriceField, AssistantPriceOffsetDirection, AssistantPriceRounding, AssistantReferencePriceSource, AssistantTriggerChangeAction, AssistantTriggerDirection, AssistantUnfilledSlicePolicy } from "./services/assistant/assistant.codecs.js";
47
- import { AssistantConversation, AssistantKey, AssistantMemory, AssistantMessage, AssistantRunIdInput, CompleteAssistantKeysInput, DecideAssistantApprovalInput, DeleteAssistantMemoryInput, ListAssistantConversationsInput, ListAssistantConversationsResult, ListAssistantKeysInput, ListAssistantMemoriesInput, ListAssistantMemoriesResult, ListAssistantMessagesInput, ListAssistantMessagesResult, PrepareAssistantKeysInput, PrepareAssistantKeysResult, PreparedAssistantKey, SendAssistantMessageInput, SetTelegramApprovalLimitsInput, TelegramApprovalLimits, WatchAssistantRunInput } from "./services/assistant/assistant.schemas.js";
48
- import { CreateStatementExportInput, GetStatementExportInput, ListStatementExportsInput, ListStatementExportsResult, StatementExport } from "./services/statement-exports/statement-exports.schemas.js";
47
+ import { AssistantAccountSelection, AssistantApprovalDecision, AssistantApprovalStatus, AssistantDisplaySetting, AssistantFailureCategory, AssistantFundingMode, AssistantKeyState, AssistantKeyView, AssistantMemoryKind, AssistantMessageRole, AssistantModelKeyCheck, AssistantOrderPriceField, AssistantPriceOffsetDirection, AssistantPriceRounding, AssistantReferencePriceSource, AssistantTriggerChangeAction, AssistantTriggerDirection, AssistantUnfilledSlicePolicy } from "./services/assistant/assistant.codecs.js";
48
+ import { AssistantConversation, AssistantKey, AssistantMemory, AssistantMessage, AssistantMessageImage, AssistantModelKey, AssistantRunIdInput, AssistantUsage, CompleteAssistantKeysInput, DecideAssistantApprovalInput, DeleteAssistantMemoryInput, GetAssistantMessageImageInput, ListAssistantConversationsInput, ListAssistantConversationsResult, ListAssistantKeysInput, ListAssistantMemoriesInput, ListAssistantMemoriesResult, ListAssistantMessagesInput, ListAssistantMessagesResult, PrepareAssistantKeysInput, PrepareAssistantKeysResult, PreparedAssistantKey, SendAssistantMessageInput, SetAssistantModelKeyInput, SetTelegramApprovalLimitsInput, TelegramApprovalLimits, WatchAssistantRunInput } from "./services/assistant/assistant.schemas.js";
49
+ import { CancelStatementExportInput, CreateStatementExportInput, GetStatementExportDownloadUrlInput, GetStatementExportInput, ListStatementExportsInput, ListStatementExportsResult, StatementExport, StatementExportDownloadUrl } from "./services/statement-exports/statement-exports.schemas.js";
49
50
  import { LedgerTransfer, LedgerTransferSide, ListTransfersInput } from "./services/transfers/transfers.schemas.js";
50
- import { BatchCreateInternalTransfersInput, BatchCreateInternalTransfersResult, CreateInternalTransferInput, CreateInternalTransferResult, GetInternalTransferInput, GetInternalTransferResult, InternalTransferBatchLegInput, InternalTransferBatchLegResult, InternalTransferDestination, ResolvedInternalTransferDestination } from "./services/internal-transfers/internal-transfers.schemas.js";
51
+ import { BatchCreateInternalTransfersInput, BatchCreateInternalTransfersResult, CreateInternalTransferInput, CreateInternalTransferResult, GetInternalTransferBatchInput, GetInternalTransferInput, GetInternalTransferResult, InternalTransferBatchLegInput, InternalTransferBatchLegResult, InternalTransferDestination, ResolvedInternalTransferDestination } from "./services/internal-transfers/internal-transfers.schemas.js";
51
52
  import { CreateDustConversionInput, DustAssetPrice, DustBalance, DustConversion, DustConversionQuote, GetDustConversionInput, ListDustBalancesInput, ListDustBalancesResult, ListDustConversionsInput, ListDustConversionsResult, QuoteDustConversionInput } from "./services/dust-conversion/dust-conversion.schemas.js";
52
53
  import { CreateTradingWithdrawResult, CreateTradingWithdrawToExternalChainInput, CreateTradingWithdrawToFundingInput, GetWalletBalancesInput, GetWalletBalancesResult, ValidateWithdrawDestinationInput, ValidateWithdrawDestinationResult } from "./services/trading-withdraws/trading-withdraws.schemas.js";
53
54
  import { CreateTradingWithdrawToExternalChainServiceInput, CreateTradingWithdrawToFundingServiceInput, PreparedTradingWithdraw, TradingWithdrawSigningConfig, TradingWithdrawWalletSigner } from "./services/trading-withdraws/trading-withdraws.js";
@@ -64,7 +65,7 @@ import { ClaimCampaign, ClaimDailyRewardInput, ClaimDailyRewardResult, ClaimPayo
64
65
  import { Checkpoint, CheckpointAssetAmount, CheckpointBiggestTrade, CheckpointChainFlow, CheckpointEarnedBadge, CheckpointFlowTotal, CheckpointFundingDay, CheckpointFundingFlowSummary, CheckpointOrderToolCounts, CheckpointOrderTypeCounts, CheckpointPairActivity, CheckpointPortfolioValuePoint, CheckpointTimeInForceCounts, CheckpointVipTierChange, CheckpointVolumePoint, ListCheckpointsInput } from "./services/checkpoints/checkpoints.schemas.js";
65
66
  import { ChangelogChange, ChangelogChangeEntry, ChangelogDeploymentGroup, ChangelogDeploymentGroupSummary, ChangelogPost, ChangelogPostSummary, ChangelogSection, GetChangelogDeploymentGroupInput, GetChangelogPostInput, ListChangelogChangesInput, ListChangelogChangesResult, ListChangelogDeploymentGroupsInput, ListChangelogDeploymentGroupsResult, ListChangelogPostsInput, ListChangelogPostsResult } from "./services/changelog/changelog.schemas.js";
66
67
  import { ListStatusEventsInput, ListStatusEventsResult, StatusEvent } from "./services/system/system.schemas.js";
67
- import { SystemVersion } from "./services/system/system.js";
68
+ import { SystemTime, SystemVersion } from "./services/system/system.js";
68
69
  import { AcknowledgeRewardAwardInput, AcknowledgeRewardAwardResult, ListRewardAwardsInput, ListRewardAwardsResult, RewardAward, SetRewardDestinationInput, SetRewardDestinationResult } from "./services/rewards/rewards.schemas.js";
69
70
  import { NextVipTierThresholds, VipMetricQuality, VipMetricStatus, VipStatus, VipTier, VipTierCatalog } from "./services/vip/vip.schemas.js";
70
71
  import { GetSpotFeeRatesInput, SpotFeeDiscount, SpotFeeRate, SpotFeeRateBreakdown } from "./services/fees/fees.schemas.js";
@@ -91,6 +92,7 @@ import { mergeLedgerBalances } from "./services/balances/balances.merge.js";
91
92
  import { compareUnsignedIntegerStrings, shouldApplyReconciliationUpdate } from "./shared/reconciliation.js";
92
93
  import { tsObjToNsString } from "./utils/time.js";
93
94
  import { EvmHex, checksumEvmAddress, evmHexToBytes, evmUtf8ToBytes, evmUtf8ToHex, isEvmAddress, isEvmAddressStrict, keccak256Hex } from "./utils/evm.js";
95
+ import "./services/account-activity/account-activity.types.js";
94
96
  import "./services/accounts/accounts.types.js";
95
97
  import "./services/address-book/address-book.types.js";
96
98
  import { AssistantKeyPreset } from "./services/api-keys/api-keys.codecs.js";
@@ -117,6 +119,7 @@ import "./services/heatmap/heatmap.types.js";
117
119
  import { InternalTransferBatchLegStatus, InternalTransferBatchStatus, InternalTransferErrorCode, InternalTransferStatus } from "./services/internal-transfers/internal-transfers.codecs.js";
118
120
  import "./services/internal-transfers/internal-transfers.types.js";
119
121
  import "./services/lifecycle/lifecycle.types.js";
122
+ import { AssetDataSourceValue } from "./services/market-data/market-data.codecs.js";
120
123
  import "./services/market-data/market-data.types.js";
121
124
  import "./services/market-overview/market-overview.types.js";
122
125
  import "./services/mfa/mfa.types.js";
@@ -140,10 +143,11 @@ import "./services/subaccounts/subaccounts.types.js";
140
143
  import { StatusEventImpact, StatusEventKind, StatusEventService, StatusEventState } from "./services/system/system.codecs.js";
141
144
  import "./services/system/system.types.js";
142
145
  import "./services/trades/trades.types.js";
146
+ import { WalletAssetUnavailableReasonValue } from "./services/trading-withdraws/trading-withdraws.codecs.js";
143
147
  import "./services/trading-withdraws/trading-withdraws.types.js";
144
148
  import { TransferSideKind } from "./services/transfers/transfers.codecs.js";
145
149
  import "./services/transfers/transfers.types.js";
146
150
  import "./services/triggers/triggers.types.js";
147
151
  import "./services/vip/vip.types.js";
148
152
  import "./services/zipper/zipper.types.js";
149
- export { type AccountCodeValue, type AccountIdentity, type AccountNotification, type AccountNotificationDetail, type AccountScope, type AccountScopedInput, type AccountSigner, type AccountSignerAuthEvents, type AccountSignerConfig, type CreateSubaccountResult as AccountSignerCreateSubaccountResult, type AccountSignerFactory, type AcknowledgeRewardAwardInput, type AcknowledgeRewardAwardResult, type ActiveAccountInfo, type AddressBook, type AddressBookAccountScope, type AddressBookEntries, type AddressBookEntriesView, type AddressBookEntry, type AddressBookRecentDestinationsView, type AddressBookTag, type AddressBookTagSummary, type AddressBookView, type AddressBookViewInvalidated, AlreadyExistsError, type ApiKey, type ApiKeyEd25519AuthProvider, type ApiKeyIdInput, type ApiKeyPolicy, type ApiKeyPolicyApplyInput, type ApiKeyPolicyCreateInput, type ApiKeyPolicyUpdateInput, type ApiKeyStatus, type ApiKeysCreateInput, type ApiKeysListInput, type ApiKeysUpdateInput, type AssetConfig, type AssetEditorialInfo, type AssetInfo, type AssistantAccountSelection, type AssistantApprovalDecision, type AssistantApprovalPreview, type AssistantApprovalStatus, type AssistantConversation, type AssistantDisplaySetting, type AssistantFailureCategory, type AssistantKey, type AssistantKeyPreset, type AssistantKeySpecInput, type AssistantKeyState, type AssistantKeyView, type AssistantMemory, type AssistantMemoryKind, type AssistantMessage, type AssistantMessageRole, type AssistantOrderPreview, type AssistantOrderPriceField, type AssistantPriceOffsetDirection, type AssistantPriceRounding, type AssistantReferencePriceSource, type AssistantRunEvent, type AssistantRunIdInput, type AssistantTriggerChangeAction, type AssistantTriggerDirection, type AssistantUnfilledSlicePolicy, type AssistantView, type AuthCookieLocation, type AuthHydrationData, type AuthLoginMethod, type AuthState, type AuthTokenStorage, type AuthTokenStorageSetOptions, AuthenticationError, type AutoWithdrawCadence, type AutoWithdrawDestination, type AutoWithdrawDestinationInput, type AutoWithdrawHoldReason, type AutoWithdrawPause, type AutoWithdrawPauseReason, type AutoWithdrawPreview, type AutoWithdrawPreviewAsset, type AutoWithdrawPreviewStatus, type AutoWithdrawRule, type AutoWithdrawRun, type AutoWithdrawRunReason, type AutoWithdrawRunState, type AutoWithdrawSchedule, type AutoWithdrawScheduleInput, type AutoWithdrawScopedInput, type AutoWithdrawStep, type AutoWithdrawStepReason, type AutoWithdrawStepState, type AutoWithdrawWeekday, type BalanceHistoryInput, type BalanceHistoryResponse, type BalanceRange, type BatchCancelOrderInput, type BatchCancelOrderResult, type BatchCancelOrdersInput, type BatchCancelOrdersResult, type BatchCancelTriggerResult, type BatchCancelTriggersInput, type BatchCancelTriggersResult, type BatchCreateInternalTransfersInput, type BatchCreateInternalTransfersResult, type BatchCreateOrderResult, type BatchCreateOrdersInput, type BatchCreateOrdersResult, type BatchGuardApprovals, type BatchReplaceAdmissionItem, type BatchReplaceOrdersInput, type BatchReplaceOrdersResult, type BatchSignProtectedActionInput, type BeginMfaChallengeInput, type BeginMfaChallengeResult, type BeginPasskeyEnrollmentInput, type BeginPasskeyEnrollmentResult, type BeginTotpEnrollmentInput, type BeginTotpEnrollmentResult, type BrokerAllowlistAction, type BrokerAllowlistEvent, type CancelAllAfterInput, type CancelAllAfterResult, type CancelAllOrdersInput, type CancelAllOrdersResponse, type CancelOcoInput, type CancelOcoResult, type CancelOrderInput, type CancelOrderResult, type CancelPriceAlertInput, type CancelTriggerInput, type CancelTriggerResult, type Candle, type CandleColumnar, type CandleColumnarInt, type CandleInt, type ChainAnalyticsRange, type ChangelogAudience, type ChangelogChange, type ChangelogChangeAvailability, type ChangelogChangeCategory, type ChangelogChangeEntry, type ChangelogDeploymentGroup, type ChangelogDeploymentGroupSummary, type ChangelogEnvironment, type ChangelogPost, type ChangelogPostSummary, type ChangelogSection, type ChangelogSort, type ChangelogSurface, type Checkpoint, type CheckpointAssetAmount, type CheckpointBadge, type CheckpointBiggestTrade, type CheckpointChainFlow, type CheckpointEarnedBadge, type CheckpointField, type CheckpointFlowTotal, type CheckpointFundingDay, type CheckpointFundingFlowSummary, type CheckpointOrderToolCounts, type CheckpointOrderTypeCounts, type CheckpointPairActivity, type CheckpointPortfolioValuePoint, type CheckpointTimeInForceCounts, type CheckpointVipTierChange, type CheckpointVolumePoint, type ClaimCampaign, type ClaimDailyRewardInput, type ClaimDailyRewardResult, type ClaimFreshStepUpInput, type ClaimFreshStepUpResult, type ClaimGeneratedUsernameInput, ClaimOutcomeUnknownError, type ClaimOutcomeUnknownErrorOptions, type ClaimPayoutDelayReason, type ClaimPolicy, type ColumnarTimeWindow, type CompleteAssistantKeysInput, type CompleteMfaChallengeResult, ConfigurationError, type ConfirmVerificationInput, type ConnectChannelParams, type ConnectPrivateOrdersParams, type ConsumeFreshStepUpInput, type CookieAuthTokenStorageOptions, type CopyAddressBookEntryInput, type CreateAddressBookEntryInput, type CreateAddressBookTagInput, type CreateDepositAddressInput, type CreateDustConversionInput, type CreateGuardSignerWalletResult, type CreateInternalTransferInput, type CreateInternalTransferResult, type CreateOcoInput, type CreateOcoResult, type CreateOrderResult, type CreateOrderbookSubscriptionInput, type CreatePolyesterAccountSignerParams, type CreatePolyesterEnvironmentParams, type CreatePriceAlertInput, type CreateServerClientFromCookiesParams, type CreateServerClientFromRequestParams, type CreateStatementExportInput, type CreateSubaccountChallengeInput, type CreateSubaccountInput, type CreateSubaccountParams, type CreateSubaccountResult$1 as CreateSubaccountResult, type CreateSubaccountResult$1 as CreateSubaccountServiceResult, type CreateTradingWithdrawResult, type CreateTradingWithdrawToExternalChainInput, type CreateTradingWithdrawToExternalChainServiceInput, type CreateTradingWithdrawToFundingInput, type CreateTradingWithdrawToFundingServiceInput, type CreateTriggerInput, type CreateTriggerResult, type CreateWalletChallengeInput, type CurrencyConversionConfig, type CurrencyConversionRates, type CurrencyMetadata, type DailyClaimReward, type DailyClaimState, type DailyClaimStatus, type DailyClaimTransfer, type DecideAssistantApprovalInput, type DeleteAddressBookEntryInput, type DeleteAddressBookTagInput, type DeleteAssistantMemoryInput, type DeleteMfaFactorInput, type DepositAddress, type DepositWithdrawConfig, type DustAssetEligibility, type DustAssetPrice, type DustBalance, type DustConversion, type DustConversionQuote, type DustConversionRefusalCode, type DustConversionState, type EffectiveSubaccountPermissions, type EquityGroupBy, type EquityHistoryInput, type EquityHistoryResponse, type EquitySeries, type EquitySeriesGrouping, type EvmHex, type ExportGuardSignerWalletResult, type ExportStatementInput, type FiatConversionRate, type FiatConversionSnapshot, type FinishPasskeyChallengeInput, type FinishPasskeyEnrollmentInput, type FinishPasskeyEnrollmentResult, type FinishTotpEnrollmentInput, type FinishTotpEnrollmentResult, type GeneratedUsernameOffer, type GetAddressBookViewInput, type GetBatchReplaceStatusInput, type GetBatchReplaceStatusResult, type GetCandlesColumnsInput, type GetCandlesInput, type GetChangelogDeploymentGroupInput, type GetChangelogPostInput, type GetDustConversionInput, type GetInternalTransferInput, type GetInternalTransferResult, type GetLifecycleAccountFlowInput, type GetLifecycleFlowInput, type GetLifecycleFlowOutput, type GetMarketTradesInput, type GetNotificationInput, type GetOrderDetailsInput, type GetOrderbookHeatmapInput, type GetOrderbookInput, type GetSpotFeeRatesInput, type GetStatementExportInput, type GetSubaccountInput, type GetTriggerInput, type GetUnifiedAssetBalancesInput, type GetUserTradesInput, type GetVerificationResponse, type GetWalletBalancesInput, type GetWalletBalancesResult, type GetZippedAssetSupplyGroupInput, type GetZippedAssetSupplyInput, type GuardApproval, type GuardSignerScopedInput, type GuardSignerStatus, type HeatmapDepthValue, type HeatmapIntervalValue, type HeatmapQuantityModeValue, type HexAddress, InternalServerError, type InternalTransferBatchLegInput, type InternalTransferBatchLegResult, type InternalTransferBatchLegStatus, type InternalTransferBatchStatus, type InternalTransferDestination, type InternalTransferErrorCode, type InternalTransferStatus, type InternalTransferWhitelistEntries, type InternalTransferWhitelistEntry, type InviteSubaccountMemberInput, type JwtAuthProvider, type LadderDetailsOutput, type LedgerBalance, type LedgerTransfer, type LedgerTransferSide, type LifecycleAssetIds, type LifecycleFlowDetail, type LifecycleFlowState, type LifecycleFlowStep, type LifecycleFlowStepActivity, type LifecycleFlowSummary, type LifecycleFlowSummaryProgress, type LifecycleFlowTimelineItem, type LifecycleFlowTxMatch, type LifecycleListOrderBy, type LifecycleListScope, type LifecycleReason, type LifecycleRequestFee, type LifecycleRequestFeeStatus, type LifecycleSort, type LifecycleTxLookupKind, type LifecycleZipperReason, type LifecycleZipperReasonCode, type ListAddressBookEntriesInput, type ListApiKeyPoliciesResponse, type ListAssetInfoInput, type ListAssistantConversationsInput, type ListAssistantConversationsResult, type ListAssistantKeysInput, type ListAssistantMemoriesInput, type ListAssistantMemoriesResult, type ListAssistantMessagesInput, type ListAssistantMessagesResult, type ListAutoWithdrawRunsInput, type ListAutoWithdrawRunsResult, type ListChangelogChangesInput, type ListChangelogChangesResult, type ListChangelogDeploymentGroupsInput, type ListChangelogDeploymentGroupsResult, type ListChangelogPostsInput, type ListChangelogPostsResult, type ListCheckpointsInput, type ListDepositAddressesInput, type ListDustBalancesInput, type ListDustBalancesResult, type ListDustConversionsInput, type ListDustConversionsResult, type ListInternalTransferWhitelistEntriesInput, type ListLifecycleAccountFlowsInput, type ListLifecycleFlowsByTxInput, type ListLifecycleFlowsByTxOutput, type ListLifecycleFlowsInput, type ListLifecycleFlowsOutput, type ListMarketOverviewInput, type ListMfaFactorsResult, type ListNotificationsInput, type ListNotificationsResult, type ListPriceAlertsInput, type ListPriceAlertsResult, type ListRewardAwardsInput, type ListRewardAwardsResult, type ListStatementExportsInput, type ListStatementExportsResult, type ListStatusEventsInput, type ListStatusEventsResult, type ListSubaccountInvitesInput, type ListTransferCounterpartiesInput, type ListTransferDestinationsInput, type ListTransfersInput, type ListTriggerEventsInput, type ListTriggerEventsResult, type ListTriggersInput, type ListTriggersResult, type LoginOptions, type LoginResult, type LoginWithWalletInput, type LoginWithWalletResponse, type MarkAllNotificationsReadInput, type MarkNotificationsInput, type MarketOverview, type MarketOverviewOrderBy, type MarketOverviewSort, type MarketOverviewSparkline, type MarketTrade, type Me, MfaEnrollmentRequiredError, type MfaFactor, MfaLastFactorRequiredError, MfaRequiredError, type MfaSessionInfo, MfaVerificationError, type MfaVerificationFailureReason, type MirroredWithdrawWhitelistEntry, type ModifyOrderInput, type ModifyOrderResult, type ModifyTriggerInput, type ModifyTriggerResult, NetworkError, type NewOrderInput, type NextVipTierThresholds, NotImplementedError, type NotificationCategory, type NotificationCounts, type NotificationReadState, type NotificationType, type OpenOrdersInput, type Order, type OrderDetails, type OrderErrorCode, type OrderErrorDetail, type OrderHistoryInput, type OrderIntentInput, type OrderLineage, type OrderTransfer, type OrderbookData, type OrderbookHeatmapDeltaBucket, type OrderbookHeatmapDeltaChain, type OrderbookHeatmapDeltaLevels, type OrderbookHeatmapKeyframe, type OrderbookHeatmapLevels, type OrderbookHeatmapLiveBucket, type OrderbookHeatmapResponse, type OrderbookLevel, type OrderbookStreamHandlers, type OrderbookSubscription, OutcomeUnknownError, POLYESTER_AUTH_TOKEN_COOKIE_NAME, POLYESTER_DEVNET_ENVIRONMENT, POLYESTER_SESSION_COOKIE_NAME, POLYESTER_TESTNET_ENVIRONMENT, type PairConfig, type PairStatus, type PauseTriggerInput, type PauseTriggerResult, PermissionError, type PolicyAction, PolicyInUseError, PolicyLockedError, type PolicyMarketScope, PolicyScopeMismatchError, type PolyesterAccountAbstractionEnvironment, PolyesterBrowserClient, type PolyesterBrowserClientConfig, PolyesterBrowserCore, PolyesterClient, type PolyesterClientBaseConfig, type PolyesterClientConfig, type PolyesterContractsEnvironment, PolyesterCore, type PolyesterEntryPointConfig, type PolyesterEnvironment, PolyesterError, type PolyesterErrorCode, type PolyesterErrorDetail, type PolyesterErrorOptions, type PolyesterMutationOptions, type PolyesterRealtime, type PolyesterRealtimeAuthConfig, type PolyesterRequestOptions, type PolyesterSafeDeploymentConfig, PolyesterServerClient, type PolyesterServerClientConfig, PolyesterServerCore, type PolyesterServices, type PortfolioEquityHistoryInput, type PortfolioEquityHistoryResponse, type PortfolioEquitySeries, type PortfolioEquitySeriesGrouping, type PortfolioEquitySnapshotResponse, PreconditionFailedError, type PrepareAssistantKeysInput, type PrepareAssistantKeysResult, type PreparedAssistantKey, type PreparedTradingWithdraw, type PreviewOrderResult, type PriceAlert, type PriceAlertChannel, type PriceAlertDirection, type PriceAlertPriceSource, type PriceAlertStatus, type PriceAlertUpdateOutcome, type PrivateOrdersEvent, type Profile, type QuoteDustConversionInput, type RateLimitConfig, type RateLimitDetail, RateLimitError, type RateLimitErrorOptions, type RateLimitFailureReason, type RateLimitPolicyClass, type RateLimitRefillModel, type RateLimitScope, type RealtimeConnection, type RealtimeConnectionState, type RealtimeConnectionStatus, RealtimeError, type RealtimeErrorOptions, type RegenerateRecoveryCodesInput, type RegenerateRecoveryCodesResult, type ReleaseFreshStepUpInput, type RemoveSubaccountMemberInput, RequestDeadlineExceededError, RequestError, RequestTooLargeError, type ResolveAccountInput, type ResolvedAccount, type ResolvedInternalTransferDestination, ResourceNotFoundError, type RespondSubaccountInviteInput, type ResumeTriggerInput, type ResumeTriggerResult, RevisionConflictError, type RewardAward, type RewardFulfillmentMethod, type RewardFulfillmentState, type RiskPolicyInput, type RotateGuardSignerWalletResult, type SdkSubscriptionErrorContext, type SendAssistantMessageInput, type ServerSessionCookieOptions, type ServerSessionSnapshot, ServiceUnavailableError, type SessionData, SessionElevationRequiredError, type SetAssistantKeysInput, type SetAutoWithdrawRuleEnabledInput, type SetAutoWithdrawRuleInput, type SetRewardDestinationInput, type SetRewardDestinationResult, type SetSubaccountMemberMfaRequirementInput, type SetTelegramApprovalLimitsInput, type SignProtectedActionInput, type SocialProvider, type SocialProviderInput, type SocialVerification, type SocialVerificationErrorCode, type SocialVerificationMethod, type SocialVerificationStatus, type SparklineIntervalName, type SpotConfig, type SpotFeeDiscount, type SpotFeeRate, type SpotFeeRateBreakdown, type SpotPairVolumeSeries, type SpotVolumeHistoryInput, type SpotVolumeHistoryResponse, type StablecoinConversionRate, StaleQuoteError, type StartVerificationInput, type StartVerificationResponse, type Statement, type StatementExport, type StatementExportFailureReason, type StatementExportStatus, type StatementPage, type StatusEvent, type StatusEventImpact, type StatusEventKind, type StatusEventService, type StatusEventState, StepUpRequiredError, type StopDetailsOutput, type StopLossInput, type Subaccount, type SubaccountActivityInput, type SubaccountChallenge, SubaccountChallengeInvalidError, type SubaccountEvent, type SubaccountIdInput, type SubaccountInvite, type SubaccountInviteStatus, type SubaccountMember, type SubaccountPermission, type SubaccountPermissionDefinition, type SubaccountPolicy, type SubaccountPolicyApplyInput, type SubaccountPolicyCreateInput, type SubaccountPolicyUpdateInput, type SubaccountRole, type SubaccountRoleCatalog, type SubaccountRoleDefinition, type SubaccountScopedInput, type SubaccountStatus, type SubscribeHandlers, type SubscribeZippedAssetSupplyInput, type SystemVersion, type TakeProfitInput, type TelegramApprovalAction, type TelegramApprovalLimits, type Timeframe, TimeoutError, TimestampSkewError, type Trade, type TradeBackfill, type TradingRateLimitClass, type TradingRateLimitRule, type TradingRateLimits, type TradingWithdrawSigningConfig, type TradingWithdrawWalletSigner, type TrailingDetailsOutput, type TrailingStopInput, type TransferCodeValue, type TransferCounterparties, type TransferCounterparty, type TransferDestination, type TransferDestinations, type TransferSideKind, TransientError, type Transports, type Trigger, type TriggerDetailsOutput, type TriggerEvent, type TwapDetailsOutput, type UnifiedAssetBalancesResponse, type UnlinkSocialAccountInput, type UpdateAddressBookEntryInput, type UpdateAddressBookTagInput, type UpdateMfaFactorInput, type UpdateMfaFactorResult, type UpdatePriceAlertInput, type UpdatePriceAlertResult, type UpdateProfileInput, type UpdateSubaccountInput, type UpdateSubaccountMemberRoleInput, UserOperationAlreadyKnownError, UserOperationNotExecutedError, UserOperationSendTimeoutError, type UsernameHistoryEntry, type ValidateWithdrawDestinationInput, type ValidateWithdrawDestinationResult, ValidationError, type VerificationReadyResponse, type VerifyRecoveryCodeChallengeInput, type VerifyTotpChallengeInput, type VipMetricQuality, type VipMetricStatus, type VipStatus, type VipTier, type VipTierCatalog, type WalletChallenge, type WatchAssistantRunInput, WithdrawDeadlineExpiredError, type WithdrawWhitelistView, type ZippedAssetSupplyBatch, type ZippedAssetSupplyGroupResponse, type ZippedAssetSupplyResponse, type ZippedAssetSupplySeries, type ZippedAssetSupplyUpdate, type ZipperAssetChainVariant, type ZipperAssetConfig, type ZipperChainConfig, type ZipperChainContractConfig, type ZipperMemoRequirement, type ZipperRouteStatus, checksumEvmAddress, columnarTimestampSecAt, compareUnsignedIntegerStrings, connectErrorToPolyesterError, createCookieAuthTokenStorage, createErrorMappingInterceptor, createMemoryAuthTokenStorage, createPolyesterEnvironment, createPolyesterServerClientFromCookies, createPolyesterServerClientFromRequest, createPolyesterServerCoreFromCookies, createPolyesterServerCoreFromRequest, errorFromHttpStatus, evmHexToBytes, evmUtf8ToBytes, evmUtf8ToHex, expandColumnarTimestampsSec, formatConnectError, formatLedgerBalance, formatUserFacingError, isAbortError, isEvmAddress, isEvmAddressStrict, isFreshStepUpRequiredError, isMfaEnrollmentRequiredError, isMfaLastFactorRequiredError, isPolicyInUseError, isPolicyLockedError, isPolicyScopeMismatchError, isResourceNotFoundError, isRetryableError, isRevisionConflictError, isSessionElevationRequiredError, isTimeoutAbortError, keccak256Hex, loadErrorDetailDecoders, mergeLedgerBalances, normalizeErrorMessage, resolveAuthCookieName, shouldApplyReconciliationUpdate, tsObjToNsString as timestampToNanoseconds, toPolyesterError, validateCreateAddressBookEntryInput };
153
+ export { type AccountActivityEvent, type AccountCodeValue, type AccountIdentity, type AccountNotification, type AccountNotificationDetail, type AccountScope, type AccountScopedInput, type AccountSigner, type AccountSignerAuthEvents, type AccountSignerConfig, type CreateSubaccountResult as AccountSignerCreateSubaccountResult, type AccountSignerFactory, type AcknowledgeRewardAwardInput, type AcknowledgeRewardAwardResult, type ActiveAccountInfo, type AddressBook, type AddressBookAccountScope, type AddressBookEntries, type AddressBookEntriesView, type AddressBookEntry, type AddressBookRecentDestinationsView, type AddressBookTag, type AddressBookTagSummary, type AddressBookView, type AddressBookViewInvalidated, AlreadyExistsError, type ApiKey, type ApiKeyEd25519AuthProvider, type ApiKeyIdInput, type ApiKeyPolicy, type ApiKeyPolicyApplyInput, type ApiKeyPolicyCreateInput, type ApiKeyPolicyUpdateInput, type ApiKeyStatus, type ApiKeysCreateInput, type ApiKeysListInput, type ApiKeysUpdateInput, type AssetConfig, type AssetDataSourceValue, type AssetEditorialInfo, type AssetInfo, type AssetMarketStats, type AssetMarketValue, type AssistantAccountSelection, type AssistantApprovalDecision, type AssistantApprovalPreview, type AssistantApprovalStatus, type AssistantConversation, type AssistantDisplaySetting, type AssistantFailureCategory, type AssistantFundingMode, type AssistantKey, type AssistantKeyPreset, type AssistantKeySpecInput, type AssistantKeyState, type AssistantKeyView, type AssistantMemory, type AssistantMemoryKind, type AssistantMessage, type AssistantMessageImage, type AssistantMessageRole, type AssistantModelKey, type AssistantModelKeyCheck, type AssistantOrderPreview, type AssistantOrderPriceField, type AssistantPriceOffsetDirection, type AssistantPriceRounding, type AssistantReferencePriceSource, type AssistantRunEvent, type AssistantRunIdInput, type AssistantTriggerChangeAction, type AssistantTriggerDirection, type AssistantUnfilledSlicePolicy, type AssistantUsage, type AssistantView, type AuthCookieLocation, type AuthHydrationData, type AuthLoginMethod, type AuthState, type AuthTokenStorage, type AuthTokenStorageSetOptions, AuthenticationError, type AutoWithdrawCadence, type AutoWithdrawDestination, type AutoWithdrawDestinationInput, type AutoWithdrawHoldReason, type AutoWithdrawPause, type AutoWithdrawPauseReason, type AutoWithdrawPreview, type AutoWithdrawPreviewAsset, type AutoWithdrawPreviewStatus, type AutoWithdrawRule, type AutoWithdrawRun, type AutoWithdrawRunReason, type AutoWithdrawRunState, type AutoWithdrawSchedule, type AutoWithdrawScheduleInput, type AutoWithdrawScopedInput, type AutoWithdrawStep, type AutoWithdrawStepReason, type AutoWithdrawStepState, type AutoWithdrawWeekday, type BalanceHistoryInput, type BalanceHistoryResponse, type BalanceRange, type BatchCancelOrderInput, type BatchCancelOrderResult, type BatchCancelOrdersInput, type BatchCancelOrdersResult, type BatchCancelTriggerResult, type BatchCancelTriggersInput, type BatchCancelTriggersResult, type BatchCreateInternalTransfersInput, type BatchCreateInternalTransfersResult, type BatchCreateOrderResult, type BatchCreateOrdersInput, type BatchCreateOrdersResult, type BatchGuardApprovals, type BatchReplaceAdmissionItem, type BatchReplaceOrdersInput, type BatchReplaceOrdersResult, type BatchSignProtectedActionInput, type BeginMfaChallengeInput, type BeginMfaChallengeResult, type BeginPasskeyEnrollmentInput, type BeginPasskeyEnrollmentResult, type BeginTotpEnrollmentInput, type BeginTotpEnrollmentResult, type BrokerAllowlistAction, type BrokerAllowlistEvent, type CancelAllAfterInput, type CancelAllAfterResult, type CancelAllOrdersInput, type CancelAllOrdersResponse, type CancelOcoInput, type CancelOcoResult, type CancelOrderInput, type CancelOrderResult, type CancelPriceAlertInput, type CancelStatementExportInput, type CancelTriggerInput, type CancelTriggerResult, type Candle, type CandleColumnar, type CandleColumnarInt, type CandleInt, type ChainAnalyticsRange, type ChangelogAudience, type ChangelogChange, type ChangelogChangeAvailability, type ChangelogChangeCategory, type ChangelogChangeEntry, type ChangelogDeploymentGroup, type ChangelogDeploymentGroupSummary, type ChangelogEnvironment, type ChangelogPost, type ChangelogPostSummary, type ChangelogSection, type ChangelogSort, type ChangelogSurface, type Checkpoint, type CheckpointAssetAmount, type CheckpointBadge, type CheckpointBiggestTrade, type CheckpointChainFlow, type CheckpointEarnedBadge, type CheckpointField, type CheckpointFlowTotal, type CheckpointFundingDay, type CheckpointFundingFlowSummary, type CheckpointOrderToolCounts, type CheckpointOrderTypeCounts, type CheckpointPairActivity, type CheckpointPortfolioValuePoint, type CheckpointTimeInForceCounts, type CheckpointVipTierChange, type CheckpointVolumePoint, type ClaimCampaign, type ClaimDailyRewardInput, type ClaimDailyRewardResult, type ClaimFreshStepUpInput, type ClaimFreshStepUpResult, type ClaimGeneratedUsernameInput, ClaimOutcomeUnknownError, type ClaimOutcomeUnknownErrorOptions, type ClaimPayoutDelayReason, type ClaimPolicy, type ColumnarTimeWindow, type CompleteAssistantKeysInput, type CompleteMfaChallengeResult, ConfigurationError, type ConfirmVerificationInput, type ConnectChannelParams, type ConnectPrivateOrdersParams, type ConsumeFreshStepUpInput, type CookieAuthTokenStorageOptions, type CopyAddressBookEntryInput, type CreateAddressBookEntryInput, type CreateAddressBookTagInput, type CreateDepositAddressInput, type CreateDustConversionInput, type CreateGuardSignerWalletResult, type CreateInternalTransferInput, type CreateInternalTransferResult, type CreateOcoInput, type CreateOcoResult, type CreateOrderResult, type CreateOrderbookSubscriptionInput, type CreatePolyesterAccountSignerParams, type CreatePolyesterEnvironmentParams, type CreatePriceAlertInput, type CreateServerClientFromCookiesParams, type CreateServerClientFromRequestParams, type CreateStatementExportInput, type CreateSubaccountChallengeInput, type CreateSubaccountInput, type CreateSubaccountParams, type CreateSubaccountResult$1 as CreateSubaccountResult, type CreateSubaccountResult$1 as CreateSubaccountServiceResult, type CreateTradingWithdrawResult, type CreateTradingWithdrawToExternalChainInput, type CreateTradingWithdrawToExternalChainServiceInput, type CreateTradingWithdrawToFundingInput, type CreateTradingWithdrawToFundingServiceInput, type CreateTriggerInput, type CreateTriggerResult, type CreateWalletChallengeInput, type CurrencyConversionConfig, type CurrencyConversionRates, type CurrencyMetadata, type DailyClaimReward, type DailyClaimState, type DailyClaimStatus, type DailyClaimTransfer, type DecideAssistantApprovalInput, type DeleteAddressBookEntryInput, type DeleteAddressBookTagInput, type DeleteAssistantMemoryInput, type DeleteMfaFactorInput, type DepositAddress, type DepositWithdrawConfig, type DustAssetEligibility, type DustAssetPrice, type DustBalance, type DustConversion, type DustConversionQuote, type DustConversionRefusalCode, type DustConversionState, type EffectiveSubaccountPermissions, type EquityGroupBy, type EquityHistoryInput, type EquityHistoryResponse, type EquitySeries, type EquitySeriesGrouping, type EvmHex, type ExportGuardSignerWalletResult, type FiatConversionRate, type FiatConversionSnapshot, type FinishPasskeyChallengeInput, type FinishPasskeyEnrollmentInput, type FinishPasskeyEnrollmentResult, type FinishTotpEnrollmentInput, type FinishTotpEnrollmentResult, type GeneratedUsernameOffer, type GetAddressBookViewInput, type GetAssistantMessageImageInput, type GetBatchReplaceStatusInput, type GetBatchReplaceStatusResult, type GetCandlesColumnsInput, type GetCandlesInput, type GetChangelogDeploymentGroupInput, type GetChangelogPostInput, type GetDustConversionInput, type GetInternalTransferBatchInput, type GetInternalTransferInput, type GetInternalTransferResult, type GetLifecycleAccountFlowInput, type GetLifecycleFlowInput, type GetLifecycleFlowOutput, type GetMarketTradesInput, type GetNotificationInput, type GetOrderDetailsInput, type GetOrderbookHeatmapInput, type GetOrderbookInput, type GetSpotFeeRatesInput, type GetStatementExportDownloadUrlInput, type GetStatementExportInput, type GetSubaccountInput, type GetTriggerInput, type GetUnifiedAssetBalancesInput, type GetUserTradesInput, type GetVerificationResponse, type GetWalletBalancesInput, type GetWalletBalancesResult, type GetZippedAssetSupplyGroupInput, type GetZippedAssetSupplyInput, type GuardApproval, type GuardSignerScopedInput, type GuardSignerStatus, type HeatmapDepthValue, type HeatmapIntervalValue, type HeatmapQuantityModeValue, type HexAddress, InternalServerError, type InternalTransferBatchLegInput, type InternalTransferBatchLegResult, type InternalTransferBatchLegStatus, type InternalTransferBatchStatus, type InternalTransferDestination, type InternalTransferErrorCode, type InternalTransferStatus, type InternalTransferWhitelistEntries, type InternalTransferWhitelistEntry, type InviteSubaccountMemberInput, type JwtAuthProvider, type LadderDetailsOutput, type LedgerBalance, type LedgerTransfer, type LedgerTransferSide, type LifecycleAssetIds, type LifecycleFlowDetail, type LifecycleFlowState, type LifecycleFlowStep, type LifecycleFlowStepActivity, type LifecycleFlowSummary, type LifecycleFlowSummaryProgress, type LifecycleFlowTimelineItem, type LifecycleFlowTxMatch, type LifecycleListOrderBy, type LifecycleListScope, type LifecycleReason, type LifecycleRequestFee, type LifecycleRequestFeeStatus, type LifecycleSort, type LifecycleTxLookupKind, type LifecycleZipperReason, type LifecycleZipperReasonCode, type ListAccountActivityInput, type ListAccountActivityResult, type ListAddressBookEntriesInput, type ListApiKeyPoliciesResponse, type ListAssetInfoInput, type ListAssistantConversationsInput, type ListAssistantConversationsResult, type ListAssistantKeysInput, type ListAssistantMemoriesInput, type ListAssistantMemoriesResult, type ListAssistantMessagesInput, type ListAssistantMessagesResult, type ListAutoWithdrawRunsInput, type ListAutoWithdrawRunsResult, type ListChangelogChangesInput, type ListChangelogChangesResult, type ListChangelogDeploymentGroupsInput, type ListChangelogDeploymentGroupsResult, type ListChangelogPostsInput, type ListChangelogPostsResult, type ListCheckpointsInput, type ListDepositAddressesInput, type ListDustBalancesInput, type ListDustBalancesResult, type ListDustConversionsInput, type ListDustConversionsResult, type ListInternalTransferWhitelistEntriesInput, type ListLifecycleAccountFlowsInput, type ListLifecycleFlowsByTxInput, type ListLifecycleFlowsByTxOutput, type ListLifecycleFlowsInput, type ListLifecycleFlowsOutput, type ListMarketOverviewInput, type ListMfaFactorsResult, type ListNotificationsInput, type ListNotificationsResult, type ListPriceAlertsInput, type ListPriceAlertsResult, type ListRewardAwardsInput, type ListRewardAwardsResult, type ListStatementExportsInput, type ListStatementExportsResult, type ListStatusEventsInput, type ListStatusEventsResult, type ListSubaccountInvitesInput, type ListTransferCounterpartiesInput, type ListTransferDestinationsInput, type ListTransfersInput, type ListTriggerEventsInput, type ListTriggerEventsResult, type ListTriggersInput, type ListTriggersResult, type LoginOptions, type LoginResult, type LoginWithWalletInput, type LoginWithWalletResponse, type MarkAllNotificationsReadInput, type MarkNotificationsInput, type MarketOverview, type MarketOverviewOrderBy, type MarketOverviewSort, type MarketOverviewSparkline, type MarketTrade, type Me, MfaEnrollmentRequiredError, type MfaFactor, MfaLastFactorRequiredError, MfaRequiredError, type MfaSessionInfo, MfaVerificationError, type MfaVerificationFailureReason, type MirroredWithdrawWhitelistEntry, type ModifyOrderInput, type ModifyOrderResult, type ModifyTriggerInput, type ModifyTriggerResult, NetworkError, type NewOrderInput, type NextVipTierThresholds, NotImplementedError, type NotificationCategory, type NotificationCounts, type NotificationReadState, type NotificationType, type OpenOrdersInput, type Order, type OrderDetails, type OrderErrorCode, type OrderErrorDetail, type OrderHistoryInput, type OrderIntentInput, type OrderLineage, type OrderTransfer, type OrderbookData, type OrderbookHeatmapDeltaBucket, type OrderbookHeatmapDeltaChain, type OrderbookHeatmapDeltaLevels, type OrderbookHeatmapKeyframe, type OrderbookHeatmapLevels, type OrderbookHeatmapLiveBucket, type OrderbookHeatmapResponse, type OrderbookLevel, type OrderbookStreamHandlers, type OrderbookSubscription, OutcomeUnknownError, POLYESTER_AUTH_TOKEN_COOKIE_NAME, POLYESTER_DEVNET_ENVIRONMENT, POLYESTER_SESSION_COOKIE_NAME, POLYESTER_TESTNET_ENVIRONMENT, type PairConfig, type PairStatus, type PauseTriggerInput, type PauseTriggerResult, PermissionError, type PolicyAction, PolicyInUseError, PolicyLockedError, type PolicyMarketScope, PolicyScopeMismatchError, type PolyesterAccountAbstractionEnvironment, PolyesterBrowserClient, type PolyesterBrowserClientConfig, PolyesterBrowserCore, PolyesterClient, type PolyesterClientBaseConfig, type PolyesterClientConfig, type PolyesterContractsEnvironment, PolyesterCore, type PolyesterEntryPointConfig, type PolyesterEnvironment, PolyesterError, type PolyesterErrorCode, type PolyesterErrorDetail, type PolyesterErrorOptions, type PolyesterMutationOptions, type PolyesterRealtime, type PolyesterRealtimeAuthConfig, type PolyesterRequestOptions, type PolyesterSafeDeploymentConfig, PolyesterServerClient, type PolyesterServerClientConfig, PolyesterServerCore, type PolyesterServices, type PortfolioEquityHistoryInput, type PortfolioEquityHistoryResponse, type PortfolioEquitySeries, type PortfolioEquitySeriesGrouping, type PortfolioEquitySnapshotResponse, PreconditionFailedError, type PrepareAssistantKeysInput, type PrepareAssistantKeysResult, type PreparedAssistantKey, type PreparedTradingWithdraw, type PreviewOrderResult, type PriceAlert, type PriceAlertChannel, type PriceAlertDirection, type PriceAlertPriceSource, type PriceAlertStatus, type PriceAlertUpdateOutcome, type PrivateOrdersEvent, type Profile, type QuoteDustConversionInput, type RateLimitConfig, type RateLimitDetail, RateLimitError, type RateLimitErrorOptions, type RateLimitFailureReason, type RateLimitPolicyClass, type RateLimitRefillModel, type RateLimitScope, type RealtimeConnection, type RealtimeConnectionState, type RealtimeConnectionStatus, RealtimeError, type RealtimeErrorOptions, type RegenerateRecoveryCodesInput, type RegenerateRecoveryCodesResult, type ReleaseFreshStepUpInput, type RemoveSubaccountMemberInput, RequestDeadlineExceededError, RequestError, RequestTooLargeError, type ResolveAccountInput, type ResolvedAccount, type ResolvedInternalTransferDestination, ResourceNotFoundError, type RespondSubaccountInviteInput, type ResumeTriggerInput, type ResumeTriggerResult, RevisionConflictError, type RewardAward, type RewardFulfillmentMethod, type RewardFulfillmentState, type RiskPolicyInput, type RotateGuardSignerWalletResult, type SdkSubscriptionErrorContext, type SendAssistantMessageInput, type ServerSessionCookieOptions, type ServerSessionSnapshot, ServiceUnavailableError, type SessionData, SessionElevationRequiredError, type SetAssistantKeysInput, type SetAssistantModelKeyInput, type SetAutoWithdrawRuleEnabledInput, type SetAutoWithdrawRuleInput, type SetRewardDestinationInput, type SetRewardDestinationResult, type SetSubaccountMemberMfaRequirementInput, type SetTelegramApprovalLimitsInput, type SignProtectedActionInput, type SocialProvider, type SocialProviderInput, type SocialVerification, type SocialVerificationErrorCode, type SocialVerificationMethod, type SocialVerificationStatus, type SparklineIntervalName, type SpotConfig, type SpotFeeDiscount, type SpotFeeRate, type SpotFeeRateBreakdown, type SpotPairVolumeSeries, type SpotVolumeHistoryInput, type SpotVolumeHistoryResponse, type StablecoinConversionRate, StaleQuoteError, type StartVerificationInput, type StartVerificationResponse, type StatementExport, type StatementExportDownloadUrl, type StatementExportFailureReason, type StatementExportStatus, type StatusEvent, type StatusEventImpact, type StatusEventKind, type StatusEventService, type StatusEventState, StepUpRequiredError, type StopDetailsOutput, type StopLossInput, type Subaccount, type SubaccountActivityInput, type SubaccountChallenge, SubaccountChallengeInvalidError, type SubaccountEvent, type SubaccountIdInput, type SubaccountInvite, type SubaccountInviteStatus, type SubaccountMember, type SubaccountPermission, type SubaccountPermissionDefinition, type SubaccountPolicy, type SubaccountPolicyApplyInput, type SubaccountPolicyCreateInput, type SubaccountPolicyUpdateInput, type SubaccountRole, type SubaccountRoleCatalog, type SubaccountRoleDefinition, type SubaccountScopedInput, type SubaccountStatus, type SubscribeHandlers, type SubscribeZippedAssetSupplyInput, type SystemTime, type SystemVersion, type TakeProfitInput, type TelegramApprovalAction, type TelegramApprovalLimits, type Timeframe, TimeoutError, TimestampSkewError, type Trade, type TradeBackfill, type TradingRateLimitClass, type TradingRateLimitRule, type TradingRateLimits, type TradingWithdrawSigningConfig, type TradingWithdrawWalletSigner, type TrailingDetailsOutput, type TrailingStopInput, type TransferCodeValue, type TransferCounterparties, type TransferCounterparty, type TransferDestination, type TransferDestinations, type TransferSideKind, TransientError, type Transports, type Trigger, type TriggerDetailsOutput, type TriggerEvent, type TwapDetailsOutput, type UnifiedAssetBalancesResponse, type UnlinkSocialAccountInput, type UpdateAddressBookEntryInput, type UpdateAddressBookTagInput, type UpdateMfaFactorInput, type UpdateMfaFactorResult, type UpdatePriceAlertInput, type UpdatePriceAlertResult, type UpdateProfileInput, type UpdateSubaccountInput, type UpdateSubaccountMemberRoleInput, UserOperationAlreadyKnownError, UserOperationNotExecutedError, UserOperationSendTimeoutError, type UsernameHistoryEntry, type ValidateWithdrawDestinationInput, type ValidateWithdrawDestinationResult, ValidationError, type VerificationReadyResponse, type VerifyRecoveryCodeChallengeInput, type VerifyTotpChallengeInput, type VipMetricQuality, type VipMetricStatus, type VipStatus, type VipTier, type VipTierCatalog, type WalletAssetUnavailableReasonValue, type WalletChallenge, type WatchAssistantRunInput, WithdrawDeadlineExpiredError, type WithdrawWhitelistView, type ZippedAssetSupplyBatch, type ZippedAssetSupplyGroupResponse, type ZippedAssetSupplyResponse, type ZippedAssetSupplySeries, type ZippedAssetSupplyUpdate, type ZipperAssetChainVariant, type ZipperAssetConfig, type ZipperChainConfig, type ZipperChainContractConfig, type ZipperMemoRequirement, type ZipperRouteStatus, type ZipperSupplyStatus, checksumEvmAddress, columnarTimestampSecAt, compareUnsignedIntegerStrings, connectErrorToPolyesterError, createCookieAuthTokenStorage, createErrorMappingInterceptor, createMemoryAuthTokenStorage, createPolyesterEnvironment, createPolyesterServerClientFromCookies, createPolyesterServerClientFromRequest, createPolyesterServerCoreFromCookies, createPolyesterServerCoreFromRequest, errorFromHttpStatus, evmHexToBytes, evmUtf8ToBytes, evmUtf8ToHex, expandColumnarTimestampsSec, formatConnectError, formatLedgerBalance, formatUserFacingError, isAbortError, isEvmAddress, isEvmAddressStrict, isFreshStepUpRequiredError, isMfaEnrollmentRequiredError, isMfaLastFactorRequiredError, isPolicyInUseError, isPolicyLockedError, isPolicyScopeMismatchError, isResourceNotFoundError, isRetryableError, isRevisionConflictError, isSessionElevationRequiredError, isTimeoutAbortError, keccak256Hex, loadErrorDetailDecoders, mergeLedgerBalances, normalizeErrorMessage, resolveAuthCookieName, shouldApplyReconciliationUpdate, tsObjToNsString as timestampToNanoseconds, toPolyesterError, validateCreateAddressBookEntryInput };
@@ -603,7 +603,11 @@ var RealtimeClient = class {
603
603
  * is reported to `onError`, or thrown synchronously when no error observer is provided.
604
604
  * Throws ValidationError when `accountId` is not a base58 public ID.
605
605
  */
606
- connectPrivateOrders(params) {
606
+ connectPrivateOrders(input) {
607
+ const params = {
608
+ ...input,
609
+ accountId: input.accountId.trim()
610
+ };
607
611
  idToBigInt(params.accountId, "accountId");
608
612
  const channel = `private:spot:orders:${params.accountId}`;
609
613
  if (!this.#hasAuth()) {
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","names":["#config","#fetch","#getAuthHeaders","#fetchToken","#tokenRetryAt","#emitErrors","#sharedSubs","#channelKind","#fetchSubscriptionToken","#emitSubscriptionError","#publicClient","#watchClient","#privateClient","#emitConnectionTokenError","#privateTokenFailure","#connection","#connectionListeners","#setConnection","#currentClient","#transportErrors","#terminateSubscriptions","#pendingTeardowns","#createPublicClient","#hasAuth","#createPrivateClient","#ensurePublicClient","#assertChannelAuth","#attachSubscriptionNow","#attachSubscriptionWhenLoaded","#ensureClientForChannel","#subscriptionOpts","#attachSubscription","#callErrorHandler","#teardownSubscription","#dropConsumers","#disconnectClientIfIdle","#hasChannelsForKind","#privateOrdersEpoch","#privateOrders","#disconnectPrivateOrders","#disconnectCentrifuge","#getOrCreateSubscription","#reportAuthErrorLater","#callConsumerHandler","#privateOrdersLoading","#disconnect","#disconnectPrivate"],"sources":["../../src/realtime/client.ts"],"sourcesContent":["import { fromBinary, type DescMessage, type MessageShape } from \"@bufbuild/protobuf\";\nimport type {\n Centrifuge,\n ErrorContext,\n SubscriptionErrorContext,\n PublicationContext,\n Subscription,\n} from \"centrifuge/build/protobuf\";\nimport type * as CentrifugeModule from \"centrifuge/build/protobuf\";\nimport {\n createSdkSubscriptionErrorContext,\n fromCentrifugeSubscriptionError,\n type SdkSubscriptionErrorContext,\n} from \"../shared/subscription-errors.js\";\nimport {\n AuthenticationError,\n errorFromHttpStatus,\n InternalServerError,\n PolyesterError,\n RealtimeError,\n} from \"../shared/errors.js\";\nimport { parseRetryAfterHeader } from \"../shared/connect-error-mapping.js\";\nimport { makeFetch } from \"../shared/transports.js\";\nimport { decodeProtoFrame } from \"../utils/streams.js\";\nimport { idToBigInt } from \"../utils/base58-id.js\";\nimport type {\n ConnectChannelParams,\n PolyesterRealtime,\n RealtimeConnection,\n RealtimeConnectionStatus,\n SubscribeHandlers,\n} from \"./types.js\";\nimport type { ConnectPrivateOrdersParams, PrivateOrderStream } from \"./private-orders.js\";\n\n// ponytail: caps a bogus or huge Retry-After; a longer server window just answers 429 again with a new hint.\nconst MAX_RETRY_AFTER_MS = 60_000;\n\ntype CentrifugeCtor = typeof CentrifugeModule.Centrifuge;\ntype CentrifugeModuleLoader = () => Promise<typeof CentrifugeModule>;\n\nconst defaultCentrifugeModuleLoader: CentrifugeModuleLoader = () =>\n import(\"centrifuge/build/protobuf\");\n\n// Centrifuge's protobuf build embeds the protobuf.js runtime (~300 KB minified).\n// Loading it lazily keeps it out of the eager module graph on both the server\n// (Cloudflare isolate cold start — SSR never opens a websocket) and the client\n// app shell; it is only fetched when the first subscription attaches.\nlet centrifugeCtorPromise: Promise<CentrifugeCtor> | null = null;\nlet loadedCentrifugeCtor: CentrifugeCtor | null = null;\nlet centrifugeModuleLoader = defaultCentrifugeModuleLoader;\nexport function __setRealtimeCentrifugeForTests(Centrifuge: CentrifugeCtor | null): void {\n loadedCentrifugeCtor = Centrifuge;\n centrifugeCtorPromise = Centrifuge ? Promise.resolve(Centrifuge) : null;\n}\n\n/** Replaces the lazy Centrifuge module loader for isolated transport-load tests. */\nexport function __setRealtimeCentrifugeLoaderForTests(loader: CentrifugeModuleLoader | null): void {\n centrifugeModuleLoader = loader ?? defaultCentrifugeModuleLoader;\n loadedCentrifugeCtor = null;\n centrifugeCtorPromise = null;\n}\n\nfunction loadCentrifuge(): Promise<CentrifugeCtor> {\n if (\n centrifugeModuleLoader === defaultCentrifugeModuleLoader &&\n (import.meta as { env?: { SSR?: boolean } }).env?.SSR\n ) {\n return Promise.reject(new Error(\"Realtime subscriptions are browser-only during SSR.\"));\n }\n\n if (!centrifugeCtorPromise) {\n const loadAttempt = Promise.resolve().then(centrifugeModuleLoader);\n const retryableLoad = loadAttempt.then(\n (mod) => {\n loadedCentrifugeCtor = mod.Centrifuge;\n return mod.Centrifuge;\n },\n (error) => {\n if (centrifugeCtorPromise === retryableLoad) centrifugeCtorPromise = null;\n throw error;\n },\n );\n centrifugeCtorPromise = retryableLoad;\n }\n return centrifugeCtorPromise;\n}\n\nexport interface RealtimeAuthRequest {\n url: string | URL;\n method: string;\n}\n\nexport interface RealtimeConfig {\n wsUrl: string;\n tokenEndpoint: string;\n subscribeEndpoint: string;\n /** Private WebSocket endpoint for account order streams (`/v1/ws/private`). */\n privateWsUrl: string;\n getAuthHeaders?: (request: RealtimeAuthRequest) => Promise<HeadersInit> | HeadersInit;\n hasAuth?: () => boolean;\n /**\n * Custom fetch implementation for realtime token requests. Defaults to the\n * global `fetch`, resolved on each request.\n */\n fetch?: typeof fetch;\n}\n\ntype ResolvedRealtimeConfig = Pick<\n RealtimeConfig,\n \"wsUrl\" | \"tokenEndpoint\" | \"subscribeEndpoint\" | \"privateWsUrl\"\n> & {\n getAuthHeaders: (request: RealtimeAuthRequest) => Promise<HeadersInit> | HeadersInit;\n hasAuth: () => boolean;\n};\n\nexport type { ConnectChannelParams, PolyesterRealtime, SubscribeHandlers } from \"./types.js\";\n\ntype PublicationHandler<T = unknown> = (data: T) => void;\ntype ErrorHandler = (ctx: SdkSubscriptionErrorContext) => void;\ntype RealtimeClientKind = \"public\" | \"private\";\n\nconst DISCONNECTED: RealtimeConnectionStatus = { state: \"disconnected\", error: null };\n/** Centrifuge client `error` types that mean a connect attempt failed; each retry emits one. */\nconst CONNECT_FAILURE_TYPES = new Set([\"transport\", \"connect\", \"connectToken\", \"connectData\"]);\n\ninterface SharedSubscription {\n channel: string;\n sub: Subscription | null;\n client: Centrifuge | null;\n attachmentEpoch: number;\n consumers: number;\n subscriptionEpoch: number;\n publicationHandlers: Set<PublicationHandler>;\n subscribedHandlers: Set<(epoch: number) => void>;\n unsubscribedHandlers: Set<() => void>;\n errorHandlers: Set<ErrorHandler>;\n}\n\n/**\n * Shared Centrifuge realtime client that multiplexes public and private protobuf subscriptions across SDK services.\n */\nexport class RealtimeClient implements PolyesterRealtime {\n #publicClient: Centrifuge | null = null;\n #privateClient: Centrifuge | null = null;\n #sharedSubs = new Map<string, SharedSubscription>();\n #pendingTeardowns = new Map<string, SharedSubscription>();\n // Loaded on first use: the stream's protobuf graph (orders included) stays out of the app shell.\n #privateOrdersLoading: Promise<PrivateOrderStream> | null = null;\n #privateOrders: PrivateOrderStream | null = null;\n #privateOrdersEpoch = 0;\n #connection: RealtimeConnection = { public: DISCONNECTED, private: DISCONNECTED };\n #connectionListeners = new Set<(connection: RealtimeConnection) => void>();\n /** Outage errors already sent to channels as `\"transport\"`; replayed to late subscribers. */\n #transportErrors = new WeakSet<Error>();\n /** The non-retryable connection token failure that stops the private socket (code 1). */\n #privateTokenFailure: Error | null = null;\n /** Token requests wait until then after a 429 with `Retry-After`. */\n #tokenRetryAt = 0;\n readonly #config: ResolvedRealtimeConfig;\n readonly #fetch: typeof fetch;\n\n constructor(config: RealtimeConfig) {\n this.#fetch = makeFetch(config.fetch);\n this.#config = {\n wsUrl: config.wsUrl,\n tokenEndpoint: config.tokenEndpoint,\n subscribeEndpoint: config.subscribeEndpoint,\n privateWsUrl: config.privateWsUrl,\n getAuthHeaders: config.getAuthHeaders ?? (() => ({})),\n hasAuth: config.hasAuth ?? (() => false),\n };\n }\n\n async #getAuthHeaders(request: RealtimeAuthRequest): Promise<HeadersInit> {\n return this.#config.getAuthHeaders(request);\n }\n\n /**\n * Every realtime token request (connection, subscription, private order stream)\n * comes through here, so one wait honors `Retry-After` for all of them; the\n * transport's own reconnect backoff still applies on top.\n */\n async #fetchToken(url: string | URL, kind: \"connection\" | \"subscription\"): Promise<string> {\n // Recheck after each await: another request's 429 may have pushed the deadline out.\n let headers: HeadersInit;\n do {\n for (let wait; (wait = this.#tokenRetryAt - Date.now()) > 0;) {\n await new Promise((resolve) => setTimeout(resolve, wait));\n }\n headers = await this.#getAuthHeaders({ url, method: \"GET\" });\n } while (this.#tokenRetryAt > Date.now());\n const res = await this.#fetch(url, { headers });\n if (!res.ok) {\n const retryAfterMs = parseRetryAfterHeader(res.headers.get(\"retry-after\"));\n if (res.status === 429 && retryAfterMs !== undefined) {\n this.#tokenRetryAt = Math.max(\n this.#tokenRetryAt,\n Date.now() + Math.min(retryAfterMs, MAX_RETRY_AFTER_MS),\n );\n }\n throw errorFromHttpStatus(res.status, `Failed to fetch ${kind} token: ${res.status}`, {\n status: res.status,\n retryAfterMs,\n });\n }\n const json = (await res.json()) as { token?: string };\n if (!json?.token) {\n throw new InternalServerError(\n `${kind === \"connection\" ? \"Connection\" : \"Subscription\"} token response had no token`,\n );\n }\n return json.token;\n }\n\n #fetchSubscriptionToken(channel: string): Promise<string> {\n const url = new URL(this.#config.subscribeEndpoint);\n url.searchParams.set(\"channel\", channel);\n return this.#fetchToken(url, \"subscription\");\n }\n\n /**\n * Delivers to the consumers registered when it starts: one a handler adds (a resubscribe)\n * is not part of it, and one a handler removes is skipped.\n */\n #emitErrors(recipients: SharedSubscription[], type: string, error: unknown): void {\n const deliveries = recipients.map((shared) => ({\n shared,\n ctx: createSdkSubscriptionErrorContext(shared.channel, type, error),\n handlers: Array.from(shared.errorHandlers),\n }));\n for (const { shared, ctx, handlers } of deliveries) {\n for (const handler of handlers) {\n if (shared.errorHandlers.has(handler)) handler(ctx);\n }\n }\n }\n\n #emitSubscriptionError(shared: SharedSubscription, type: string, error: unknown): void {\n this.#emitErrors([shared], type, error);\n }\n\n #emitConnectionTokenError(error: unknown): void {\n const privateSubs = [...this.#sharedSubs.values()].filter(\n (shared) => this.#channelKind(shared.channel) === \"private\",\n );\n this.#emitErrors(privateSubs, \"connection_token\", error);\n }\n\n #subscriptionOpts(\n Centrifuge: CentrifugeCtor,\n shared: SharedSubscription,\n attachmentEpoch: number,\n ) {\n if (this.#channelKind(shared.channel) !== \"private\") return undefined;\n return {\n getToken: async () => {\n try {\n return await this.#fetchSubscriptionToken(shared.channel);\n } catch (error) {\n if (shared.attachmentEpoch === attachmentEpoch) {\n this.#emitSubscriptionError(shared, \"subscription_token\", error);\n }\n if (error instanceof PolyesterError && !error.retryable) {\n throw new Centrifuge.UnauthorizedError(error.message);\n }\n throw error;\n }\n },\n };\n }\n\n #hasAuth(): boolean {\n return this.#config.hasAuth();\n }\n\n #channelKind(channel: string): RealtimeClientKind {\n return channel.startsWith(\"private:\") ? \"private\" : \"public\";\n }\n\n #createPublicClient(Centrifuge: CentrifugeCtor): Centrifuge {\n const client = new Centrifuge(this.#config.wsUrl);\n this.#publicClient = client;\n this.#watchClient(client, \"public\");\n client.connect();\n return client;\n }\n\n #createPrivateClient(Centrifuge: CentrifugeCtor): Centrifuge {\n let client: Centrifuge;\n const opts = {\n getToken: async () => {\n try {\n return await this.#fetchToken(this.#config.tokenEndpoint, \"connection\");\n } catch (error) {\n if (this.#privateClient === client) {\n this.#emitConnectionTokenError(error);\n }\n if (error instanceof PolyesterError && !error.retryable) {\n if (this.#privateClient === client) this.#privateTokenFailure = error;\n throw new Centrifuge.UnauthorizedError(error.message);\n }\n throw error;\n }\n },\n };\n\n client = new Centrifuge(this.#config.wsUrl, opts);\n this.#privateClient = client;\n this.#privateTokenFailure = null;\n this.#watchClient(client, \"private\");\n client.connect();\n return client;\n }\n\n #currentClient(kind: RealtimeClientKind): Centrifuge | null {\n return kind === \"private\" ? this.#privateClient : this.#publicClient;\n }\n\n #setConnection(kind: RealtimeClientKind, status: RealtimeConnectionStatus): void {\n const current = this.#connection[kind];\n if (current.state === status.state && current.error === status.error) return;\n this.#connection = { ...this.#connection, [kind]: status };\n const connection = this.#connection;\n // Notify once Centrifuge has finished its transition, so a listener can disconnect or\n // subscribe safely. A newer status replaces this one, even mid-delivery.\n // Snapshot: a listener added during delivery (one replacing itself) waits for the next change.\n queueMicrotask(() => {\n for (const listener of Array.from(this.#connectionListeners)) {\n if (this.#connection !== connection) return;\n if (!this.#connectionListeners.has(listener)) continue;\n try {\n listener(connection);\n } catch {\n // Keep one listener from starving the others.\n }\n }\n });\n }\n\n #watchClient(client: Centrifuge, kind: RealtimeClientKind): void {\n this.#setConnection(kind, { state: \"connecting\", error: null });\n\n client.on(\"state\", ({ newState, oldState }) => {\n // `disconnected` is recorded by the handlers below, which know the reason.\n if (this.#currentClient(kind) !== client || newState === \"disconnected\") return;\n // A restart after a terminal close starts a new outage.\n const { error } = this.#connection[kind];\n this.#setConnection(kind, {\n state: newState,\n error: newState === \"connected\" || oldState === \"disconnected\" ? null : error,\n });\n });\n\n // Centrifuge stays in \"connecting\" across failed attempts, so the `connecting`\n // event fires once; each failed attempt arrives as a client `error` instead.\n client.on(\"error\", (ctx: ErrorContext) => {\n if (this.#currentClient(kind) !== client || !CONNECT_FAILURE_TYPES.has(ctx.type))\n return;\n const { code, message } = ctx.error as { code?: unknown; message?: unknown };\n // 109: the cached token expired; Centrifuge fetches a new one and reconnects.\n if (ctx.type === \"connect\" && code === 109) return;\n // Report the first failure of an outage only, not every reconnect retry. A token\n // failure only marks the status (private channels get \"connection_token\" from\n // getToken), so a socket failure after one is still sent to channels.\n const current = this.#connection[kind].error;\n if (current && (ctx.type === \"connectToken\" || this.#transportErrors.has(current)))\n return;\n const error = new RealtimeError(\n `Realtime ${kind} connection failed: ${typeof message === \"string\" && message ? message : ctx.type}`,\n { realtimeCode: typeof code === \"number\" ? code : 0, retryable: true },\n );\n this.#setConnection(kind, { state: \"connecting\", error });\n // Private channels already receive connection token failures as \"connection_token\".\n if (ctx.type === \"connectToken\") return;\n this.#transportErrors.add(error);\n // A consumer added by a handler gets the replay in subscribe() instead.\n const affected = [...this.#sharedSubs.values()].filter(\n (shared) => shared.client === client,\n );\n this.#emitErrors(affected, \"transport\", error);\n });\n\n client.on(\"disconnected\", (ctx) => {\n // Code 0 (disconnectCalled) comes from our own teardown, which drops the client first.\n if (this.#currentClient(kind) !== client || ctx.code === 0) return;\n // Centrifuge reports a rejected private token as \"unauthorized\"; record the real failure.\n const tokenFailure =\n kind === \"private\" && ctx.code === 1 ? this.#privateTokenFailure : null;\n if (kind === \"private\") this.#privateTokenFailure = null;\n this.#setConnection(kind, {\n state: \"disconnected\",\n error:\n tokenFailure ??\n new RealtimeError(ctx.reason || \"Realtime connection closed\", {\n realtimeCode: ctx.code,\n }),\n });\n // Code 1 (unauthorized) on the private socket: channels already got the token\n // error, and an explicit subscribe() restarts this client, so keep it. The public\n // socket has no token to fix, so there it is terminal like any other close.\n if (ctx.code === 1 && kind === \"private\") return;\n if (kind === \"private\") this.#privateClient = null;\n else this.#publicClient = null;\n this.#terminateSubscriptions(\n [...this.#sharedSubs.values(), ...this.#pendingTeardowns.values()].filter(\n (shared) => shared.client === client,\n ),\n \"disconnected\",\n ctx,\n );\n });\n }\n\n #ensurePublicClient(Centrifuge: CentrifugeCtor): Centrifuge {\n return this.#publicClient ?? this.#createPublicClient(Centrifuge);\n }\n\n #assertChannelAuth(channel: string): void {\n if (this.#channelKind(channel) === \"private\" && !this.#hasAuth()) {\n throw new AuthenticationError(\n `Cannot subscribe to private channel \"${channel}\" without authentication`,\n );\n }\n }\n\n #ensureClientForChannel(Centrifuge: CentrifugeCtor, channel: string): Centrifuge {\n if (this.#channelKind(channel) === \"private\") {\n return this.#privateClient ?? this.#createPrivateClient(Centrifuge);\n }\n\n return this.#ensurePublicClient(Centrifuge);\n }\n\n #attachSubscription(shared: SharedSubscription): void {\n if (shared.sub) return;\n\n // Auth failures must surface synchronously to subscribe() callers, as\n // they did when centrifuge was imported statically.\n this.#assertChannelAuth(shared.channel);\n\n const attachmentEpoch = shared.attachmentEpoch + 1;\n shared.attachmentEpoch = attachmentEpoch;\n\n // Once the transport module is loaded, attachment stays fully\n // synchronous — only the very first attach pays the dynamic import.\n if (loadedCentrifugeCtor) {\n this.#attachSubscriptionNow(loadedCentrifugeCtor, shared, attachmentEpoch);\n return;\n }\n void this.#attachSubscriptionWhenLoaded(shared, attachmentEpoch);\n }\n\n async #attachSubscriptionWhenLoaded(\n shared: SharedSubscription,\n attachmentEpoch: number,\n ): Promise<void> {\n let Centrifuge: CentrifugeCtor;\n try {\n Centrifuge = await loadCentrifuge();\n } catch (error) {\n if (shared.attachmentEpoch !== attachmentEpoch) return;\n if (this.#sharedSubs.get(shared.channel) === shared) {\n this.#sharedSubs.delete(shared.channel);\n }\n this.#emitSubscriptionError(shared, \"transport_load\", error);\n return;\n }\n\n // The subscription may have been torn down or re-attached while the\n // transport module was loading.\n if (shared.attachmentEpoch !== attachmentEpoch || shared.sub) return;\n if (this.#sharedSubs.get(shared.channel) !== shared) return;\n\n try {\n this.#assertChannelAuth(shared.channel);\n this.#attachSubscriptionNow(Centrifuge, shared, attachmentEpoch);\n } catch (error) {\n this.#sharedSubs.delete(shared.channel);\n this.#emitSubscriptionError(shared, \"auth\", error);\n }\n }\n\n #attachSubscriptionNow(\n Centrifuge: CentrifugeCtor,\n shared: SharedSubscription,\n attachmentEpoch: number,\n ): void {\n const client = this.#ensureClientForChannel(Centrifuge, shared.channel);\n\n const sub = client.newSubscription(\n shared.channel,\n this.#subscriptionOpts(Centrifuge, shared, attachmentEpoch),\n );\n shared.sub = sub;\n shared.client = client;\n\n sub.on(\"publication\", (ctx: PublicationContext) => {\n if (shared.sub !== sub || shared.attachmentEpoch !== attachmentEpoch) return;\n for (const handler of shared.publicationHandlers) handler(ctx.data);\n });\n sub.on(\"subscribed\", () => {\n if (shared.sub !== sub || shared.attachmentEpoch !== attachmentEpoch) return;\n const subscriptionEpoch = ++shared.subscriptionEpoch;\n for (const handler of shared.subscribedHandlers) handler(subscriptionEpoch);\n });\n sub.on(\"unsubscribed\", (ctx) => {\n if (shared.sub !== sub || shared.attachmentEpoch !== attachmentEpoch) return;\n // Codes from 100 are the server's: a refused (re)subscribe or a terminal unsubscribe\n // push. Below 100 the client ended it, and a token failure was already reported.\n if (ctx.code >= 100) {\n this.#terminateSubscriptions([shared], \"unsubscribed\", ctx);\n return;\n }\n for (const handler of shared.unsubscribedHandlers) handler();\n });\n sub.on(\"error\", (ctx: SubscriptionErrorContext) => {\n if (shared.sub !== sub || shared.attachmentEpoch !== attachmentEpoch) return;\n const sdkCtx = fromCentrifugeSubscriptionError(ctx);\n for (const handler of shared.errorHandlers) handler(sdkCtx);\n });\n\n sub.subscribe();\n }\n\n #getOrCreateSubscription(channel: string): SharedSubscription {\n const existing = this.#sharedSubs.get(channel);\n if (existing) return existing;\n\n const pending = this.#pendingTeardowns.get(channel);\n if (pending) {\n this.#pendingTeardowns.delete(channel);\n this.#sharedSubs.set(channel, pending);\n if (!pending.sub) {\n this.#attachSubscription(pending);\n } else if (pending.sub.state !== \"subscribed\") {\n pending.sub.subscribe();\n }\n return pending;\n }\n\n const shared: SharedSubscription = {\n channel,\n sub: null,\n client: null,\n attachmentEpoch: 0,\n consumers: 0,\n subscriptionEpoch: 0,\n publicationHandlers: new Set(),\n subscribedHandlers: new Set(),\n unsubscribedHandlers: new Set(),\n errorHandlers: new Set(),\n };\n\n this.#sharedSubs.set(channel, shared);\n try {\n this.#attachSubscription(shared);\n } catch (error) {\n this.#sharedSubs.delete(channel);\n throw error;\n }\n return shared;\n }\n\n #callErrorHandler(handler: ErrorHandler | undefined, ctx: SdkSubscriptionErrorContext): void {\n if (!handler) return;\n\n try {\n handler(ctx);\n } catch {\n // Keep error reporting isolated from other subscription consumers.\n }\n }\n\n #callConsumerHandler(\n channel: string,\n type: string,\n handler: () => void,\n onError?: ErrorHandler,\n ): void {\n try {\n handler();\n } catch (error) {\n this.#callErrorHandler(\n onError,\n createSdkSubscriptionErrorContext(channel, type, error),\n );\n }\n }\n\n #terminateSubscriptions(\n subscriptions: SharedSubscription[],\n type: \"disconnected\" | \"unsubscribed\",\n ctx: { code: number; reason: string },\n ): void {\n const notifications = subscriptions.map((shared) => ({\n error: createSdkSubscriptionErrorContext(shared.channel, type, {\n code: ctx.code,\n message: ctx.reason,\n }),\n errorHandlers: [...shared.errorHandlers],\n closeHandlers: [...shared.unsubscribedHandlers],\n }));\n\n // Finish cleanup for every affected channel before callbacks can resubscribe.\n for (const shared of subscriptions) {\n if (this.#sharedSubs.get(shared.channel) === shared) {\n this.#sharedSubs.delete(shared.channel);\n }\n if (this.#pendingTeardowns.get(shared.channel) === shared) {\n this.#pendingTeardowns.delete(shared.channel);\n }\n this.#teardownSubscription(shared);\n this.#dropConsumers(shared);\n }\n\n for (const { error, errorHandlers, closeHandlers } of notifications) {\n for (const handler of errorHandlers) handler(error);\n for (const handler of closeHandlers) handler();\n }\n }\n\n /** Forgets a dropped channel's consumers, so an error delivery in progress skips them. */\n #dropConsumers(shared: SharedSubscription): void {\n shared.publicationHandlers.clear();\n shared.subscribedHandlers.clear();\n shared.unsubscribedHandlers.clear();\n shared.errorHandlers.clear();\n }\n\n #teardownSubscription(shared: SharedSubscription): void {\n const sub = shared.sub;\n const client = shared.client;\n const kind = this.#channelKind(shared.channel);\n shared.sub = null;\n shared.client = null;\n shared.attachmentEpoch++;\n if (!sub) return;\n\n try {\n if (sub.state !== \"unsubscribed\") {\n sub.unsubscribe();\n }\n } catch {\n // noop\n }\n try {\n client?.removeSubscription?.(sub);\n } catch {\n // noop\n }\n this.#disconnectClientIfIdle(kind);\n }\n\n #hasChannelsForKind(kind: RealtimeClientKind): boolean {\n for (const shared of this.#sharedSubs.values()) {\n if (this.#channelKind(shared.channel) === kind) return true;\n }\n for (const shared of this.#pendingTeardowns.values()) {\n if (this.#channelKind(shared.channel) === kind) return true;\n }\n return false;\n }\n\n #disconnectClientIfIdle(kind: RealtimeClientKind): void {\n if (this.#hasChannelsForKind(kind)) return;\n\n const client = this.#currentClient(kind);\n if (kind === \"private\") {\n this.#privateClient = null;\n } else {\n this.#publicClient = null;\n }\n // A terminal close already recorded its error and dropped the client.\n if (client) this.#setConnection(kind, DISCONNECTED);\n\n try {\n client?.disconnect();\n } catch {\n // noop\n }\n }\n\n /** Consumers still waiting for the stream module see the new epoch and never connect. */\n #disconnectPrivateOrders(): void {\n this.#privateOrdersEpoch++;\n this.#privateOrders?.disconnect();\n }\n\n #disconnect(): void {\n this.#disconnectPrivateOrders();\n this.#disconnectCentrifuge();\n }\n\n /** Leaves private order streams alone: they run on their own socket. */\n #disconnectCentrifuge(): void {\n const publicClient = this.#publicClient;\n const privateClient = this.#privateClient;\n\n for (const shared of [...this.#sharedSubs.values(), ...this.#pendingTeardowns.values()]) {\n this.#dropConsumers(shared);\n }\n this.#pendingTeardowns.clear();\n this.#sharedSubs.clear();\n this.#publicClient = null;\n this.#privateClient = null;\n if (publicClient) this.#setConnection(\"public\", DISCONNECTED);\n if (privateClient) this.#setConnection(\"private\", DISCONNECTED);\n\n try {\n publicClient?.disconnect();\n } catch {\n // noop\n }\n try {\n privateClient?.disconnect();\n } catch {\n // noop\n }\n }\n\n #disconnectPrivate(): void {\n this.#disconnectPrivateOrders();\n const privateClient = this.#privateClient;\n this.#privateClient = null;\n if (privateClient) this.#setConnection(\"private\", DISCONNECTED);\n\n for (const [channel, shared] of this.#sharedSubs) {\n if (this.#channelKind(channel) !== \"private\") continue;\n this.#sharedSubs.delete(channel);\n this.#teardownSubscription(shared);\n this.#dropConsumers(shared);\n }\n for (const [channel, shared] of this.#pendingTeardowns) {\n if (this.#channelKind(channel) !== \"private\") continue;\n this.#pendingTeardowns.delete(channel);\n this.#teardownSubscription(shared);\n this.#dropConsumers(shared);\n }\n\n try {\n privateClient?.disconnect();\n } catch {\n // noop\n }\n }\n\n /** Reports a missing-auth error on the next microtask unless the caller unsubscribes first. */\n #reportAuthErrorLater(\n channel: string,\n error: AuthenticationError,\n onError: ErrorHandler,\n ): () => void {\n let closed = false;\n const ctx = createSdkSubscriptionErrorContext(channel, \"auth\", error);\n queueMicrotask(() => {\n if (!closed) this.#callErrorHandler(onError, ctx);\n });\n return () => {\n closed = true;\n };\n }\n\n /**\n * Subscribes to a realtime channel and returns an unsubscribe function. Missing\n * authentication is reported to `onError`, or thrown synchronously when no error\n * observer is provided. Non-retryable token failures stop automatic retries;\n * calling subscribe again after correcting the failure restarts private realtime.\n */\n subscribe<T>(channel: string, handlers: SubscribeHandlers<T>): () => void {\n let shared: SharedSubscription;\n try {\n shared = this.#getOrCreateSubscription(channel);\n } catch (error) {\n if (!(error instanceof AuthenticationError)) throw error;\n if (!handlers.onError) throw error;\n\n return this.#reportAuthErrorLater(channel, error, handlers.onError);\n }\n shared.consumers++;\n\n const publicationHandler = handlers.onPublication;\n const errorHandler = handlers.onError;\n const subscribedHandler = handlers.onSubscribed;\n const unsubscribedHandler = handlers.onUnsubscribed;\n\n // Set by the returned unsubscribe: a delivery already under way skips this consumer.\n let closed = false;\n const onError: ErrorHandler | undefined = errorHandler\n ? (ctx) => {\n if (!closed) this.#callErrorHandler(errorHandler, ctx);\n }\n : undefined;\n const onPub: PublicationHandler = (data) => {\n this.#callConsumerHandler(\n channel,\n \"publication_handler\",\n () => publicationHandler(data as T),\n onError,\n );\n };\n let lastSubscribedEpoch = -1;\n const onSubscribed = subscribedHandler\n ? (subscriptionEpoch: number) => {\n if (subscriptionEpoch <= lastSubscribedEpoch) return;\n lastSubscribedEpoch = subscriptionEpoch;\n this.#callConsumerHandler(\n channel,\n \"subscribed_handler\",\n subscribedHandler,\n onError,\n );\n }\n : undefined;\n const onUnsubscribed = unsubscribedHandler\n ? () => {\n if (closed) return;\n this.#callConsumerHandler(\n channel,\n \"unsubscribed_handler\",\n unsubscribedHandler,\n onError,\n );\n }\n : undefined;\n\n shared.publicationHandlers.add(onPub);\n\n if (onSubscribed) shared.subscribedHandlers.add(onSubscribed);\n if (onUnsubscribed) shared.unsubscribedHandlers.add(onUnsubscribed);\n if (onError) shared.errorHandlers.add(onError);\n\n // Only an explicit subscribe restarts terminal private token failures.\n if (this.#channelKind(channel) === \"private\") {\n const reconnect = shared.client?.state === \"disconnected\";\n const resubscribe = shared.sub?.state === \"unsubscribed\";\n // hasAuth() reads the token provider, so only call it when a restart is possible.\n if ((reconnect || resubscribe) && this.#hasAuth()) {\n if (reconnect) shared.client?.connect();\n if (resubscribe) shared.sub?.subscribe();\n }\n }\n\n // Joining a socket that is already failing: this consumer missed the outage's one report.\n const outage = this.#connection[this.#channelKind(channel)].error;\n if (onError && outage && this.#transportErrors.has(outage)) {\n const ctx = createSdkSubscriptionErrorContext(channel, \"transport\", outage);\n queueMicrotask(() => {\n if (closed || this.#connection[this.#channelKind(channel)].error !== outage) return;\n onError(ctx);\n });\n }\n if (onSubscribed && shared.sub?.state === \"subscribed\") {\n const subscriptionEpoch = shared.subscriptionEpoch;\n queueMicrotask(() => {\n if (closed || shared.sub?.state !== \"subscribed\") return;\n onSubscribed(subscriptionEpoch);\n });\n }\n\n return () => {\n if (closed) return;\n closed = true;\n\n shared.publicationHandlers.delete(onPub);\n if (onSubscribed) shared.subscribedHandlers.delete(onSubscribed);\n if (onUnsubscribed) shared.unsubscribedHandlers.delete(onUnsubscribed);\n if (onError) shared.errorHandlers.delete(onError);\n\n shared.consumers--;\n if (shared.consumers <= 0) {\n const currentShared = this.#sharedSubs.get(channel);\n if (currentShared !== shared) return;\n\n this.#sharedSubs.delete(channel);\n this.#pendingTeardowns.set(channel, shared);\n\n queueMicrotask(() => {\n if (this.#pendingTeardowns.get(channel) !== shared) return;\n this.#pendingTeardowns.delete(channel);\n\n this.#teardownSubscription(shared);\n\n if (this.#sharedSubs.size === 0 && this.#pendingTeardowns.size === 0) {\n this.#disconnectCentrifuge();\n }\n });\n }\n };\n }\n\n /**\n * Connects to a realtime channel with a custom message decoder.\n */\n connectChannel<T extends DescMessage>(params: ConnectChannelParams<T>): () => void {\n return this.subscribe<Uint8Array>(params.channel, {\n onPublication: (data) => {\n let decoded: MessageShape<T>;\n try {\n decoded = fromBinary(params.schema, data);\n } catch (error) {\n this.#callErrorHandler(\n params.onError,\n createSdkSubscriptionErrorContext(params.channel, \"decode\", error),\n );\n return;\n }\n params.onPublication(decoded);\n },\n onSubscribed: params.onConnected,\n onUnsubscribed: params.onDisconnected,\n onError: params.onError,\n });\n }\n\n /**\n * Connects to a realtime channel that emits protobuf messages.\n */\n connectProtoChannel<T extends DescMessage>(params: ConnectChannelParams<T>): () => void {\n return this.subscribe<Uint8Array | MessageShape<T>>(params.channel, {\n onPublication: (data) => {\n let msg: MessageShape<T> | null;\n try {\n msg = decodeProtoFrame(params.schema, data);\n } catch (error) {\n this.#callErrorHandler(\n params.onError,\n createSdkSubscriptionErrorContext(params.channel, \"decode\", error),\n );\n return;\n }\n if (!msg) {\n this.#callErrorHandler(\n params.onError,\n createSdkSubscriptionErrorContext(\n params.channel,\n \"decode\",\n \"Unable to decode protobuf frame\",\n ),\n );\n return;\n }\n params.onPublication(msg);\n },\n onSubscribed: params.onConnected,\n onUnsubscribed: params.onDisconnected,\n onError: params.onError,\n });\n }\n\n /**\n * Streams one account's orders over the private WebSocket. Missing authentication\n * is reported to `onError`, or thrown synchronously when no error observer is provided.\n * Throws ValidationError when `accountId` is not a base58 public ID.\n */\n connectPrivateOrders(params: ConnectPrivateOrdersParams): () => void {\n idToBigInt(params.accountId, \"accountId\");\n const channel = `private:spot:orders:${params.accountId}`;\n if (!this.#hasAuth()) {\n const error = new AuthenticationError(\n `Cannot subscribe to private channel \"${channel}\" without authentication`,\n );\n if (!params.onError) throw error;\n return this.#reportAuthErrorLater(channel, error, params.onError);\n }\n // Once loaded, connect at once: an unsubscribe and resubscribe in one tick keeps the stream.\n if (this.#privateOrders) return this.#privateOrders.connect(params);\n const loading = (this.#privateOrdersLoading ??= import(\"./private-orders.js\").then(\n ({ PrivateOrderStream }) =>\n (this.#privateOrders = new PrivateOrderStream({\n url: this.#config.privateWsUrl,\n fetchConnectToken: () =>\n this.#fetchToken(this.#config.tokenEndpoint, \"connection\"),\n fetchSubscribeToken: (ch) => this.#fetchSubscriptionToken(ch),\n })),\n ));\n const epoch = this.#privateOrdersEpoch;\n let closed = false;\n let stop: (() => void) | undefined;\n loading.then(\n (stream) => {\n if (!closed && epoch === this.#privateOrdersEpoch) stop = stream.connect(params);\n },\n (error) => {\n if (this.#privateOrdersLoading === loading) this.#privateOrdersLoading = null;\n if (closed || epoch !== this.#privateOrdersEpoch) return;\n const ctx = createSdkSubscriptionErrorContext(channel, \"transport_load\", error);\n this.#callErrorHandler(params.onError, ctx);\n this.#callConsumerHandler(\n channel,\n \"unsubscribed_handler\",\n () => params.onDisconnected?.(),\n params.onError,\n );\n },\n );\n return () => {\n closed = true;\n stop?.();\n };\n }\n\n /**\n * Disconnects the realtime client from all active channels.\n */\n disconnect(): void {\n this.#disconnect();\n }\n\n /**\n * Disconnects authenticated realtime state without touching public channels.\n */\n disconnectPrivate(): void {\n this.#disconnectPrivate();\n }\n\n /**\n * Status of the public and private sockets. A socket that cannot connect stays\n * `\"connecting\"` with `error` set, and every channel on it gets one `\"transport\"`\n * error per outage. Private order streams run on their own socket and are not included.\n */\n get connection(): RealtimeConnection {\n return this.#connection;\n }\n\n /** Calls `listener` with the current {@link connection} after it changes, in a microtask; a status replaced before then is skipped. Returns an unsubscribe function. */\n onConnectionChange(listener: (connection: RealtimeConnection) => void): () => void {\n this.#connectionListeners.add(listener);\n return () => this.#connectionListeners.delete(listener);\n }\n\n get activeChannels(): number {\n return this.#sharedSubs.size + (this.#privateOrders?.activeChannels ?? 0);\n }\n\n get totalConsumers(): number {\n let total = this.#privateOrders?.totalConsumers ?? 0;\n for (const shared of this.#sharedSubs.values()) {\n total += shared.consumers;\n }\n return total;\n }\n}\n"],"mapp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,sBAAsB,OAAO,KAAKQ,wBAAwB,EAAE;EAChE,CAAC,CACT;EACA,MAAM,QAAQ,KAAK6B;EACnB,IAAI,SAAS;EACb,IAAI;EACJ,QAAQ,MACH,WAAW;GACR,IAAI,CAAC,UAAU,UAAU,KAAKA,qBAAqB,OAAO,OAAO,QAAQ,MAAM;EACnF,IACC,UAAU;GACP,IAAI,KAAKO,0BAA0B,SAAS,KAAKA,wBAAwB;GACzE,IAAI,UAAU,UAAU,KAAKP,qBAAqB;GAClD,MAAM,MAAM,kCAAkC,SAAS,kBAAkB,KAAK;GAC9E,KAAKL,kBAAkB,OAAO,SAAS,GAAG;GAC1C,KAAKW,qBACD,SACA,8BACM,OAAO,iBAAiB,GAC9B,OAAO,OACX;EACJ,CACJ;EACA,aAAa;GACT,SAAS;GACT,OAAO;EACX;CACJ;;;;CAKA,aAAmB;EACf,KAAKE,YAAY;CACrB;;;;CAKA,oBAA0B;EACtB,KAAKC,mBAAmB;CAC5B;;;;;;CAOA,IAAI,aAAiC;EACjC,OAAO,KAAK/B;CAChB;;CAGA,mBAAmB,UAAgE;EAC/E,KAAKC,qBAAqB,IAAI,QAAQ;EACtC,aAAa,KAAKA,qBAAqB,OAAO,QAAQ;CAC1D;CAEA,IAAI,iBAAyB;EACzB,OAAO,KAAKV,YAAY,QAAQ,KAAKgC,gBAAgB,kBAAkB;CAC3E;CAEA,IAAI,iBAAyB;EACzB,IAAI,QAAQ,KAAKA,gBAAgB,kBAAkB;EACnD,KAAK,MAAM,UAAU,KAAKhC,YAAY,OAAO,GACzC,SAAS,OAAO;EAEpB,OAAO;CACX;AACJ"}
1
+ {"version":3,"file":"client.js","names":["#config","#fetch","#getAuthHeaders","#fetchToken","#tokenRetryAt","#emitErrors","#sharedSubs","#channelKind","#fetchSubscriptionToken","#emitSubscriptionError","#publicClient","#watchClient","#privateClient","#emitConnectionTokenError","#privateTokenFailure","#connection","#connectionListeners","#setConnection","#currentClient","#transportErrors","#terminateSubscriptions","#pendingTeardowns","#createPublicClient","#hasAuth","#createPrivateClient","#ensurePublicClient","#assertChannelAuth","#attachSubscriptionNow","#attachSubscriptionWhenLoaded","#ensureClientForChannel","#subscriptionOpts","#attachSubscription","#callErrorHandler","#teardownSubscription","#dropConsumers","#disconnectClientIfIdle","#hasChannelsForKind","#privateOrdersEpoch","#privateOrders","#disconnectPrivateOrders","#disconnectCentrifuge","#getOrCreateSubscription","#reportAuthErrorLater","#callConsumerHandler","#privateOrdersLoading","#disconnect","#disconnectPrivate"],"sources":["../../src/realtime/client.ts"],"sourcesContent":["import { fromBinary, type DescMessage, type MessageShape } from \"@bufbuild/protobuf\";\nimport type {\n Centrifuge,\n ErrorContext,\n SubscriptionErrorContext,\n PublicationContext,\n Subscription,\n} from \"centrifuge/build/protobuf\";\nimport type * as CentrifugeModule from \"centrifuge/build/protobuf\";\nimport {\n createSdkSubscriptionErrorContext,\n fromCentrifugeSubscriptionError,\n type SdkSubscriptionErrorContext,\n} from \"../shared/subscription-errors.js\";\nimport {\n AuthenticationError,\n errorFromHttpStatus,\n InternalServerError,\n PolyesterError,\n RealtimeError,\n} from \"../shared/errors.js\";\nimport { parseRetryAfterHeader } from \"../shared/connect-error-mapping.js\";\nimport { makeFetch } from \"../shared/transports.js\";\nimport { decodeProtoFrame } from \"../utils/streams.js\";\nimport { idToBigInt } from \"../utils/base58-id.js\";\nimport type {\n ConnectChannelParams,\n PolyesterRealtime,\n RealtimeConnection,\n RealtimeConnectionStatus,\n SubscribeHandlers,\n} from \"./types.js\";\nimport type { ConnectPrivateOrdersParams, PrivateOrderStream } from \"./private-orders.js\";\n\n// ponytail: caps a bogus or huge Retry-After; a longer server window just answers 429 again with a new hint.\nconst MAX_RETRY_AFTER_MS = 60_000;\n\ntype CentrifugeCtor = typeof CentrifugeModule.Centrifuge;\ntype CentrifugeModuleLoader = () => Promise<typeof CentrifugeModule>;\n\nconst defaultCentrifugeModuleLoader: CentrifugeModuleLoader = () =>\n import(\"centrifuge/build/protobuf\");\n\n// Centrifuge's protobuf build embeds the protobuf.js runtime (~300 KB minified).\n// Loading it lazily keeps it out of the eager module graph on both the server\n// (Cloudflare isolate cold start — SSR never opens a websocket) and the client\n// app shell; it is only fetched when the first subscription attaches.\nlet centrifugeCtorPromise: Promise<CentrifugeCtor> | null = null;\nlet loadedCentrifugeCtor: CentrifugeCtor | null = null;\nlet centrifugeModuleLoader = defaultCentrifugeModuleLoader;\nexport function __setRealtimeCentrifugeForTests(Centrifuge: CentrifugeCtor | null): void {\n loadedCentrifugeCtor = Centrifuge;\n centrifugeCtorPromise = Centrifuge ? Promise.resolve(Centrifuge) : null;\n}\n\n/** Replaces the lazy Centrifuge module loader for isolated transport-load tests. */\nexport function __setRealtimeCentrifugeLoaderForTests(loader: CentrifugeModuleLoader | null): void {\n centrifugeModuleLoader = loader ?? defaultCentrifugeModuleLoader;\n loadedCentrifugeCtor = null;\n centrifugeCtorPromise = null;\n}\n\nfunction loadCentrifuge(): Promise<CentrifugeCtor> {\n if (\n centrifugeModuleLoader === defaultCentrifugeModuleLoader &&\n (import.meta as { env?: { SSR?: boolean } }).env?.SSR\n ) {\n return Promise.reject(new Error(\"Realtime subscriptions are browser-only during SSR.\"));\n }\n\n if (!centrifugeCtorPromise) {\n const loadAttempt = Promise.resolve().then(centrifugeModuleLoader);\n const retryableLoad = loadAttempt.then(\n (mod) => {\n loadedCentrifugeCtor = mod.Centrifuge;\n return mod.Centrifuge;\n },\n (error) => {\n if (centrifugeCtorPromise === retryableLoad) centrifugeCtorPromise = null;\n throw error;\n },\n );\n centrifugeCtorPromise = retryableLoad;\n }\n return centrifugeCtorPromise;\n}\n\nexport interface RealtimeAuthRequest {\n url: string | URL;\n method: string;\n}\n\nexport interface RealtimeConfig {\n wsUrl: string;\n tokenEndpoint: string;\n subscribeEndpoint: string;\n /** Private WebSocket endpoint for account order streams (`/v1/ws/private`). */\n privateWsUrl: string;\n getAuthHeaders?: (request: RealtimeAuthRequest) => Promise<HeadersInit> | HeadersInit;\n hasAuth?: () => boolean;\n /**\n * Custom fetch implementation for realtime token requests. Defaults to the\n * global `fetch`, resolved on each request.\n */\n fetch?: typeof fetch;\n}\n\ntype ResolvedRealtimeConfig = Pick<\n RealtimeConfig,\n \"wsUrl\" | \"tokenEndpoint\" | \"subscribeEndpoint\" | \"privateWsUrl\"\n> & {\n getAuthHeaders: (request: RealtimeAuthRequest) => Promise<HeadersInit> | HeadersInit;\n hasAuth: () => boolean;\n};\n\nexport type { ConnectChannelParams, PolyesterRealtime, SubscribeHandlers } from \"./types.js\";\n\ntype PublicationHandler<T = unknown> = (data: T) => void;\ntype ErrorHandler = (ctx: SdkSubscriptionErrorContext) => void;\ntype RealtimeClientKind = \"public\" | \"private\";\n\nconst DISCONNECTED: RealtimeConnectionStatus = { state: \"disconnected\", error: null };\n/** Centrifuge client `error` types that mean a connect attempt failed; each retry emits one. */\nconst CONNECT_FAILURE_TYPES = new Set([\"transport\", \"connect\", \"connectToken\", \"connectData\"]);\n\ninterface SharedSubscription {\n channel: string;\n sub: Subscription | null;\n client: Centrifuge | null;\n attachmentEpoch: number;\n consumers: number;\n subscriptionEpoch: number;\n publicationHandlers: Set<PublicationHandler>;\n subscribedHandlers: Set<(epoch: number) => void>;\n unsubscribedHandlers: Set<() => void>;\n errorHandlers: Set<ErrorHandler>;\n}\n\n/**\n * Shared Centrifuge realtime client that multiplexes public and private protobuf subscriptions across SDK services.\n */\nexport class RealtimeClient implements PolyesterRealtime {\n #publicClient: Centrifuge | null = null;\n #privateClient: Centrifuge | null = null;\n #sharedSubs = new Map<string, SharedSubscription>();\n #pendingTeardowns = new Map<string, SharedSubscription>();\n // Loaded on first use: the stream's protobuf graph (orders included) stays out of the app shell.\n #privateOrdersLoading: Promise<PrivateOrderStream> | null = null;\n #privateOrders: PrivateOrderStream | null = null;\n #privateOrdersEpoch = 0;\n #connection: RealtimeConnection = { public: DISCONNECTED, private: DISCONNECTED };\n #connectionListeners = new Set<(connection: RealtimeConnection) => void>();\n /** Outage errors already sent to channels as `\"transport\"`; replayed to late subscribers. */\n #transportErrors = new WeakSet<Error>();\n /** The non-retryable connection token failure that stops the private socket (code 1). */\n #privateTokenFailure: Error | null = null;\n /** Token requests wait until then after a 429 with `Retry-After`. */\n #tokenRetryAt = 0;\n readonly #config: ResolvedRealtimeConfig;\n readonly #fetch: typeof fetch;\n\n constructor(config: RealtimeConfig) {\n this.#fetch = makeFetch(config.fetch);\n this.#config = {\n wsUrl: config.wsUrl,\n tokenEndpoint: config.tokenEndpoint,\n subscribeEndpoint: config.subscribeEndpoint,\n privateWsUrl: config.privateWsUrl,\n getAuthHeaders: config.getAuthHeaders ?? (() => ({})),\n hasAuth: config.hasAuth ?? (() => false),\n };\n }\n\n async #getAuthHeaders(request: RealtimeAuthRequest): Promise<HeadersInit> {\n return this.#config.getAuthHeaders(request);\n }\n\n /**\n * Every realtime token request (connection, subscription, private order stream)\n * comes through here, so one wait honors `Retry-After` for all of them; the\n * transport's own reconnect backoff still applies on top.\n */\n async #fetchToken(url: string | URL, kind: \"connection\" | \"subscription\"): Promise<string> {\n // Recheck after each await: another request's 429 may have pushed the deadline out.\n let headers: HeadersInit;\n do {\n for (let wait; (wait = this.#tokenRetryAt - Date.now()) > 0;) {\n await new Promise((resolve) => setTimeout(resolve, wait));\n }\n headers = await this.#getAuthHeaders({ url, method: \"GET\" });\n } while (this.#tokenRetryAt > Date.now());\n const res = await this.#fetch(url, { headers });\n if (!res.ok) {\n const retryAfterMs = parseRetryAfterHeader(res.headers.get(\"retry-after\"));\n if (res.status === 429 && retryAfterMs !== undefined) {\n this.#tokenRetryAt = Math.max(\n this.#tokenRetryAt,\n Date.now() + Math.min(retryAfterMs, MAX_RETRY_AFTER_MS),\n );\n }\n throw errorFromHttpStatus(res.status, `Failed to fetch ${kind} token: ${res.status}`, {\n status: res.status,\n retryAfterMs,\n });\n }\n const json = (await res.json()) as { token?: string };\n if (!json?.token) {\n throw new InternalServerError(\n `${kind === \"connection\" ? \"Connection\" : \"Subscription\"} token response had no token`,\n );\n }\n return json.token;\n }\n\n #fetchSubscriptionToken(channel: string): Promise<string> {\n const url = new URL(this.#config.subscribeEndpoint);\n url.searchParams.set(\"channel\", channel);\n return this.#fetchToken(url, \"subscription\");\n }\n\n /**\n * Delivers to the consumers registered when it starts: one a handler adds (a resubscribe)\n * is not part of it, and one a handler removes is skipped.\n */\n #emitErrors(recipients: SharedSubscription[], type: string, error: unknown): void {\n const deliveries = recipients.map((shared) => ({\n shared,\n ctx: createSdkSubscriptionErrorContext(shared.channel, type, error),\n handlers: Array.from(shared.errorHandlers),\n }));\n for (const { shared, ctx, handlers } of deliveries) {\n for (const handler of handlers) {\n if (shared.errorHandlers.has(handler)) handler(ctx);\n }\n }\n }\n\n #emitSubscriptionError(shared: SharedSubscription, type: string, error: unknown): void {\n this.#emitErrors([shared], type, error);\n }\n\n #emitConnectionTokenError(error: unknown): void {\n const privateSubs = [...this.#sharedSubs.values()].filter(\n (shared) => this.#channelKind(shared.channel) === \"private\",\n );\n this.#emitErrors(privateSubs, \"connection_token\", error);\n }\n\n #subscriptionOpts(\n Centrifuge: CentrifugeCtor,\n shared: SharedSubscription,\n attachmentEpoch: number,\n ) {\n if (this.#channelKind(shared.channel) !== \"private\") return undefined;\n return {\n getToken: async () => {\n try {\n return await this.#fetchSubscriptionToken(shared.channel);\n } catch (error) {\n if (shared.attachmentEpoch === attachmentEpoch) {\n this.#emitSubscriptionError(shared, \"subscription_token\", error);\n }\n if (error instanceof PolyesterError && !error.retryable) {\n throw new Centrifuge.UnauthorizedError(error.message);\n }\n throw error;\n }\n },\n };\n }\n\n #hasAuth(): boolean {\n return this.#config.hasAuth();\n }\n\n #channelKind(channel: string): RealtimeClientKind {\n return channel.startsWith(\"private:\") ? \"private\" : \"public\";\n }\n\n #createPublicClient(Centrifuge: CentrifugeCtor): Centrifuge {\n const client = new Centrifuge(this.#config.wsUrl);\n this.#publicClient = client;\n this.#watchClient(client, \"public\");\n client.connect();\n return client;\n }\n\n #createPrivateClient(Centrifuge: CentrifugeCtor): Centrifuge {\n let client: Centrifuge;\n const opts = {\n getToken: async () => {\n try {\n return await this.#fetchToken(this.#config.tokenEndpoint, \"connection\");\n } catch (error) {\n if (this.#privateClient === client) {\n this.#emitConnectionTokenError(error);\n }\n if (error instanceof PolyesterError && !error.retryable) {\n if (this.#privateClient === client) this.#privateTokenFailure = error;\n throw new Centrifuge.UnauthorizedError(error.message);\n }\n throw error;\n }\n },\n };\n\n client = new Centrifuge(this.#config.wsUrl, opts);\n this.#privateClient = client;\n this.#privateTokenFailure = null;\n this.#watchClient(client, \"private\");\n client.connect();\n return client;\n }\n\n #currentClient(kind: RealtimeClientKind): Centrifuge | null {\n return kind === \"private\" ? this.#privateClient : this.#publicClient;\n }\n\n #setConnection(kind: RealtimeClientKind, status: RealtimeConnectionStatus): void {\n const current = this.#connection[kind];\n if (current.state === status.state && current.error === status.error) return;\n this.#connection = { ...this.#connection, [kind]: status };\n const connection = this.#connection;\n // Notify once Centrifuge has finished its transition, so a listener can disconnect or\n // subscribe safely. A newer status replaces this one, even mid-delivery.\n // Snapshot: a listener added during delivery (one replacing itself) waits for the next change.\n queueMicrotask(() => {\n for (const listener of Array.from(this.#connectionListeners)) {\n if (this.#connection !== connection) return;\n if (!this.#connectionListeners.has(listener)) continue;\n try {\n listener(connection);\n } catch {\n // Keep one listener from starving the others.\n }\n }\n });\n }\n\n #watchClient(client: Centrifuge, kind: RealtimeClientKind): void {\n this.#setConnection(kind, { state: \"connecting\", error: null });\n\n client.on(\"state\", ({ newState, oldState }) => {\n // `disconnected` is recorded by the handlers below, which know the reason.\n if (this.#currentClient(kind) !== client || newState === \"disconnected\") return;\n // A restart after a terminal close starts a new outage.\n const { error } = this.#connection[kind];\n this.#setConnection(kind, {\n state: newState,\n error: newState === \"connected\" || oldState === \"disconnected\" ? null : error,\n });\n });\n\n // Centrifuge stays in \"connecting\" across failed attempts, so the `connecting`\n // event fires once; each failed attempt arrives as a client `error` instead.\n client.on(\"error\", (ctx: ErrorContext) => {\n if (this.#currentClient(kind) !== client || !CONNECT_FAILURE_TYPES.has(ctx.type))\n return;\n const { code, message } = ctx.error as { code?: unknown; message?: unknown };\n // 109: the cached token expired; Centrifuge fetches a new one and reconnects.\n if (ctx.type === \"connect\" && code === 109) return;\n // Report the first failure of an outage only, not every reconnect retry. A token\n // failure only marks the status (private channels get \"connection_token\" from\n // getToken), so a socket failure after one is still sent to channels.\n const current = this.#connection[kind].error;\n if (current && (ctx.type === \"connectToken\" || this.#transportErrors.has(current)))\n return;\n const error = new RealtimeError(\n `Realtime ${kind} connection failed: ${typeof message === \"string\" && message ? message : ctx.type}`,\n { realtimeCode: typeof code === \"number\" ? code : 0, retryable: true },\n );\n this.#setConnection(kind, { state: \"connecting\", error });\n // Private channels already receive connection token failures as \"connection_token\".\n if (ctx.type === \"connectToken\") return;\n this.#transportErrors.add(error);\n // A consumer added by a handler gets the replay in subscribe() instead.\n const affected = [...this.#sharedSubs.values()].filter(\n (shared) => shared.client === client,\n );\n this.#emitErrors(affected, \"transport\", error);\n });\n\n client.on(\"disconnected\", (ctx) => {\n // Code 0 (disconnectCalled) comes from our own teardown, which drops the client first.\n if (this.#currentClient(kind) !== client || ctx.code === 0) return;\n // Centrifuge reports a rejected private token as \"unauthorized\"; record the real failure.\n const tokenFailure =\n kind === \"private\" && ctx.code === 1 ? this.#privateTokenFailure : null;\n if (kind === \"private\") this.#privateTokenFailure = null;\n this.#setConnection(kind, {\n state: \"disconnected\",\n error:\n tokenFailure ??\n new RealtimeError(ctx.reason || \"Realtime connection closed\", {\n realtimeCode: ctx.code,\n }),\n });\n // Code 1 (unauthorized) on the private socket: channels already got the token\n // error, and an explicit subscribe() restarts this client, so keep it. The public\n // socket has no token to fix, so there it is terminal like any other close.\n if (ctx.code === 1 && kind === \"private\") return;\n if (kind === \"private\") this.#privateClient = null;\n else this.#publicClient = null;\n this.#terminateSubscriptions(\n [...this.#sharedSubs.values(), ...this.#pendingTeardowns.values()].filter(\n (shared) => shared.client === client,\n ),\n \"disconnected\",\n ctx,\n );\n });\n }\n\n #ensurePublicClient(Centrifuge: CentrifugeCtor): Centrifuge {\n return this.#publicClient ?? this.#createPublicClient(Centrifuge);\n }\n\n #assertChannelAuth(channel: string): void {\n if (this.#channelKind(channel) === \"private\" && !this.#hasAuth()) {\n throw new AuthenticationError(\n `Cannot subscribe to private channel \"${channel}\" without authentication`,\n );\n }\n }\n\n #ensureClientForChannel(Centrifuge: CentrifugeCtor, channel: string): Centrifuge {\n if (this.#channelKind(channel) === \"private\") {\n return this.#privateClient ?? this.#createPrivateClient(Centrifuge);\n }\n\n return this.#ensurePublicClient(Centrifuge);\n }\n\n #attachSubscription(shared: SharedSubscription): void {\n if (shared.sub) return;\n\n // Auth failures must surface synchronously to subscribe() callers, as\n // they did when centrifuge was imported statically.\n this.#assertChannelAuth(shared.channel);\n\n const attachmentEpoch = shared.attachmentEpoch + 1;\n shared.attachmentEpoch = attachmentEpoch;\n\n // Once the transport module is loaded, attachment stays fully\n // synchronous — only the very first attach pays the dynamic import.\n if (loadedCentrifugeCtor) {\n this.#attachSubscriptionNow(loadedCentrifugeCtor, shared, attachmentEpoch);\n return;\n }\n void this.#attachSubscriptionWhenLoaded(shared, attachmentEpoch);\n }\n\n async #attachSubscriptionWhenLoaded(\n shared: SharedSubscription,\n attachmentEpoch: number,\n ): Promise<void> {\n let Centrifuge: CentrifugeCtor;\n try {\n Centrifuge = await loadCentrifuge();\n } catch (error) {\n if (shared.attachmentEpoch !== attachmentEpoch) return;\n if (this.#sharedSubs.get(shared.channel) === shared) {\n this.#sharedSubs.delete(shared.channel);\n }\n this.#emitSubscriptionError(shared, \"transport_load\", error);\n return;\n }\n\n // The subscription may have been torn down or re-attached while the\n // transport module was loading.\n if (shared.attachmentEpoch !== attachmentEpoch || shared.sub) return;\n if (this.#sharedSubs.get(shared.channel) !== shared) return;\n\n try {\n this.#assertChannelAuth(shared.channel);\n this.#attachSubscriptionNow(Centrifuge, shared, attachmentEpoch);\n } catch (error) {\n this.#sharedSubs.delete(shared.channel);\n this.#emitSubscriptionError(shared, \"auth\", error);\n }\n }\n\n #attachSubscriptionNow(\n Centrifuge: CentrifugeCtor,\n shared: SharedSubscription,\n attachmentEpoch: number,\n ): void {\n const client = this.#ensureClientForChannel(Centrifuge, shared.channel);\n\n const sub = client.newSubscription(\n shared.channel,\n this.#subscriptionOpts(Centrifuge, shared, attachmentEpoch),\n );\n shared.sub = sub;\n shared.client = client;\n\n sub.on(\"publication\", (ctx: PublicationContext) => {\n if (shared.sub !== sub || shared.attachmentEpoch !== attachmentEpoch) return;\n for (const handler of shared.publicationHandlers) handler(ctx.data);\n });\n sub.on(\"subscribed\", () => {\n if (shared.sub !== sub || shared.attachmentEpoch !== attachmentEpoch) return;\n const subscriptionEpoch = ++shared.subscriptionEpoch;\n for (const handler of shared.subscribedHandlers) handler(subscriptionEpoch);\n });\n sub.on(\"unsubscribed\", (ctx) => {\n if (shared.sub !== sub || shared.attachmentEpoch !== attachmentEpoch) return;\n // Codes from 100 are the server's: a refused (re)subscribe or a terminal unsubscribe\n // push. Below 100 the client ended it, and a token failure was already reported.\n if (ctx.code >= 100) {\n this.#terminateSubscriptions([shared], \"unsubscribed\", ctx);\n return;\n }\n for (const handler of shared.unsubscribedHandlers) handler();\n });\n sub.on(\"error\", (ctx: SubscriptionErrorContext) => {\n if (shared.sub !== sub || shared.attachmentEpoch !== attachmentEpoch) return;\n const sdkCtx = fromCentrifugeSubscriptionError(ctx);\n for (const handler of shared.errorHandlers) handler(sdkCtx);\n });\n\n sub.subscribe();\n }\n\n #getOrCreateSubscription(channel: string): SharedSubscription {\n const existing = this.#sharedSubs.get(channel);\n if (existing) return existing;\n\n const pending = this.#pendingTeardowns.get(channel);\n if (pending) {\n this.#pendingTeardowns.delete(channel);\n this.#sharedSubs.set(channel, pending);\n if (!pending.sub) {\n this.#attachSubscription(pending);\n } else if (pending.sub.state !== \"subscribed\") {\n pending.sub.subscribe();\n }\n return pending;\n }\n\n const shared: SharedSubscription = {\n channel,\n sub: null,\n client: null,\n attachmentEpoch: 0,\n consumers: 0,\n subscriptionEpoch: 0,\n publicationHandlers: new Set(),\n subscribedHandlers: new Set(),\n unsubscribedHandlers: new Set(),\n errorHandlers: new Set(),\n };\n\n this.#sharedSubs.set(channel, shared);\n try {\n this.#attachSubscription(shared);\n } catch (error) {\n this.#sharedSubs.delete(channel);\n throw error;\n }\n return shared;\n }\n\n #callErrorHandler(handler: ErrorHandler | undefined, ctx: SdkSubscriptionErrorContext): void {\n if (!handler) return;\n\n try {\n handler(ctx);\n } catch {\n // Keep error reporting isolated from other subscription consumers.\n }\n }\n\n #callConsumerHandler(\n channel: string,\n type: string,\n handler: () => void,\n onError?: ErrorHandler,\n ): void {\n try {\n handler();\n } catch (error) {\n this.#callErrorHandler(\n onError,\n createSdkSubscriptionErrorContext(channel, type, error),\n );\n }\n }\n\n #terminateSubscriptions(\n subscriptions: SharedSubscription[],\n type: \"disconnected\" | \"unsubscribed\",\n ctx: { code: number; reason: string },\n ): void {\n const notifications = subscriptions.map((shared) => ({\n error: createSdkSubscriptionErrorContext(shared.channel, type, {\n code: ctx.code,\n message: ctx.reason,\n }),\n errorHandlers: [...shared.errorHandlers],\n closeHandlers: [...shared.unsubscribedHandlers],\n }));\n\n // Finish cleanup for every affected channel before callbacks can resubscribe.\n for (const shared of subscriptions) {\n if (this.#sharedSubs.get(shared.channel) === shared) {\n this.#sharedSubs.delete(shared.channel);\n }\n if (this.#pendingTeardowns.get(shared.channel) === shared) {\n this.#pendingTeardowns.delete(shared.channel);\n }\n this.#teardownSubscription(shared);\n this.#dropConsumers(shared);\n }\n\n for (const { error, errorHandlers, closeHandlers } of notifications) {\n for (const handler of errorHandlers) handler(error);\n for (const handler of closeHandlers) handler();\n }\n }\n\n /** Forgets a dropped channel's consumers, so an error delivery in progress skips them. */\n #dropConsumers(shared: SharedSubscription): void {\n shared.publicationHandlers.clear();\n shared.subscribedHandlers.clear();\n shared.unsubscribedHandlers.clear();\n shared.errorHandlers.clear();\n }\n\n #teardownSubscription(shared: SharedSubscription): void {\n const sub = shared.sub;\n const client = shared.client;\n const kind = this.#channelKind(shared.channel);\n shared.sub = null;\n shared.client = null;\n shared.attachmentEpoch++;\n if (!sub) return;\n\n try {\n if (sub.state !== \"unsubscribed\") {\n sub.unsubscribe();\n }\n } catch {\n // noop\n }\n try {\n client?.removeSubscription?.(sub);\n } catch {\n // noop\n }\n this.#disconnectClientIfIdle(kind);\n }\n\n #hasChannelsForKind(kind: RealtimeClientKind): boolean {\n for (const shared of this.#sharedSubs.values()) {\n if (this.#channelKind(shared.channel) === kind) return true;\n }\n for (const shared of this.#pendingTeardowns.values()) {\n if (this.#channelKind(shared.channel) === kind) return true;\n }\n return false;\n }\n\n #disconnectClientIfIdle(kind: RealtimeClientKind): void {\n if (this.#hasChannelsForKind(kind)) return;\n\n const client = this.#currentClient(kind);\n if (kind === \"private\") {\n this.#privateClient = null;\n } else {\n this.#publicClient = null;\n }\n // A terminal close already recorded its error and dropped the client.\n if (client) this.#setConnection(kind, DISCONNECTED);\n\n try {\n client?.disconnect();\n } catch {\n // noop\n }\n }\n\n /** Consumers still waiting for the stream module see the new epoch and never connect. */\n #disconnectPrivateOrders(): void {\n this.#privateOrdersEpoch++;\n this.#privateOrders?.disconnect();\n }\n\n #disconnect(): void {\n this.#disconnectPrivateOrders();\n this.#disconnectCentrifuge();\n }\n\n /** Leaves private order streams alone: they run on their own socket. */\n #disconnectCentrifuge(): void {\n const publicClient = this.#publicClient;\n const privateClient = this.#privateClient;\n\n for (const shared of [...this.#sharedSubs.values(), ...this.#pendingTeardowns.values()]) {\n this.#dropConsumers(shared);\n }\n this.#pendingTeardowns.clear();\n this.#sharedSubs.clear();\n this.#publicClient = null;\n this.#privateClient = null;\n if (publicClient) this.#setConnection(\"public\", DISCONNECTED);\n if (privateClient) this.#setConnection(\"private\", DISCONNECTED);\n\n try {\n publicClient?.disconnect();\n } catch {\n // noop\n }\n try {\n privateClient?.disconnect();\n } catch {\n // noop\n }\n }\n\n #disconnectPrivate(): void {\n this.#disconnectPrivateOrders();\n const privateClient = this.#privateClient;\n this.#privateClient = null;\n if (privateClient) this.#setConnection(\"private\", DISCONNECTED);\n\n for (const [channel, shared] of this.#sharedSubs) {\n if (this.#channelKind(channel) !== \"private\") continue;\n this.#sharedSubs.delete(channel);\n this.#teardownSubscription(shared);\n this.#dropConsumers(shared);\n }\n for (const [channel, shared] of this.#pendingTeardowns) {\n if (this.#channelKind(channel) !== \"private\") continue;\n this.#pendingTeardowns.delete(channel);\n this.#teardownSubscription(shared);\n this.#dropConsumers(shared);\n }\n\n try {\n privateClient?.disconnect();\n } catch {\n // noop\n }\n }\n\n /** Reports a missing-auth error on the next microtask unless the caller unsubscribes first. */\n #reportAuthErrorLater(\n channel: string,\n error: AuthenticationError,\n onError: ErrorHandler,\n ): () => void {\n let closed = false;\n const ctx = createSdkSubscriptionErrorContext(channel, \"auth\", error);\n queueMicrotask(() => {\n if (!closed) this.#callErrorHandler(onError, ctx);\n });\n return () => {\n closed = true;\n };\n }\n\n /**\n * Subscribes to a realtime channel and returns an unsubscribe function. Missing\n * authentication is reported to `onError`, or thrown synchronously when no error\n * observer is provided. Non-retryable token failures stop automatic retries;\n * calling subscribe again after correcting the failure restarts private realtime.\n */\n subscribe<T>(channel: string, handlers: SubscribeHandlers<T>): () => void {\n let shared: SharedSubscription;\n try {\n shared = this.#getOrCreateSubscription(channel);\n } catch (error) {\n if (!(error instanceof AuthenticationError)) throw error;\n if (!handlers.onError) throw error;\n\n return this.#reportAuthErrorLater(channel, error, handlers.onError);\n }\n shared.consumers++;\n\n const publicationHandler = handlers.onPublication;\n const errorHandler = handlers.onError;\n const subscribedHandler = handlers.onSubscribed;\n const unsubscribedHandler = handlers.onUnsubscribed;\n\n // Set by the returned unsubscribe: a delivery already under way skips this consumer.\n let closed = false;\n const onError: ErrorHandler | undefined = errorHandler\n ? (ctx) => {\n if (!closed) this.#callErrorHandler(errorHandler, ctx);\n }\n : undefined;\n const onPub: PublicationHandler = (data) => {\n this.#callConsumerHandler(\n channel,\n \"publication_handler\",\n () => publicationHandler(data as T),\n onError,\n );\n };\n let lastSubscribedEpoch = -1;\n const onSubscribed = subscribedHandler\n ? (subscriptionEpoch: number) => {\n if (subscriptionEpoch <= lastSubscribedEpoch) return;\n lastSubscribedEpoch = subscriptionEpoch;\n this.#callConsumerHandler(\n channel,\n \"subscribed_handler\",\n subscribedHandler,\n onError,\n );\n }\n : undefined;\n const onUnsubscribed = unsubscribedHandler\n ? () => {\n if (closed) return;\n this.#callConsumerHandler(\n channel,\n \"unsubscribed_handler\",\n unsubscribedHandler,\n onError,\n );\n }\n : undefined;\n\n shared.publicationHandlers.add(onPub);\n\n if (onSubscribed) shared.subscribedHandlers.add(onSubscribed);\n if (onUnsubscribed) shared.unsubscribedHandlers.add(onUnsubscribed);\n if (onError) shared.errorHandlers.add(onError);\n\n // Only an explicit subscribe restarts terminal private token failures.\n if (this.#channelKind(channel) === \"private\") {\n const reconnect = shared.client?.state === \"disconnected\";\n const resubscribe = shared.sub?.state === \"unsubscribed\";\n // hasAuth() reads the token provider, so only call it when a restart is possible.\n if ((reconnect || resubscribe) && this.#hasAuth()) {\n if (reconnect) shared.client?.connect();\n if (resubscribe) shared.sub?.subscribe();\n }\n }\n\n // Joining a socket that is already failing: this consumer missed the outage's one report.\n const outage = this.#connection[this.#channelKind(channel)].error;\n if (onError && outage && this.#transportErrors.has(outage)) {\n const ctx = createSdkSubscriptionErrorContext(channel, \"transport\", outage);\n queueMicrotask(() => {\n if (closed || this.#connection[this.#channelKind(channel)].error !== outage) return;\n onError(ctx);\n });\n }\n if (onSubscribed && shared.sub?.state === \"subscribed\") {\n const subscriptionEpoch = shared.subscriptionEpoch;\n queueMicrotask(() => {\n if (closed || shared.sub?.state !== \"subscribed\") return;\n onSubscribed(subscriptionEpoch);\n });\n }\n\n return () => {\n if (closed) return;\n closed = true;\n\n shared.publicationHandlers.delete(onPub);\n if (onSubscribed) shared.subscribedHandlers.delete(onSubscribed);\n if (onUnsubscribed) shared.unsubscribedHandlers.delete(onUnsubscribed);\n if (onError) shared.errorHandlers.delete(onError);\n\n shared.consumers--;\n if (shared.consumers <= 0) {\n const currentShared = this.#sharedSubs.get(channel);\n if (currentShared !== shared) return;\n\n this.#sharedSubs.delete(channel);\n this.#pendingTeardowns.set(channel, shared);\n\n queueMicrotask(() => {\n if (this.#pendingTeardowns.get(channel) !== shared) return;\n this.#pendingTeardowns.delete(channel);\n\n this.#teardownSubscription(shared);\n\n if (this.#sharedSubs.size === 0 && this.#pendingTeardowns.size === 0) {\n this.#disconnectCentrifuge();\n }\n });\n }\n };\n }\n\n /**\n * Connects to a realtime channel with a custom message decoder.\n */\n connectChannel<T extends DescMessage>(params: ConnectChannelParams<T>): () => void {\n return this.subscribe<Uint8Array>(params.channel, {\n onPublication: (data) => {\n let decoded: MessageShape<T>;\n try {\n decoded = fromBinary(params.schema, data);\n } catch (error) {\n this.#callErrorHandler(\n params.onError,\n createSdkSubscriptionErrorContext(params.channel, \"decode\", error),\n );\n return;\n }\n params.onPublication(decoded);\n },\n onSubscribed: params.onConnected,\n onUnsubscribed: params.onDisconnected,\n onError: params.onError,\n });\n }\n\n /**\n * Connects to a realtime channel that emits protobuf messages.\n */\n connectProtoChannel<T extends DescMessage>(params: ConnectChannelParams<T>): () => void {\n return this.subscribe<Uint8Array | MessageShape<T>>(params.channel, {\n onPublication: (data) => {\n let msg: MessageShape<T> | null;\n try {\n msg = decodeProtoFrame(params.schema, data);\n } catch (error) {\n this.#callErrorHandler(\n params.onError,\n createSdkSubscriptionErrorContext(params.channel, \"decode\", error),\n );\n return;\n }\n if (!msg) {\n this.#callErrorHandler(\n params.onError,\n createSdkSubscriptionErrorContext(\n params.channel,\n \"decode\",\n \"Unable to decode protobuf frame\",\n ),\n );\n return;\n }\n params.onPublication(msg);\n },\n onSubscribed: params.onConnected,\n onUnsubscribed: params.onDisconnected,\n onError: params.onError,\n });\n }\n\n /**\n * Streams one account's orders over the private WebSocket. Missing authentication\n * is reported to `onError`, or thrown synchronously when no error observer is provided.\n * Throws ValidationError when `accountId` is not a base58 public ID.\n */\n connectPrivateOrders(input: ConnectPrivateOrdersParams): () => void {\n // The base58 check trims, so the stream must use the trimmed ID too.\n const params = { ...input, accountId: input.accountId.trim() };\n idToBigInt(params.accountId, \"accountId\");\n const channel = `private:spot:orders:${params.accountId}`;\n if (!this.#hasAuth()) {\n const error = new AuthenticationError(\n `Cannot subscribe to private channel \"${channel}\" without authentication`,\n );\n if (!params.onError) throw error;\n return this.#reportAuthErrorLater(channel, error, params.onError);\n }\n // Once loaded, connect at once: an unsubscribe and resubscribe in one tick keeps the stream.\n if (this.#privateOrders) return this.#privateOrders.connect(params);\n const loading = (this.#privateOrdersLoading ??= import(\"./private-orders.js\").then(\n ({ PrivateOrderStream }) =>\n (this.#privateOrders = new PrivateOrderStream({\n url: this.#config.privateWsUrl,\n fetchConnectToken: () =>\n this.#fetchToken(this.#config.tokenEndpoint, \"connection\"),\n fetchSubscribeToken: (ch) => this.#fetchSubscriptionToken(ch),\n })),\n ));\n const epoch = this.#privateOrdersEpoch;\n let closed = false;\n let stop: (() => void) | undefined;\n loading.then(\n (stream) => {\n if (!closed && epoch === this.#privateOrdersEpoch) stop = stream.connect(params);\n },\n (error) => {\n if (this.#privateOrdersLoading === loading) this.#privateOrdersLoading = null;\n if (closed || epoch !== this.#privateOrdersEpoch) return;\n const ctx = createSdkSubscriptionErrorContext(channel, \"transport_load\", error);\n this.#callErrorHandler(params.onError, ctx);\n this.#callConsumerHandler(\n channel,\n \"unsubscribed_handler\",\n () => params.onDisconnected?.(),\n params.onError,\n );\n },\n );\n return () => {\n closed = true;\n stop?.();\n };\n }\n\n /**\n * Disconnects the realtime client from all active channels.\n */\n disconnect(): void {\n this.#disconnect();\n }\n\n /**\n * Disconnects authenticated realtime state without touching public channels.\n */\n disconnectPrivate(): void {\n this.#disconnectPrivate();\n }\n\n /**\n * Status of the public and private sockets. A socket that cannot connect stays\n * `\"connecting\"` with `error` set, and every channel on it gets one `\"transport\"`\n * error per outage. Private order streams run on their own socket and are not included.\n */\n get connection(): RealtimeConnection {\n return this.#connection;\n }\n\n /** Calls `listener` with the current {@link connection} after it changes, in a microtask; a status replaced before then is skipped. Returns an unsubscribe function. */\n onConnectionChange(listener: (connection: RealtimeConnection) => void): () => void {\n this.#connectionListeners.add(listener);\n return () => this.#connectionListeners.delete(listener);\n }\n\n get activeChannels(): number {\n return this.#sharedSubs.size + (this.#privateOrders?.activeChannels ?? 0);\n }\n\n get totalConsumers(): number {\n let total = this.#privateOrders?.totalConsumers ?? 0;\n for (const shared of this.#sharedSubs.values()) {\n total += shared.consumers;\n }\n return total;\n }\n}\n"],"mappings":";;;;;;;;AAmCA,MAAM,qBAAqB;AAK3B,MAAM,sCACF,OAAO;AAMX,IAAI,wBAAwD;AAC5D,IAAI,uBAA8C;AAClD,IAAI,yBAAyB;AAa7B,SAAS,iBAA0C;CAC/C,IACI,2BAA2B,iCAC1B,YAA4C,KAAK,KAElD,OAAO,QAAQ,uBAAO,IAAI,MAAM,qDAAqD,CAAC;CAG1F,IAAI,CAAC,uBAAuB;EAExB,MAAM,gBADc,QAAQ,QAAQ,CAAC,CAAC,KAAK,sBACX,CAAC,CAAC,MAC7B,QAAQ;GACL,uBAAuB,IAAI;GAC3B,OAAO,IAAI;EACf,IACC,UAAU;GACP,IAAI,0BAA0B,eAAe,wBAAwB;GACrE,MAAM;EACV,CACJ;EACA,wBAAwB;CAC5B;CACA,OAAO;AACX;AAoCA,MAAM,eAAyC;CAAE,OAAO;CAAgB,OAAO;AAAK;;AAEpF,MAAM,wCAAwB,IAAI,IAAI;CAAC;CAAa;CAAW;CAAgB;AAAa,CAAC;;;;AAkB7F,IAAa,iBAAb,MAAyD;CACrD,gBAAmC;CACnC,iBAAoC;CACpC,8BAAc,IAAI,IAAgC;CAClD,oCAAoB,IAAI,IAAgC;CAExD,wBAA4D;CAC5D,iBAA4C;CAC5C,sBAAsB;CACtB,c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,aAAa,KAAKA,qBAAqB,OAAO,QAAQ;CAC1D;CAEA,IAAI,iBAAyB;EACzB,OAAO,KAAKV,YAAY,QAAQ,KAAKgC,gBAAgB,kBAAkB;CAC3E;CAEA,IAAI,iBAAyB;EACzB,IAAI,QAAQ,KAAKA,gBAAgB,kBAAkB;EACnD,KAAK,MAAM,UAAU,KAAKhC,YAAY,OAAO,GACzC,SAAS,OAAO;EAEpB,OAAO;CACX;AACJ"}
@@ -1,3 +1,4 @@
1
+ import { PolyesterError } from "../shared/errors.js";
1
2
  import { createSdkSubscriptionErrorContext } from "../shared/subscription-errors.js";
2
3
  import { formatConnectError } from "../utils/errors.js";
3
4
  import { isDev } from "../utils/is-dev.js";
@@ -71,10 +72,11 @@ function snapshotThenStream(params) {
71
72
  reportBufferedPublicationError(error);
72
73
  }
73
74
  }
74
- function scheduleSnapshotRetry() {
75
+ function scheduleSnapshotRetry(error) {
75
76
  const retry = params.snapshotRetry;
76
77
  if (!retry || retryAttempts >= retry.maxAttempts || disposed) return;
77
- const delayMs = retry.delayMs * 2 ** retryAttempts;
78
+ if (error instanceof PolyesterError && !error.retryable) return;
79
+ const delayMs = Math.min(retry.delayMs * 2 ** retryAttempts, retry.maxDelayMs ?? Number.POSITIVE_INFINITY);
78
80
  retryAttempts++;
79
81
  retryTimer = setTimeout(() => {
80
82
  retryTimer = null;
@@ -100,7 +102,7 @@ function snapshotThenStream(params) {
100
102
  ready = true;
101
103
  applyBufferedAsLive();
102
104
  }
103
- scheduleSnapshotRetry();
105
+ scheduleSnapshotRetry(error);
104
106
  });
105
107
  }
106
108
  const unsubscribeRealtime = params.realtime.connectProtoChannel({
@@ -1 +1 @@
1
- {"version":3,"file":"snapshot-then-stream.js","names":[],"sources":["../../src/realtime/snapshot-then-stream.ts"],"sourcesContent":["import type { DescMessage, MessageShape } from \"@bufbuild/protobuf\";\nimport {\n createSdkSubscriptionErrorContext,\n type SdkSubscriptionErrorContext,\n} from \"../shared/subscription-errors.js\";\nimport type { PolyesterRealtime } from \"./types.js\";\nimport { formatConnectError } from \"../utils/errors.js\";\nimport { isDev } from \"../utils/is-dev.js\";\n\nexport interface SnapshotThenStreamSubscription {\n unsubscribe: () => void;\n refreshSnapshot: () => void;\n isReady: () => boolean;\n isDisposed: () => boolean;\n}\n\nexport interface SnapshotThenStreamInput<TSchema extends DescMessage, TSnapshot, TPublication> {\n realtime: PolyesterRealtime;\n channel: string;\n schema: TSchema;\n maxBufferedPublications?: number;\n bufferPublicationKey?: (publication: TPublication) => PropertyKey;\n snapshotRetry?: {\n maxAttempts: number;\n delayMs: number;\n };\n snapshotFailureMode?: \"wait\" | \"live\" | ((error: unknown) => \"wait\" | \"live\");\n snapshotErrorLog?: string;\n fetchSnapshot: () => Promise<TSnapshot>;\n readPublication: (message: MessageShape<TSchema>) => readonly TPublication[];\n applySnapshot: (snapshot: TSnapshot, bufferedPublications: readonly TPublication[]) => void;\n applyLivePublications: (publications: readonly TPublication[]) => void;\n onOpen?: () => void;\n onClose?: () => void;\n onError?: (ctx: SdkSubscriptionErrorContext) => void;\n}\n\n/**\n * Snapshot-then-stream for feed state. By default, the buffer caps at\n * `maxBufferedPublications` and drops the OLDEST publications, which is correct for\n * ephemeral feeds where a later publication supersedes earlier ones. Keyed state can\n * provide `bufferPublicationKey` to retain the latest value for every key without FIFO\n * loss. Entity transitions (orders, triggers, balances, trades) must NOT use this —\n * their ordering contract lives in the app-side `EntityStreamStore`, which buffers\n * unbounded and replays because dropping an event loses a row transition.\n */\nexport function snapshotThenStream<TSchema extends DescMessage, TSnapshot, TPublication>(\n params: SnapshotThenStreamInput<TSchema, TSnapshot, TPublication>,\n): SnapshotThenStreamSubscription {\n const maxBufferedPublications = params.maxBufferedPublications ?? 200;\n let droppedPublications = 0;\n\n let ready = false;\n let disposed = false;\n let refreshGeneration = 0;\n let pendingPublications: TPublication[] = [];\n let retryAttempts = 0;\n let retryTimer: ReturnType<typeof setTimeout> | null = null;\n\n function reportSnapshotError(error: unknown): void {\n if (isDev() && params.snapshotErrorLog) {\n console.error(params.snapshotErrorLog, error);\n }\n params.onError?.(\n createSdkSubscriptionErrorContext(\n params.channel,\n \"snapshot\",\n error instanceof Error ? error : formatConnectError(error, \"snapshot failed\"),\n ),\n );\n }\n\n function takePendingPublications(): TPublication[] {\n const buffered = pendingPublications;\n pendingPublications = [];\n return buffered;\n }\n\n function applyBufferedAsLive(): void {\n const buffered = takePendingPublications();\n if (buffered.length === 0) return;\n applyLivePublications(buffered);\n }\n\n function bufferPublications(publications: readonly TPublication[]): void {\n if (params.bufferPublicationKey) {\n const byKey = new Map<PropertyKey, TPublication>();\n for (const publication of pendingPublications) {\n byKey.set(params.bufferPublicationKey(publication), publication);\n }\n for (const publication of publications) {\n byKey.set(params.bufferPublicationKey(publication), publication);\n }\n pendingPublications = Array.from(byKey.values());\n return;\n }\n\n const next = pendingPublications.concat(publications);\n if (next.length > maxBufferedPublications) {\n droppedPublications += next.length - maxBufferedPublications;\n if (isDev()) {\n console.warn(\n `[snapshot-then-stream] ${params.channel}: buffer cap dropped ${droppedPublications} publication(s) while snapshot in flight`,\n );\n }\n }\n pendingPublications = next.slice(-maxBufferedPublications);\n }\n\n function clearRetryTimer(): void {\n if (retryTimer === null) return;\n clearTimeout(retryTimer);\n retryTimer = null;\n }\n\n function reportBufferedPublicationError(error: unknown): void {\n params.onError?.(\n createSdkSubscriptionErrorContext(params.channel, \"publication_handler\", error),\n );\n }\n\n function applyLivePublications(publications: readonly TPublication[]): void {\n try {\n params.applyLivePublications(publications);\n } catch (error) {\n reportBufferedPublicationError(error);\n }\n }\n\n function applySnapshot(\n snapshot: TSnapshot,\n bufferedPublications: readonly TPublication[],\n ): void {\n try {\n params.applySnapshot(snapshot, bufferedPublications);\n } catch (error) {\n reportBufferedPublicationError(error);\n }\n }\n\n function scheduleSnapshotRetry(): void {\n const retry = params.snapshotRetry;\n if (!retry || retryAttempts >= retry.maxAttempts || disposed) return;\n\n const delayMs = retry.delayMs * 2 ** retryAttempts;\n retryAttempts++;\n retryTimer = setTimeout(() => {\n retryTimer = null;\n refreshSnapshot(false);\n }, delayMs);\n }\n\n function refreshSnapshot(resetRetries = true): void {\n if (disposed) return;\n clearRetryTimer();\n if (resetRetries) retryAttempts = 0;\n\n const generation = ++refreshGeneration;\n ready = false;\n\n Promise.resolve()\n .then(() => params.fetchSnapshot())\n .then((snapshot) => {\n if (disposed || generation !== refreshGeneration) return;\n\n const buffered = takePendingPublications();\n applySnapshot(snapshot, buffered);\n\n if (disposed || generation !== refreshGeneration) return;\n ready = true;\n retryAttempts = 0;\n })\n .catch((error: unknown) => {\n if (disposed || generation !== refreshGeneration) return;\n reportSnapshotError(error);\n const failureMode =\n typeof params.snapshotFailureMode === \"function\"\n ? params.snapshotFailureMode(error)\n : params.snapshotFailureMode;\n if (failureMode === \"live\") {\n ready = true;\n applyBufferedAsLive();\n }\n scheduleSnapshotRetry();\n });\n }\n\n const unsubscribeRealtime = params.realtime.connectProtoChannel({\n channel: params.channel,\n schema: params.schema,\n onPublication: (message) => {\n const publications = params.readPublication(message);\n if (publications.length === 0) return;\n\n if (!ready) {\n bufferPublications(publications);\n return;\n }\n\n applyLivePublications(publications);\n },\n onConnected: () => {\n if (disposed) return;\n pendingPublications = [];\n refreshSnapshot();\n params.onOpen?.();\n },\n onDisconnected: () => {\n if (disposed) return;\n clearRetryTimer();\n refreshGeneration++;\n ready = false;\n pendingPublications = [];\n params.onClose?.();\n },\n onError: params.onError,\n });\n\n function unsubscribe(): void {\n disposed = true;\n clearRetryTimer();\n refreshGeneration++;\n pendingPublications = [];\n try {\n unsubscribeRealtime();\n } catch {\n // noop\n }\n }\n\n return {\n unsubscribe,\n refreshSnapshot,\n isReady: () => ready,\n isDisposed: () => disposed,\n };\n}\n"],"mappings":";;;;;;;;;;;;;AA8CA,SAAgB,mBACZ,QAC8B;CAC9B,MAAM,0BAA0B,OAAO,2BAA2B;CAClE,IAAI,sBAAsB;CAE1B,IAAI,QAAQ;CACZ,IAAI,WAAW;CACf,I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AAI,UAAU;GACd,sBAAsB,CAAC;GACvB,gBAAgB;GAChB,OAAO,SAAS;EACpB;EACA,sBAAsB;GAClB,IAAI,UAAU;GACd,gBAAgB;GAChB;GACA,QAAQ;GACR,sBAAsB,CAAC;GACvB,OAAO,UAAU;EACrB;EACA,SAAS,OAAO;CACpB,CAAC;CAED,SAAS,cAAoB;EACzB,WAAW;EACX,gBAAgB;EAChB;EACA,sBAAsB,CAAC;EACvB,IAAI;GACA,oBAAoB;EACxB,QAAQ,CAER;CACJ;CAEA,OAAO;EACH;EACA;EACA,eAAe;EACf,kBAAkB;CACtB;AACJ"}
1
+ {"version":3,"file":"snapshot-then-stream.js","names":[],"sources":["../../src/realtime/snapshot-then-stream.ts"],"sourcesContent":["import type { DescMessage, MessageShape } from \"@bufbuild/protobuf\";\nimport {\n createSdkSubscriptionErrorContext,\n type SdkSubscriptionErrorContext,\n} from \"../shared/subscription-errors.js\";\nimport type { PolyesterRealtime } from \"./types.js\";\nimport { formatConnectError } from \"../utils/errors.js\";\nimport { PolyesterError } from \"../shared/errors.js\";\nimport { isDev } from \"../utils/is-dev.js\";\n\nexport interface SnapshotThenStreamSubscription {\n unsubscribe: () => void;\n refreshSnapshot: () => void;\n isReady: () => boolean;\n isDisposed: () => boolean;\n}\n\nexport interface SnapshotThenStreamInput<TSchema extends DescMessage, TSnapshot, TPublication> {\n realtime: PolyesterRealtime;\n channel: string;\n schema: TSchema;\n maxBufferedPublications?: number;\n bufferPublicationKey?: (publication: TPublication) => PropertyKey;\n /** Exponential backoff from `delayMs`, capped at `maxDelayMs`; never retries a non-retryable PolyesterError. */\n snapshotRetry?: {\n maxAttempts: number;\n delayMs: number;\n maxDelayMs?: number;\n };\n snapshotFailureMode?: \"wait\" | \"live\" | ((error: unknown) => \"wait\" | \"live\");\n snapshotErrorLog?: string;\n fetchSnapshot: () => Promise<TSnapshot>;\n readPublication: (message: MessageShape<TSchema>) => readonly TPublication[];\n applySnapshot: (snapshot: TSnapshot, bufferedPublications: readonly TPublication[]) => void;\n applyLivePublications: (publications: readonly TPublication[]) => void;\n onOpen?: () => void;\n onClose?: () => void;\n onError?: (ctx: SdkSubscriptionErrorContext) => void;\n}\n\n/**\n * Snapshot-then-stream for feed state. By default, the buffer caps at\n * `maxBufferedPublications` and drops the OLDEST publications, which is correct for\n * ephemeral feeds where a later publication supersedes earlier ones. Keyed state can\n * provide `bufferPublicationKey` to retain the latest value for every key without FIFO\n * loss. Entity transitions (orders, triggers, balances, trades) must NOT use this —\n * their ordering contract lives in the app-side `EntityStreamStore`, which buffers\n * unbounded and replays because dropping an event loses a row transition.\n */\nexport function snapshotThenStream<TSchema extends DescMessage, TSnapshot, TPublication>(\n params: SnapshotThenStreamInput<TSchema, TSnapshot, TPublication>,\n): SnapshotThenStreamSubscription {\n const maxBufferedPublications = params.maxBufferedPublications ?? 200;\n let droppedPublications = 0;\n\n let ready = false;\n let disposed = false;\n let refreshGeneration = 0;\n let pendingPublications: TPublication[] = [];\n let retryAttempts = 0;\n let retryTimer: ReturnType<typeof setTimeout> | null = null;\n\n function reportSnapshotError(error: unknown): void {\n if (isDev() && params.snapshotErrorLog) {\n console.error(params.snapshotErrorLog, error);\n }\n params.onError?.(\n createSdkSubscriptionErrorContext(\n params.channel,\n \"snapshot\",\n error instanceof Error ? error : formatConnectError(error, \"snapshot failed\"),\n ),\n );\n }\n\n function takePendingPublications(): TPublication[] {\n const buffered = pendingPublications;\n pendingPublications = [];\n return buffered;\n }\n\n function applyBufferedAsLive(): void {\n const buffered = takePendingPublications();\n if (buffered.length === 0) return;\n applyLivePublications(buffered);\n }\n\n function bufferPublications(publications: readonly TPublication[]): void {\n if (params.bufferPublicationKey) {\n const byKey = new Map<PropertyKey, TPublication>();\n for (const publication of pendingPublications) {\n byKey.set(params.bufferPublicationKey(publication), publication);\n }\n for (const publication of publications) {\n byKey.set(params.bufferPublicationKey(publication), publication);\n }\n pendingPublications = Array.from(byKey.values());\n return;\n }\n\n const next = pendingPublications.concat(publications);\n if (next.length > maxBufferedPublications) {\n droppedPublications += next.length - maxBufferedPublications;\n if (isDev()) {\n console.warn(\n `[snapshot-then-stream] ${params.channel}: buffer cap dropped ${droppedPublications} publication(s) while snapshot in flight`,\n );\n }\n }\n pendingPublications = next.slice(-maxBufferedPublications);\n }\n\n function clearRetryTimer(): void {\n if (retryTimer === null) return;\n clearTimeout(retryTimer);\n retryTimer = null;\n }\n\n function reportBufferedPublicationError(error: unknown): void {\n params.onError?.(\n createSdkSubscriptionErrorContext(params.channel, \"publication_handler\", error),\n );\n }\n\n function applyLivePublications(publications: readonly TPublication[]): void {\n try {\n params.applyLivePublications(publications);\n } catch (error) {\n reportBufferedPublicationError(error);\n }\n }\n\n function applySnapshot(\n snapshot: TSnapshot,\n bufferedPublications: readonly TPublication[],\n ): void {\n try {\n params.applySnapshot(snapshot, bufferedPublications);\n } catch (error) {\n reportBufferedPublicationError(error);\n }\n }\n\n function scheduleSnapshotRetry(error: unknown): void {\n const retry = params.snapshotRetry;\n if (!retry || retryAttempts >= retry.maxAttempts || disposed) return;\n if (error instanceof PolyesterError && !error.retryable) return;\n\n const delayMs = Math.min(\n retry.delayMs * 2 ** retryAttempts,\n retry.maxDelayMs ?? Number.POSITIVE_INFINITY,\n );\n retryAttempts++;\n retryTimer = setTimeout(() => {\n retryTimer = null;\n refreshSnapshot(false);\n }, delayMs);\n }\n\n function refreshSnapshot(resetRetries = true): void {\n if (disposed) return;\n clearRetryTimer();\n if (resetRetries) retryAttempts = 0;\n\n const generation = ++refreshGeneration;\n ready = false;\n\n Promise.resolve()\n .then(() => params.fetchSnapshot())\n .then((snapshot) => {\n if (disposed || generation !== refreshGeneration) return;\n\n const buffered = takePendingPublications();\n applySnapshot(snapshot, buffered);\n\n if (disposed || generation !== refreshGeneration) return;\n ready = true;\n retryAttempts = 0;\n })\n .catch((error: unknown) => {\n if (disposed || generation !== refreshGeneration) return;\n reportSnapshotError(error);\n const failureMode =\n typeof params.snapshotFailureMode === \"function\"\n ? params.snapshotFailureMode(error)\n : params.snapshotFailureMode;\n if (failureMode === \"live\") {\n ready = true;\n applyBufferedAsLive();\n }\n scheduleSnapshotRetry(error);\n });\n }\n\n const unsubscribeRealtime = params.realtime.connectProtoChannel({\n channel: params.channel,\n schema: params.schema,\n onPublication: (message) => {\n const publications = params.readPublication(message);\n if (publications.length === 0) return;\n\n if (!ready) {\n bufferPublications(publications);\n return;\n }\n\n applyLivePublications(publications);\n },\n onConnected: () => {\n if (disposed) return;\n pendingPublications = [];\n refreshSnapshot();\n params.onOpen?.();\n },\n onDisconnected: () => {\n if (disposed) return;\n clearRetryTimer();\n refreshGeneration++;\n ready = false;\n pendingPublications = [];\n params.onClose?.();\n },\n onError: params.onError,\n });\n\n function unsubscribe(): void {\n disposed = true;\n clearRetryTimer();\n refreshGeneration++;\n pendingPublications = [];\n try {\n unsubscribeRealtime();\n } catch {\n // noop\n }\n }\n\n return {\n unsubscribe,\n refreshSnapshot,\n isReady: () => ready,\n isDisposed: () => disposed,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAiDA,SAAgB,mBACZ,QAC8B;CAC9B,MAAM,0BAA0B,OAAO,2BAA2B;CAClE,IAAI,sBAAsB;CAE1B,IAAI,QAAQ;CACZ,IAAI,WAAW;CACf,IAAI,oBAAoB;CACxB,IAAI,sBAAsC,CAAC;CAC3C,IAAI,gBAAgB;CACpB,IAAI,aAAmD;CAEvD,SAAS,oBAAoB,OAAsB;EAC/C,IAAI,MAAM,KAAK,OAAO,kBAClB,QAAQ,MAAM,OAAO,kBAAkB,KAAK;EAEhD,OAAO,UACH,kCACI,OAAO,SACP,YACA,iBAAiB,QAAQ,QAAQ,mBAAmB,OAAO,iBAAiB,CAChF,CACJ;CACJ;CAEA,SAAS,0BAA0C;EAC/C,MAAM,WAAW;EACjB,sBAAsB,CAAC;EACvB,OAAO;CACX;CAEA,SAAS,sBAA4B;EACjC,MAAM,WAAW,wBAAwB;EACzC,IAAI,SAAS,WAAW,GAAG;EAC3B,sBAAsB,QA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;EACf,kBAAkB;CACtB;AACJ"}
@@ -0,0 +1,22 @@
1
+ import { AuthApiTransports } from "../../shared/transports.js";
2
+ import { PolyesterRequestOptions } from "../../shared/request-options.js";
3
+ import { ListAccountActivityInput, ListAccountActivityResult } from "./account-activity.schemas.js";
4
+ //#region src/services/account-activity/account-activity.d.ts
5
+ /**
6
+ * Reads the security and activity events of the caller's main account and its sub-accounts in
7
+ * one feed: sign-ins, API key, MFA, policy, member, invite and saved-destination changes.
8
+ */
9
+ declare class AccountActivityService {
10
+ #private;
11
+ constructor(transports: AuthApiTransports);
12
+ /**
13
+ * Lists events newest first. Only the main account's own session or an API key with
14
+ * `read-account-activity` may call it; a key scoped to a sub-account reads only that
15
+ * sub-account's events and may not set `includeMainAccount`. A sub-account the caller may
16
+ * not read throws `ResourceNotFoundError`.
17
+ */
18
+ list(input?: ListAccountActivityInput, options?: PolyesterRequestOptions): Promise<ListAccountActivityResult>;
19
+ }
20
+ //#endregion
21
+ export { AccountActivityService };
22
+ //# sourceMappingURL=account-activity.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"account-activity.d.ts","names":[],"sources":["../../../src/services/account-activity/account-activity.ts"],"mappings":";;;;;;;;cAoBa;;EAGG,YAAA,YAAY;;;;;;;EAUlB,KACF,QAAO,0BACP,UAAU,0BACX,QAAQ"}