@hashgraphonline/standards-sdk 0.1.141 → 0.1.143-feat-adapter-registry.canary.fb173dc.54

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 (350) hide show
  1. package/README.md +24 -1
  2. package/dist/cjs/hcs-11/client.d.ts.map +1 -1
  3. package/dist/cjs/hcs-11/types.d.ts +1 -0
  4. package/dist/cjs/hcs-11/types.d.ts.map +1 -1
  5. package/dist/cjs/hcs-12/validation/schemas.d.ts +8 -8
  6. package/dist/cjs/hcs-16/base-client.d.ts.map +1 -1
  7. package/dist/cjs/hcs-17/types.d.ts.map +1 -1
  8. package/dist/cjs/hcs-20/sdk.d.ts.map +1 -1
  9. package/dist/cjs/hcs-20/types.d.ts +9 -8
  10. package/dist/cjs/hcs-20/types.d.ts.map +1 -1
  11. package/dist/cjs/hcs-21/base-client.d.ts +14 -12
  12. package/dist/cjs/hcs-21/base-client.d.ts.map +1 -1
  13. package/dist/cjs/hcs-21/browser.d.ts +17 -7
  14. package/dist/cjs/hcs-21/browser.d.ts.map +1 -1
  15. package/dist/cjs/hcs-21/index.d.ts +1 -0
  16. package/dist/cjs/hcs-21/index.d.ts.map +1 -1
  17. package/dist/cjs/hcs-21/sdk.d.ts +70 -6
  18. package/dist/cjs/hcs-21/sdk.d.ts.map +1 -1
  19. package/dist/cjs/hcs-21/tx.d.ts +6 -2
  20. package/dist/cjs/hcs-21/tx.d.ts.map +1 -1
  21. package/dist/cjs/hcs-21/types.d.ts +751 -66
  22. package/dist/cjs/hcs-21/types.d.ts.map +1 -1
  23. package/dist/cjs/hcs-21/verify.d.ts +6 -0
  24. package/dist/cjs/hcs-21/verify.d.ts.map +1 -0
  25. package/dist/cjs/inscribe/inscriber.d.ts +3 -1
  26. package/dist/cjs/inscribe/inscriber.d.ts.map +1 -1
  27. package/dist/cjs/inscribe/quote-cache.d.ts.map +1 -1
  28. package/dist/cjs/inscribe/types.d.ts +7 -0
  29. package/dist/cjs/inscribe/types.d.ts.map +1 -1
  30. package/dist/cjs/services/registry-broker/client/adapters.d.ts +20 -0
  31. package/dist/cjs/services/registry-broker/client/adapters.d.ts.map +1 -0
  32. package/dist/cjs/services/registry-broker/client/agents.d.ts +16 -0
  33. package/dist/cjs/services/registry-broker/client/agents.d.ts.map +1 -0
  34. package/dist/cjs/services/registry-broker/client/base-client.d.ts +57 -0
  35. package/dist/cjs/services/registry-broker/client/base-client.d.ts.map +1 -0
  36. package/dist/cjs/services/registry-broker/client/chat-history.d.ts +23 -0
  37. package/dist/cjs/services/registry-broker/client/chat-history.d.ts.map +1 -0
  38. package/dist/cjs/services/registry-broker/client/chat.d.ts +33 -0
  39. package/dist/cjs/services/registry-broker/client/chat.d.ts.map +1 -0
  40. package/dist/cjs/services/registry-broker/client/credits.d.ts +40 -0
  41. package/dist/cjs/services/registry-broker/client/credits.d.ts.map +1 -0
  42. package/dist/cjs/services/registry-broker/client/encrypted-chat-manager.d.ts +35 -0
  43. package/dist/cjs/services/registry-broker/client/encrypted-chat-manager.d.ts.map +1 -0
  44. package/dist/cjs/services/registry-broker/client/encryption.d.ts +33 -0
  45. package/dist/cjs/services/registry-broker/client/encryption.d.ts.map +1 -0
  46. package/dist/cjs/services/registry-broker/client/errors.d.ts +19 -0
  47. package/dist/cjs/services/registry-broker/client/errors.d.ts.map +1 -0
  48. package/dist/cjs/services/registry-broker/client/ledger-auth.d.ts +10 -0
  49. package/dist/cjs/services/registry-broker/client/ledger-auth.d.ts.map +1 -0
  50. package/dist/cjs/services/registry-broker/client/search.d.ts +19 -0
  51. package/dist/cjs/services/registry-broker/client/search.d.ts.map +1 -0
  52. package/dist/cjs/services/registry-broker/client/utils.d.ts +21 -0
  53. package/dist/cjs/services/registry-broker/client/utils.d.ts.map +1 -0
  54. package/dist/cjs/services/registry-broker/client.d.ts +2 -204
  55. package/dist/cjs/services/registry-broker/client.d.ts.map +1 -1
  56. package/dist/cjs/services/registry-broker/private-key-signer.d.ts.map +1 -1
  57. package/dist/cjs/services/registry-broker/schemas.d.ts +1473 -177
  58. package/dist/cjs/services/registry-broker/schemas.d.ts.map +1 -1
  59. package/dist/cjs/services/registry-broker/types.d.ts +45 -3
  60. package/dist/cjs/services/registry-broker/types.d.ts.map +1 -1
  61. package/dist/cjs/services/types.d.ts +1 -0
  62. package/dist/cjs/services/types.d.ts.map +1 -1
  63. package/dist/cjs/standards-sdk.cjs +2 -2
  64. package/dist/cjs/standards-sdk.cjs.map +1 -1
  65. package/dist/cjs/utils/dynamic-import.d.ts +1 -0
  66. package/dist/cjs/utils/dynamic-import.d.ts.map +1 -1
  67. package/dist/es/hcs-11/client.d.ts.map +1 -1
  68. package/dist/es/hcs-11/types.d.ts +1 -0
  69. package/dist/es/hcs-11/types.d.ts.map +1 -1
  70. package/dist/es/hcs-12/validation/schemas.d.ts +8 -8
  71. package/dist/es/hcs-16/base-client.d.ts.map +1 -1
  72. package/dist/es/hcs-17/types.d.ts.map +1 -1
  73. package/dist/es/hcs-20/sdk.d.ts.map +1 -1
  74. package/dist/es/hcs-20/types.d.ts +9 -8
  75. package/dist/es/hcs-20/types.d.ts.map +1 -1
  76. package/dist/es/hcs-21/base-client.d.ts +14 -12
  77. package/dist/es/hcs-21/base-client.d.ts.map +1 -1
  78. package/dist/es/hcs-21/browser.d.ts +17 -7
  79. package/dist/es/hcs-21/browser.d.ts.map +1 -1
  80. package/dist/es/hcs-21/index.d.ts +1 -0
  81. package/dist/es/hcs-21/index.d.ts.map +1 -1
  82. package/dist/es/hcs-21/sdk.d.ts +70 -6
  83. package/dist/es/hcs-21/sdk.d.ts.map +1 -1
  84. package/dist/es/hcs-21/tx.d.ts +6 -2
  85. package/dist/es/hcs-21/tx.d.ts.map +1 -1
  86. package/dist/es/hcs-21/types.d.ts +751 -66
  87. package/dist/es/hcs-21/types.d.ts.map +1 -1
  88. package/dist/es/hcs-21/verify.d.ts +6 -0
  89. package/dist/es/hcs-21/verify.d.ts.map +1 -0
  90. package/dist/es/inscribe/inscriber.d.ts +3 -1
  91. package/dist/es/inscribe/inscriber.d.ts.map +1 -1
  92. package/dist/es/inscribe/quote-cache.d.ts.map +1 -1
  93. package/dist/es/inscribe/types.d.ts +7 -0
  94. package/dist/es/inscribe/types.d.ts.map +1 -1
  95. package/dist/es/services/registry-broker/client/adapters.d.ts +20 -0
  96. package/dist/es/services/registry-broker/client/adapters.d.ts.map +1 -0
  97. package/dist/es/services/registry-broker/client/agents.d.ts +16 -0
  98. package/dist/es/services/registry-broker/client/agents.d.ts.map +1 -0
  99. package/dist/es/services/registry-broker/client/base-client.d.ts +57 -0
  100. package/dist/es/services/registry-broker/client/base-client.d.ts.map +1 -0
  101. package/dist/es/services/registry-broker/client/chat-history.d.ts +23 -0
  102. package/dist/es/services/registry-broker/client/chat-history.d.ts.map +1 -0
  103. package/dist/es/services/registry-broker/client/chat.d.ts +33 -0
  104. package/dist/es/services/registry-broker/client/chat.d.ts.map +1 -0
  105. package/dist/es/services/registry-broker/client/credits.d.ts +40 -0
  106. package/dist/es/services/registry-broker/client/credits.d.ts.map +1 -0
  107. package/dist/es/services/registry-broker/client/encrypted-chat-manager.d.ts +35 -0
  108. package/dist/es/services/registry-broker/client/encrypted-chat-manager.d.ts.map +1 -0
  109. package/dist/es/services/registry-broker/client/encryption.d.ts +33 -0
  110. package/dist/es/services/registry-broker/client/encryption.d.ts.map +1 -0
  111. package/dist/es/services/registry-broker/client/errors.d.ts +19 -0
  112. package/dist/es/services/registry-broker/client/errors.d.ts.map +1 -0
  113. package/dist/es/services/registry-broker/client/ledger-auth.d.ts +10 -0
  114. package/dist/es/services/registry-broker/client/ledger-auth.d.ts.map +1 -0
  115. package/dist/es/services/registry-broker/client/search.d.ts +19 -0
  116. package/dist/es/services/registry-broker/client/search.d.ts.map +1 -0
  117. package/dist/es/services/registry-broker/client/utils.d.ts +21 -0
  118. package/dist/es/services/registry-broker/client/utils.d.ts.map +1 -0
  119. package/dist/es/services/registry-broker/client.d.ts +2 -204
  120. package/dist/es/services/registry-broker/client.d.ts.map +1 -1
  121. package/dist/es/services/registry-broker/private-key-signer.d.ts.map +1 -1
  122. package/dist/es/services/registry-broker/schemas.d.ts +1473 -177
  123. package/dist/es/services/registry-broker/schemas.d.ts.map +1 -1
  124. package/dist/es/services/registry-broker/types.d.ts +45 -3
  125. package/dist/es/services/registry-broker/types.d.ts.map +1 -1
  126. package/dist/es/services/types.d.ts +1 -0
  127. package/dist/es/services/types.d.ts.map +1 -1
  128. package/dist/es/standards-sdk.es.js +73 -51
  129. package/dist/es/standards-sdk.es.js.map +1 -1
  130. package/dist/es/standards-sdk.es10.js +2 -2
  131. package/dist/es/standards-sdk.es100.js +26 -229
  132. package/dist/es/standards-sdk.es100.js.map +1 -1
  133. package/dist/es/standards-sdk.es101.js +228 -109
  134. package/dist/es/standards-sdk.es101.js.map +1 -1
  135. package/dist/es/standards-sdk.es102.js +94 -15
  136. package/dist/es/standards-sdk.es102.js.map +1 -1
  137. package/dist/es/standards-sdk.es103.js +30 -80
  138. package/dist/es/standards-sdk.es103.js.map +1 -1
  139. package/dist/es/standards-sdk.es104.js +80 -27
  140. package/dist/es/standards-sdk.es104.js.map +1 -1
  141. package/dist/es/standards-sdk.es105.js +25 -136
  142. package/dist/es/standards-sdk.es105.js.map +1 -1
  143. package/dist/es/standards-sdk.es106.js +140 -27
  144. package/dist/es/standards-sdk.es106.js.map +1 -1
  145. package/dist/es/standards-sdk.es107.js +27 -20
  146. package/dist/es/standards-sdk.es107.js.map +1 -1
  147. package/dist/es/standards-sdk.es108.js +18 -156
  148. package/dist/es/standards-sdk.es108.js.map +1 -1
  149. package/dist/es/standards-sdk.es109.js +148 -196
  150. package/dist/es/standards-sdk.es109.js.map +1 -1
  151. package/dist/es/standards-sdk.es110.js +167 -747
  152. package/dist/es/standards-sdk.es110.js.map +1 -1
  153. package/dist/es/standards-sdk.es111.js +786 -9
  154. package/dist/es/standards-sdk.es111.js.map +1 -1
  155. package/dist/es/standards-sdk.es112.js +13 -567
  156. package/dist/es/standards-sdk.es112.js.map +1 -1
  157. package/dist/es/standards-sdk.es113.js +541 -576
  158. package/dist/es/standards-sdk.es113.js.map +1 -1
  159. package/dist/es/standards-sdk.es114.js +601 -12
  160. package/dist/es/standards-sdk.es114.js.map +1 -1
  161. package/dist/es/standards-sdk.es115.js +13 -2
  162. package/dist/es/standards-sdk.es115.js.map +1 -1
  163. package/dist/es/standards-sdk.es116.js +2 -83
  164. package/dist/es/standards-sdk.es116.js.map +1 -1
  165. package/dist/es/standards-sdk.es117.js +80 -36
  166. package/dist/es/standards-sdk.es117.js.map +1 -1
  167. package/dist/es/standards-sdk.es118.js +39 -2
  168. package/dist/es/standards-sdk.es118.js.map +1 -1
  169. package/dist/es/standards-sdk.es119.js +2 -223
  170. package/dist/es/standards-sdk.es119.js.map +1 -1
  171. package/dist/es/standards-sdk.es12.js +1 -1
  172. package/dist/es/standards-sdk.es120.js +193 -1110
  173. package/dist/es/standards-sdk.es120.js.map +1 -1
  174. package/dist/es/standards-sdk.es121.js +1059 -225
  175. package/dist/es/standards-sdk.es121.js.map +1 -1
  176. package/dist/es/standards-sdk.es122.js +303 -419
  177. package/dist/es/standards-sdk.es122.js.map +1 -1
  178. package/dist/es/standards-sdk.es123.js +418 -351
  179. package/dist/es/standards-sdk.es123.js.map +1 -1
  180. package/dist/es/standards-sdk.es124.js +348 -754
  181. package/dist/es/standards-sdk.es124.js.map +1 -1
  182. package/dist/es/standards-sdk.es125.js +854 -178
  183. package/dist/es/standards-sdk.es125.js.map +1 -1
  184. package/dist/es/standards-sdk.es126.js +153 -1512
  185. package/dist/es/standards-sdk.es126.js.map +1 -1
  186. package/dist/es/standards-sdk.es127.js +1373 -1977
  187. package/dist/es/standards-sdk.es127.js.map +1 -1
  188. package/dist/es/standards-sdk.es128.js +176 -51
  189. package/dist/es/standards-sdk.es128.js.map +1 -1
  190. package/dist/es/standards-sdk.es129.js +196 -76
  191. package/dist/es/standards-sdk.es129.js.map +1 -1
  192. package/dist/es/standards-sdk.es13.js +1 -1
  193. package/dist/es/standards-sdk.es130.js +98 -153
  194. package/dist/es/standards-sdk.es130.js.map +1 -1
  195. package/dist/es/standards-sdk.es131.js +122 -8
  196. package/dist/es/standards-sdk.es131.js.map +1 -1
  197. package/dist/es/standards-sdk.es132.js +234 -73
  198. package/dist/es/standards-sdk.es132.js.map +1 -1
  199. package/dist/es/standards-sdk.es133.js +171 -56
  200. package/dist/es/standards-sdk.es133.js.map +1 -1
  201. package/dist/es/standards-sdk.es134.js +123 -29
  202. package/dist/es/standards-sdk.es134.js.map +1 -1
  203. package/dist/es/standards-sdk.es135.js +313 -125
  204. package/dist/es/standards-sdk.es135.js.map +1 -1
  205. package/dist/es/standards-sdk.es136.js +358 -34
  206. package/dist/es/standards-sdk.es136.js.map +1 -1
  207. package/dist/es/standards-sdk.es137.js +17 -732
  208. package/dist/es/standards-sdk.es137.js.map +1 -1
  209. package/dist/es/standards-sdk.es138.js +65 -12264
  210. package/dist/es/standards-sdk.es138.js.map +1 -1
  211. package/dist/es/standards-sdk.es139.js +86 -16
  212. package/dist/es/standards-sdk.es139.js.map +1 -1
  213. package/dist/es/standards-sdk.es14.js +1 -1
  214. package/dist/es/standards-sdk.es140.js +152 -49
  215. package/dist/es/standards-sdk.es140.js.map +1 -1
  216. package/dist/es/standards-sdk.es141.js +7 -64
  217. package/dist/es/standards-sdk.es141.js.map +1 -1
  218. package/dist/es/standards-sdk.es142.js +71 -157
  219. package/dist/es/standards-sdk.es142.js.map +1 -1
  220. package/dist/es/standards-sdk.es143.js +49 -306
  221. package/dist/es/standards-sdk.es143.js.map +1 -1
  222. package/dist/es/standards-sdk.es144.js +28 -346
  223. package/dist/es/standards-sdk.es144.js.map +1 -1
  224. package/dist/es/standards-sdk.es145.js +112 -427
  225. package/dist/es/standards-sdk.es145.js.map +1 -1
  226. package/dist/es/standards-sdk.es146.js +40 -329
  227. package/dist/es/standards-sdk.es146.js.map +1 -1
  228. package/dist/es/standards-sdk.es147.js +12277 -66
  229. package/dist/es/standards-sdk.es147.js.map +1 -1
  230. package/dist/es/standards-sdk.es148.js +20 -0
  231. package/dist/es/standards-sdk.es148.js.map +1 -0
  232. package/dist/es/standards-sdk.es149.js +59 -0
  233. package/dist/es/standards-sdk.es149.js.map +1 -0
  234. package/dist/es/standards-sdk.es15.js +1 -1
  235. package/dist/es/standards-sdk.es150.js +85 -0
  236. package/dist/es/standards-sdk.es150.js.map +1 -0
  237. package/dist/es/standards-sdk.es151.js +175 -0
  238. package/dist/es/standards-sdk.es151.js.map +1 -0
  239. package/dist/es/standards-sdk.es152.js +325 -0
  240. package/dist/es/standards-sdk.es152.js.map +1 -0
  241. package/dist/es/standards-sdk.es153.js +349 -0
  242. package/dist/es/standards-sdk.es153.js.map +1 -0
  243. package/dist/es/standards-sdk.es154.js +456 -0
  244. package/dist/es/standards-sdk.es154.js.map +1 -0
  245. package/dist/es/standards-sdk.es155.js +334 -0
  246. package/dist/es/standards-sdk.es155.js.map +1 -0
  247. package/dist/es/standards-sdk.es156.js +79 -0
  248. package/dist/es/standards-sdk.es156.js.map +1 -0
  249. package/dist/es/standards-sdk.es157.js +874 -0
  250. package/dist/es/standards-sdk.es157.js.map +1 -0
  251. package/dist/es/standards-sdk.es158.js +242 -0
  252. package/dist/es/standards-sdk.es158.js.map +1 -0
  253. package/dist/es/standards-sdk.es159.js +247 -0
  254. package/dist/es/standards-sdk.es159.js.map +1 -0
  255. package/dist/es/standards-sdk.es16.js +1 -1
  256. package/dist/es/standards-sdk.es17.js +13 -11
  257. package/dist/es/standards-sdk.es17.js.map +1 -1
  258. package/dist/es/standards-sdk.es19.js +20 -17
  259. package/dist/es/standards-sdk.es19.js.map +1 -1
  260. package/dist/es/standards-sdk.es20.js +17 -14
  261. package/dist/es/standards-sdk.es20.js.map +1 -1
  262. package/dist/es/standards-sdk.es21.js +1 -1
  263. package/dist/es/standards-sdk.es22.js +1 -1
  264. package/dist/es/standards-sdk.es23.js +1 -1
  265. package/dist/es/standards-sdk.es24.js +1 -1
  266. package/dist/es/standards-sdk.es25.js +1 -1
  267. package/dist/es/standards-sdk.es26.js +1 -1
  268. package/dist/es/standards-sdk.es27.js +1 -1
  269. package/dist/es/standards-sdk.es28.js +24 -19
  270. package/dist/es/standards-sdk.es28.js.map +1 -1
  271. package/dist/es/standards-sdk.es29.js.map +1 -1
  272. package/dist/es/standards-sdk.es3.js +2 -2
  273. package/dist/es/standards-sdk.es31.js +2 -2
  274. package/dist/es/standards-sdk.es32.js +4 -4
  275. package/dist/es/standards-sdk.es33.js +1 -1
  276. package/dist/es/standards-sdk.es36.js +16 -13
  277. package/dist/es/standards-sdk.es36.js.map +1 -1
  278. package/dist/es/standards-sdk.es37.js +4 -4
  279. package/dist/es/standards-sdk.es38.js +2 -2
  280. package/dist/es/standards-sdk.es39.js +2 -2
  281. package/dist/es/standards-sdk.es40.js +1 -1
  282. package/dist/es/standards-sdk.es41.js +1 -1
  283. package/dist/es/standards-sdk.es42.js +2 -2
  284. package/dist/es/standards-sdk.es47.js +1 -1
  285. package/dist/es/standards-sdk.es5.js +2 -2
  286. package/dist/es/standards-sdk.es52.js +1 -1
  287. package/dist/es/standards-sdk.es54.js +1 -1
  288. package/dist/es/standards-sdk.es57.js +2 -2
  289. package/dist/es/standards-sdk.es59.js +1 -1
  290. package/dist/es/standards-sdk.es6.js +2 -2
  291. package/dist/es/standards-sdk.es60.js +1 -1
  292. package/dist/es/standards-sdk.es61.js +15 -12
  293. package/dist/es/standards-sdk.es61.js.map +1 -1
  294. package/dist/es/standards-sdk.es63.js +1 -1
  295. package/dist/es/standards-sdk.es65.js +2 -2
  296. package/dist/es/standards-sdk.es66.js +3 -3
  297. package/dist/es/standards-sdk.es69.js +2 -2
  298. package/dist/es/standards-sdk.es7.js +2 -2
  299. package/dist/es/standards-sdk.es70.js +3 -3
  300. package/dist/es/standards-sdk.es71.js +2 -2
  301. package/dist/es/standards-sdk.es72.js +1 -1
  302. package/dist/es/standards-sdk.es73.js.map +1 -1
  303. package/dist/es/standards-sdk.es75.js +2 -2
  304. package/dist/es/standards-sdk.es77.js +5 -3
  305. package/dist/es/standards-sdk.es77.js.map +1 -1
  306. package/dist/es/standards-sdk.es78.js +12 -11
  307. package/dist/es/standards-sdk.es78.js.map +1 -1
  308. package/dist/es/standards-sdk.es79.js +1 -1
  309. package/dist/es/standards-sdk.es8.js +1 -1
  310. package/dist/es/standards-sdk.es80.js +113 -29
  311. package/dist/es/standards-sdk.es80.js.map +1 -1
  312. package/dist/es/standards-sdk.es82.js +23 -4
  313. package/dist/es/standards-sdk.es82.js.map +1 -1
  314. package/dist/es/standards-sdk.es83.js +39 -14
  315. package/dist/es/standards-sdk.es83.js.map +1 -1
  316. package/dist/es/standards-sdk.es84.js +198 -17
  317. package/dist/es/standards-sdk.es84.js.map +1 -1
  318. package/dist/es/standards-sdk.es85.js +256 -9
  319. package/dist/es/standards-sdk.es85.js.map +1 -1
  320. package/dist/es/standards-sdk.es86.js +55 -21
  321. package/dist/es/standards-sdk.es86.js.map +1 -1
  322. package/dist/es/standards-sdk.es87.js +22 -75
  323. package/dist/es/standards-sdk.es87.js.map +1 -1
  324. package/dist/es/standards-sdk.es88.js +45 -30
  325. package/dist/es/standards-sdk.es88.js.map +1 -1
  326. package/dist/es/standards-sdk.es89.js +57 -22
  327. package/dist/es/standards-sdk.es89.js.map +1 -1
  328. package/dist/es/standards-sdk.es90.js +28 -23
  329. package/dist/es/standards-sdk.es90.js.map +1 -1
  330. package/dist/es/standards-sdk.es91.js +23 -167
  331. package/dist/es/standards-sdk.es91.js.map +1 -1
  332. package/dist/es/standards-sdk.es92.js +158 -119
  333. package/dist/es/standards-sdk.es92.js.map +1 -1
  334. package/dist/es/standards-sdk.es93.js +68 -95
  335. package/dist/es/standards-sdk.es93.js.map +1 -1
  336. package/dist/es/standards-sdk.es94.js +136 -119
  337. package/dist/es/standards-sdk.es94.js.map +1 -1
  338. package/dist/es/standards-sdk.es95.js +139 -39
  339. package/dist/es/standards-sdk.es95.js.map +1 -1
  340. package/dist/es/standards-sdk.es96.js +42 -257
  341. package/dist/es/standards-sdk.es96.js.map +1 -1
  342. package/dist/es/standards-sdk.es97.js +243 -80
  343. package/dist/es/standards-sdk.es97.js.map +1 -1
  344. package/dist/es/standards-sdk.es98.js +47 -48
  345. package/dist/es/standards-sdk.es98.js.map +1 -1
  346. package/dist/es/standards-sdk.es99.js +100 -28
  347. package/dist/es/standards-sdk.es99.js.map +1 -1
  348. package/dist/es/utils/dynamic-import.d.ts +1 -0
  349. package/dist/es/utils/dynamic-import.d.ts.map +1 -1
  350. package/package.json +6 -10
@@ -1,4 +1,4 @@
1
- "use strict";var e;Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("util"),r=require("zod"),i=require("@hashgraph/sdk"),o=require("axios"),n=require("@hashgraph/proto"),s=require("@hashgraphonline/standards-sdk"),a=require("buffer"),c=require("ethers"),l=require("file-type"),d=require("node:path"),u=require("node:buffer"),p=require("node:crypto"),h=require("@noble/curves/secp256k1.js"),g=require("viem/accounts");require("viem/chains");const m=require("x402-axios"),f=require("x402/types"),y=require("mime-types"),b=require("date-fns"),w=require("crypto");var I="undefined"!=typeof document?document.currentScript:null;function T(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const r in e)if("default"!==r){const i=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:()=>e[r]})}return t.default=e,Object.freeze(t)}const S=T(d),k=T(y),E=/^\d+\.\d+\.\d+$/u,v=Symbol.for("standards-sdk.topic-auto-renew.patch"),A=Symbol.for("standards-sdk.account-id.patch"),C=function(){const e=function(){try{if("undefined"!=typeof module&&module?.createRequire)return module}catch{}try{if("function"==typeof require){const e=require("module");if(e?.createRequire)return e}}catch{}return null}();if(e?.createRequire)try{return e.createRequire("undefined"==typeof document?require("url").pathToFileURL(__filename).href:I&&"SCRIPT"===I.tagName.toUpperCase()&&I.src||new URL("standards-sdk.cjs",document.baseURI).href)}catch{return null}if("function"==typeof require)return require;return null}();function x(e,t){try{return e(t)}catch{return null}}function R(e,t){if(!e||!t)return;!function(e){if(Reflect.get(e,A))return;const t=e.fromString.bind(e);e.fromString=function(e){if("string"==typeof e)return t(e);const r=_(e);if(r)return t(r);if(P(e)){const r=O(e.shard),i=O(e.realm),o=O(e.num);if(r&&i&&o)return t(`${r}.${i}.${o}`)}return t(e)},Reflect.set(e,A,!0)}(t);const r=e.prototype;if(Reflect.get(r,v))return;const i=r.setAutoRenewAccountId,o=r.freezeWith;r.setAutoRenewAccountId=function(e){const r=N(e,t);return r?(function(e){const t=e;t._requireNotFrozen?.()}(this),this._autoRenewAccountId=r,this):i.call(this,e)},r.freezeWith=function(e){if(!this.getAutoRenewAccountId||"function"!=typeof this.getAutoRenewAccountId)return o.call(this,e);if(!this.getAutoRenewAccountId()){const r=this.transactionId?.accountId,i=e?.operatorAccountId,o=N(r,t)??N(i,t);o&&(this._autoRenewAccountId=o)}return o.call(this,e)},Reflect.set(r,v,!0)}function N(e,t){if(e instanceof t)return e;if("string"==typeof e&&E.test(e))return t.fromString(e);const r=function(e){if("string"==typeof e&&E.test(e))return e;const t=_(e);if(t)return t;if(P(e)){const t=O(e.shard),r=O(e.realm),i=O(e.num);if(t&&r&&i){const e=`${t}.${r}.${i}`;if(E.test(e))return e}}return null}(e);return r?t.fromString(r):null}function _(e){if("object"!=typeof e||null===e)return null;const t=e.toString;if("function"!=typeof t)return null;const r=t.call(e);return"string"!=typeof r?null:E.test(r)?r:null}function P(e){if("object"!=typeof e||null===e)return!1;const t=e;return F(t.shard)&&F(t.realm)&&F(t.num)}function F(e){return"object"==typeof e&&null!==e&&"function"==typeof e.toString}function O(e){if("number"==typeof e&&Number.isFinite(e))return String(Math.trunc(e));if("bigint"==typeof e)return e.toString();if(F(e)){const t=e.toString();if(/^\d+$/u.test(t))return t}return null}C?function(e){const t=x(e,"@hashgraph/sdk/lib/account/AccountId.cjs"),r=x(e,"@hashgraph/sdk/lib/topic/TopicCreateTransaction.cjs"),i=x(e,"@hashgraph/sdk"),o=[];t?.default&&r?.default&&o.push({accountId:t.default,topic:r.default});i&&o.push({accountId:i.AccountId??i.default?.AccountId,topic:i.TopicCreateTransaction??i.default?.TopicCreateTransaction});for(const n of o)R(n.topic,n.accountId);Reflect.set(globalThis,"__standardsSdkTopicAutoRenewPatched",!0)}(C):Reflect.set(globalThis,"__standardsSdkTopicAutoRenewPatched",!1);let D=null;let z=((e=class{constructor(e={}){if(D)return D(e);const t="undefined"!=typeof process&&"true"===process.env?.DISABLE_LOGS;this.silent=e.silent||t,this.level=this.silent?"silent":e.level||"info",this.moduleContext=e.module||"app",this.prettyPrint=!this.silent&&!1!==e.prettyPrint}static getInstance(t={}){const r=t.module||"default";if("undefined"!=typeof process&&"true"===process.env?.DISABLE_LOGS&&e.instances.has(r)){"silent"!==e.instances.get(r).getLevel()&&e.instances.delete(r)}if(!e.instances.has(r)){const i=D?D(t):new e(t);e.instances.set(r,i)}return e.instances.get(r)}setLogLevel(e){this.level=e}getLevel(){return this.level}setSilent(e){this.silent=e,e&&(this.level="silent")}setModule(e){this.moduleContext=e}formatArgs(e){if(0===e.length)return{msg:""};if(1===e.length)return"string"==typeof e[0]?{msg:e[0]}:{msg:"",data:e[0]};const t=[],r=[];e.forEach(e=>{"string"==typeof e||"number"==typeof e||"boolean"==typeof e?t.push(String(e)):r.push(e)});const i=t.join(" ");return r.length>0?{msg:i,data:r}:{msg:i}}shouldLog(e){if(this.silent||"silent"===this.level)return!1;const t=["trace","debug","info","warn","error","silent"],r=t.indexOf(this.level);return t.indexOf(e)>=r}getConsoleMethod(e){return"error"===e?console.error:"warn"===e?console.warn:"debug"===e?console.debug:console.log}writeLog(e,...r){if(!this.shouldLog(e))return;const{msg:i,data:o}=this.formatArgs(r),n=(new Date).toISOString(),s=this.getConsoleMethod(e);if(this.prettyPrint){let r=`${n} ${e.toUpperCase().padEnd(5)} [${this.moduleContext}] ${i}`;o&&(r+="\n"+t.inspect(o,{colors:!0,depth:3})),s(r)}else{const t={timestamp:n,level:e,module:this.moduleContext,message:i,...o&&{data:o}};s(JSON.stringify(t))}}debug(...e){this.writeLog("debug",...e)}info(...e){this.writeLog("info",...e)}warn(...e){this.writeLog("warn",...e)}error(...e){this.writeLog("error",...e)}trace(...e){this.writeLog("trace",...e)}static clearInstances(){e.instances.clear()}}).instances=new Map,e);const B=e=>new Promise(t=>setTimeout(t,e));class M{constructor(){this.modelViewerLoaded=!1,this.modelViewerLoading=null,this.config={cdnUrl:"https://kiloscribe.com/api/inscription-cdn/",network:"mainnet",retryAttempts:3,retryBackoff:300,debug:!1,showLoadingIndicator:!1,loadingCallbackName:null},this.configMapping={hcsCdnUrl:"cdnUrl",hcsNetwork:"network",hcsRetryAttempts:"retryAttempts",hcsRetryBackoff:"retryBackoff",hcsDebug:"debug",hcsShowLoadingIndicator:"showLoadingIndicator",hcsLoadingCallbackName:"loadingCallbackName"},this.LoadedScripts={},this.LoadedWasm={},this.LoadedImages={},this.LoadedVideos={},this.LoadedAudios={},this.LoadedAudioUrls={},this.LoadedGLBs={},this.scriptLoadedEvent=new Event("HCSScriptLoaded"),this.loadQueue=[],this.isProcessingQueue=!1;try{this.logger=z.getInstance({module:"HCS-3",level:this.config.debug?"debug":"error"})}catch(e){this.logger=this.createFallbackLogger()}}createFallbackLogger(){return{debug:(...e)=>this.config.debug&&console.debug("[HCS-3]",...e),info:(...e)=>this.config.debug&&console.info("[HCS-3]",...e),warn:(...e)=>console.warn("[HCS-3]",...e),error:(...e)=>console.error("[HCS-3]",...e),setLogLevel:e=>{this.config.debug="debug"===e}}}log(...e){if(0===e.length)this.logger.debug("");else if(1===e.length)this.logger.debug(String(e[0]));else{const t=String(e[0]),r=e.slice(1);this.logger.debug(t,r)}}error(...e){if(0===e.length)this.logger.error("");else if(1===e.length)this.logger.error(String(e[0]));else{const t=String(e[0]),r=e.slice(1);this.logger.error(t,r)}}loadConfigFromHTML(){const e=document.querySelector("script[data-hcs-config]");e&&(Object.keys(this.configMapping).forEach(t=>{if(e.dataset[t]){const r=this.configMapping[t];let i=e.dataset[t];"true"===i&&(i=!0),"false"===i&&(i=!1),isNaN(Number(i))||""===i||(i=Number(i)),this.config[r]=i}}),this.logger.setLogLevel(this.config.debug?"debug":"error")),this.log("Loaded config:",this.config)}updateLoadingStatus(e,t){if("loaded"!==this.LoadedScripts[e]&&(this.config.showLoadingIndicator&&console.log("[HCS Loading] "+e+" : "+t),this.LoadedScripts[e]=t,this.config.loadingCallbackName&&"function"==typeof window[this.config.loadingCallbackName])){const r=window[this.config.loadingCallbackName];"function"==typeof r&&r(e,t)}}async fetchWithRetry(e,t=this.config.retryAttempts,r=this.config.retryBackoff){try{const t=await fetch(e);if(!t.ok)throw new Error("HTTP error! status: "+t.status);return t}catch(i){if(t>0)return this.log("Retrying fetch for "+e+" Attempts left: "+(t-1)),await this.sleep(r),this.fetchWithRetry(e,t-1,2*r);throw i}}sleep(e){return B(e)}isDuplicate(e){return!!this.LoadedScripts[e]}async retrieveHCS1Data(e,t=this.config.cdnUrl,r=this.config.network){const i=r.replace(/['"]+/g,""),o=await this.fetchWithRetry(t+e+"?network="+i);return await o.blob()}async loadScript(e){const t=e.getAttribute("data-src"),r=e.getAttribute("data-script-id"),i=t?.split("/").pop(),o=e.getAttribute("type"),n=e.hasAttribute("data-required"),s="module"===e.getAttribute("type");if(!this.isDuplicate(i||"")){this.updateLoadingStatus(r,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,a=e.getAttribute("data-network")||this.config.network,c=await this.retrieveHCS1Data(i,t,a);if("wasm"===o){const t=await c.arrayBuffer(),i=await WebAssembly.compile(t);this.LoadedWasm[r]=await WebAssembly.instantiate(i,{env:{},...e.dataset}),this.updateLoadingStatus(r,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded wasm: "+r)}else{const e=await c.text(),t=document.createElement("script");if(t.textContent=e,t.className="hcs-inline-script",r&&t.setAttribute("data-loaded-script-id",r),s){t.type="module";const r=new Blob([e],{type:"application/javascript"});t.src=URL.createObjectURL(r)}document.body.appendChild(t),this.updateLoadingStatus(r,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded script: "+r),t.onerror=e=>{if(this.error("Failed to load "+o+": "+r,e),this.updateLoadingStatus(r,"failed"),n)throw e}}}catch(a){if(this.error("Failed to load "+o+": "+r,a),this.updateLoadingStatus(r,"failed"),n)throw a}}}async loadModuleExports(e){const t=document.querySelector('script[data-loaded-script-id="'+e+'"]');if(!t)throw new Error("Module script with id "+e+" not found");const r=t.getAttribute("src");if(!r)throw new Error("Module script "+e+" has no src attribute");try{const e=new Function("url","return import(url)");return await e(r)}catch(i){throw this.error("Failed to import module",i),i}}async loadStylesheet(e){const t=e.getAttribute("data-src"),r=e.getAttribute("data-script-id"),i=t?.split("/").pop(),o=e.hasAttribute("data-required");if(!this.isDuplicate(i||"")){this.updateLoadingStatus(r,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,o=e.getAttribute("data-network")||this.config.network,n=await this.retrieveHCS1Data(i,t,o),s=await n.text(),a=document.createElement("style");a.textContent=s,document.head.appendChild(a),this.updateLoadingStatus(r,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded and inlined stylesheet: "+r)}catch(n){if(this.error("Failed to load stylesheet: "+r,n),this.updateLoadingStatus(r,"failed"),o)throw n}}}async loadImage(e){const t=e.getAttribute("data-src"),r=t?.split("/").pop();this.log("Loading image: "+r),this.updateLoadingStatus("Image: "+r,"loaded");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,i=e.getAttribute("data-network")||this.config.network,o=await this.retrieveHCS1Data(r,t,i),n=URL.createObjectURL(o);e.src=n,this.LoadedImages[r]=n,this.updateLoadingStatus("Image: "+r,"loaded"),this.log("Loaded image: "+r)}catch(i){this.error("Failed to load image: "+r,i),this.updateLoadingStatus("Image: "+r,"failed")}}async loadMedia(e,t){const r=e.getAttribute("data-src"),i=r?.split("/").pop();this.log("Loading "+t+": "+i),this.updateLoadingStatus(t+": "+i,"loading");try{const r=e.getAttribute("data-cdn-url")||this.config.cdnUrl,o=e.getAttribute("data-network")||this.config.network,n=await this.retrieveHCS1Data(i,r,o),s=URL.createObjectURL(n);e.src=s,"video"===t?this.LoadedVideos[i]=s:this.LoadedAudioUrls[i]=s,this.updateLoadingStatus(t+": "+i,"loaded"),this.log("Loaded "+t+": "+i)}catch(o){this.error("Failed to load "+t+": "+i,o),this.updateLoadingStatus(t+": "+i,"failed")}}async loadModelViewer(){return this.modelViewerLoading?this.modelViewerLoading:this.modelViewerLoaded?Promise.resolve():(this.modelViewerLoading=new Promise(e=>{const t=document.createElement("script");t.setAttribute("data-src","hcs://1/0.0.7293044"),t.setAttribute("data-script-id","model-viewer"),t.setAttribute("type","module"),window.addEventListener("HCSScriptLoaded",()=>{this.modelViewerLoaded=!0,e()},{once:!0}),this.loadScript(t)}),this.modelViewerLoading)}async loadGLB(e){await this.loadModelViewer();const t=e.getAttribute("data-src"),r=t?.split("/").pop();this.log("Loading GLB: "+r),this.updateLoadingStatus("GLB: "+r,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,i=e.getAttribute("data-network")||this.config.network;let o;"model-viewer"!==e.tagName.toLowerCase()?(o=document.createElement("model-viewer"),Array.from(e.attributes).forEach(e=>{o.setAttribute(e.name,e.value)}),o.setAttribute("camera-controls",""),o.setAttribute("auto-rotate",""),o.setAttribute("ar",""),e.parentNode?.replaceChild(o,e)):o=e;const n=await this.retrieveHCS1Data(r,t,i),s=URL.createObjectURL(n);o.setAttribute("src",s),this.LoadedGLBs[r]=s,this.updateLoadingStatus("GLB: "+r,"loaded"),this.log("Loaded GLB: "+r)}catch(i){this.error("Failed to load GLB: "+r,i),this.updateLoadingStatus("GLB: "+r,"failed")}}async loadResource(e,t,r){return new Promise(i=>{this.loadQueue.push({element:e,type:t,order:r,resolve:i}),this.processQueue()})}async processQueue(){if(!this.isProcessingQueue){for(this.isProcessingQueue=!0;this.loadQueue.length>0;){const t=this.loadQueue.shift();try{"script"===t.type?await this.loadScript(t.element):"image"===t.type?await this.loadImage(t.element):"video"===t.type||"audio"===t.type?await this.loadMedia(t.element,t.type):"glb"===t.type?await this.loadGLB(t.element):"css"===t.type&&await this.loadStylesheet(t.element),t.resolve()}catch(e){if(this.error("Error processing queue item:",e),"script"===t.type&&t.element.hasAttribute("data-required"))break}}this.isProcessingQueue=!1}}async replaceHCSInStyle(e){let t=e,r=t.indexOf("hcs://");for(;-1!==r;){let e=r;for(;e<t.length&&!["'",'"'," ",")"].includes(t[e]);)e++;const o=t.substring(r,e),n=o.split("/").pop();try{const i=this.config.cdnUrl,s=this.config.network,a=await this.retrieveHCS1Data(n,i,s),c=URL.createObjectURL(a);t=t.substring(0,r)+c+t.substring(e),this.LoadedImages[n]=c,this.log("Replaced CSS HCS URL: "+o+" with "+c)}catch(i){this.error("Failed to load CSS image: "+n,i)}r=t.indexOf("hcs://",r+1)}return t}async processInlineStyles(){const e=document.querySelectorAll('[style*="hcs://"]');this.log("Found "+e.length+" elements with HCS style references");for(const r of Array.from(e)){const e=r.getAttribute("style");if(e){this.log("Processing style: "+e);const t=await this.replaceHCSInStyle(e);e!==t&&(r.setAttribute("style",t),this.log("Updated style to: "+t))}}const t=document.querySelectorAll("style");for(const r of Array.from(t))if(r.textContent?.includes("hcs://")){const e=await this.replaceHCSInStyle(r.textContent);r.textContent!==e&&(r.textContent=e)}}async init(){return this.loadConfigFromHTML(),new Promise(e=>{const t=async()=>{const t=document.querySelectorAll('script[data-src^="hcs://"]'),r=document.querySelectorAll('img[data-src^="hcs://"], img[src^="hcs://"]'),i=document.querySelectorAll('video[data-src^="hcs://"], video[src^="hcs://"]'),o=document.querySelectorAll('audio[data-src^="hcs://"], audio[src^="hcs://"]'),n=document.querySelectorAll('model-viewer[data-src^="hcs://"]'),s=document.querySelectorAll('link[data-src^="hcs://"]');document.querySelectorAll('[src^="hcs://"]').forEach(e=>{const t=e.getAttribute("src");t&&(e.setAttribute("data-src",t),e.removeAttribute("src"))}),await this.processInlineStyles();const a=[];[{elements:t,type:"script"},{elements:r,type:"image"},{elements:i,type:"video"},{elements:o,type:"audio"},{elements:n,type:"glb"},{elements:s,type:"css"}].forEach(({elements:e,type:t})=>{e.forEach(e=>{const r=parseInt(e.getAttribute("data-load-order")||"")||1/0;a.push(this.loadResource(e,t,r))})}),await Promise.all(a);const c=new MutationObserver(e=>{e.forEach(e=>{if(e.addedNodes.forEach(e=>{if(e.nodeType===Node.ELEMENT_NODE){const t=e;if(t.getAttribute("style")?.includes("hcs://")&&this.processInlineStyles(),"style"===t.tagName.toLowerCase()&&t.textContent?.includes("hcs://")&&this.processInlineStyles(),t.getAttribute("src")?.startsWith("hcs://")){const e=t.getAttribute("src");t.setAttribute("data-src",e),t.removeAttribute("src");switch(t.tagName.toLowerCase()){case"img":this.loadResource(t,"image",1/0);break;case"video":this.loadResource(t,"video",1/0);break;case"audio":this.loadResource(t,"audio",1/0);break;case"script":this.loadResource(t,"script",1/0)}}t.matches('script[data-src^="hcs://"]')?this.loadResource(t,"script",1/0):t.matches('img[data-src^="hcs://"]')?this.loadResource(t,"image",1/0):t.matches('video[data-src^="hcs://"]')?this.loadResource(t,"video",1/0):t.matches('audio[data-src^="hcs://"]')?this.loadResource(t,"audio",1/0):t.matches('model-viewer[data-src^="hcs://"]')?this.loadResource(t,"glb",1/0):t.matches('link[data-src^="hcs://"]')&&this.loadResource(t,"css",1/0);t.querySelectorAll('[data-src^="hcs://"], [src^="hcs://"]').forEach(e=>{const t=e,r=t.tagName.toLowerCase(),i=t.getAttribute("src");switch(i?.startsWith("hcs://")&&(t.setAttribute("data-src",i),t.removeAttribute("src")),r){case"script":this.loadResource(t,"script",1/0);break;case"img":this.loadResource(t,"image",1/0);break;case"video":this.loadResource(t,"video",1/0);break;case"audio":this.loadResource(t,"audio",1/0);break;case"model-viewer":this.loadResource(t,"glb",1/0);break;case"link":this.loadResource(t,"css",1/0)}})}}),"attributes"===e.type){const t=e.target;if("style"===e.attributeName&&t.getAttribute("style")?.includes("hcs://"))this.processInlineStyles();else if("src"===e.attributeName){const e=t.getAttribute("src");if(e?.startsWith("hcs://")){t.setAttribute("data-src",e),t.removeAttribute("src");const r=t.tagName.toLowerCase();["img","video","audio"].includes(r)&&this.loadResource(t,r,1/0)}}}})});document.body?c.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","src","data-src"]}):document.addEventListener("DOMContentLoaded",()=>{c.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","src","data-src"]})}),e()};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t):t()})}async preloadImage(e){this.log("Loading image:"+e),this.updateLoadingStatus("image: "+e,"loading");const t=await this.retrieveHCS1Data(e),r=URL.createObjectURL(t);return this.LoadedImages[e]=r,this.updateLoadingStatus("image: "+e,"loaded"),r}async preloadAudio(e){const t=document.createElement("audio");t.setAttribute("data-topic-id",e),t.setAttribute("data-src","hcs://1/"+e),document.body.appendChild(t),await this.loadMedia(t,"audio");const r=document.querySelector('audio[data-topic-id="'+e+'"]');return r?this.LoadedAudioUrls[e]=r.src:console.error("Failed to preload audio: "+e),this.LoadedAudioUrls[e]}async playAudio(e,t=1){const r=this.LoadedAudioUrls[e];if(r){const i=new Audio(r);i.volume=t,this.LoadedAudios[e]=i,i.play().catch(e=>{console.error("Failed to play audio:",e)}),i.addEventListener("ended",()=>{i.remove(),delete this.LoadedAudios[e]})}else console.error("Audio not preloaded: "+e)}async pauseAudio(e){const t=document.querySelector('audio[data-topic-id="'+e+'"]');t?(console.log("found element",t),t.pause(),this.LoadedAudios[e]?.pause()):this.LoadedAudios[e]?.pause()}async loadAndPlayAudio(e,t=!1,r=1){let i=document.querySelector('audio[data-topic-id="'+e+'"]');if(i)i.volume=r,await i.play();else{const o=document.createElement("audio");o.volume=r,t&&o.setAttribute("autoplay","autoplay"),o.setAttribute("data-topic-id",e),o.setAttribute("data-src","hcs://1/"+e),document.body.appendChild(o),await this.loadMedia(o,"audio"),i=document.querySelector('audio[data-topic-id="'+e+'"]'),t||await i.play()}}}var K=(e=>(e.REGISTER="register",e))(K||{}),U=(e=>(e[e.NON_INDEXED=1]="NON_INDEXED",e))(U||{});function L(e){return`hcs://6/${e}`}const $=r.z.string().regex(/^\d+\.\d+\.\d+$/,{message:"Topic ID must be in Hedera format (e.g., '0.0.123456')"}),H=r.z.object({p:r.z.literal("hcs-6"),op:r.z.enum(["register"]),m:r.z.string().max(500,"Memo must not exceed 500 characters").optional()}),q=H.extend({op:r.z.literal("register"),t_id:$}),j=r.z.discriminatedUnion("op",[q]);function W(e){return e>=3600}function V(e){if(!W(e))throw new Error("TTL must be at least 3600 seconds (1 hour)");return`hcs-6:1:${e}`}class G{constructor(e,t,r){this.maxRetries=5,this.initialDelayMs=2e3,this.maxDelayMs=3e4,this.backoffFactor=2,this.network=e,this.apiKey=r?.apiKey,this.customHeaders=r?.headers||{},this.baseUrl=r?.customUrl||this.getMirrorNodeUrl(),this.logger=t||new z({level:"debug",module:"MirrorNode"}),this.isServerEnvironment="undefined"==typeof window,r?.customUrl&&this.logger.info(`Using custom mirror node URL: ${r.customUrl}`),r?.apiKey&&this.logger.info("Using API key for mirror node requests")}configureRetry(e){this.maxRetries=e.maxRetries??this.maxRetries,this.initialDelayMs=e.initialDelayMs??this.initialDelayMs,this.maxDelayMs=e.maxDelayMs??this.maxDelayMs,this.backoffFactor=e.backoffFactor??this.backoffFactor,this.logger.info(`Retry configuration updated: maxRetries=${this.maxRetries}, initialDelayMs=${this.initialDelayMs}, maxDelayMs=${this.maxDelayMs}, backoffFactor=${this.backoffFactor}`)}configureMirrorNode(e){e.customUrl&&(this.baseUrl=e.customUrl,this.logger.info(`Updated mirror node URL: ${e.customUrl}`)),e.apiKey&&(this.apiKey=e.apiKey,this.logger.info("Updated API key for mirror node requests")),e.headers&&(this.customHeaders={...this.customHeaders,...e.headers},this.logger.info("Updated custom headers for mirror node requests"))}constructUrl(e){if(this.baseUrl.includes("<API-KEY>")&&this.apiKey){const t=this.baseUrl.replace("<API-KEY>",this.apiKey);return e.startsWith("/")?`${t}${e}`:`${t}/${e}`}return e.startsWith("/")?`${this.baseUrl}${e}`:`${this.baseUrl}/${e}`}getMirrorNodeUrl(){return"mainnet"===this.network?"https://mainnet-public.mirrornode.hedera.com":"https://testnet.mirrornode.hedera.com"}getBaseUrl(){return this.baseUrl}async getPublicKey(e){this.logger.debug(`Getting public key for account ${e}`);const t=await this.requestAccount(e);try{if(!t||!t.key)throw new Error(`Failed to retrieve public key for account ID: ${e}`);return i.PublicKey.fromString(t.key.key)}catch(r){const e=`Error fetching public key from Mirror Node: ${r.message}`;throw this.logger.error(e),new Error(e)}}async getAccountMemo(e){this.logger.debug(`Getting account memo for account ID: ${e}`);try{const t=await this._requestWithRetry(`/api/v1/accounts/${e}`);return t?.memo?t.memo:(this.logger.warn(`No memo found for account ${e}`),null)}catch(t){const r=t;return this.logger.error(`Failed to get account memo for ${e} after retries: ${r.message}`),null}}async getTopicInfo(e){try{this.logger.debug(`Fetching topic info for ${e}`);return await this._requestWithRetry(`/api/v1/topics/${e}`)}catch(t){const r=`Error retrieving topic information for ${e} after retries: ${t.message}`;throw this.logger.error(r),new Error(r)}}async getTopicFees(e){try{return(await this.getTopicInfo(e)).custom_fees}catch(t){const e=`Error retrieving topic fees: ${t.message}`;return this.logger.error(e),null}}async getHBARPrice(e){try{const t=i.Timestamp.fromDate(e).toString();this.logger.debug(`Fetching HBAR price for timestamp ${t}`);const r=await this._requestWithRetry(`/api/v1/network/exchangerate?timestamp=${t}`);return Number(r?.current_rate?.cent_equivalent)/Number(r?.current_rate?.hbar_equivalent)/100}catch(t){const e=`Error retrieving HBAR price: ${t.message}`;return this.logger.error(e),null}}async getTokenInfo(e){this.logger.debug(`Fetching token info for ${e}`);try{const t=await this._requestWithRetry(`/api/v1/tokens/${e}`);return t?(this.logger.trace(`Token info found for ${e}:`,t),t):(this.logger.warn(`No token info found for ${e}`),null)}catch(t){const r=`Error fetching token info for ${e}: ${t.message}`;return this.logger.error(r),null}}async getTopicMessages(e,t){this.logger.trace(`Querying messages for topic ${e}${t?" with filters":""}`);let r=`/api/v1/topics/${e}/messages`;const i=new URLSearchParams;if(t){if(void 0!==t.sequenceNumber){const e="number"==typeof t.sequenceNumber?t.sequenceNumber.toString():t.sequenceNumber;e.match(/^(gt|gte|lt|lte|eq|ne):/)?i.append("sequencenumber",e):i.append("sequencenumber",`gt:${e}`)}t.limit&&i.append("limit",t.limit.toString()),t.order&&i.append("order",t.order)}const o=i.toString();o&&(r+=`?${o}`);const n=[];let s=r;for(;s;)try{const e=await this._requestWithRetry(s);if(e.messages&&e.messages.length>0)for(const t of e.messages)try{if(!t.message)continue;let e,r;try{e=this.isServerEnvironment?globalThis.Buffer.from(t.message,"base64").toString("utf-8"):(new TextDecoder).decode(Uint8Array.from(atob(t.message),e=>e.charCodeAt(0)))}catch(a){const e=`Error decoding message: ${a}`;this.logger.error(e);continue}try{r=JSON.parse(e)}catch(a){const t=`Invalid JSON message content: ${e}`;this.logger.error(t);continue}r.sequence_number=t.sequence_number,n.push({...r,consensus_timestamp:t.consensus_timestamp,sequence_number:t.sequence_number,running_hash:t.running_hash,running_hash_version:t.running_hash_version,topic_id:t.topic_id,payer:t.payer_account_id,created:new Date(1e3*Number(t.consensus_timestamp))})}catch(a){const e=`Error processing message: ${a.message}`;this.logger.error(e)}s=e.links?.next||""}catch(c){const t=`Error querying topic messages for topic ${e} (endpoint: ${s}) after retries: ${c.message}`;throw this.logger.error(t),new Error(t)}return n}async requestAccount(e){try{this.logger.debug(`Requesting account info for ${e}`);const t=await this._requestWithRetry(`/api/v1/accounts/${e}`);if(!t)throw new Error(`No data received from mirror node for account: ${e}`);return t}catch(t){const r=`Failed to fetch account ${e} after retries: ${t.message}`;throw this.logger.error(r),new Error(r)}}async checkKeyListAccess(e,t){try{const r=n.proto.Key.decode(e);return this.evaluateKeyAccess(r,t)}catch(r){const e=`Error decoding protobuf key: ${r.message}`;throw this.logger.error(e),new Error(e)}}async evaluateKeyAccess(e,t){return e.ed25519?this.compareEd25519Key(e.ed25519,t):e.keyList?this.evaluateKeyList(e.keyList,t):!(!e.thresholdKey||!e.thresholdKey.keys)&&this.evaluateKeyList(e.thresholdKey.keys,t)}async evaluateKeyList(e,t){const r=e.keys||[];for(const o of r)if(o)if(o.ed25519){if(this.compareEd25519Key(o.ed25519,t))return!0}else if(o.keyList||o.thresholdKey)try{const e=n.proto.Key.encode({...o.keyList?{keyList:o.keyList}:{},...o.thresholdKey?{thresholdKey:o.thresholdKey}:{}}).finish();if(await this.checkKeyListAccess(globalThis.Buffer.from(e),t))return!0}catch(i){const e=`Error in nested key: ${i.message}`;this.logger.debug(e)}return!1}compareEd25519Key(e,t){try{return i.PublicKey.fromBytes(globalThis.Buffer.from(e)).toString()===t.toString()}catch(r){const e=`Error comparing Ed25519 key: ${r.message}`;return this.logger.debug(e),!1}}async getScheduleInfo(e){try{this.logger.info(`Getting information for scheduled transaction ${e}`);const t=await this._requestWithRetry(`/api/v1/schedules/${e}`);return t||(this.logger.warn(`No schedule info found for ${e} after retries.`),null)}catch(t){return this.logger.error(`Error fetching schedule info for ${e} after retries: ${t.message}`),null}}async getScheduledTransactionStatus(e){try{this.logger.info(`Checking status of scheduled transaction ${e}`);const t=await this.getScheduleInfo(e);if(!t)throw new Error(`Schedule ${e} not found`);return{executed:Boolean(t.executed_timestamp),executedDate:t.executed_timestamp?new Date(1e3*Number(t.executed_timestamp)):void 0,deleted:t.deleted||!1}}catch(t){throw this.logger.error(`Error checking scheduled transaction status: ${t}`),t}}async getTransaction(e){this.logger.info(`Getting transaction details for ID/hash: ${e}`);try{const t=await this._requestWithRetry(`/api/v1/transactions/${e}`);return t?.transactions?.length>0?(this.logger.trace(`Transaction details found for ${e}:`,t.transactions[0]),t.transactions[0]):(this.logger.warn(`No transaction details found for ${e} or unexpected response structure.`),null)}catch(t){const r=t;return this.logger.error(`Failed to get transaction details for ${e} after retries: ${r.message}`),null}}async _requestWithRetry(e,t){let r=0,i=this.initialDelayMs;const n=this.constructUrl(e),s={...t,headers:{...this.customHeaders,...t?.headers}};for(this.apiKey&&(s.headers={...s.headers,Authorization:`Bearer ${this.apiKey}`,"X-API-Key":this.apiKey});r<this.maxRetries;)try{return(await o.get(n,s)).data}catch(a){r++;const e=r>=this.maxRetries,t=a.response?.status;if(t&&t>404&&t<500&&429!==t)throw this.logger.error(`Client error for ${n} (status ${t}): ${a.message}. Not retrying.`),a;if(e)throw this.logger.error(`Max retries (${this.maxRetries}) reached for ${n}. Last error: ${a.message}`),a;this.logger.warn(`Attempt ${r}/${this.maxRetries} failed for ${n}: ${a.message}. Retrying in ${i}ms...`),await new Promise(e=>setTimeout(e,i)),i=Math.min(i*this.backoffFactor,this.maxDelayMs)}throw new Error(`Failed to fetch data from ${n} after ${this.maxRetries} attempts.`)}async _fetchWithRetry(e,t){let r=0,i=this.initialDelayMs;const o={...this.customHeaders};t?.headers&&(t.headers instanceof Headers?t.headers.forEach((e,t)=>{o[t]=e}):Array.isArray(t.headers)?t.headers.forEach(([e,t])=>{o[e]=t}):Object.assign(o,t.headers)),this.apiKey&&(o.Authorization=`Bearer ${this.apiKey}`,o["X-API-Key"]=this.apiKey);const n={...t,headers:o};for(;r<this.maxRetries;)try{const t=await fetch(e,n);if(!t.ok){if(t.status>=400&&t.status<500&&429!==t.status)throw this.logger.error(`Client error for ${e} (status ${t.status}): ${t.statusText}. Not retrying.`),new Error(`Fetch failed with status ${t.status}: ${t.statusText} for URL: ${e}`);throw new Error(`Fetch failed with status ${t.status}: ${t.statusText} for URL: ${e}`)}return await t.json()}catch(s){if(r++,r>=this.maxRetries)throw this.logger.error(`Max retries (${this.maxRetries}) reached for ${e}. Last error: ${s.message}`),s;this.logger.warn(`Attempt ${r}/${this.maxRetries} failed for ${e}: ${s.message}. Retrying in ${i}ms...`),await new Promise(e=>setTimeout(e,i)),i=Math.min(i*this.backoffFactor,this.maxDelayMs)}throw new Error(`Failed to fetch data from ${e} after ${this.maxRetries} attempts.`)}async getAccountBalance(e){this.logger.info(`Getting balance for account ${e}`);try{const t=await this.requestAccount(e);if(t&&t.balance){return t.balance.balance/1e8}return this.logger.warn(`Could not retrieve balance for account ${e} from account info.`),null}catch(t){return this.logger.error(`Error fetching numerical balance for account ${e}: ${t.message}`),null}}async getTopicMessagesByFilter(e,t){this.logger.trace(`Querying messages for topic ${e} with filters: ${JSON.stringify(t)}`);let r=`/api/v1/topics/${e}/messages`;const i=new URLSearchParams;t?.limit&&i.append("limit",t.limit.toString()),t?.sequenceNumber&&i.append("sequencenumber",t.sequenceNumber),t?.startTime&&i.append("timestamp",`gte:${t.startTime}`),t?.endTime&&i.append("timestamp",`lt:${t.endTime}`),t?.order&&i.append("order",t.order);const o=i.toString();o&&(r+=`?${o}`);const n=[];let s=0;try{for(;r&&s<10;){s++;const e=await this._requestWithRetry(r);if(e.messages&&e.messages.length>0)for(const t of e.messages)try{if(!t.message)continue;let e;e=this.isServerEnvironment?globalThis.Buffer.from(t.message,"base64").toString("utf-8"):(new TextDecoder).decode(Uint8Array.from(atob(t.message),e=>e.charCodeAt(0)));let r={};try{r=JSON.parse(e)}catch(a){this.logger.debug(`Message content is not valid JSON, using raw: ${e}`),r={raw_content:e}}const i={...r,consensus_timestamp:t.consensus_timestamp,sequence_number:t.sequence_number,payer_account_id:t.payer_account_id,topic_id:t.topic_id,running_hash:t.running_hash,running_hash_version:t.running_hash_version,chunk_info:t.chunk_info,created:new Date(1e3*Number(t.consensus_timestamp.split(".")[0])+Number(t.consensus_timestamp.split(".")[1]||0)/1e6),payer:t.payer_account_id};n.push(i)}catch(c){this.logger.error(`Error processing individual message: ${c.message}`)}if(t?.limit&&n.length>=t.limit)break;r=e.links?.next?`${e.links.next}`:""}return n}catch(l){const t=l;return this.logger.error(`Error querying filtered topic messages for ${e}: ${t.message}`),null}}async getAccountTokens(e,t=100){this.logger.info(`Getting tokens for account ${e}`);let r=[],i=`/api/v1/accounts/${e}/tokens?limit=${t}`;try{for(let e=0;e<10&&i;e++){const e=await this._requestWithRetry(i);if(e&&e.tokens&&(r=r.concat(e.tokens)),i=e.links?.next||"",!i||t&&r.length>=t){t&&r.length>t&&(r=r.slice(0,t));break}}return r}catch(o){return this.logger.error(`Error fetching tokens for account ${e}: ${o.message}`),null}}async getTransactionByTimestamp(e){this.logger.info(`Getting transaction by timestamp: ${e}`);try{return(await this._requestWithRetry(`/api/v1/transactions?timestamp=${e}&limit=1`)).transactions}catch(t){return this.logger.error(`Error fetching transaction by timestamp ${e}: ${t}`),[]}}async getAccountNfts(e,t,r=100){this.logger.info(`Getting NFTs for account ${e}${t?` for token ${t}`:""}`);let i=[],o=`/api/v1/accounts/${e}/nfts?limit=${r}`;t&&(o+=`&token.id=${t}`);try{for(let e=0;e<10&&o;e++){const e=await this._requestWithRetry(o);if(e&&e.nfts){const t=e.nfts.map(e=>{let t;if(e.metadata)try{t=this.isServerEnvironment?globalThis.Buffer.from(e.metadata,"base64").toString("utf-8"):(new TextDecoder).decode(Uint8Array.from(atob(e.metadata),e=>e.charCodeAt(0)))}catch(r){this.logger.warn(`Failed to decode metadata for NFT ${e.token_id} SN ${e.serial_number}: ${r.message}`)}return{...e,token_uri:t}});i=i.concat(t)}if(o=e.links?.next||"",!o)break}return i}catch(n){return this.logger.error(`Error fetching NFTs for account ${e}: ${n.message}`),null}}async validateNFTOwnership(e,t,r){this.logger.info(`Validating ownership of NFT ${t} SN ${r} for account ${e}`);try{const i=await this.getAccountNfts(e,t);if(i){return i.find(e=>e.token_id===t&&e.serial_number===r)||null}return null}catch(i){return this.logger.error(`Error validating NFT ownership: ${i.message}`),null}}async readSmartContractQuery(e,t,r,o){this.logger.info(`Reading smart contract ${e} with selector ${t}`);const n=e.startsWith("0x")?e:`0x${i.AccountId.fromString(e).toSolidityAddress()}`,s=r.startsWith("0x")?r:`0x${i.AccountId.fromString(r).toSolidityAddress()}`,a={block:o?.block||"latest",data:t,estimate:o?.estimate||!1,from:s,to:n,gas:o?.gas,gasPrice:o?.gasPrice,value:o?.value||0};Object.keys(a).forEach(e=>{const t=e;void 0===a[t]&&delete a[t]});try{const e=this.constructUrl("/api/v1/contracts/call");return await this._fetchWithRetry(e,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json"}})}catch(c){return this.logger.error(`Error reading smart contract ${e}: ${c.message}`),null}}async getOutstandingTokenAirdrops(e,t){this.logger.info(`Getting outstanding token airdrops sent by account ${e}`);let r=`/api/v1/accounts/${e}/airdrops/outstanding`;const i=new URLSearchParams;t?.limit&&i.append("limit",t.limit.toString()),t?.order&&i.append("order",t.order),t?.receiverId&&i.append("receiver.id",t.receiverId),t?.serialNumber&&i.append("serialnumber",t.serialNumber),t?.tokenId&&i.append("token.id",t.tokenId);const o=i.toString();o&&(r+=`?${o}`);try{return(await this._requestWithRetry(r)).airdrops||[]}catch(n){return this.logger.error(`Error fetching outstanding token airdrops for account ${e}: ${n.message}`),null}}async getPendingTokenAirdrops(e,t){this.logger.info(`Getting pending token airdrops received by account ${e}`);let r=`/api/v1/accounts/${e}/airdrops/pending`;const i=new URLSearchParams;t?.limit&&i.append("limit",t.limit.toString()),t?.order&&i.append("order",t.order),t?.senderId&&i.append("sender.id",t.senderId),t?.serialNumber&&i.append("serialnumber",t.serialNumber),t?.tokenId&&i.append("token.id",t.tokenId);const o=i.toString();o&&(r+=`?${o}`);try{return(await this._requestWithRetry(r)).airdrops||[]}catch(n){return this.logger.error(`Error fetching pending token airdrops for account ${e}: ${n.message}`),null}}async getBlocks(e){this.logger.info("Getting blocks from the network");let t="/api/v1/blocks";const r=new URLSearchParams;e?.limit&&r.append("limit",e.limit.toString()),e?.order&&r.append("order",e.order),e?.timestamp&&r.append("timestamp",e.timestamp),e?.blockNumber&&r.append("block.number",e.blockNumber);const i=r.toString();i&&(t+=`?${i}`);try{return(await this._requestWithRetry(t)).blocks||[]}catch(o){return this.logger.error(`Error fetching blocks: ${o.message}`),null}}async getBlock(e){this.logger.info(`Getting block ${e}`);try{return await this._requestWithRetry(`/api/v1/blocks/${e}`)}catch(t){return this.logger.error(`Error fetching block ${e}: ${t.message}`),null}}async getContracts(e){this.logger.info("Getting contracts from the network");let t="/api/v1/contracts";const r=new URLSearchParams;e?.contractId&&r.append("contract.id",e.contractId),e?.limit&&r.append("limit",e.limit.toString()),e?.order&&r.append("order",e.order);const i=r.toString();i&&(t+=`?${i}`);try{return(await this._requestWithRetry(t)).contracts||[]}catch(o){return this.logger.error(`Error fetching contracts: ${o.message}`),null}}async getContract(e,t){this.logger.info(`Getting contract ${e}`);let r=`/api/v1/contracts/${e}`;t&&(r+=`?timestamp=${t}`);try{return await this._requestWithRetry(r)}catch(i){return this.logger.error(`Error fetching contract ${e}: ${i.message}`),null}}async getContractResults(e){this.logger.info("Getting contract results from the network");let t="/api/v1/contracts/results";const r=new URLSearchParams;e?.from&&r.append("from",e.from),e?.blockHash&&r.append("block.hash",e.blockHash),e?.blockNumber&&r.append("block.number",e.blockNumber),void 0!==e?.internal&&r.append("internal",e.internal.toString()),e?.limit&&r.append("limit",e.limit.toString()),e?.order&&r.append("order",e.order),e?.timestamp&&r.append("timestamp",e.timestamp),e?.transactionIndex&&r.append("transaction.index",e.transactionIndex.toString());const i=r.toString();i&&(t+=`?${i}`);try{return(await this._requestWithRetry(t)).results||[]}catch(o){return this.logger.error(`Error fetching contract results: ${o.message}`),null}}async getContractResult(e,t){this.logger.info(`Getting contract result for ${e}`);let r=`/api/v1/contracts/results/${e}`;void 0!==t&&(r+=`?nonce=${t}`);try{return await this._requestWithRetry(r)}catch(i){return this.logger.error(`Error fetching contract result for ${e}: ${i.message}`),null}}async getContractResultsByContract(e,t){this.logger.info(`Getting contract results for contract ${e}`);let r=`/api/v1/contracts/${e}/results`;const i=new URLSearchParams;t?.blockHash&&i.append("block.hash",t.blockHash),t?.blockNumber&&i.append("block.number",t.blockNumber),t?.from&&i.append("from",t.from),void 0!==t?.internal&&i.append("internal",t.internal.toString()),t?.limit&&i.append("limit",t.limit.toString()),t?.order&&i.append("order",t.order),t?.timestamp&&i.append("timestamp",t.timestamp),t?.transactionIndex&&i.append("transaction.index",t.transactionIndex.toString());const o=i.toString();o&&(r+=`?${o}`);try{return(await this._requestWithRetry(r)).results||[]}catch(n){return this.logger.error(`Error fetching contract results for ${e}: ${n.message}`),null}}async getContractState(e,t){this.logger.info(`Getting contract state for ${e}`);let r=`/api/v1/contracts/${e}/state`;const i=new URLSearchParams;t?.limit&&i.append("limit",t.limit.toString()),t?.order&&i.append("order",t.order),t?.slot&&i.append("slot",t.slot),t?.timestamp&&i.append("timestamp",t.timestamp);const o=i.toString();o&&(r+=`?${o}`);try{return(await this._requestWithRetry(r)).state||[]}catch(n){return this.logger.error(`Error fetching contract state for ${e}: ${n.message}`),null}}async getContractActions(e,t){this.logger.info(`Getting contract actions for ${e}`);let r=`/api/v1/contracts/results/${e}/actions`;const i=new URLSearchParams;t?.index&&i.append("index",t.index),t?.limit&&i.append("limit",t.limit.toString()),t?.order&&i.append("order",t.order);const o=i.toString();o&&(r+=`?${o}`);try{return(await this._requestWithRetry(r)).actions||[]}catch(n){return this.logger.error(`Error fetching contract actions for ${e}: ${n.message}`),null}}async getContractLogs(e){this.logger.info("Getting contract logs from the network");let t="/api/v1/contracts/results/logs";const r=new URLSearchParams;e?.index&&r.append("index",e.index),e?.limit&&r.append("limit",e.limit.toString()),e?.order&&r.append("order",e.order),e?.timestamp&&r.append("timestamp",e.timestamp),e?.topic0&&r.append("topic0",e.topic0),e?.topic1&&r.append("topic1",e.topic1),e?.topic2&&r.append("topic2",e.topic2),e?.topic3&&r.append("topic3",e.topic3),e?.transactionHash&&r.append("transaction.hash",e.transactionHash);const i=r.toString();i&&(t+=`?${i}`);try{return(await this._requestWithRetry(t)).logs||[]}catch(o){return this.logger.error(`Error fetching contract logs: ${o.message}`),null}}async getContractLogsByContract(e,t){this.logger.info(`Getting contract logs for contract ${e}`);let r=`/api/v1/contracts/${e}/results/logs`;const i=new URLSearchParams;t?.index&&i.append("index",t.index),t?.limit&&i.append("limit",t.limit.toString()),t?.order&&i.append("order",t.order),t?.timestamp&&i.append("timestamp",t.timestamp),t?.topic0&&i.append("topic0",t.topic0),t?.topic1&&i.append("topic1",t.topic1),t?.topic2&&i.append("topic2",t.topic2),t?.topic3&&i.append("topic3",t.topic3);const o=i.toString();o&&(r+=`?${o}`);try{return(await this._requestWithRetry(r)).logs||[]}catch(n){return this.logger.error(`Error fetching contract logs for ${e}: ${n.message}`),null}}async getNftInfo(e,t){this.logger.info(`Getting NFT info for ${e}/${t}`);const r=`/api/v1/tokens/${e}/nfts/${t}`;try{return await this._requestWithRetry(r)}catch(i){return this.logger.error(`Error fetching NFT info for ${e}/${t}: ${i.message}`),null}}async getNftsByToken(e,t){this.logger.info(`Getting NFTs for token ${e}`);let r=`/api/v1/tokens/${e}/nfts`;const i=new URLSearchParams;t?.accountId&&i.append("account.id",t.accountId),t?.limit&&i.append("limit",t.limit.toString()),t?.order&&i.append("order",t.order),t?.serialNumber&&i.append("serialnumber",t.serialNumber);const o=i.toString();o&&(r+=`?${o}`);try{return(await this._requestWithRetry(r)).nfts||[]}catch(n){return this.logger.error(`Error fetching NFTs for token ${e}: ${n.message}`),null}}async getNetworkInfo(){this.logger.info("Getting network information");try{return await this._requestWithRetry("/api/v1/network/nodes")}catch(e){return this.logger.error(`Error fetching network info: ${e.message}`),null}}async getNetworkFees(e){this.logger.info("Getting network fees");let t="/api/v1/network/fees";e&&(t+=`?timestamp=${e}`);try{return await this._requestWithRetry(t)}catch(r){return this.logger.error(`Error fetching network fees: ${r.message}`),null}}async getNetworkSupply(e){this.logger.info("Getting network supply");let t="/api/v1/network/supply";e&&(t+=`?timestamp=${e}`);try{return await this._requestWithRetry(t)}catch(r){return this.logger.error(`Error fetching network supply: ${r.message}`),null}}async getNetworkStake(e){this.logger.info("Getting network stake");let t="/api/v1/network/stake";e&&(t+=`?timestamp=${e}`);try{return await this._requestWithRetry(t)}catch(r){return this.logger.error(`Error fetching network stake: ${r.message}`),null}}async getOpcodeTraces(e,t){this.logger.info(`Getting opcode traces for ${e}`);let r=`/api/v1/contracts/results/${e}/opcodes`;const i=new URLSearchParams;void 0!==t?.stack&&i.append("stack",t.stack.toString()),void 0!==t?.memory&&i.append("memory",t.memory.toString()),void 0!==t?.storage&&i.append("storage",t.storage.toString());const o=i.toString();o&&(r+=`?${o}`);try{return await this._requestWithRetry(r)}catch(n){return this.logger.error(`Error fetching opcode traces for ${e}: ${n.message}`),null}}}class J{constructor(e){this.network=e.network,this.logger=e.logger||z.getInstance({level:e.logLevel||"info",module:"HCS6Client",silent:e.silent}),this.mirrorNode=new G(this.network,this.logger,e.mirrorNodeUrl?{customUrl:e.mirrorNodeUrl}:void 0)}parseRegistryTypeFromMemo(e){try{const t=/hcs-6:(\d):(\d+)/,r=e.match(t);if(r&&3===r.length){const e=parseInt(r[1]),t=parseInt(r[2]);if(e===U.NON_INDEXED&&W(t))return{registryType:e,ttl:t}}return}catch(t){return void this.logger.error(`Error parsing HCS-6 registry type from memo: ${t}`)}}generateRegistryMemo(e){return V(e)}validateMessage(e){try{return j.parse(e),{valid:!0,errors:[]}}catch(t){const e=[];return t instanceof r.ZodError?t.errors.forEach(t=>{const r=t.path.join(".");e.push(`${r?r+": ":""}${t.message}`)}):e.push(`Unexpected error: ${t}`),this.logger.debug(`HCS-6 message validation failed: ${e.join(", ")}`),{valid:!1,errors:e}}}createRegisterMessage(e,t){return{p:"hcs-6",op:K.REGISTER,t_id:e,m:t}}parseRegistryEntries(e,t,r,i){const o=[];let n;this.logger.debug(`Parsing ${t.length} messages for HCS-6 topic ${e}`);for(const a of t)try{if(!a.message){this.logger.debug(`Message is missing 'message' property: ${JSON.stringify(a)}`);continue}const t=globalThis.Buffer.from(a.message,"base64").toString("utf-8"),i=JSON.parse(t);this.logger.debug(`Successfully parsed HCS-6 message: ${JSON.stringify(i)}`);const{valid:s,errors:c}=this.validateMessage(i);if(!s){this.logger.warn(`Invalid HCS-6 message: ${c.join(", ")}`);continue}const l={topicId:e,sequence:a.sequence_number,timestamp:a.consensus_timestamp,payer:a.payer_account_id,message:i,consensus_timestamp:a.consensus_timestamp,registry_type:r};o.push(l),(!n||l.timestamp>n.timestamp)&&(n=l)}catch(s){this.logger.warn(`Error parsing HCS-6 message: ${s}`)}return this.logger.debug(`Parsed ${o.length} valid entries for HCS-6 topic ${e}`),{topicId:e,registryType:r,ttl:i,entries:n?[n]:[],latestEntry:n}}async validateHCS6Topic(e){try{const t=await this.mirrorNode.getTopicInfo(e),r=this.parseRegistryTypeFromMemo(t.memo);return r?r.registryType===U.NON_INDEXED||(this.logger.warn(`Topic ${e} is not a valid HCS-6 registry (must be non-indexed)`),!1):(this.logger.warn(`Topic ${e} is not a valid HCS-6 registry (invalid memo format)`),!1)}catch(t){return this.logger.error(`Error validating HCS-6 topic ${e}: ${t}`),!1}}}function Y(e){const{memo:t,adminKey:r,submitKey:o,operatorPublicKey:n}=e,s=(new i.TopicCreateTransaction).setTopicMemo(t),a=e=>{if(e){if(e instanceof i.PublicKey||e instanceof i.KeyList)return e;if("boolean"==typeof e)return e?n:void 0;if("string"==typeof e)try{return i.PublicKey.fromString(e)}catch{return}}},c=a(r);c&&s.setAdminKey(c);const l=a(o);return l&&s.setSubmitKey(l),s}function X(e){const t=(new i.TopicMessageSubmitTransaction).setTopicId(i.TopicId.fromString(e.topicId)).setMessage(e.message);return e.transactionMemo&&t.setTransactionMemo(e.transactionMemo),t}function Z(e){return Y({memo:e.memoOverride??`hcs-6:1:${e.ttl}`,submitKey:e.submitKey,adminKey:e.adminKey,operatorPublicKey:e.operatorPublicKey})}var Q=(e=>(e.ED25519="ed25519",e.ECDSA="ecdsa",e.UNKNOWN="unknown",e))(Q||{});const ee=class{static detect(e){try{let t,r="raw";if("string"==typeof e){let i=e.trim();if(i.includes("-----BEGIN"))return this.detectFromPem(i);if(i.toLowerCase().startsWith("0x")&&(i=i.substring(2)),this.isValidHex(i))t=this.hexToBytes(i),r="hex";else{if(!this.isBase64(i))return{type:"unknown",format:"raw",isPrivateKey:!1,confidence:"certain"};t=globalThis.Buffer.from(i,"base64"),r="der"}}else t=e instanceof globalThis.Buffer?new Uint8Array(e):e;return this.detectFromBytes(t,r)}catch(t){return{type:"unknown",format:"raw",isPrivateKey:!1,confidence:"certain"}}}static detectFromBytes(e,t){if(this.hasPrefix(e,this.ED25519_PUBLIC_KEY_PREFIX)){const t=this.ED25519_PUBLIC_KEY_PREFIX.length;return{type:"ed25519",format:"der",isPrivateKey:!1,rawBytes:e.slice(t),confidence:"certain"}}if(this.hasPrefix(e,this.ED25519_PRIVATE_KEY_PREFIX)){const t=this.ED25519_PRIVATE_KEY_PREFIX.length;if(e.length>=t+32)return{type:"ed25519",format:"der",isPrivateKey:!0,rawBytes:e.slice(t,t+32),confidence:"certain"}}if(this.hasPrefix(e,this.ECDSA_SECP256K1_PUBLIC_KEY_PREFIX)){const t=this.ECDSA_SECP256K1_PUBLIC_KEY_PREFIX.length;return{type:"ecdsa",format:"der",isPrivateKey:!1,rawBytes:e.slice(t),confidence:"certain"}}if(this.hasPrefix(e,this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_SHORT)){const t=this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_SHORT.length;return{type:"ecdsa",format:"der",isPrivateKey:!0,rawBytes:e.slice(t),confidence:"certain"}}if(this.hasPrefix(e,this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX)){const t=this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX.length;return{type:"ecdsa",format:"der",isPrivateKey:!0,rawBytes:e.slice(t,t+32),confidence:"certain"}}if(this.hasPrefix(e,this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_LONG)){const t=this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_LONG.length;return{type:"ecdsa",format:"der",isPrivateKey:!0,rawBytes:e.slice(t,t+32),confidence:"certain"}}if(e.length>36&&this.containsECDSAPrivateKeyPattern(e))return{type:"ecdsa",format:"der",isPrivateKey:!0,rawBytes:this.extractECDSAPrivateKey(e),confidence:"certain"};switch(e.length){case this.ED25519_PUBLIC_KEY_LENGTH:if("hex"===t){const t=Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join(""),r=this.tryCreateKey(t);if("unknown"!==r.type)return r}return{type:"unknown",format:t,isPrivateKey:!1,rawBytes:e,confidence:"certain"};case this.ED25519_EXPANDED_PRIVATE_KEY_LENGTH:return{type:"ed25519",format:t,isPrivateKey:!0,rawBytes:e,confidence:"certain"}}return{type:"unknown",format:t,isPrivateKey:!1,rawBytes:e,confidence:"certain"}}static detectFromPem(e){const t=e.trim(),r=t.includes("PRIVATE KEY"),i={EC_PRIVATE:/-----BEGIN EC PRIVATE KEY-----/,EC_PUBLIC:/-----BEGIN EC PUBLIC KEY-----/,PRIVATE:/-----BEGIN PRIVATE KEY-----/,PUBLIC:/-----BEGIN PUBLIC KEY-----/};let o=!1;for(const[a,c]of Object.entries(i))if(c.test(t)&&a.includes("EC")){o=!0;break}const n=t.match(/-----BEGIN[\s\S]+?-----[\r\n]+([\s\S]+?)[\r\n]+-----END/);if(!n)return{type:"unknown",format:"pem",isPrivateKey:r,confidence:"certain"};const s=n[1].replace(/\s/g,"");try{const e=globalThis.Buffer.from(s,"base64"),t=this.detectFromBytes(new Uint8Array(e),"der");return"unknown"===t.type&&o?{type:"ecdsa",format:"pem",isPrivateKey:r,rawBytes:e,confidence:"certain"}:{...t,format:"pem"}}catch{return{type:"unknown",format:"pem",isPrivateKey:r,confidence:"certain"}}}static tryCreateKey(e){try{if("string"==typeof e){let t=e.trim();if(t.toLowerCase().startsWith("0x")&&(t=t.substring(2)),this.isValidHex(t)&&64===t.length){const e=this.hexToBytes(t),r=this.detectBySignature(t);return"unknown"!==r.type?{type:r.type,format:"hex",isPrivateKey:!0,rawBytes:e,confidence:r.confidence,warning:r.warning}:{type:"unknown",format:"hex",isPrivateKey:!1,rawBytes:e,confidence:"certain"}}}}catch{}return{type:"unknown",format:"hex",isPrivateKey:!1,rawBytes:new Uint8Array,confidence:"certain"}}static detectBySignature(e){const t=BigInt("0x"+e),r=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141");if(0n===t)return{type:"ed25519",confidence:"certain"};if(t>=r)return{type:"ed25519",confidence:"certain"};let o=!1,n=!1;try{const t=i.PrivateKey.fromStringED25519(e),r=new Uint8Array([1,2,3,4,5]),n=t.sign(r);t.publicKey.verify(r,n)&&(o=!0)}catch{}try{const t=i.PrivateKey.fromStringECDSA(e),r=new Uint8Array([1,2,3,4,5]),o=t.sign(r);t.publicKey.verify(r,o)&&(n=!0)}catch{}if(o&&n){const t=this.hexToBytes(e);if(168===t[0]&&1===t[1])return{type:"ed25519",confidence:"uncertain",warning:"Detection based on byte pattern heuristic. Both ED25519 and ECDSA accept this key."};let r=0;for(const e of t)e>=128&&r++;const i=r/t.length;return i>=.4&&i<=.6?{type:"ecdsa",confidence:"uncertain",warning:"Detection based on entropy heuristic. Both ED25519 and ECDSA accept this key."}:{type:"ecdsa",confidence:"uncertain",warning:"Detection based on entropy heuristic. Both ED25519 and ECDSA accept this key. Defaulting to ECDSA."}}return o&&!n?{type:"ed25519",confidence:"certain"}:n&&!o?{type:"ecdsa",confidence:"certain"}:{type:"unknown",confidence:"certain"}}static isValidHex(e){return/^[0-9a-fA-F]+$/.test(e)&&e.length%2==0}static isBase64(e){try{return globalThis.Buffer.from(e,"base64").toString("base64")===e}catch{return!1}}static hexToBytes(e){const t=new Uint8Array(e.length/2);for(let r=0;r<e.length;r+=2)t[r/2]=parseInt(e.substr(r,2),16);return t}static hasPrefix(e,t){if(e.length<t.length)return!1;for(let r=0;r<t.length;r++)if(e[r]!==t[r])return!1;return!0}static containsECDSAPrivateKeyPattern(e){for(let t=0;t<e.length-7;t++)if(48===e[t]&&116===e[t+1]&&2===e[t+2]&&1===e[t+3]&&1===e[t+4]&&4===e[t+5]&&32===e[t+6])return!0;return!1}static extractECDSAPrivateKey(e){for(let t=0;t<e.length-32;t++)if(4===e[t]&&32===e[t+1])return e.slice(t+2,t+34);return e}};ee.ED25519_PUBLIC_KEY_LENGTH=32,ee.ED25519_EXPANDED_PRIVATE_KEY_LENGTH=64,ee.ED25519_PUBLIC_KEY_PREFIX=globalThis.Buffer.from([48,42,48,5,6,3,43,101,112,3,33,0]),ee.ED25519_PRIVATE_KEY_PREFIX=globalThis.Buffer.from([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]),ee.ECDSA_SECP256K1_PUBLIC_KEY_PREFIX=globalThis.Buffer.from([48,86,48,16,6,7,42,134,72,206,61,2,1,6,5,43,129,4,0,10,3,66,0]),ee.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX=globalThis.Buffer.from([48,116,2,1,1,4,32]),ee.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_SHORT=globalThis.Buffer.from([48,48,2,1,0,48,7,6,5,43,129,4,0,10,4,34,4,32]),ee.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_LONG=globalThis.Buffer.from([48,119,2,1,1,4,32]);let te=ee;function re(e){const t=te.detect(e);if("unknown"!==t.type)try{const r="ecdsa"===t.type?i.PrivateKey.fromStringECDSA(e):i.PrivateKey.fromStringED25519(e),o={detectedType:t.type,privateKey:r};return"uncertain"===t.confidence&&(o.warning="Key type detection is uncertain. If you have the associated account ID, consider using the Hedera mirror node to confirm the key type."),o}catch(r){}try{return{detectedType:"ecdsa",privateKey:i.PrivateKey.fromStringECDSA(e),warning:"Using ECDSA as default. If you have the associated account ID, consider using the Hedera mirror node to confirm the key type."}}catch(o){try{return{detectedType:"ed25519",privateKey:i.PrivateKey.fromStringED25519(e),warning:"Using ED25519 as fallback. If you have the associated account ID, consider using the Hedera mirror node to confirm the key type."}}catch(n){throw new Error(`Failed to parse private key as either ECDSA or ED25519: ${o}`)}}}class ie{constructor(e){this.mirror=e.mirrorNode,this.logger=e.logger}bestGuessOperatorKey(e,t){if("string"!=typeof e)return{keyType:t||"ecdsa",privateKey:e};if(t){return{keyType:t,privateKey:"ed25519"===t?i.PrivateKey.fromStringED25519(e):i.PrivateKey.fromStringECDSA(e)}}try{const t=re(e);return{keyType:t.detectedType,privateKey:t.privateKey}}catch{return{keyType:"ecdsa",privateKey:i.PrivateKey.fromStringECDSA(e)}}}async resolveOperatorKey(e,t,r){if("string"!=typeof t)return{keyType:r||"ecdsa",privateKey:t};if(r){return{keyType:r,privateKey:"ed25519"===r?i.PrivateKey.fromStringED25519(t):i.PrivateKey.fromStringECDSA(t)}}const o="string"==typeof e?e:e.toString();try{const e=await this.mirror.requestAccount(o),r=(e?.key?._type||"").includes("ED25519")?"ed25519":"ecdsa";return{keyType:r,privateKey:"ed25519"===r?i.PrivateKey.fromStringED25519(t):i.PrivateKey.fromStringECDSA(t)}}catch{return this.logger.warn("Mirror node key detection failed; using local detection or default ECDSA"),this.bestGuessOperatorKey(t)}}async resolveSupplyKey(e,t,r,o){try{const n=await this.mirror.getTokenInfo(e),s=n?.supply_key?._type||"";return"string"!=typeof t?t:o?"ed25519"===o?i.PrivateKey.fromStringED25519(t):i.PrivateKey.fromStringECDSA(t):s.includes("ED25519")?i.PrivateKey.fromStringED25519(t):s.includes("ECDSA")?i.PrivateKey.fromStringECDSA(t):"ed25519"===r?i.PrivateKey.fromStringED25519(t):i.PrivateKey.fromStringECDSA(t)}catch{return"string"!=typeof t?t:o?"ed25519"===o?i.PrivateKey.fromStringED25519(t):i.PrivateKey.fromStringECDSA(t):"ed25519"===r?i.PrivateKey.fromStringED25519(t):i.PrivateKey.fromStringECDSA(t)}}}function oe(e){const t="string"==typeof e.operatorId?i.AccountId.fromString(e.operatorId):e.operatorId,r=e.client?e.client:"mainnet"===e.network?i.Client.forMainnet():i.Client.forTestnet(),o=new ie({mirrorNode:e.mirrorNode,logger:e.logger});let n,s;const a=o.bestGuessOperatorKey(e.operatorKey,e.keyType);n=a.keyType,s=a.privateKey,r.setOperator(t.toString(),s);const c=(async()=>{try{const i=await o.resolveOperatorKey(t,e.operatorKey,e.keyType);n=i.keyType,s=i.privateKey,r.setOperator(t.toString(),s)}catch{}})();return{client:r,operatorId:t,get operatorKey(){return s},get keyType(){return n},ensureInitialized:async()=>{await c}}}for(var ne=Object.defineProperty,se=((e,t,r)=>((e,t,r)=>t in e?ne(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r)),ae={},ce={byteLength:function(e){var t=ge(e),r=t[0],i=t[1];return 3*(r+i)/4-i},toByteArray:function(e){var t,r,i=ge(e),o=i[0],n=i[1],s=new ue(function(e,t,r){return 3*(t+r)/4-r}(0,o,n)),a=0,c=n>0?o-4:o;for(r=0;r<c;r+=4)t=de[e.charCodeAt(r)]<<18|de[e.charCodeAt(r+1)]<<12|de[e.charCodeAt(r+2)]<<6|de[e.charCodeAt(r+3)],s[a++]=t>>16&255,s[a++]=t>>8&255,s[a++]=255&t;2===n&&(t=de[e.charCodeAt(r)]<<2|de[e.charCodeAt(r+1)]>>4,s[a++]=255&t);1===n&&(t=de[e.charCodeAt(r)]<<10|de[e.charCodeAt(r+1)]<<4|de[e.charCodeAt(r+2)]>>2,s[a++]=t>>8&255,s[a++]=255&t);return s},fromByteArray:function(e){for(var t,r=e.length,i=r%3,o=[],n=16383,s=0,a=r-i;s<a;s+=n)o.push(fe(e,s,s+n>a?a:s+n));1===i?(t=e[r-1],o.push(le[t>>2]+le[t<<4&63]+"==")):2===i&&(t=(e[r-2]<<8)+e[r-1],o.push(le[t>>10]+le[t>>4&63]+le[t<<2&63]+"="));return o.join("")}},le=[],de=[],ue="undefined"!=typeof Uint8Array?Uint8Array:Array,pe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",he=0;he<64;++he)le[he]=pe[he],de[pe.charCodeAt(he)]=he;function ge(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function me(e){return le[e>>18&63]+le[e>>12&63]+le[e>>6&63]+le[63&e]}function fe(e,t,r){for(var i,o=[],n=t;n<r;n+=3)i=(e[n]<<16&16711680)+(e[n+1]<<8&65280)+(255&e[n+2]),o.push(me(i));return o.join("")}de["-".charCodeAt(0)]=62,de["_".charCodeAt(0)]=63;var ye={
1
+ "use strict";var e;Object.create,Object.defineProperty,Object.getOwnPropertyDescriptor,Object.getOwnPropertyNames,Object.getPrototypeOf,Object.prototype.hasOwnProperty;Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("util"),r=require("zod"),i=require("@hashgraph/sdk"),o=require("axios"),n=require("@hashgraph/proto"),s=require("@hashgraphonline/standards-sdk"),a=require("buffer"),c=require("ethers"),l=require("file-type"),d=require("bignumber.js"),u=require("node:path"),p=require("node:buffer"),h=require("node:crypto"),g=require("@noble/curves/secp256k1.js"),m=require("node:module"),f=require("mime-types"),y=require("date-fns"),b=require("crypto");var w="undefined"!=typeof document?document.currentScript:null;function I(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const r in e)if("default"!==r){const i=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:()=>e[r]})}return t.default=e,Object.freeze(t)}const T=I(u),S=I(f),k=/^\d+\.\d+\.\d+$/u,E=Symbol.for("standards-sdk.topic-auto-renew.patch"),v=Symbol.for("standards-sdk.account-id.patch"),A=function(){const e=function(){try{if("undefined"!=typeof module&&module?.createRequire)return module}catch{}try{if("function"==typeof require){const e=require("module");if(e?.createRequire)return e}}catch{}return null}();if(e?.createRequire)try{return e.createRequire("undefined"==typeof document?require("url").pathToFileURL(__filename).href:w&&"SCRIPT"===w.tagName.toUpperCase()&&w.src||new URL("standards-sdk.cjs",document.baseURI).href)}catch{return null}if("function"==typeof require)return require;return null}();function C(e,t){try{return e(t)}catch{return null}}function x(e,t){if(!e||!t)return;!function(e){if(Reflect.get(e,v))return;const t=e.fromString.bind(e);e.fromString=function(e){if("string"==typeof e)return t(e);const r=N(e);if(r)return t(r);if(_(e)){const r=F(e.shard),i=F(e.realm),o=F(e.num);if(r&&i&&o)return t(`${r}.${i}.${o}`)}return t(e)},Reflect.set(e,v,!0)}(t);const r=e.prototype;if(Reflect.get(r,E))return;const i=r.setAutoRenewAccountId,o=r.freezeWith;r.setAutoRenewAccountId=function(e){const r=R(e,t);return r?(function(e){const t=e;t._requireNotFrozen?.()}(this),this._autoRenewAccountId=r,this):i.call(this,e)},r.freezeWith=function(e){if(!this.getAutoRenewAccountId||"function"!=typeof this.getAutoRenewAccountId)return o.call(this,e);if(!this.getAutoRenewAccountId()){const r=this.transactionId?.accountId,i=e?.operatorAccountId,o=R(r,t)??R(i,t);o&&(this._autoRenewAccountId=o)}return o.call(this,e)},Reflect.set(r,E,!0)}function R(e,t){if(e instanceof t)return e;if("string"==typeof e&&k.test(e))return t.fromString(e);const r=function(e){if("string"==typeof e&&k.test(e))return e;const t=N(e);if(t)return t;if(_(e)){const t=F(e.shard),r=F(e.realm),i=F(e.num);if(t&&r&&i){const e=`${t}.${r}.${i}`;if(k.test(e))return e}}return null}(e);return r?t.fromString(r):null}function N(e){if("object"!=typeof e||null===e)return null;const t=e.toString;if("function"!=typeof t)return null;const r=t.call(e);return"string"!=typeof r?null:k.test(r)?r:null}function _(e){if("object"!=typeof e||null===e)return!1;const t=e;return P(t.shard)&&P(t.realm)&&P(t.num)}function P(e){return"object"==typeof e&&null!==e&&"function"==typeof e.toString}function F(e){if("number"==typeof e&&Number.isFinite(e))return String(Math.trunc(e));if("bigint"==typeof e)return e.toString();if(P(e)){const t=e.toString();if(/^\d+$/u.test(t))return t}return null}A?function(e){const t=C(e,"@hashgraph/sdk/lib/account/AccountId.cjs"),r=C(e,"@hashgraph/sdk/lib/topic/TopicCreateTransaction.cjs"),i=C(e,"@hashgraph/sdk"),o=[];t?.default&&r?.default&&o.push({accountId:t.default,topic:r.default});i&&o.push({accountId:i.AccountId??i.default?.AccountId,topic:i.TopicCreateTransaction??i.default?.TopicCreateTransaction});for(const n of o)x(n.topic,n.accountId);Reflect.set(globalThis,"__standardsSdkTopicAutoRenewPatched",!0)}(A):Reflect.set(globalThis,"__standardsSdkTopicAutoRenewPatched",!1);let z=null;let O=((e=class{constructor(e={}){if(z)return z(e);const t="undefined"!=typeof process&&"true"===process.env?.DISABLE_LOGS;this.silent=e.silent||t,this.level=this.silent?"silent":e.level||"info",this.moduleContext=e.module||"app",this.prettyPrint=!this.silent&&!1!==e.prettyPrint}static getInstance(t={}){const r=t.module||"default";if("undefined"!=typeof process&&"true"===process.env?.DISABLE_LOGS&&e.instances.has(r)){"silent"!==e.instances.get(r).getLevel()&&e.instances.delete(r)}if(!e.instances.has(r)){const i=z?z(t):new e(t);e.instances.set(r,i)}return e.instances.get(r)}setLogLevel(e){this.level=e}getLevel(){return this.level}setSilent(e){this.silent=e,e&&(this.level="silent")}setModule(e){this.moduleContext=e}formatArgs(e){if(0===e.length)return{msg:""};if(1===e.length)return"string"==typeof e[0]?{msg:e[0]}:{msg:"",data:e[0]};const t=[],r=[];e.forEach(e=>{"string"==typeof e||"number"==typeof e||"boolean"==typeof e?t.push(String(e)):r.push(e)});const i=t.join(" ");return r.length>0?{msg:i,data:r}:{msg:i}}shouldLog(e){if(this.silent||"silent"===this.level)return!1;const t=["trace","debug","info","warn","error","silent"],r=t.indexOf(this.level);return t.indexOf(e)>=r}getConsoleMethod(e){return"error"===e?console.error:"warn"===e?console.warn:"debug"===e?console.debug:console.log}writeLog(e,...r){if(!this.shouldLog(e))return;const{msg:i,data:o}=this.formatArgs(r),n=(new Date).toISOString(),s=this.getConsoleMethod(e);if(this.prettyPrint){let r=`${n} ${e.toUpperCase().padEnd(5)} [${this.moduleContext}] ${i}`;o&&(r+="\n"+t.inspect(o,{colors:!0,depth:3})),s(r)}else{const t={timestamp:n,level:e,module:this.moduleContext,message:i,...o&&{data:o}};s(JSON.stringify(t))}}debug(...e){this.writeLog("debug",...e)}info(...e){this.writeLog("info",...e)}warn(...e){this.writeLog("warn",...e)}error(...e){this.writeLog("error",...e)}trace(...e){this.writeLog("trace",...e)}static clearInstances(){e.instances.clear()}}).instances=new Map,e);const D=e=>new Promise(t=>setTimeout(t,e));class M{constructor(){this.modelViewerLoaded=!1,this.modelViewerLoading=null,this.config={cdnUrl:"https://kiloscribe.com/api/inscription-cdn/",network:"mainnet",retryAttempts:3,retryBackoff:300,debug:!1,showLoadingIndicator:!1,loadingCallbackName:null},this.configMapping={hcsCdnUrl:"cdnUrl",hcsNetwork:"network",hcsRetryAttempts:"retryAttempts",hcsRetryBackoff:"retryBackoff",hcsDebug:"debug",hcsShowLoadingIndicator:"showLoadingIndicator",hcsLoadingCallbackName:"loadingCallbackName"},this.LoadedScripts={},this.LoadedWasm={},this.LoadedImages={},this.LoadedVideos={},this.LoadedAudios={},this.LoadedAudioUrls={},this.LoadedGLBs={},this.scriptLoadedEvent=new Event("HCSScriptLoaded"),this.loadQueue=[],this.isProcessingQueue=!1;try{this.logger=O.getInstance({module:"HCS-3",level:this.config.debug?"debug":"error"})}catch(e){this.logger=this.createFallbackLogger()}}createFallbackLogger(){return{debug:(...e)=>this.config.debug&&console.debug("[HCS-3]",...e),info:(...e)=>this.config.debug&&console.info("[HCS-3]",...e),warn:(...e)=>console.warn("[HCS-3]",...e),error:(...e)=>console.error("[HCS-3]",...e),setLogLevel:e=>{this.config.debug="debug"===e}}}log(...e){if(0===e.length)this.logger.debug("");else if(1===e.length)this.logger.debug(String(e[0]));else{const t=String(e[0]),r=e.slice(1);this.logger.debug(t,r)}}error(...e){if(0===e.length)this.logger.error("");else if(1===e.length)this.logger.error(String(e[0]));else{const t=String(e[0]),r=e.slice(1);this.logger.error(t,r)}}loadConfigFromHTML(){const e=document.querySelector("script[data-hcs-config]");e&&(Object.keys(this.configMapping).forEach(t=>{if(e.dataset[t]){const r=this.configMapping[t];let i=e.dataset[t];"true"===i&&(i=!0),"false"===i&&(i=!1),isNaN(Number(i))||""===i||(i=Number(i)),this.config[r]=i}}),this.logger.setLogLevel(this.config.debug?"debug":"error")),this.log("Loaded config:",this.config)}updateLoadingStatus(e,t){if("loaded"!==this.LoadedScripts[e]&&(this.config.showLoadingIndicator&&console.log("[HCS Loading] "+e+" : "+t),this.LoadedScripts[e]=t,this.config.loadingCallbackName&&"function"==typeof window[this.config.loadingCallbackName])){const r=window[this.config.loadingCallbackName];"function"==typeof r&&r(e,t)}}async fetchWithRetry(e,t=this.config.retryAttempts,r=this.config.retryBackoff){try{const t=await fetch(e);if(!t.ok)throw new Error("HTTP error! status: "+t.status);return t}catch(i){if(t>0)return this.log("Retrying fetch for "+e+" Attempts left: "+(t-1)),await this.sleep(r),this.fetchWithRetry(e,t-1,2*r);throw i}}sleep(e){return D(e)}isDuplicate(e){return!!this.LoadedScripts[e]}async retrieveHCS1Data(e,t=this.config.cdnUrl,r=this.config.network){const i=r.replace(/['"]+/g,""),o=await this.fetchWithRetry(t+e+"?network="+i);return await o.blob()}async loadScript(e){const t=e.getAttribute("data-src"),r=e.getAttribute("data-script-id"),i=t?.split("/").pop(),o=e.getAttribute("type"),n=e.hasAttribute("data-required"),s="module"===e.getAttribute("type");if(!this.isDuplicate(i||"")){this.updateLoadingStatus(r,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,a=e.getAttribute("data-network")||this.config.network,c=await this.retrieveHCS1Data(i,t,a);if("wasm"===o){const t=await c.arrayBuffer(),i=await WebAssembly.compile(t);this.LoadedWasm[r]=await WebAssembly.instantiate(i,{env:{},...e.dataset}),this.updateLoadingStatus(r,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded wasm: "+r)}else{const e=await c.text(),t=document.createElement("script");if(t.textContent=e,t.className="hcs-inline-script",r&&t.setAttribute("data-loaded-script-id",r),s){t.type="module";const r=new Blob([e],{type:"application/javascript"});t.src=URL.createObjectURL(r)}document.body.appendChild(t),this.updateLoadingStatus(r,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded script: "+r),t.onerror=e=>{if(this.error("Failed to load "+o+": "+r,e),this.updateLoadingStatus(r,"failed"),n)throw e}}}catch(a){if(this.error("Failed to load "+o+": "+r,a),this.updateLoadingStatus(r,"failed"),n)throw a}}}async loadModuleExports(e){const t=document.querySelector('script[data-loaded-script-id="'+e+'"]');if(!t)throw new Error("Module script with id "+e+" not found");const r=t.getAttribute("src");if(!r)throw new Error("Module script "+e+" has no src attribute");try{const e=new Function("url","return import(url)");return await e(r)}catch(i){throw this.error("Failed to import module",i),i}}async loadStylesheet(e){const t=e.getAttribute("data-src"),r=e.getAttribute("data-script-id"),i=t?.split("/").pop(),o=e.hasAttribute("data-required");if(!this.isDuplicate(i||"")){this.updateLoadingStatus(r,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,o=e.getAttribute("data-network")||this.config.network,n=await this.retrieveHCS1Data(i,t,o),s=await n.text(),a=document.createElement("style");a.textContent=s,document.head.appendChild(a),this.updateLoadingStatus(r,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded and inlined stylesheet: "+r)}catch(n){if(this.error("Failed to load stylesheet: "+r,n),this.updateLoadingStatus(r,"failed"),o)throw n}}}async loadImage(e){const t=e.getAttribute("data-src"),r=t?.split("/").pop();this.log("Loading image: "+r),this.updateLoadingStatus("Image: "+r,"loaded");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,i=e.getAttribute("data-network")||this.config.network,o=await this.retrieveHCS1Data(r,t,i),n=URL.createObjectURL(o);e.src=n,this.LoadedImages[r]=n,this.updateLoadingStatus("Image: "+r,"loaded"),this.log("Loaded image: "+r)}catch(i){this.error("Failed to load image: "+r,i),this.updateLoadingStatus("Image: "+r,"failed")}}async loadMedia(e,t){const r=e.getAttribute("data-src"),i=r?.split("/").pop();this.log("Loading "+t+": "+i),this.updateLoadingStatus(t+": "+i,"loading");try{const r=e.getAttribute("data-cdn-url")||this.config.cdnUrl,o=e.getAttribute("data-network")||this.config.network,n=await this.retrieveHCS1Data(i,r,o),s=URL.createObjectURL(n);e.src=s,"video"===t?this.LoadedVideos[i]=s:this.LoadedAudioUrls[i]=s,this.updateLoadingStatus(t+": "+i,"loaded"),this.log("Loaded "+t+": "+i)}catch(o){this.error("Failed to load "+t+": "+i,o),this.updateLoadingStatus(t+": "+i,"failed")}}async loadModelViewer(){return this.modelViewerLoading?this.modelViewerLoading:this.modelViewerLoaded?Promise.resolve():(this.modelViewerLoading=new Promise(e=>{const t=document.createElement("script");t.setAttribute("data-src","hcs://1/0.0.7293044"),t.setAttribute("data-script-id","model-viewer"),t.setAttribute("type","module"),window.addEventListener("HCSScriptLoaded",()=>{this.modelViewerLoaded=!0,e()},{once:!0}),this.loadScript(t)}),this.modelViewerLoading)}async loadGLB(e){await this.loadModelViewer();const t=e.getAttribute("data-src"),r=t?.split("/").pop();this.log("Loading GLB: "+r),this.updateLoadingStatus("GLB: "+r,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,i=e.getAttribute("data-network")||this.config.network;let o;"model-viewer"!==e.tagName.toLowerCase()?(o=document.createElement("model-viewer"),Array.from(e.attributes).forEach(e=>{o.setAttribute(e.name,e.value)}),o.setAttribute("camera-controls",""),o.setAttribute("auto-rotate",""),o.setAttribute("ar",""),e.parentNode?.replaceChild(o,e)):o=e;const n=await this.retrieveHCS1Data(r,t,i),s=URL.createObjectURL(n);o.setAttribute("src",s),this.LoadedGLBs[r]=s,this.updateLoadingStatus("GLB: "+r,"loaded"),this.log("Loaded GLB: "+r)}catch(i){this.error("Failed to load GLB: "+r,i),this.updateLoadingStatus("GLB: "+r,"failed")}}async loadResource(e,t,r){return new Promise(i=>{this.loadQueue.push({element:e,type:t,order:r,resolve:i}),this.processQueue()})}async processQueue(){if(!this.isProcessingQueue){for(this.isProcessingQueue=!0;this.loadQueue.length>0;){const t=this.loadQueue.shift();try{"script"===t.type?await this.loadScript(t.element):"image"===t.type?await this.loadImage(t.element):"video"===t.type||"audio"===t.type?await this.loadMedia(t.element,t.type):"glb"===t.type?await this.loadGLB(t.element):"css"===t.type&&await this.loadStylesheet(t.element),t.resolve()}catch(e){if(this.error("Error processing queue item:",e),"script"===t.type&&t.element.hasAttribute("data-required"))break}}this.isProcessingQueue=!1}}async replaceHCSInStyle(e){let t=e,r=t.indexOf("hcs://");for(;-1!==r;){let e=r;for(;e<t.length&&!["'",'"'," ",")"].includes(t[e]);)e++;const o=t.substring(r,e),n=o.split("/").pop();try{const i=this.config.cdnUrl,s=this.config.network,a=await this.retrieveHCS1Data(n,i,s),c=URL.createObjectURL(a);t=t.substring(0,r)+c+t.substring(e),this.LoadedImages[n]=c,this.log("Replaced CSS HCS URL: "+o+" with "+c)}catch(i){this.error("Failed to load CSS image: "+n,i)}r=t.indexOf("hcs://",r+1)}return t}async processInlineStyles(){const e=document.querySelectorAll('[style*="hcs://"]');this.log("Found "+e.length+" elements with HCS style references");for(const r of Array.from(e)){const e=r.getAttribute("style");if(e){this.log("Processing style: "+e);const t=await this.replaceHCSInStyle(e);e!==t&&(r.setAttribute("style",t),this.log("Updated style to: "+t))}}const t=document.querySelectorAll("style");for(const r of Array.from(t))if(r.textContent?.includes("hcs://")){const e=await this.replaceHCSInStyle(r.textContent);r.textContent!==e&&(r.textContent=e)}}async init(){return this.loadConfigFromHTML(),new Promise(e=>{const t=async()=>{const t=document.querySelectorAll('script[data-src^="hcs://"]'),r=document.querySelectorAll('img[data-src^="hcs://"], img[src^="hcs://"]'),i=document.querySelectorAll('video[data-src^="hcs://"], video[src^="hcs://"]'),o=document.querySelectorAll('audio[data-src^="hcs://"], audio[src^="hcs://"]'),n=document.querySelectorAll('model-viewer[data-src^="hcs://"]'),s=document.querySelectorAll('link[data-src^="hcs://"]');document.querySelectorAll('[src^="hcs://"]').forEach(e=>{const t=e.getAttribute("src");t&&(e.setAttribute("data-src",t),e.removeAttribute("src"))}),await this.processInlineStyles();const a=[];[{elements:t,type:"script"},{elements:r,type:"image"},{elements:i,type:"video"},{elements:o,type:"audio"},{elements:n,type:"glb"},{elements:s,type:"css"}].forEach(({elements:e,type:t})=>{e.forEach(e=>{const r=parseInt(e.getAttribute("data-load-order")||"")||1/0;a.push(this.loadResource(e,t,r))})}),await Promise.all(a);const c=new MutationObserver(e=>{e.forEach(e=>{if(e.addedNodes.forEach(e=>{if(e.nodeType===Node.ELEMENT_NODE){const t=e;if(t.getAttribute("style")?.includes("hcs://")&&this.processInlineStyles(),"style"===t.tagName.toLowerCase()&&t.textContent?.includes("hcs://")&&this.processInlineStyles(),t.getAttribute("src")?.startsWith("hcs://")){const e=t.getAttribute("src");t.setAttribute("data-src",e),t.removeAttribute("src");switch(t.tagName.toLowerCase()){case"img":this.loadResource(t,"image",1/0);break;case"video":this.loadResource(t,"video",1/0);break;case"audio":this.loadResource(t,"audio",1/0);break;case"script":this.loadResource(t,"script",1/0)}}t.matches('script[data-src^="hcs://"]')?this.loadResource(t,"script",1/0):t.matches('img[data-src^="hcs://"]')?this.loadResource(t,"image",1/0):t.matches('video[data-src^="hcs://"]')?this.loadResource(t,"video",1/0):t.matches('audio[data-src^="hcs://"]')?this.loadResource(t,"audio",1/0):t.matches('model-viewer[data-src^="hcs://"]')?this.loadResource(t,"glb",1/0):t.matches('link[data-src^="hcs://"]')&&this.loadResource(t,"css",1/0);t.querySelectorAll('[data-src^="hcs://"], [src^="hcs://"]').forEach(e=>{const t=e,r=t.tagName.toLowerCase(),i=t.getAttribute("src");switch(i?.startsWith("hcs://")&&(t.setAttribute("data-src",i),t.removeAttribute("src")),r){case"script":this.loadResource(t,"script",1/0);break;case"img":this.loadResource(t,"image",1/0);break;case"video":this.loadResource(t,"video",1/0);break;case"audio":this.loadResource(t,"audio",1/0);break;case"model-viewer":this.loadResource(t,"glb",1/0);break;case"link":this.loadResource(t,"css",1/0)}})}}),"attributes"===e.type){const t=e.target;if("style"===e.attributeName&&t.getAttribute("style")?.includes("hcs://"))this.processInlineStyles();else if("src"===e.attributeName){const e=t.getAttribute("src");if(e?.startsWith("hcs://")){t.setAttribute("data-src",e),t.removeAttribute("src");const r=t.tagName.toLowerCase();["img","video","audio"].includes(r)&&this.loadResource(t,r,1/0)}}}})});document.body?c.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","src","data-src"]}):document.addEventListener("DOMContentLoaded",()=>{c.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","src","data-src"]})}),e()};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t):t()})}async preloadImage(e){this.log("Loading image:"+e),this.updateLoadingStatus("image: "+e,"loading");const t=await this.retrieveHCS1Data(e),r=URL.createObjectURL(t);return this.LoadedImages[e]=r,this.updateLoadingStatus("image: "+e,"loaded"),r}async preloadAudio(e){const t=document.createElement("audio");t.setAttribute("data-topic-id",e),t.setAttribute("data-src","hcs://1/"+e),document.body.appendChild(t),await this.loadMedia(t,"audio");const r=document.querySelector('audio[data-topic-id="'+e+'"]');return r?this.LoadedAudioUrls[e]=r.src:console.error("Failed to preload audio: "+e),this.LoadedAudioUrls[e]}async playAudio(e,t=1){const r=this.LoadedAudioUrls[e];if(r){const i=new Audio(r);i.volume=t,this.LoadedAudios[e]=i,i.play().catch(e=>{console.error("Failed to play audio:",e)}),i.addEventListener("ended",()=>{i.remove(),delete this.LoadedAudios[e]})}else console.error("Audio not preloaded: "+e)}async pauseAudio(e){const t=document.querySelector('audio[data-topic-id="'+e+'"]');t?(console.log("found element",t),t.pause(),this.LoadedAudios[e]?.pause()):this.LoadedAudios[e]?.pause()}async loadAndPlayAudio(e,t=!1,r=1){let i=document.querySelector('audio[data-topic-id="'+e+'"]');if(i)i.volume=r,await i.play();else{const o=document.createElement("audio");o.volume=r,t&&o.setAttribute("autoplay","autoplay"),o.setAttribute("data-topic-id",e),o.setAttribute("data-src","hcs://1/"+e),document.body.appendChild(o),await this.loadMedia(o,"audio"),i=document.querySelector('audio[data-topic-id="'+e+'"]'),t||await i.play()}}}var B=(e=>(e.REGISTER="register",e))(B||{}),K=(e=>(e[e.NON_INDEXED=1]="NON_INDEXED",e))(K||{});function U(e){return`hcs://6/${e}`}const L=r.z.string().regex(/^\d+\.\d+\.\d+$/,{message:"Topic ID must be in Hedera format (e.g., '0.0.123456')"}),$=r.z.object({p:r.z.literal("hcs-6"),op:r.z.enum(["register"]),m:r.z.string().max(500,"Memo must not exceed 500 characters").optional()}),H=$.extend({op:r.z.literal("register"),t_id:L}),q=r.z.discriminatedUnion("op",[H]);function j(e){return e>=3600}function W(e){if(!j(e))throw new Error("TTL must be at least 3600 seconds (1 hour)");return`hcs-6:1:${e}`}class V{constructor(e,t,r){this.maxRetries=5,this.initialDelayMs=2e3,this.maxDelayMs=3e4,this.backoffFactor=2,this.network=e,this.apiKey=r?.apiKey,this.customHeaders=r?.headers||{},this.baseUrl=r?.customUrl||this.getMirrorNodeUrl(),this.logger=t||new O({level:"debug",module:"MirrorNode"}),this.isServerEnvironment="undefined"==typeof window,r?.customUrl&&this.logger.info(`Using custom mirror node URL: ${r.customUrl}`),r?.apiKey&&this.logger.info("Using API key for mirror node requests")}configureRetry(e){this.maxRetries=e.maxRetries??this.maxRetries,this.initialDelayMs=e.initialDelayMs??this.initialDelayMs,this.maxDelayMs=e.maxDelayMs??this.maxDelayMs,this.backoffFactor=e.backoffFactor??this.backoffFactor,this.logger.info(`Retry configuration updated: maxRetries=${this.maxRetries}, initialDelayMs=${this.initialDelayMs}, maxDelayMs=${this.maxDelayMs}, backoffFactor=${this.backoffFactor}`)}configureMirrorNode(e){e.customUrl&&(this.baseUrl=e.customUrl,this.logger.info(`Updated mirror node URL: ${e.customUrl}`)),e.apiKey&&(this.apiKey=e.apiKey,this.logger.info("Updated API key for mirror node requests")),e.headers&&(this.customHeaders={...this.customHeaders,...e.headers},this.logger.info("Updated custom headers for mirror node requests"))}constructUrl(e){if(this.baseUrl.includes("<API-KEY>")&&this.apiKey){const t=this.baseUrl.replace("<API-KEY>",this.apiKey);return e.startsWith("/")?`${t}${e}`:`${t}/${e}`}return e.startsWith("/")?`${this.baseUrl}${e}`:`${this.baseUrl}/${e}`}getMirrorNodeUrl(){return"mainnet"===this.network?"https://mainnet-public.mirrornode.hedera.com":"https://testnet.mirrornode.hedera.com"}getBaseUrl(){return this.baseUrl}async getPublicKey(e){this.logger.debug(`Getting public key for account ${e}`);const t=await this.requestAccount(e);try{if(!t||!t.key)throw new Error(`Failed to retrieve public key for account ID: ${e}`);return i.PublicKey.fromString(t.key.key)}catch(r){const e=`Error fetching public key from Mirror Node: ${r.message}`;throw this.logger.error(e),new Error(e)}}async getAccountMemo(e){this.logger.debug(`Getting account memo for account ID: ${e}`);try{const t=await this._requestWithRetry(`/api/v1/accounts/${e}`);return t?.memo?t.memo:(this.logger.warn(`No memo found for account ${e}`),null)}catch(t){const r=t;return this.logger.error(`Failed to get account memo for ${e} after retries: ${r.message}`),null}}async getTopicInfo(e){try{this.logger.debug(`Fetching topic info for ${e}`);return await this._requestWithRetry(`/api/v1/topics/${e}`)}catch(t){const r=`Error retrieving topic information for ${e} after retries: ${t.message}`;throw this.logger.error(r),new Error(r)}}async getTopicFees(e){try{return(await this.getTopicInfo(e)).custom_fees}catch(t){const e=`Error retrieving topic fees: ${t.message}`;return this.logger.error(e),null}}async getHBARPrice(e){try{const t=i.Timestamp.fromDate(e).toString();this.logger.debug(`Fetching HBAR price for timestamp ${t}`);const r=await this._requestWithRetry(`/api/v1/network/exchangerate?timestamp=${t}`);return Number(r?.current_rate?.cent_equivalent)/Number(r?.current_rate?.hbar_equivalent)/100}catch(t){const e=`Error retrieving HBAR price: ${t.message}`;return this.logger.error(e),null}}async getTokenInfo(e){this.logger.debug(`Fetching token info for ${e}`);try{const t=await this._requestWithRetry(`/api/v1/tokens/${e}`);return t?(this.logger.trace(`Token info found for ${e}:`,t),t):(this.logger.warn(`No token info found for ${e}`),null)}catch(t){const r=`Error fetching token info for ${e}: ${t.message}`;return this.logger.error(r),null}}async getTopicMessages(e,t){this.logger.trace(`Querying messages for topic ${e}${t?" with filters":""}`);let r=`/api/v1/topics/${e}/messages`;const i=new URLSearchParams;if(t){if(void 0!==t.sequenceNumber){const e="number"==typeof t.sequenceNumber?t.sequenceNumber.toString():t.sequenceNumber;e.match(/^(gt|gte|lt|lte|eq|ne):/)?i.append("sequencenumber",e):i.append("sequencenumber",`gt:${e}`)}t.limit&&i.append("limit",t.limit.toString()),t.order&&i.append("order",t.order)}const o=i.toString();o&&(r+=`?${o}`);const n=[];let s=r;for(;s;)try{const e=await this._requestWithRetry(s);if(e.messages&&e.messages.length>0)for(const t of e.messages)try{if(!t.message)continue;let e,r;try{e=this.isServerEnvironment?globalThis.Buffer.from(t.message,"base64").toString("utf-8"):(new TextDecoder).decode(Uint8Array.from(atob(t.message),e=>e.charCodeAt(0)))}catch(a){const e=`Error decoding message: ${a}`;this.logger.error(e);continue}try{r=JSON.parse(e)}catch(a){const t=`Invalid JSON message content: ${e}`;this.logger.error(t);continue}r.sequence_number=t.sequence_number,n.push({...r,consensus_timestamp:t.consensus_timestamp,sequence_number:t.sequence_number,running_hash:t.running_hash,running_hash_version:t.running_hash_version,topic_id:t.topic_id,payer:t.payer_account_id,created:new Date(1e3*Number(t.consensus_timestamp))})}catch(a){const e=`Error processing message: ${a.message}`;this.logger.error(e)}s=e.links?.next||""}catch(c){const t=`Error querying topic messages for topic ${e} (endpoint: ${s}) after retries: ${c.message}`;throw this.logger.error(t),new Error(t)}return n}async requestAccount(e){try{this.logger.debug(`Requesting account info for ${e}`);const t=await this._requestWithRetry(`/api/v1/accounts/${e}`);if(!t)throw new Error(`No data received from mirror node for account: ${e}`);return t}catch(t){const r=`Failed to fetch account ${e} after retries: ${t.message}`;throw this.logger.error(r),new Error(r)}}async checkKeyListAccess(e,t){try{const r=n.proto.Key.decode(e);return this.evaluateKeyAccess(r,t)}catch(r){const e=`Error decoding protobuf key: ${r.message}`;throw this.logger.error(e),new Error(e)}}async evaluateKeyAccess(e,t){return e.ed25519?this.compareEd25519Key(e.ed25519,t):e.keyList?this.evaluateKeyList(e.keyList,t):!(!e.thresholdKey||!e.thresholdKey.keys)&&this.evaluateKeyList(e.thresholdKey.keys,t)}async evaluateKeyList(e,t){const r=e.keys||[];for(const o of r)if(o)if(o.ed25519){if(this.compareEd25519Key(o.ed25519,t))return!0}else if(o.keyList||o.thresholdKey)try{const e=n.proto.Key.encode({...o.keyList?{keyList:o.keyList}:{},...o.thresholdKey?{thresholdKey:o.thresholdKey}:{}}).finish();if(await this.checkKeyListAccess(globalThis.Buffer.from(e),t))return!0}catch(i){const e=`Error in nested key: ${i.message}`;this.logger.debug(e)}return!1}compareEd25519Key(e,t){try{return i.PublicKey.fromBytes(globalThis.Buffer.from(e)).toString()===t.toString()}catch(r){const e=`Error comparing Ed25519 key: ${r.message}`;return this.logger.debug(e),!1}}async getScheduleInfo(e){try{this.logger.info(`Getting information for scheduled transaction ${e}`);const t=await this._requestWithRetry(`/api/v1/schedules/${e}`);return t||(this.logger.warn(`No schedule info found for ${e} after retries.`),null)}catch(t){return this.logger.error(`Error fetching schedule info for ${e} after retries: ${t.message}`),null}}async getScheduledTransactionStatus(e){try{this.logger.info(`Checking status of scheduled transaction ${e}`);const t=await this.getScheduleInfo(e);if(!t)throw new Error(`Schedule ${e} not found`);return{executed:Boolean(t.executed_timestamp),executedDate:t.executed_timestamp?new Date(1e3*Number(t.executed_timestamp)):void 0,deleted:t.deleted||!1}}catch(t){throw this.logger.error(`Error checking scheduled transaction status: ${t}`),t}}async getTransaction(e){this.logger.info(`Getting transaction details for ID/hash: ${e}`);try{const t=await this._requestWithRetry(`/api/v1/transactions/${e}`);return t?.transactions?.length>0?(this.logger.trace(`Transaction details found for ${e}:`,t.transactions[0]),t.transactions[0]):(this.logger.warn(`No transaction details found for ${e} or unexpected response structure.`),null)}catch(t){const r=t;return this.logger.error(`Failed to get transaction details for ${e} after retries: ${r.message}`),null}}async _requestWithRetry(e,t){let r=0,i=this.initialDelayMs;const n=this.constructUrl(e),s={...t,headers:{...this.customHeaders,...t?.headers}};for(this.apiKey&&(s.headers={...s.headers,Authorization:`Bearer ${this.apiKey}`,"X-API-Key":this.apiKey});r<this.maxRetries;)try{return(await o.get(n,s)).data}catch(a){r++;const e=r>=this.maxRetries,t=a.response?.status;if(t&&t>404&&t<500&&429!==t)throw this.logger.error(`Client error for ${n} (status ${t}): ${a.message}. Not retrying.`),a;if(e)throw this.logger.error(`Max retries (${this.maxRetries}) reached for ${n}. Last error: ${a.message}`),a;this.logger.warn(`Attempt ${r}/${this.maxRetries} failed for ${n}: ${a.message}. Retrying in ${i}ms...`),await new Promise(e=>setTimeout(e,i)),i=Math.min(i*this.backoffFactor,this.maxDelayMs)}throw new Error(`Failed to fetch data from ${n} after ${this.maxRetries} attempts.`)}async _fetchWithRetry(e,t){let r=0,i=this.initialDelayMs;const o={...this.customHeaders};t?.headers&&(t.headers instanceof Headers?t.headers.forEach((e,t)=>{o[t]=e}):Array.isArray(t.headers)?t.headers.forEach(([e,t])=>{o[e]=t}):Object.assign(o,t.headers)),this.apiKey&&(o.Authorization=`Bearer ${this.apiKey}`,o["X-API-Key"]=this.apiKey);const n={...t,headers:o};for(;r<this.maxRetries;)try{const t=await fetch(e,n);if(!t.ok){if(t.status>=400&&t.status<500&&429!==t.status)throw this.logger.error(`Client error for ${e} (status ${t.status}): ${t.statusText}. Not retrying.`),new Error(`Fetch failed with status ${t.status}: ${t.statusText} for URL: ${e}`);throw new Error(`Fetch failed with status ${t.status}: ${t.statusText} for URL: ${e}`)}return await t.json()}catch(s){if(r++,r>=this.maxRetries)throw this.logger.error(`Max retries (${this.maxRetries}) reached for ${e}. Last error: ${s.message}`),s;this.logger.warn(`Attempt ${r}/${this.maxRetries} failed for ${e}: ${s.message}. Retrying in ${i}ms...`),await new Promise(e=>setTimeout(e,i)),i=Math.min(i*this.backoffFactor,this.maxDelayMs)}throw new Error(`Failed to fetch data from ${e} after ${this.maxRetries} attempts.`)}async getAccountBalance(e){this.logger.info(`Getting balance for account ${e}`);try{const t=await this.requestAccount(e);if(t&&t.balance){return t.balance.balance/1e8}return this.logger.warn(`Could not retrieve balance for account ${e} from account info.`),null}catch(t){return this.logger.error(`Error fetching numerical balance for account ${e}: ${t.message}`),null}}async getTopicMessagesByFilter(e,t){this.logger.trace(`Querying messages for topic ${e} with filters: ${JSON.stringify(t)}`);let r=`/api/v1/topics/${e}/messages`;const i=new URLSearchParams;t?.limit&&i.append("limit",t.limit.toString()),t?.sequenceNumber&&i.append("sequencenumber",t.sequenceNumber),t?.startTime&&i.append("timestamp",`gte:${t.startTime}`),t?.endTime&&i.append("timestamp",`lt:${t.endTime}`),t?.order&&i.append("order",t.order);const o=i.toString();o&&(r+=`?${o}`);const n=[];let s=0;try{for(;r&&s<10;){s++;const e=await this._requestWithRetry(r);if(e.messages&&e.messages.length>0)for(const t of e.messages)try{if(!t.message)continue;let e;e=this.isServerEnvironment?globalThis.Buffer.from(t.message,"base64").toString("utf-8"):(new TextDecoder).decode(Uint8Array.from(atob(t.message),e=>e.charCodeAt(0)));let r={};try{r=JSON.parse(e)}catch(a){this.logger.debug(`Message content is not valid JSON, using raw: ${e}`),r={raw_content:e}}const i={...r,consensus_timestamp:t.consensus_timestamp,sequence_number:t.sequence_number,payer_account_id:t.payer_account_id,topic_id:t.topic_id,running_hash:t.running_hash,running_hash_version:t.running_hash_version,chunk_info:t.chunk_info,created:new Date(1e3*Number(t.consensus_timestamp.split(".")[0])+Number(t.consensus_timestamp.split(".")[1]||0)/1e6),payer:t.payer_account_id};n.push(i)}catch(c){this.logger.error(`Error processing individual message: ${c.message}`)}if(t?.limit&&n.length>=t.limit)break;r=e.links?.next?`${e.links.next}`:""}return n}catch(l){const t=l;return this.logger.error(`Error querying filtered topic messages for ${e}: ${t.message}`),null}}async getAccountTokens(e,t=100){this.logger.info(`Getting tokens for account ${e}`);let r=[],i=`/api/v1/accounts/${e}/tokens?limit=${t}`;try{for(let e=0;e<10&&i;e++){const e=await this._requestWithRetry(i);if(e&&e.tokens&&(r=r.concat(e.tokens)),i=e.links?.next||"",!i||t&&r.length>=t){t&&r.length>t&&(r=r.slice(0,t));break}}return r}catch(o){return this.logger.error(`Error fetching tokens for account ${e}: ${o.message}`),null}}async getTransactionByTimestamp(e){this.logger.info(`Getting transaction by timestamp: ${e}`);try{return(await this._requestWithRetry(`/api/v1/transactions?timestamp=${e}&limit=1`)).transactions}catch(t){return this.logger.error(`Error fetching transaction by timestamp ${e}: ${t}`),[]}}async getAccountNfts(e,t,r=100){this.logger.info(`Getting NFTs for account ${e}${t?` for token ${t}`:""}`);let i=[],o=`/api/v1/accounts/${e}/nfts?limit=${r}`;t&&(o+=`&token.id=${t}`);try{for(let e=0;e<10&&o;e++){const e=await this._requestWithRetry(o);if(e&&e.nfts){const t=e.nfts.map(e=>{let t;if(e.metadata)try{t=this.isServerEnvironment?globalThis.Buffer.from(e.metadata,"base64").toString("utf-8"):(new TextDecoder).decode(Uint8Array.from(atob(e.metadata),e=>e.charCodeAt(0)))}catch(r){this.logger.warn(`Failed to decode metadata for NFT ${e.token_id} SN ${e.serial_number}: ${r.message}`)}return{...e,token_uri:t}});i=i.concat(t)}if(o=e.links?.next||"",!o)break}return i}catch(n){return this.logger.error(`Error fetching NFTs for account ${e}: ${n.message}`),null}}async validateNFTOwnership(e,t,r){this.logger.info(`Validating ownership of NFT ${t} SN ${r} for account ${e}`);try{const i=await this.getAccountNfts(e,t);if(i){return i.find(e=>e.token_id===t&&e.serial_number===r)||null}return null}catch(i){return this.logger.error(`Error validating NFT ownership: ${i.message}`),null}}async readSmartContractQuery(e,t,r,o){this.logger.info(`Reading smart contract ${e} with selector ${t}`);const n=e.startsWith("0x")?e:`0x${i.AccountId.fromString(e).toSolidityAddress()}`,s=r.startsWith("0x")?r:`0x${i.AccountId.fromString(r).toSolidityAddress()}`,a={block:o?.block||"latest",data:t,estimate:o?.estimate||!1,from:s,to:n,gas:o?.gas,gasPrice:o?.gasPrice,value:o?.value||0};Object.keys(a).forEach(e=>{const t=e;void 0===a[t]&&delete a[t]});try{const e=this.constructUrl("/api/v1/contracts/call");return await this._fetchWithRetry(e,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json"}})}catch(c){return this.logger.error(`Error reading smart contract ${e}: ${c.message}`),null}}async getOutstandingTokenAirdrops(e,t){this.logger.info(`Getting outstanding token airdrops sent by account ${e}`);let r=`/api/v1/accounts/${e}/airdrops/outstanding`;const i=new URLSearchParams;t?.limit&&i.append("limit",t.limit.toString()),t?.order&&i.append("order",t.order),t?.receiverId&&i.append("receiver.id",t.receiverId),t?.serialNumber&&i.append("serialnumber",t.serialNumber),t?.tokenId&&i.append("token.id",t.tokenId);const o=i.toString();o&&(r+=`?${o}`);try{return(await this._requestWithRetry(r)).airdrops||[]}catch(n){return this.logger.error(`Error fetching outstanding token airdrops for account ${e}: ${n.message}`),null}}async getPendingTokenAirdrops(e,t){this.logger.info(`Getting pending token airdrops received by account ${e}`);let r=`/api/v1/accounts/${e}/airdrops/pending`;const i=new URLSearchParams;t?.limit&&i.append("limit",t.limit.toString()),t?.order&&i.append("order",t.order),t?.senderId&&i.append("sender.id",t.senderId),t?.serialNumber&&i.append("serialnumber",t.serialNumber),t?.tokenId&&i.append("token.id",t.tokenId);const o=i.toString();o&&(r+=`?${o}`);try{return(await this._requestWithRetry(r)).airdrops||[]}catch(n){return this.logger.error(`Error fetching pending token airdrops for account ${e}: ${n.message}`),null}}async getBlocks(e){this.logger.info("Getting blocks from the network");let t="/api/v1/blocks";const r=new URLSearchParams;e?.limit&&r.append("limit",e.limit.toString()),e?.order&&r.append("order",e.order),e?.timestamp&&r.append("timestamp",e.timestamp),e?.blockNumber&&r.append("block.number",e.blockNumber);const i=r.toString();i&&(t+=`?${i}`);try{return(await this._requestWithRetry(t)).blocks||[]}catch(o){return this.logger.error(`Error fetching blocks: ${o.message}`),null}}async getBlock(e){this.logger.info(`Getting block ${e}`);try{return await this._requestWithRetry(`/api/v1/blocks/${e}`)}catch(t){return this.logger.error(`Error fetching block ${e}: ${t.message}`),null}}async getContracts(e){this.logger.info("Getting contracts from the network");let t="/api/v1/contracts";const r=new URLSearchParams;e?.contractId&&r.append("contract.id",e.contractId),e?.limit&&r.append("limit",e.limit.toString()),e?.order&&r.append("order",e.order);const i=r.toString();i&&(t+=`?${i}`);try{return(await this._requestWithRetry(t)).contracts||[]}catch(o){return this.logger.error(`Error fetching contracts: ${o.message}`),null}}async getContract(e,t){this.logger.info(`Getting contract ${e}`);let r=`/api/v1/contracts/${e}`;t&&(r+=`?timestamp=${t}`);try{return await this._requestWithRetry(r)}catch(i){return this.logger.error(`Error fetching contract ${e}: ${i.message}`),null}}async getContractResults(e){this.logger.info("Getting contract results from the network");let t="/api/v1/contracts/results";const r=new URLSearchParams;e?.from&&r.append("from",e.from),e?.blockHash&&r.append("block.hash",e.blockHash),e?.blockNumber&&r.append("block.number",e.blockNumber),void 0!==e?.internal&&r.append("internal",e.internal.toString()),e?.limit&&r.append("limit",e.limit.toString()),e?.order&&r.append("order",e.order),e?.timestamp&&r.append("timestamp",e.timestamp),e?.transactionIndex&&r.append("transaction.index",e.transactionIndex.toString());const i=r.toString();i&&(t+=`?${i}`);try{return(await this._requestWithRetry(t)).results||[]}catch(o){return this.logger.error(`Error fetching contract results: ${o.message}`),null}}async getContractResult(e,t){this.logger.info(`Getting contract result for ${e}`);let r=`/api/v1/contracts/results/${e}`;void 0!==t&&(r+=`?nonce=${t}`);try{return await this._requestWithRetry(r)}catch(i){return this.logger.error(`Error fetching contract result for ${e}: ${i.message}`),null}}async getContractResultsByContract(e,t){this.logger.info(`Getting contract results for contract ${e}`);let r=`/api/v1/contracts/${e}/results`;const i=new URLSearchParams;t?.blockHash&&i.append("block.hash",t.blockHash),t?.blockNumber&&i.append("block.number",t.blockNumber),t?.from&&i.append("from",t.from),void 0!==t?.internal&&i.append("internal",t.internal.toString()),t?.limit&&i.append("limit",t.limit.toString()),t?.order&&i.append("order",t.order),t?.timestamp&&i.append("timestamp",t.timestamp),t?.transactionIndex&&i.append("transaction.index",t.transactionIndex.toString());const o=i.toString();o&&(r+=`?${o}`);try{return(await this._requestWithRetry(r)).results||[]}catch(n){return this.logger.error(`Error fetching contract results for ${e}: ${n.message}`),null}}async getContractState(e,t){this.logger.info(`Getting contract state for ${e}`);let r=`/api/v1/contracts/${e}/state`;const i=new URLSearchParams;t?.limit&&i.append("limit",t.limit.toString()),t?.order&&i.append("order",t.order),t?.slot&&i.append("slot",t.slot),t?.timestamp&&i.append("timestamp",t.timestamp);const o=i.toString();o&&(r+=`?${o}`);try{return(await this._requestWithRetry(r)).state||[]}catch(n){return this.logger.error(`Error fetching contract state for ${e}: ${n.message}`),null}}async getContractActions(e,t){this.logger.info(`Getting contract actions for ${e}`);let r=`/api/v1/contracts/results/${e}/actions`;const i=new URLSearchParams;t?.index&&i.append("index",t.index),t?.limit&&i.append("limit",t.limit.toString()),t?.order&&i.append("order",t.order);const o=i.toString();o&&(r+=`?${o}`);try{return(await this._requestWithRetry(r)).actions||[]}catch(n){return this.logger.error(`Error fetching contract actions for ${e}: ${n.message}`),null}}async getContractLogs(e){this.logger.info("Getting contract logs from the network");let t="/api/v1/contracts/results/logs";const r=new URLSearchParams;e?.index&&r.append("index",e.index),e?.limit&&r.append("limit",e.limit.toString()),e?.order&&r.append("order",e.order),e?.timestamp&&r.append("timestamp",e.timestamp),e?.topic0&&r.append("topic0",e.topic0),e?.topic1&&r.append("topic1",e.topic1),e?.topic2&&r.append("topic2",e.topic2),e?.topic3&&r.append("topic3",e.topic3),e?.transactionHash&&r.append("transaction.hash",e.transactionHash);const i=r.toString();i&&(t+=`?${i}`);try{return(await this._requestWithRetry(t)).logs||[]}catch(o){return this.logger.error(`Error fetching contract logs: ${o.message}`),null}}async getContractLogsByContract(e,t){this.logger.info(`Getting contract logs for contract ${e}`);let r=`/api/v1/contracts/${e}/results/logs`;const i=new URLSearchParams;t?.index&&i.append("index",t.index),t?.limit&&i.append("limit",t.limit.toString()),t?.order&&i.append("order",t.order),t?.timestamp&&i.append("timestamp",t.timestamp),t?.topic0&&i.append("topic0",t.topic0),t?.topic1&&i.append("topic1",t.topic1),t?.topic2&&i.append("topic2",t.topic2),t?.topic3&&i.append("topic3",t.topic3);const o=i.toString();o&&(r+=`?${o}`);try{return(await this._requestWithRetry(r)).logs||[]}catch(n){return this.logger.error(`Error fetching contract logs for ${e}: ${n.message}`),null}}async getNftInfo(e,t){this.logger.info(`Getting NFT info for ${e}/${t}`);const r=`/api/v1/tokens/${e}/nfts/${t}`;try{return await this._requestWithRetry(r)}catch(i){return this.logger.error(`Error fetching NFT info for ${e}/${t}: ${i.message}`),null}}async getNftsByToken(e,t){this.logger.info(`Getting NFTs for token ${e}`);let r=`/api/v1/tokens/${e}/nfts`;const i=new URLSearchParams;t?.accountId&&i.append("account.id",t.accountId),t?.limit&&i.append("limit",t.limit.toString()),t?.order&&i.append("order",t.order),t?.serialNumber&&i.append("serialnumber",t.serialNumber);const o=i.toString();o&&(r+=`?${o}`);try{return(await this._requestWithRetry(r)).nfts||[]}catch(n){return this.logger.error(`Error fetching NFTs for token ${e}: ${n.message}`),null}}async getNetworkInfo(){this.logger.info("Getting network information");try{return await this._requestWithRetry("/api/v1/network/nodes")}catch(e){return this.logger.error(`Error fetching network info: ${e.message}`),null}}async getNetworkFees(e){this.logger.info("Getting network fees");let t="/api/v1/network/fees";e&&(t+=`?timestamp=${e}`);try{return await this._requestWithRetry(t)}catch(r){return this.logger.error(`Error fetching network fees: ${r.message}`),null}}async getNetworkSupply(e){this.logger.info("Getting network supply");let t="/api/v1/network/supply";e&&(t+=`?timestamp=${e}`);try{return await this._requestWithRetry(t)}catch(r){return this.logger.error(`Error fetching network supply: ${r.message}`),null}}async getNetworkStake(e){this.logger.info("Getting network stake");let t="/api/v1/network/stake";e&&(t+=`?timestamp=${e}`);try{return await this._requestWithRetry(t)}catch(r){return this.logger.error(`Error fetching network stake: ${r.message}`),null}}async getOpcodeTraces(e,t){this.logger.info(`Getting opcode traces for ${e}`);let r=`/api/v1/contracts/results/${e}/opcodes`;const i=new URLSearchParams;void 0!==t?.stack&&i.append("stack",t.stack.toString()),void 0!==t?.memory&&i.append("memory",t.memory.toString()),void 0!==t?.storage&&i.append("storage",t.storage.toString());const o=i.toString();o&&(r+=`?${o}`);try{return await this._requestWithRetry(r)}catch(n){return this.logger.error(`Error fetching opcode traces for ${e}: ${n.message}`),null}}}class G{constructor(e){this.network=e.network,this.logger=e.logger||O.getInstance({level:e.logLevel||"info",module:"HCS6Client",silent:e.silent}),this.mirrorNode=new V(this.network,this.logger,e.mirrorNodeUrl?{customUrl:e.mirrorNodeUrl}:void 0)}parseRegistryTypeFromMemo(e){try{const t=/hcs-6:(\d):(\d+)/,r=e.match(t);if(r&&3===r.length){const e=parseInt(r[1]),t=parseInt(r[2]);if(e===K.NON_INDEXED&&j(t))return{registryType:e,ttl:t}}return}catch(t){return void this.logger.error(`Error parsing HCS-6 registry type from memo: ${t}`)}}generateRegistryMemo(e){return W(e)}validateMessage(e){try{return q.parse(e),{valid:!0,errors:[]}}catch(t){const e=[];return t instanceof r.ZodError?t.errors.forEach(t=>{const r=t.path.join(".");e.push(`${r?r+": ":""}${t.message}`)}):e.push(`Unexpected error: ${t}`),this.logger.debug(`HCS-6 message validation failed: ${e.join(", ")}`),{valid:!1,errors:e}}}createRegisterMessage(e,t){return{p:"hcs-6",op:B.REGISTER,t_id:e,m:t}}parseRegistryEntries(e,t,r,i){const o=[];let n;this.logger.debug(`Parsing ${t.length} messages for HCS-6 topic ${e}`);for(const a of t)try{if(!a.message){this.logger.debug(`Message is missing 'message' property: ${JSON.stringify(a)}`);continue}const t=globalThis.Buffer.from(a.message,"base64").toString("utf-8"),i=JSON.parse(t);this.logger.debug(`Successfully parsed HCS-6 message: ${JSON.stringify(i)}`);const{valid:s,errors:c}=this.validateMessage(i);if(!s){this.logger.warn(`Invalid HCS-6 message: ${c.join(", ")}`);continue}const l={topicId:e,sequence:a.sequence_number,timestamp:a.consensus_timestamp,payer:a.payer_account_id,message:i,consensus_timestamp:a.consensus_timestamp,registry_type:r};o.push(l),(!n||l.timestamp>n.timestamp)&&(n=l)}catch(s){this.logger.warn(`Error parsing HCS-6 message: ${s}`)}return this.logger.debug(`Parsed ${o.length} valid entries for HCS-6 topic ${e}`),{topicId:e,registryType:r,ttl:i,entries:n?[n]:[],latestEntry:n}}async validateHCS6Topic(e){try{const t=await this.mirrorNode.getTopicInfo(e),r=this.parseRegistryTypeFromMemo(t.memo);return r?r.registryType===K.NON_INDEXED||(this.logger.warn(`Topic ${e} is not a valid HCS-6 registry (must be non-indexed)`),!1):(this.logger.warn(`Topic ${e} is not a valid HCS-6 registry (invalid memo format)`),!1)}catch(t){return this.logger.error(`Error validating HCS-6 topic ${e}: ${t}`),!1}}}function J(e){const{memo:t,adminKey:r,submitKey:o,operatorPublicKey:n}=e,s=(new i.TopicCreateTransaction).setTopicMemo(t),a=e=>{if(e){if(e instanceof i.PublicKey||e instanceof i.KeyList)return e;if("boolean"==typeof e)return e?n:void 0;if("string"==typeof e)try{return i.PublicKey.fromString(e)}catch{return}}},c=a(r);c&&s.setAdminKey(c);const l=a(o);return l&&s.setSubmitKey(l),s}function Y(e){const t=(new i.TopicMessageSubmitTransaction).setTopicId(i.TopicId.fromString(e.topicId)).setMessage(e.message);return e.transactionMemo&&t.setTransactionMemo(e.transactionMemo),t}function X(e){return J({memo:e.memoOverride??`hcs-6:1:${e.ttl}`,submitKey:e.submitKey,adminKey:e.adminKey,operatorPublicKey:e.operatorPublicKey})}var Z=(e=>(e.ED25519="ed25519",e.ECDSA="ecdsa",e.UNKNOWN="unknown",e))(Z||{});const Q=class{static detect(e){try{let t,r="raw";if("string"==typeof e){let i=e.trim();if(i.includes("-----BEGIN"))return this.detectFromPem(i);if(i.toLowerCase().startsWith("0x")&&(i=i.substring(2)),this.isValidHex(i))t=this.hexToBytes(i),r="hex";else{if(!this.isBase64(i))return{type:"unknown",format:"raw",isPrivateKey:!1,confidence:"certain"};t=globalThis.Buffer.from(i,"base64"),r="der"}}else t=e instanceof globalThis.Buffer?new Uint8Array(e):e;return this.detectFromBytes(t,r)}catch(t){return{type:"unknown",format:"raw",isPrivateKey:!1,confidence:"certain"}}}static detectFromBytes(e,t){if(this.hasPrefix(e,this.ED25519_PUBLIC_KEY_PREFIX)){const t=this.ED25519_PUBLIC_KEY_PREFIX.length;return{type:"ed25519",format:"der",isPrivateKey:!1,rawBytes:e.slice(t),confidence:"certain"}}if(this.hasPrefix(e,this.ED25519_PRIVATE_KEY_PREFIX)){const t=this.ED25519_PRIVATE_KEY_PREFIX.length;if(e.length>=t+32)return{type:"ed25519",format:"der",isPrivateKey:!0,rawBytes:e.slice(t,t+32),confidence:"certain"}}if(this.hasPrefix(e,this.ECDSA_SECP256K1_PUBLIC_KEY_PREFIX)){const t=this.ECDSA_SECP256K1_PUBLIC_KEY_PREFIX.length;return{type:"ecdsa",format:"der",isPrivateKey:!1,rawBytes:e.slice(t),confidence:"certain"}}if(this.hasPrefix(e,this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_SHORT)){const t=this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_SHORT.length;return{type:"ecdsa",format:"der",isPrivateKey:!0,rawBytes:e.slice(t),confidence:"certain"}}if(this.hasPrefix(e,this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX)){const t=this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX.length;return{type:"ecdsa",format:"der",isPrivateKey:!0,rawBytes:e.slice(t,t+32),confidence:"certain"}}if(this.hasPrefix(e,this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_LONG)){const t=this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_LONG.length;return{type:"ecdsa",format:"der",isPrivateKey:!0,rawBytes:e.slice(t,t+32),confidence:"certain"}}if(e.length>36&&this.containsECDSAPrivateKeyPattern(e))return{type:"ecdsa",format:"der",isPrivateKey:!0,rawBytes:this.extractECDSAPrivateKey(e),confidence:"certain"};switch(e.length){case this.ED25519_PUBLIC_KEY_LENGTH:if("hex"===t){const t=Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join(""),r=this.tryCreateKey(t);if("unknown"!==r.type)return r}return{type:"unknown",format:t,isPrivateKey:!1,rawBytes:e,confidence:"certain"};case this.ED25519_EXPANDED_PRIVATE_KEY_LENGTH:return{type:"ed25519",format:t,isPrivateKey:!0,rawBytes:e,confidence:"certain"}}return{type:"unknown",format:t,isPrivateKey:!1,rawBytes:e,confidence:"certain"}}static detectFromPem(e){const t=e.trim(),r=t.includes("PRIVATE KEY"),i={EC_PRIVATE:/-----BEGIN EC PRIVATE KEY-----/,EC_PUBLIC:/-----BEGIN EC PUBLIC KEY-----/,PRIVATE:/-----BEGIN PRIVATE KEY-----/,PUBLIC:/-----BEGIN PUBLIC KEY-----/};let o=!1;for(const[a,c]of Object.entries(i))if(c.test(t)&&a.includes("EC")){o=!0;break}const n=t.match(/-----BEGIN[\s\S]+?-----[\r\n]+([\s\S]+?)[\r\n]+-----END/);if(!n)return{type:"unknown",format:"pem",isPrivateKey:r,confidence:"certain"};const s=n[1].replace(/\s/g,"");try{const e=globalThis.Buffer.from(s,"base64"),t=this.detectFromBytes(new Uint8Array(e),"der");return"unknown"===t.type&&o?{type:"ecdsa",format:"pem",isPrivateKey:r,rawBytes:e,confidence:"certain"}:{...t,format:"pem"}}catch{return{type:"unknown",format:"pem",isPrivateKey:r,confidence:"certain"}}}static tryCreateKey(e){try{if("string"==typeof e){let t=e.trim();if(t.toLowerCase().startsWith("0x")&&(t=t.substring(2)),this.isValidHex(t)&&64===t.length){const e=this.hexToBytes(t),r=this.detectBySignature(t);return"unknown"!==r.type?{type:r.type,format:"hex",isPrivateKey:!0,rawBytes:e,confidence:r.confidence,warning:r.warning}:{type:"unknown",format:"hex",isPrivateKey:!1,rawBytes:e,confidence:"certain"}}}}catch{}return{type:"unknown",format:"hex",isPrivateKey:!1,rawBytes:new Uint8Array,confidence:"certain"}}static detectBySignature(e){const t=BigInt("0x"+e),r=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141");if(0n===t)return{type:"ed25519",confidence:"certain"};if(t>=r)return{type:"ed25519",confidence:"certain"};let o=!1,n=!1;try{const t=i.PrivateKey.fromStringED25519(e),r=new Uint8Array([1,2,3,4,5]),n=t.sign(r);t.publicKey.verify(r,n)&&(o=!0)}catch{}try{const t=i.PrivateKey.fromStringECDSA(e),r=new Uint8Array([1,2,3,4,5]),o=t.sign(r);t.publicKey.verify(r,o)&&(n=!0)}catch{}if(o&&n){const t=this.hexToBytes(e);if(168===t[0]&&1===t[1])return{type:"ed25519",confidence:"uncertain",warning:"Detection based on byte pattern heuristic. Both ED25519 and ECDSA accept this key."};let r=0;for(const e of t)e>=128&&r++;const i=r/t.length;return i>=.4&&i<=.6?{type:"ecdsa",confidence:"uncertain",warning:"Detection based on entropy heuristic. Both ED25519 and ECDSA accept this key."}:{type:"ecdsa",confidence:"uncertain",warning:"Detection based on entropy heuristic. Both ED25519 and ECDSA accept this key. Defaulting to ECDSA."}}return o&&!n?{type:"ed25519",confidence:"certain"}:n&&!o?{type:"ecdsa",confidence:"certain"}:{type:"unknown",confidence:"certain"}}static isValidHex(e){return/^[0-9a-fA-F]+$/.test(e)&&e.length%2==0}static isBase64(e){try{return globalThis.Buffer.from(e,"base64").toString("base64")===e}catch{return!1}}static hexToBytes(e){const t=new Uint8Array(e.length/2);for(let r=0;r<e.length;r+=2)t[r/2]=parseInt(e.substr(r,2),16);return t}static hasPrefix(e,t){if(e.length<t.length)return!1;for(let r=0;r<t.length;r++)if(e[r]!==t[r])return!1;return!0}static containsECDSAPrivateKeyPattern(e){for(let t=0;t<e.length-7;t++)if(48===e[t]&&116===e[t+1]&&2===e[t+2]&&1===e[t+3]&&1===e[t+4]&&4===e[t+5]&&32===e[t+6])return!0;return!1}static extractECDSAPrivateKey(e){for(let t=0;t<e.length-32;t++)if(4===e[t]&&32===e[t+1])return e.slice(t+2,t+34);return e}};Q.ED25519_PUBLIC_KEY_LENGTH=32,Q.ED25519_EXPANDED_PRIVATE_KEY_LENGTH=64,Q.ED25519_PUBLIC_KEY_PREFIX=globalThis.Buffer.from([48,42,48,5,6,3,43,101,112,3,33,0]),Q.ED25519_PRIVATE_KEY_PREFIX=globalThis.Buffer.from([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]),Q.ECDSA_SECP256K1_PUBLIC_KEY_PREFIX=globalThis.Buffer.from([48,86,48,16,6,7,42,134,72,206,61,2,1,6,5,43,129,4,0,10,3,66,0]),Q.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX=globalThis.Buffer.from([48,116,2,1,1,4,32]),Q.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_SHORT=globalThis.Buffer.from([48,48,2,1,0,48,7,6,5,43,129,4,0,10,4,34,4,32]),Q.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_LONG=globalThis.Buffer.from([48,119,2,1,1,4,32]);let ee=Q;function te(e){const t=ee.detect(e);if("unknown"!==t.type)try{const r="ecdsa"===t.type?i.PrivateKey.fromStringECDSA(e):i.PrivateKey.fromStringED25519(e),o={detectedType:t.type,privateKey:r};return"uncertain"===t.confidence&&(o.warning="Key type detection is uncertain. If you have the associated account ID, consider using the Hedera mirror node to confirm the key type."),o}catch(r){}try{return{detectedType:"ecdsa",privateKey:i.PrivateKey.fromStringECDSA(e),warning:"Using ECDSA as default. If you have the associated account ID, consider using the Hedera mirror node to confirm the key type."}}catch(o){try{return{detectedType:"ed25519",privateKey:i.PrivateKey.fromStringED25519(e),warning:"Using ED25519 as fallback. If you have the associated account ID, consider using the Hedera mirror node to confirm the key type."}}catch(n){throw new Error(`Failed to parse private key as either ECDSA or ED25519: ${o}`)}}}class re{constructor(e){this.mirror=e.mirrorNode,this.logger=e.logger}bestGuessOperatorKey(e,t){if("string"!=typeof e)return{keyType:t||"ecdsa",privateKey:e};if(t){return{keyType:t,privateKey:"ed25519"===t?i.PrivateKey.fromStringED25519(e):i.PrivateKey.fromStringECDSA(e)}}try{const t=te(e);return{keyType:t.detectedType,privateKey:t.privateKey}}catch{return{keyType:"ecdsa",privateKey:i.PrivateKey.fromStringECDSA(e)}}}async resolveOperatorKey(e,t,r){if("string"!=typeof t)return{keyType:r||"ecdsa",privateKey:t};if(r){return{keyType:r,privateKey:"ed25519"===r?i.PrivateKey.fromStringED25519(t):i.PrivateKey.fromStringECDSA(t)}}const o="string"==typeof e?e:e.toString();try{const e=await this.mirror.requestAccount(o),r=(e?.key?._type||"").includes("ED25519")?"ed25519":"ecdsa";return{keyType:r,privateKey:"ed25519"===r?i.PrivateKey.fromStringED25519(t):i.PrivateKey.fromStringECDSA(t)}}catch{return this.logger.warn("Mirror node key detection failed; using local detection or default ECDSA"),this.bestGuessOperatorKey(t)}}async resolveSupplyKey(e,t,r,o){try{const n=await this.mirror.getTokenInfo(e),s=n?.supply_key?._type||"";return"string"!=typeof t?t:o?"ed25519"===o?i.PrivateKey.fromStringED25519(t):i.PrivateKey.fromStringECDSA(t):s.includes("ED25519")?i.PrivateKey.fromStringED25519(t):s.includes("ECDSA")?i.PrivateKey.fromStringECDSA(t):"ed25519"===r?i.PrivateKey.fromStringED25519(t):i.PrivateKey.fromStringECDSA(t)}catch{return"string"!=typeof t?t:o?"ed25519"===o?i.PrivateKey.fromStringED25519(t):i.PrivateKey.fromStringECDSA(t):"ed25519"===r?i.PrivateKey.fromStringED25519(t):i.PrivateKey.fromStringECDSA(t)}}}function ie(e){const t="string"==typeof e.operatorId?i.AccountId.fromString(e.operatorId):e.operatorId,r=e.client?e.client:"mainnet"===e.network?i.Client.forMainnet():i.Client.forTestnet(),o=new re({mirrorNode:e.mirrorNode,logger:e.logger});let n,s;const a=o.bestGuessOperatorKey(e.operatorKey,e.keyType);n=a.keyType,s=a.privateKey,r.setOperator(t.toString(),s);const c=(async()=>{try{const i=await o.resolveOperatorKey(t,e.operatorKey,e.keyType);n=i.keyType,s=i.privateKey,r.setOperator(t.toString(),s)}catch{}})();return{client:r,operatorId:t,get operatorKey(){return s},get keyType(){return n},ensureInitialized:async()=>{await c}}}for(var oe=Object.defineProperty,ne=((e,t,r)=>((e,t,r)=>t in e?oe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r)),se={},ae={byteLength:function(e){var t=he(e),r=t[0],i=t[1];return 3*(r+i)/4-i},toByteArray:function(e){var t,r,i=he(e),o=i[0],n=i[1],s=new de(function(e,t,r){return 3*(t+r)/4-r}(0,o,n)),a=0,c=n>0?o-4:o;for(r=0;r<c;r+=4)t=le[e.charCodeAt(r)]<<18|le[e.charCodeAt(r+1)]<<12|le[e.charCodeAt(r+2)]<<6|le[e.charCodeAt(r+3)],s[a++]=t>>16&255,s[a++]=t>>8&255,s[a++]=255&t;2===n&&(t=le[e.charCodeAt(r)]<<2|le[e.charCodeAt(r+1)]>>4,s[a++]=255&t);1===n&&(t=le[e.charCodeAt(r)]<<10|le[e.charCodeAt(r+1)]<<4|le[e.charCodeAt(r+2)]>>2,s[a++]=t>>8&255,s[a++]=255&t);return s},fromByteArray:function(e){for(var t,r=e.length,i=r%3,o=[],n=16383,s=0,a=r-i;s<a;s+=n)o.push(me(e,s,s+n>a?a:s+n));1===i?(t=e[r-1],o.push(ce[t>>2]+ce[t<<4&63]+"==")):2===i&&(t=(e[r-2]<<8)+e[r-1],o.push(ce[t>>10]+ce[t>>4&63]+ce[t<<2&63]+"="));return o.join("")}},ce=[],le=[],de="undefined"!=typeof Uint8Array?Uint8Array:Array,ue="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",pe=0;pe<64;++pe)ce[pe]=ue[pe],le[ue.charCodeAt(pe)]=pe;function he(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function ge(e){return ce[e>>18&63]+ce[e>>12&63]+ce[e>>6&63]+ce[63&e]}function me(e,t,r){for(var i,o=[],n=t;n<r;n+=3)i=(e[n]<<16&16711680)+(e[n+1]<<8&65280)+(255&e[n+2]),o.push(ge(i));return o.join("")}le["-".charCodeAt(0)]=62,le["_".charCodeAt(0)]=63;var fe={
2
2
  /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
3
3
  read:function(e,t,r,i,o){var n,s,a=8*o-i-1,c=(1<<a)-1,l=c>>1,d=-7,u=r?o-1:0,p=r?-1:1,h=e[t+u];for(u+=p,n=h&(1<<-d)-1,h>>=-d,d+=a;d>0;n=256*n+e[t+u],u+=p,d-=8);for(s=n&(1<<-d)-1,n>>=-d,d+=i;d>0;s=256*s+e[t+u],u+=p,d-=8);if(0===n)n=1-l;else{if(n===c)return s?NaN:1/0*(h?-1:1);s+=Math.pow(2,i),n-=l}return(h?-1:1)*s*Math.pow(2,n-i)},write:function(e,t,r,i,o,n){var s,a,c,l=8*n-o-1,d=(1<<l)-1,u=d>>1,p=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,h=i?0:n-1,g=i?1:-1,m=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=d):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),(t+=s+u>=1?p/c:p*Math.pow(2,1-u))*c>=2&&(s++,c/=2),s+u>=d?(a=0,s=d):s+u>=1?(a=(t*c-1)*Math.pow(2,o),s+=u):(a=t*Math.pow(2,u-1)*Math.pow(2,o),s=0));o>=8;e[r+h]=255&a,h+=g,a/=256,o-=8);for(s=s<<o|a,l+=o;l>0;e[r+h]=255&s,h+=g,s/=256,l-=8);e[r+h-g]|=128*m}};
4
4
  /*!
@@ -7,5 +7,5 @@ read:function(e,t,r,i,o){var n,s,a=8*o-i-1,c=(1<<a)-1,l=c>>1,d=-7,u=r?o-1:0,p=r?
7
7
  * @author Feross Aboukhadijeh <https://feross.org>
8
8
  * @license MIT
9
9
  */
10
- !function(e){const t=ce,r=ye,i="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=l,e.SlowBuffer=function(e){+e!=e&&(e=0);return l.alloc(+e)},e.INSPECT_MAX_BYTES=50;const o=2147483647;e.kMaxLength=o;const{Uint8Array:n,ArrayBuffer:s,SharedArrayBuffer:a}=globalThis;function c(e){if(e>o)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new n(e);return Object.setPrototypeOf(t,l.prototype),t}function l(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return p(e)}return d(e,t,r)}function d(e,t,r){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!l.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|f(e,t);let i=c(r);const o=i.write(e,t);o!==r&&(i=i.slice(0,o));return i}(e,t);if(s.isView(e))return function(e){if(Y(e,n)){const t=new n(e);return g(t.buffer,t.byteOffset,t.byteLength)}return h(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(Y(e,s)||e&&Y(e.buffer,s))return g(e,t,r);if(void 0!==a&&(Y(e,a)||e&&Y(e.buffer,a)))return g(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const i=e.valueOf&&e.valueOf();if(null!=i&&i!==e)return l.from(i,t,r);const o=function(e){if(l.isBuffer(e)){const t=0|m(e.length),r=c(t);return 0===r.length||e.copy(r,0,0,t),r}if(void 0!==e.length)return"number"!=typeof e.length||X(e.length)?c(0):h(e);if("Buffer"===e.type&&Array.isArray(e.data))return h(e.data)}(e);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return l.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function u(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function p(e){return u(e),c(e<0?0:0|m(e))}function h(e){const t=e.length<0?0:0|m(e.length),r=c(t);for(let i=0;i<t;i+=1)r[i]=255&e[i];return r}function g(e,t,r){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(r||0))throw new RangeError('"length" is outside of buffer bounds');let i;return i=void 0===t&&void 0===r?new n(e):void 0===r?new n(e,t):new n(e,t,r),Object.setPrototypeOf(i,l.prototype),i}function m(e){if(e>=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function f(e,t){if(l.isBuffer(e))return e.length;if(s.isView(e)||Y(e,s))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const r=e.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===r)return 0;let o=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return V(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return G(e).length;default:if(o)return i?-1:V(e).length;t=(""+t).toLowerCase(),o=!0}}function y(e,t,r){let i=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return _(this,t,r);case"utf8":case"utf-8":return C(this,t,r);case"ascii":return R(this,t,r);case"latin1":case"binary":return N(this,t,r);case"base64":return A(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return P(this,t,r);default:if(i)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),i=!0}}function b(e,t,r){const i=e[t];e[t]=e[r],e[r]=i}function w(e,t,r,i,o){if(0===e.length)return-1;if("string"==typeof r?(i=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),X(r=+r)&&(r=o?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(o)return-1;r=e.length-1}else if(r<0){if(!o)return-1;r=0}if("string"==typeof t&&(t=l.from(t,i)),l.isBuffer(t))return 0===t.length?-1:I(e,t,r,i,o);if("number"==typeof t)return t&=255,"function"==typeof n.prototype.indexOf?o?n.prototype.indexOf.call(e,t,r):n.prototype.lastIndexOf.call(e,t,r):I(e,[t],r,i,o);throw new TypeError("val must be string, number or Buffer")}function I(e,t,r,i,o){let n,s=1,a=e.length,c=t.length;if(void 0!==i&&("ucs2"===(i=String(i).toLowerCase())||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){if(e.length<2||t.length<2)return-1;s=2,a/=2,c/=2,r/=2}function l(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(o){let i=-1;for(n=r;n<a;n++)if(l(e,n)===l(t,-1===i?0:n-i)){if(-1===i&&(i=n),n-i+1===c)return i*s}else-1!==i&&(n-=n-i),i=-1}else for(r+c>a&&(r=a-c),n=r;n>=0;n--){let r=!0;for(let i=0;i<c;i++)if(l(e,n+i)!==l(t,i)){r=!1;break}if(r)return n}return-1}function T(e,t,r,i){r=Number(r)||0;const o=e.length-r;i?(i=Number(i))>o&&(i=o):i=o;const n=t.length;let s;for(i>n/2&&(i=n/2),s=0;s<i;++s){const i=parseInt(t.substr(2*s,2),16);if(X(i))return s;e[r+s]=i}return s}function S(e,t,r,i){return J(V(t,e.length-r),e,r,i)}function k(e,t,r,i){return J(function(e){const t=[];for(let r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}(t),e,r,i)}function E(e,t,r,i){return J(G(t),e,r,i)}function v(e,t,r,i){return J(function(e,t){let r,i,o;const n=[];for(let s=0;s<e.length&&!((t-=2)<0);++s)r=e.charCodeAt(s),i=r>>8,o=r%256,n.push(o),n.push(i);return n}(t,e.length-r),e,r,i)}function A(e,r,i){return 0===r&&i===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(r,i))}function C(e,t,r){r=Math.min(e.length,r);const i=[];let o=t;for(;o<r;){const t=e[o];let n=null,s=t>239?4:t>223?3:t>191?2:1;if(o+s<=r){let r,i,a,c;switch(s){case 1:t<128&&(n=t);break;case 2:r=e[o+1],128==(192&r)&&(c=(31&t)<<6|63&r,c>127&&(n=c));break;case 3:r=e[o+1],i=e[o+2],128==(192&r)&&128==(192&i)&&(c=(15&t)<<12|(63&r)<<6|63&i,c>2047&&(c<55296||c>57343)&&(n=c));break;case 4:r=e[o+1],i=e[o+2],a=e[o+3],128==(192&r)&&128==(192&i)&&128==(192&a)&&(c=(15&t)<<18|(63&r)<<12|(63&i)<<6|63&a,c>65535&&c<1114112&&(n=c))}}null===n?(n=65533,s=1):n>65535&&(n-=65536,i.push(n>>>10&1023|55296),n=56320|1023&n),i.push(n),o+=s}return function(e){const t=e.length;if(t<=x)return String.fromCharCode.apply(String,e);let r="",i=0;for(;i<t;)r+=String.fromCharCode.apply(String,e.slice(i,i+=x));return r}(i)}l.TYPED_ARRAY_SUPPORT=function(){try{const e=new n(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,n.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),l.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(l.prototype,"parent",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.buffer}}),Object.defineProperty(l.prototype,"offset",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.byteOffset}}),l.poolSize=8192,l.from=function(e,t,r){return d(e,t,r)},Object.setPrototypeOf(l.prototype,n.prototype),Object.setPrototypeOf(l,n),l.alloc=function(e,t,r){return function(e,t,r){return u(e),e<=0?c(e):void 0!==t?"string"==typeof r?c(e).fill(t,r):c(e).fill(t):c(e)}(e,t,r)},l.allocUnsafe=function(e){return p(e)},l.allocUnsafeSlow=function(e){return p(e)},l.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==l.prototype},l.compare=function(e,t){if(Y(e,n)&&(e=l.from(e,e.offset,e.byteLength)),Y(t,n)&&(t=l.from(t,t.offset,t.byteLength)),!l.isBuffer(e)||!l.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let r=e.length,i=t.length;for(let o=0,n=Math.min(r,i);o<n;++o)if(e[o]!==t[o]){r=e[o],i=t[o];break}return r<i?-1:i<r?1:0},l.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},l.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return l.alloc(0);let r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;const i=l.allocUnsafe(t);let o=0;for(r=0;r<e.length;++r){let t=e[r];if(Y(t,n))o+t.length>i.length?(l.isBuffer(t)||(t=l.from(t)),t.copy(i,o)):n.prototype.set.call(i,t,o);else{if(!l.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(i,o)}o+=t.length}return i},l.byteLength=f,l.prototype._isBuffer=!0,l.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)b(this,t,t+1);return this},l.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)b(this,t,t+3),b(this,t+1,t+2);return this},l.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)b(this,t,t+7),b(this,t+1,t+6),b(this,t+2,t+5),b(this,t+3,t+4);return this},l.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?C(this,0,e):y.apply(this,arguments)},l.prototype.toLocaleString=l.prototype.toString,l.prototype.equals=function(e){if(!l.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===l.compare(this,e)},l.prototype.inspect=function(){let t="";const r=e.INSPECT_MAX_BYTES;return t=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(t+=" ... "),"<Buffer "+t+">"},i&&(l.prototype[i]=l.prototype.inspect),l.prototype.compare=function(e,t,r,i,o){if(Y(e,n)&&(e=l.from(e,e.offset,e.byteLength)),!l.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===i&&(i=0),void 0===o&&(o=this.length),t<0||r>e.length||i<0||o>this.length)throw new RangeError("out of range index");if(i>=o&&t>=r)return 0;if(i>=o)return-1;if(t>=r)return 1;if(this===e)return 0;let s=(o>>>=0)-(i>>>=0),a=(r>>>=0)-(t>>>=0);const c=Math.min(s,a),d=this.slice(i,o),u=e.slice(t,r);for(let n=0;n<c;++n)if(d[n]!==u[n]){s=d[n],a=u[n];break}return s<a?-1:a<s?1:0},l.prototype.includes=function(e,t,r){return-1!==this.indexOf(e,t,r)},l.prototype.indexOf=function(e,t,r){return w(this,e,t,r,!0)},l.prototype.lastIndexOf=function(e,t,r){return w(this,e,t,r,!1)},l.prototype.write=function(e,t,r,i){if(void 0===t)i="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)i=t,r=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(r)?(r>>>=0,void 0===i&&(i="utf8")):(i=r,r=void 0)}const o=this.length-t;if((void 0===r||r>o)&&(r=o),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");let n=!1;for(;;)switch(i){case"hex":return T(this,e,t,r);case"utf8":case"utf-8":return S(this,e,t,r);case"ascii":case"latin1":case"binary":return k(this,e,t,r);case"base64":return E(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return v(this,e,t,r);default:if(n)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),n=!0}},l.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const x=4096;function R(e,t,r){let i="";r=Math.min(e.length,r);for(let o=t;o<r;++o)i+=String.fromCharCode(127&e[o]);return i}function N(e,t,r){let i="";r=Math.min(e.length,r);for(let o=t;o<r;++o)i+=String.fromCharCode(e[o]);return i}function _(e,t,r){const i=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>i)&&(r=i);let o="";for(let n=t;n<r;++n)o+=Z[e[n]];return o}function P(e,t,r){const i=e.slice(t,r);let o="";for(let n=0;n<i.length-1;n+=2)o+=String.fromCharCode(i[n]+256*i[n+1]);return o}function F(e,t,r){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>r)throw new RangeError("Trying to access beyond buffer length")}function O(e,t,r,i,o,n){if(!l.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||t<n)throw new RangeError('"value" argument is out of bounds');if(r+i>e.length)throw new RangeError("Index out of range")}function D(e,t,r,i,o){H(t,i,o,e,r,7);let n=Number(t&BigInt(4294967295));e[r++]=n,n>>=8,e[r++]=n,n>>=8,e[r++]=n,n>>=8,e[r++]=n;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=s,s>>=8,e[r++]=s,s>>=8,e[r++]=s,s>>=8,e[r++]=s,r}function z(e,t,r,i,o){H(t,i,o,e,r,7);let n=Number(t&BigInt(4294967295));e[r+7]=n,n>>=8,e[r+6]=n,n>>=8,e[r+5]=n,n>>=8,e[r+4]=n;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=s,s>>=8,e[r+2]=s,s>>=8,e[r+1]=s,s>>=8,e[r]=s,r+8}function B(e,t,r,i,o,n){if(r+i>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function M(e,t,i,o,n){return t=+t,i>>>=0,n||B(e,0,i,4),r.write(e,t,i,o,23,4),i+4}function K(e,t,i,o,n){return t=+t,i>>>=0,n||B(e,0,i,8),r.write(e,t,i,o,52,8),i+8}l.prototype.slice=function(e,t){const r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t<e&&(t=e);const i=this.subarray(e,t);return Object.setPrototypeOf(i,l.prototype),i},l.prototype.readUintLE=l.prototype.readUIntLE=function(e,t,r){e>>>=0,t>>>=0,r||F(e,t,this.length);let i=this[e],o=1,n=0;for(;++n<t&&(o*=256);)i+=this[e+n]*o;return i},l.prototype.readUintBE=l.prototype.readUIntBE=function(e,t,r){e>>>=0,t>>>=0,r||F(e,t,this.length);let i=this[e+--t],o=1;for(;t>0&&(o*=256);)i+=this[e+--t]*o;return i},l.prototype.readUint8=l.prototype.readUInt8=function(e,t){return e>>>=0,t||F(e,1,this.length),this[e]},l.prototype.readUint16LE=l.prototype.readUInt16LE=function(e,t){return e>>>=0,t||F(e,2,this.length),this[e]|this[e+1]<<8},l.prototype.readUint16BE=l.prototype.readUInt16BE=function(e,t){return e>>>=0,t||F(e,2,this.length),this[e]<<8|this[e+1]},l.prototype.readUint32LE=l.prototype.readUInt32LE=function(e,t){return e>>>=0,t||F(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},l.prototype.readUint32BE=l.prototype.readUInt32BE=function(e,t){return e>>>=0,t||F(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},l.prototype.readBigUInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||j(e,this.length-8);const i=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,o=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(i)+(BigInt(o)<<BigInt(32))}),l.prototype.readBigUInt64BE=Q(function(e){q(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||j(e,this.length-8);const i=t*2**24+65536*this[++e]+256*this[++e]+this[++e],o=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(i)<<BigInt(32))+BigInt(o)}),l.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||F(e,t,this.length);let i=this[e],o=1,n=0;for(;++n<t&&(o*=256);)i+=this[e+n]*o;return o*=128,i>=o&&(i-=Math.pow(2,8*t)),i},l.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||F(e,t,this.length);let i=t,o=1,n=this[e+--i];for(;i>0&&(o*=256);)n+=this[e+--i]*o;return o*=128,n>=o&&(n-=Math.pow(2,8*t)),n},l.prototype.readInt8=function(e,t){return e>>>=0,t||F(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},l.prototype.readInt16LE=function(e,t){e>>>=0,t||F(e,2,this.length);const r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},l.prototype.readInt16BE=function(e,t){e>>>=0,t||F(e,2,this.length);const r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},l.prototype.readInt32LE=function(e,t){return e>>>=0,t||F(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},l.prototype.readInt32BE=function(e,t){return e>>>=0,t||F(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},l.prototype.readBigInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||j(e,this.length-8);const i=this[e+4]+256*this[e+5]+65536*this[e+6]+(r<<24);return(BigInt(i)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)}),l.prototype.readBigInt64BE=Q(function(e){q(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||j(e,this.length-8);const i=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(i)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+r)}),l.prototype.readFloatLE=function(e,t){return e>>>=0,t||F(e,4,this.length),r.read(this,e,!0,23,4)},l.prototype.readFloatBE=function(e,t){return e>>>=0,t||F(e,4,this.length),r.read(this,e,!1,23,4)},l.prototype.readDoubleLE=function(e,t){return e>>>=0,t||F(e,8,this.length),r.read(this,e,!0,52,8)},l.prototype.readDoubleBE=function(e,t){return e>>>=0,t||F(e,8,this.length),r.read(this,e,!1,52,8)},l.prototype.writeUintLE=l.prototype.writeUIntLE=function(e,t,r,i){if(e=+e,t>>>=0,r>>>=0,!i){O(this,e,t,r,Math.pow(2,8*r)-1,0)}let o=1,n=0;for(this[t]=255&e;++n<r&&(o*=256);)this[t+n]=e/o&255;return t+r},l.prototype.writeUintBE=l.prototype.writeUIntBE=function(e,t,r,i){if(e=+e,t>>>=0,r>>>=0,!i){O(this,e,t,r,Math.pow(2,8*r)-1,0)}let o=r-1,n=1;for(this[t+o]=255&e;--o>=0&&(n*=256);)this[t+o]=e/n&255;return t+r},l.prototype.writeUint8=l.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,1,255,0),this[t]=255&e,t+1},l.prototype.writeUint16LE=l.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},l.prototype.writeUint16BE=l.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},l.prototype.writeUint32LE=l.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},l.prototype.writeUint32BE=l.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},l.prototype.writeBigUInt64LE=Q(function(e,t=0){return D(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),l.prototype.writeBigUInt64BE=Q(function(e,t=0){return z(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),l.prototype.writeIntLE=function(e,t,r,i){if(e=+e,t>>>=0,!i){const i=Math.pow(2,8*r-1);O(this,e,t,r,i-1,-i)}let o=0,n=1,s=0;for(this[t]=255&e;++o<r&&(n*=256);)e<0&&0===s&&0!==this[t+o-1]&&(s=1),this[t+o]=(e/n|0)-s&255;return t+r},l.prototype.writeIntBE=function(e,t,r,i){if(e=+e,t>>>=0,!i){const i=Math.pow(2,8*r-1);O(this,e,t,r,i-1,-i)}let o=r-1,n=1,s=0;for(this[t+o]=255&e;--o>=0&&(n*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/n|0)-s&255;return t+r},l.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},l.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},l.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},l.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},l.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},l.prototype.writeBigInt64LE=Q(function(e,t=0){return D(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),l.prototype.writeBigInt64BE=Q(function(e,t=0){return z(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),l.prototype.writeFloatLE=function(e,t,r){return M(this,e,t,!0,r)},l.prototype.writeFloatBE=function(e,t,r){return M(this,e,t,!1,r)},l.prototype.writeDoubleLE=function(e,t,r){return K(this,e,t,!0,r)},l.prototype.writeDoubleBE=function(e,t,r){return K(this,e,t,!1,r)},l.prototype.copy=function(e,t,r,i){if(!l.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),i||0===i||(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i<r&&(i=r),i===r)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t<i-r&&(i=e.length-t+r);const o=i-r;return this===e&&"function"==typeof n.prototype.copyWithin?this.copyWithin(t,r,i):n.prototype.set.call(e,this.subarray(r,i),t),o},l.prototype.fill=function(e,t,r,i){if("string"==typeof e){if("string"==typeof t?(i=t,t=0,r=this.length):"string"==typeof r&&(i=r,r=this.length),void 0!==i&&"string"!=typeof i)throw new TypeError("encoding must be a string");if("string"==typeof i&&!l.isEncoding(i))throw new TypeError("Unknown encoding: "+i);if(1===e.length){const t=e.charCodeAt(0);("utf8"===i&&t<128||"latin1"===i)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<r)throw new RangeError("Out of range index");if(r<=t)return this;let o;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o<r;++o)this[o]=e;else{const n=l.isBuffer(e)?e:l.from(e,i),s=n.length;if(0===s)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(o=0;o<r-t;++o)this[o+t]=n[o%s]}return this};const U={};function L(e,t,r){U[e]=class extends r{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function $(e){let t="",r=e.length;const i="-"===e[0]?1:0;for(;r>=i+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function H(e,t,r,i,o,n){if(e>r||e<t){const r="bigint"==typeof t?"n":"";let i;throw i=0===t||t===BigInt(0)?`>= 0${r} and < 2${r} ** ${8*(n+1)}${r}`:`>= -(2${r} ** ${8*(n+1)-1}${r}) and < 2 ** ${8*(n+1)-1}${r}`,new U.ERR_OUT_OF_RANGE("value",i,e)}!function(e,t,r){q(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||j(t,e.length-(r+1))}(i,o,n)}function q(e,t){if("number"!=typeof e)throw new U.ERR_INVALID_ARG_TYPE(t,"number",e)}function j(e,t,r){if(Math.floor(e)!==e)throw q(e,r),new U.ERR_OUT_OF_RANGE("offset","an integer",e);if(t<0)throw new U.ERR_BUFFER_OUT_OF_BOUNDS;throw new U.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${t}`,e)}L("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),L("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),L("ERR_OUT_OF_RANGE",function(e,t,r){let i=`The value of "${e}" is out of range.`,o=r;return Number.isInteger(r)&&Math.abs(r)>2**32?o=$(String(r)):"bigint"==typeof r&&(o=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(o=$(o)),o+="n"),i+=` It must be ${t}. Received ${o}`,i},RangeError);const W=/[^+/0-9A-Za-z-_]/g;function V(e,t){let r;t=t||1/0;const i=e.length;let o=null;const n=[];for(let s=0;s<i;++s){if(r=e.charCodeAt(s),r>55295&&r<57344){if(!o){if(r>56319){(t-=3)>-1&&n.push(239,191,189);continue}if(s+1===i){(t-=3)>-1&&n.push(239,191,189);continue}o=r;continue}if(r<56320){(t-=3)>-1&&n.push(239,191,189),o=r;continue}r=65536+(o-55296<<10|r-56320)}else o&&(t-=3)>-1&&n.push(239,191,189);if(o=null,r<128){if((t-=1)<0)break;n.push(r)}else if(r<2048){if((t-=2)<0)break;n.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;n.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;n.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return n}function G(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(W,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function J(e,t,r,i){let o;for(o=0;o<i&&!(o+r>=t.length||o>=e.length);++o)t[o+r]=e[o];return o}function Y(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function X(e){return e!=e}const Z=function(){const e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){const i=16*r;for(let o=0;o<16;++o)t[i+o]=e[r]+e[o]}return t}();function Q(e){return"undefined"==typeof BigInt?ee:e}function ee(){throw new Error("BigInt not supported")}}(ae);const be=ae.Buffer,we=ae.Buffer,Ie=globalThis||self;function Te(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Se,ke,Ee={exports:{}},ve=Ee.exports={};function Ae(){throw new Error("setTimeout has not been defined")}function Ce(){throw new Error("clearTimeout has not been defined")}function xe(e){if(Se===setTimeout)return setTimeout(e,0);if((Se===Ae||!Se)&&setTimeout)return Se=setTimeout,setTimeout(e,0);try{return Se(e,0)}catch(t){try{return Se.call(null,e,0)}catch(r){return Se.call(this,e,0)}}}!function(){try{Se="function"==typeof setTimeout?setTimeout:Ae}catch(e){Se=Ae}try{ke="function"==typeof clearTimeout?clearTimeout:Ce}catch(e){ke=Ce}}();var Re,Ne=[],_e=!1,Pe=-1;function Fe(){_e&&Re&&(_e=!1,Re.length?Ne=Re.concat(Ne):Pe=-1,Ne.length&&Oe())}function Oe(){if(!_e){var e=xe(Fe);_e=!0;for(var t=Ne.length;t;){for(Re=Ne,Ne=[];++Pe<t;)Re&&Re[Pe].run();Pe=-1,t=Ne.length}Re=null,_e=!1,function(e){if(ke===clearTimeout)return clearTimeout(e);if((ke===Ce||!ke)&&clearTimeout)return ke=clearTimeout,clearTimeout(e);try{return ke(e)}catch(t){try{return ke.call(null,e)}catch(r){return ke.call(this,e)}}}(e)}}function De(e,t){this.fun=e,this.array=t}function ze(){}ve.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];Ne.push(new De(e,t)),1!==Ne.length||_e||xe(Oe)},De.prototype.run=function(){this.fun.apply(null,this.array)},ve.title="browser",ve.browser=!0,ve.env={},ve.argv=[],ve.version="",ve.versions={},ve.on=ze,ve.addListener=ze,ve.once=ze,ve.off=ze,ve.removeListener=ze,ve.removeAllListeners=ze,ve.emit=ze,ve.prependListener=ze,ve.prependOnceListener=ze,ve.listeners=function(e){return[]},ve.binding=function(e){throw new Error("process.binding is not supported")},ve.cwd=function(){return"/"},ve.chdir=function(e){throw new Error("process.chdir is not supported")},ve.umask=function(){return 0};const Be=Te(Ee.exports);function Me(e,t){return function(){return e.apply(t,arguments)}}const{toString:Ke}=Object.prototype,{getPrototypeOf:Ue}=Object,{iterator:Le,toStringTag:$e}=Symbol,He=(e=>t=>{const r=Ke.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),qe=e=>(e=e.toLowerCase(),t=>He(t)===e),je=e=>t=>typeof t===e,{isArray:We}=Array,Ve=je("undefined");function Ge(e){return null!==e&&!Ve(e)&&null!==e.constructor&&!Ve(e.constructor)&&Xe(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const Je=qe("ArrayBuffer");const Ye=je("string"),Xe=je("function"),Ze=je("number"),Qe=e=>null!==e&&"object"==typeof e,et=e=>{if("object"!==He(e))return!1;const t=Ue(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||$e in e||Le in e)},tt=qe("Date"),rt=qe("File"),it=qe("Blob"),ot=qe("FileList"),nt=qe("URLSearchParams"),[st,at,ct,lt]=["ReadableStream","Request","Response","Headers"].map(qe);function dt(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let i,o;if("object"!=typeof e&&(e=[e]),We(e))for(i=0,o=e.length;i<o;i++)t.call(null,e[i],i,e);else{if(Ge(e))return;const o=r?Object.getOwnPropertyNames(e):Object.keys(e),n=o.length;let s;for(i=0;i<n;i++)s=o[i],t.call(null,e[s],s,e)}}function ut(e,t){if(Ge(e))return null;t=t.toLowerCase();const r=Object.keys(e);let i,o=r.length;for(;o-- >0;)if(i=r[o],t===i.toLowerCase())return i;return null}const pt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:Ie,ht=e=>!Ve(e)&&e!==pt;const gt=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&Ue(Uint8Array)),mt=qe("HTMLFormElement"),ft=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),yt=qe("RegExp"),bt=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),i={};dt(r,(r,o)=>{let n;!1!==(n=t(r,o,e))&&(i[o]=n||r)}),Object.defineProperties(e,i)};const wt=qe("AsyncFunction"),It=(Tt="function"==typeof setImmediate,St=Xe(pt.postMessage),Tt?setImmediate:St?(kt=`axios@${Math.random()}`,Et=[],pt.addEventListener("message",({source:e,data:t})=>{e===pt&&t===kt&&Et.length&&Et.shift()()},!1),e=>{Et.push(e),pt.postMessage(kt,"*")}):e=>setTimeout(e));var Tt,St,kt,Et;const vt="undefined"!=typeof queueMicrotask?queueMicrotask.bind(pt):void 0!==Be&&Be.nextTick||It,At={isArray:We,isArrayBuffer:Je,isBuffer:Ge,isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||Xe(e.append)&&("formdata"===(t=He(e))||"object"===t&&Xe(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&Je(e.buffer),t},isString:Ye,isNumber:Ze,isBoolean:e=>!0===e||!1===e,isObject:Qe,isPlainObject:et,isEmptyObject:e=>{if(!Qe(e)||Ge(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(t){return!1}},isReadableStream:st,isRequest:at,isResponse:ct,isHeaders:lt,isUndefined:Ve,isDate:tt,isFile:rt,isBlob:it,isRegExp:yt,isFunction:Xe,isStream:e=>Qe(e)&&Xe(e.pipe),isURLSearchParams:nt,isTypedArray:gt,isFileList:ot,forEach:dt,merge:function e(){const{caseless:t}=ht(this)&&this||{},r={},i=(i,o)=>{const n=t&&ut(r,o)||o;et(r[n])&&et(i)?r[n]=e(r[n],i):et(i)?r[n]=e({},i):We(i)?r[n]=i.slice():r[n]=i};for(let o=0,n=arguments.length;o<n;o++)arguments[o]&&dt(arguments[o],i);return r},extend:(e,t,r,{allOwnKeys:i}={})=>(dt(t,(t,i)=>{r&&Xe(t)?e[i]=Me(t,r):e[i]=t},{allOwnKeys:i}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,r,i)=>{e.prototype=Object.create(t.prototype,i),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject:(e,t,r,i)=>{let o,n,s;const a={};if(t=t||{},null==e)return t;do{for(o=Object.getOwnPropertyNames(e),n=o.length;n-- >0;)s=o[n],i&&!i(s,e,t)||a[s]||(t[s]=e[s],a[s]=!0);e=!1!==r&&Ue(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:He,kindOfTest:qe,endsWith:(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const i=e.indexOf(t,r);return-1!==i&&i===r},toArray:e=>{if(!e)return null;if(We(e))return e;let t=e.length;if(!Ze(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{const r=(e&&e[Le]).call(e);let i;for(;(i=r.next())&&!i.done;){const r=i.value;t.call(e,r[0],r[1])}},matchAll:(e,t)=>{let r;const i=[];for(;null!==(r=e.exec(t));)i.push(r);return i},isHTMLForm:mt,hasOwnProperty:ft,hasOwnProp:ft,reduceDescriptors:bt,freezeMethods:e=>{bt(e,(t,r)=>{if(Xe(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const i=e[r];Xe(i)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")}))})},toObjectSet:(e,t)=>{const r={},i=e=>{e.forEach(e=>{r[e]=!0})};return We(e)?i(e):i(String(e).split(t)),r},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(e,t,r){return t.toUpperCase()+r}),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:ut,global:pt,isContextDefined:ht,isSpecCompliantForm:function(e){return!!(e&&Xe(e.append)&&"FormData"===e[$e]&&e[Le])},toJSONObject:e=>{const t=new Array(10),r=(e,i)=>{if(Qe(e)){if(t.indexOf(e)>=0)return;if(Ge(e))return e;if(!("toJSON"in e)){t[i]=e;const o=We(e)?[]:{};return dt(e,(e,t)=>{const n=r(e,i+1);!Ve(n)&&(o[t]=n)}),t[i]=void 0,o}}return e};return r(e,0)},isAsyncFn:wt,isThenable:e=>e&&(Qe(e)||Xe(e))&&Xe(e.then)&&Xe(e.catch),setImmediate:It,asap:vt,isIterable:e=>null!=e&&Xe(e[Le])};function Ct(e,t,r,i,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),i&&(this.request=i),o&&(this.response=o,this.status=o.status?o.status:null)}At.inherits(Ct,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:At.toJSONObject(this.config),code:this.code,status:this.status}}});const xt=Ct.prototype,Rt={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{Rt[e]={value:e}}),Object.defineProperties(Ct,Rt),Object.defineProperty(xt,"isAxiosError",{value:!0}),Ct.from=(e,t,r,i,o,n)=>{const s=Object.create(xt);return At.toFlatObject(e,s,function(e){return e!==Error.prototype},e=>"isAxiosError"!==e),Ct.call(s,e.message,t,r,i,o),s.cause=e,s.name=e.name,n&&Object.assign(s,n),s};function Nt(e){return At.isPlainObject(e)||At.isArray(e)}function _t(e){return At.endsWith(e,"[]")?e.slice(0,-2):e}function Pt(e,t,r){return e?e.concat(t).map(function(e,t){return e=_t(e),!r&&t?"["+e+"]":e}).join(r?".":""):t}const Ft=At.toFlatObject(At,{},null,function(e){return/^is[A-Z]/.test(e)});function Ot(e,t,r){if(!At.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const i=(r=At.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!At.isUndefined(t[e])})).metaTokens,o=r.visitor||l,n=r.dots,s=r.indexes,a=(r.Blob||"undefined"!=typeof Blob&&Blob)&&At.isSpecCompliantForm(t);if(!At.isFunction(o))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(At.isDate(e))return e.toISOString();if(At.isBoolean(e))return e.toString();if(!a&&At.isBlob(e))throw new Ct("Blob is not supported. Use a Buffer instead.");return At.isArrayBuffer(e)||At.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):be.from(e):e}function l(e,r,o){let a=e;if(e&&!o&&"object"==typeof e)if(At.endsWith(r,"{}"))r=i?r:r.slice(0,-2),e=JSON.stringify(e);else if(At.isArray(e)&&function(e){return At.isArray(e)&&!e.some(Nt)}(e)||(At.isFileList(e)||At.endsWith(r,"[]"))&&(a=At.toArray(e)))return r=_t(r),a.forEach(function(e,i){!At.isUndefined(e)&&null!==e&&t.append(!0===s?Pt([r],i,n):null===s?r:r+"[]",c(e))}),!1;return!!Nt(e)||(t.append(Pt(o,r,n),c(e)),!1)}const d=[],u=Object.assign(Ft,{defaultVisitor:l,convertValue:c,isVisitable:Nt});if(!At.isObject(e))throw new TypeError("data must be an object");return function e(r,i){if(!At.isUndefined(r)){if(-1!==d.indexOf(r))throw Error("Circular reference detected in "+i.join("."));d.push(r),At.forEach(r,function(r,n){!0===(!(At.isUndefined(r)||null===r)&&o.call(t,r,At.isString(n)?n.trim():n,i,u))&&e(r,i?i.concat(n):[n])}),d.pop()}}(e),t}function Dt(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function zt(e,t){this._pairs=[],e&&Ot(e,this,t)}const Bt=zt.prototype;function Mt(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Kt(e,t,r){if(!t)return e;const i=r&&r.encode||Mt;At.isFunction(r)&&(r={serialize:r});const o=r&&r.serialize;let n;if(n=o?o(t,r):At.isURLSearchParams(t)?t.toString():new zt(t,r).toString(i),n){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+n}return e}Bt.append=function(e,t){this._pairs.push([e,t])},Bt.toString=function(e){const t=e?function(t){return e.call(this,t,Dt)}:Dt;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};class Ut{constructor(){this.handlers=[]}use(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){At.forEach(this.handlers,function(t){null!==t&&e(t)})}}const Lt={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},$t={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:zt,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},Ht="undefined"!=typeof window&&"undefined"!=typeof document,qt="object"==typeof navigator&&navigator||void 0,jt=Ht&&(!qt||["ReactNative","NativeScript","NS"].indexOf(qt.product)<0),Wt="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,Vt=Ht&&window.location.href||"http://localhost",Gt={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Ht,hasStandardBrowserEnv:jt,hasStandardBrowserWebWorkerEnv:Wt,navigator:qt,origin:Vt},Symbol.toStringTag,{value:"Module"})),...$t};function Jt(e){function t(e,r,i,o){let n=e[o++];if("__proto__"===n)return!0;const s=Number.isFinite(+n),a=o>=e.length;if(n=!n&&At.isArray(i)?i.length:n,a)return At.hasOwnProp(i,n)?i[n]=[i[n],r]:i[n]=r,!s;i[n]&&At.isObject(i[n])||(i[n]=[]);return t(e,r,i[n],o)&&At.isArray(i[n])&&(i[n]=function(e){const t={},r=Object.keys(e);let i;const o=r.length;let n;for(i=0;i<o;i++)n=r[i],t[n]=e[n];return t}(i[n])),!s}if(At.isFormData(e)&&At.isFunction(e.entries)){const r={};return At.forEachEntry(e,(e,i)=>{t(function(e){return At.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0])}(e),i,r,0)}),r}return null}const Yt={transitional:Lt,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const r=t.getContentType()||"",i=r.indexOf("application/json")>-1,o=At.isObject(e);o&&At.isHTMLForm(e)&&(e=new FormData(e));if(At.isFormData(e))return i?JSON.stringify(Jt(e)):e;if(At.isArrayBuffer(e)||At.isBuffer(e)||At.isStream(e)||At.isFile(e)||At.isBlob(e)||At.isReadableStream(e))return e;if(At.isArrayBufferView(e))return e.buffer;if(At.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let n;if(o){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return Ot(e,new Gt.classes.URLSearchParams,{visitor:function(e,t,r,i){return Gt.isNode&&At.isBuffer(e)?(this.append(t,e.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},...t})}(e,this.formSerializer).toString();if((n=At.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return Ot(n?{"files[]":e}:e,t&&new t,this.formSerializer)}}return o||i?(t.setContentType("application/json",!1),function(e,t,r){if(At.isString(e))try{return(t||JSON.parse)(e),At.trim(e)}catch(i){if("SyntaxError"!==i.name)throw i}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||Yt.transitional,r=t&&t.forcedJSONParsing,i="json"===this.responseType;if(At.isResponse(e)||At.isReadableStream(e))return e;if(e&&At.isString(e)&&(r&&!this.responseType||i)){const r=!(t&&t.silentJSONParsing)&&i;try{return JSON.parse(e)}catch(o){if(r){if("SyntaxError"===o.name)throw Ct.from(o,Ct.ERR_BAD_RESPONSE,this,null,this.response);throw o}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Gt.classes.FormData,Blob:Gt.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};At.forEach(["delete","get","head","post","put","patch"],e=>{Yt.headers[e]={}});const Xt=At.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),Zt=Symbol("internals");function Qt(e){return e&&String(e).trim().toLowerCase()}function er(e){return!1===e||null==e?e:At.isArray(e)?e.map(er):String(e)}function tr(e,t,r,i,o){return At.isFunction(i)?i.call(this,t,r):(o&&(t=r),At.isString(t)?At.isString(i)?-1!==t.indexOf(i):At.isRegExp(i)?i.test(t):void 0:void 0)}let rr=class{constructor(e){e&&this.set(e)}set(e,t,r){const i=this;function o(e,t,r){const o=Qt(t);if(!o)throw new Error("header name must be a non-empty string");const n=At.findKey(i,o);(!n||void 0===i[n]||!0===r||void 0===r&&!1!==i[n])&&(i[n||t]=er(e))}const n=(e,t)=>At.forEach(e,(e,r)=>o(e,r,t));if(At.isPlainObject(e)||e instanceof this.constructor)n(e,t);else if(At.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))n((e=>{const t={};let r,i,o;return e&&e.split("\n").forEach(function(e){o=e.indexOf(":"),r=e.substring(0,o).trim().toLowerCase(),i=e.substring(o+1).trim(),!r||t[r]&&Xt[r]||("set-cookie"===r?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)}),t})(e),t);else if(At.isObject(e)&&At.isIterable(e)){let r,i,o={};for(const t of e){if(!At.isArray(t))throw TypeError("Object iterator must return a key-value pair");o[i=t[0]]=(r=o[i])?At.isArray(r)?[...r,t[1]]:[r,t[1]]:t[1]}n(o,t)}else null!=e&&o(t,e,r);return this}get(e,t){if(e=Qt(e)){const r=At.findKey(this,e);if(r){const e=this[r];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let i;for(;i=r.exec(e);)t[i[1]]=i[2];return t}(e);if(At.isFunction(t))return t.call(this,e,r);if(At.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=Qt(e)){const r=At.findKey(this,e);return!(!r||void 0===this[r]||t&&!tr(0,this[r],r,t))}return!1}delete(e,t){const r=this;let i=!1;function o(e){if(e=Qt(e)){const o=At.findKey(r,e);!o||t&&!tr(0,r[o],o,t)||(delete r[o],i=!0)}}return At.isArray(e)?e.forEach(o):o(e),i}clear(e){const t=Object.keys(this);let r=t.length,i=!1;for(;r--;){const o=t[r];e&&!tr(0,this[o],o,e,!0)||(delete this[o],i=!0)}return i}normalize(e){const t=this,r={};return At.forEach(this,(i,o)=>{const n=At.findKey(r,o);if(n)return t[n]=er(i),void delete t[o];const s=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,r)=>t.toUpperCase()+r)}(o):String(o).trim();s!==o&&delete t[o],t[s]=er(i),r[s]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return At.forEach(this,(r,i)=>{null!=r&&!1!==r&&(t[i]=e&&At.isArray(r)?r.join(", "):r)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const r=new this(e);return t.forEach(e=>r.set(e)),r}static accessor(e){const t=(this[Zt]=this[Zt]={accessors:{}}).accessors,r=this.prototype;function i(e){const i=Qt(e);t[i]||(!function(e,t){const r=At.toCamelCase(" "+t);["get","set","has"].forEach(i=>{Object.defineProperty(e,i+r,{value:function(e,r,o){return this[i].call(this,t,e,r,o)},configurable:!0})})}(r,e),t[i]=!0)}return At.isArray(e)?e.forEach(i):i(e),this}};function ir(e,t){const r=this||Yt,i=t||r,o=rr.from(i.headers);let n=i.data;return At.forEach(e,function(e){n=e.call(r,n,o.normalize(),t?t.status:void 0)}),o.normalize(),n}function or(e){return!(!e||!e.__CANCEL__)}function nr(e,t,r){Ct.call(this,null==e?"canceled":e,Ct.ERR_CANCELED,t,r),this.name="CanceledError"}function sr(e,t,r){const i=r.config.validateStatus;r.status&&i&&!i(r.status)?t(new Ct("Request failed with status code "+r.status,[Ct.ERR_BAD_REQUEST,Ct.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}rr.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),At.reduceDescriptors(rr.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}}),At.freezeMethods(rr),At.inherits(nr,Ct,{__CANCEL__:!0});const ar=(e,t,r=3)=>{let i=0;const o=function(e,t){e=e||10;const r=new Array(e),i=new Array(e);let o,n=0,s=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),l=i[s];o||(o=c),r[n]=a,i[n]=c;let d=s,u=0;for(;d!==n;)u+=r[d++],d%=e;if(n=(n+1)%e,n===s&&(s=(s+1)%e),c-o<t)return;const p=l&&c-l;return p?Math.round(1e3*u/p):void 0}}(50,250);return function(e,t){let r,i,o=0,n=1e3/t;const s=(t,n=Date.now())=>{o=n,r=null,i&&(clearTimeout(i),i=null),e(...t)};return[(...e)=>{const t=Date.now(),a=t-o;a>=n?s(e,t):(r=e,i||(i=setTimeout(()=>{i=null,s(r)},n-a)))},()=>r&&s(r)]}(r=>{const n=r.loaded,s=r.lengthComputable?r.total:void 0,a=n-i,c=o(a);i=n;e({loaded:n,total:s,progress:s?n/s:void 0,bytes:a,rate:c||void 0,estimated:c&&s&&n<=s?(s-n)/c:void 0,event:r,lengthComputable:null!=s,[t?"download":"upload"]:!0})},r)},cr=(e,t)=>{const r=null!=e;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},lr=e=>(...t)=>At.asap(()=>e(...t)),dr=Gt.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,Gt.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(Gt.origin),Gt.navigator&&/(msie|trident)/i.test(Gt.navigator.userAgent)):()=>!0,ur=Gt.hasStandardBrowserEnv?{write(e,t,r,i,o,n){const s=[e+"="+encodeURIComponent(t)];At.isNumber(r)&&s.push("expires="+new Date(r).toGMTString()),At.isString(i)&&s.push("path="+i),At.isString(o)&&s.push("domain="+o),!0===n&&s.push("secure"),document.cookie=s.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function pr(e,t,r){let i=!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t);return e&&(i||0==r)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const hr=e=>e instanceof rr?{...e}:e;function gr(e,t){t=t||{};const r={};function i(e,t,r,i){return At.isPlainObject(e)&&At.isPlainObject(t)?At.merge.call({caseless:i},e,t):At.isPlainObject(t)?At.merge({},t):At.isArray(t)?t.slice():t}function o(e,t,r,o){return At.isUndefined(t)?At.isUndefined(e)?void 0:i(void 0,e,0,o):i(e,t,0,o)}function n(e,t){if(!At.isUndefined(t))return i(void 0,t)}function s(e,t){return At.isUndefined(t)?At.isUndefined(e)?void 0:i(void 0,e):i(void 0,t)}function a(r,o,n){return n in t?i(r,o):n in e?i(void 0,r):void 0}const c={url:n,method:n,data:n,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:a,headers:(e,t,r)=>o(hr(e),hr(t),0,!0)};return At.forEach(Object.keys({...e,...t}),function(i){const n=c[i]||o,s=n(e[i],t[i],i);At.isUndefined(s)&&n!==a||(r[i]=s)}),r}const mr=e=>{const t=gr({},e);let r,{data:i,withXSRFToken:o,xsrfHeaderName:n,xsrfCookieName:s,headers:a,auth:c}=t;if(t.headers=a=rr.from(a),t.url=Kt(pr(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),At.isFormData(i))if(Gt.hasStandardBrowserEnv||Gt.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(!1!==(r=a.getContentType())){const[e,...t]=r?r.split(";").map(e=>e.trim()).filter(Boolean):[];a.setContentType([e||"multipart/form-data",...t].join("; "))}if(Gt.hasStandardBrowserEnv&&(o&&At.isFunction(o)&&(o=o(t)),o||!1!==o&&dr(t.url))){const e=n&&s&&ur.read(s);e&&a.set(n,e)}return t},fr="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise(function(t,r){const i=mr(e);let o=i.data;const n=rr.from(i.headers).normalize();let s,a,c,l,d,{responseType:u,onUploadProgress:p,onDownloadProgress:h}=i;function g(){l&&l(),d&&d(),i.cancelToken&&i.cancelToken.unsubscribe(s),i.signal&&i.signal.removeEventListener("abort",s)}let m=new XMLHttpRequest;function f(){if(!m)return;const i=rr.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders());sr(function(e){t(e),g()},function(e){r(e),g()},{data:u&&"text"!==u&&"json"!==u?m.response:m.responseText,status:m.status,statusText:m.statusText,headers:i,config:e,request:m}),m=null}m.open(i.method.toUpperCase(),i.url,!0),m.timeout=i.timeout,"onloadend"in m?m.onloadend=f:m.onreadystatechange=function(){m&&4===m.readyState&&(0!==m.status||m.responseURL&&0===m.responseURL.indexOf("file:"))&&setTimeout(f)},m.onabort=function(){m&&(r(new Ct("Request aborted",Ct.ECONNABORTED,e,m)),m=null)},m.onerror=function(){r(new Ct("Network Error",Ct.ERR_NETWORK,e,m)),m=null},m.ontimeout=function(){let t=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const o=i.transitional||Lt;i.timeoutErrorMessage&&(t=i.timeoutErrorMessage),r(new Ct(t,o.clarifyTimeoutError?Ct.ETIMEDOUT:Ct.ECONNABORTED,e,m)),m=null},void 0===o&&n.setContentType(null),"setRequestHeader"in m&&At.forEach(n.toJSON(),function(e,t){m.setRequestHeader(t,e)}),At.isUndefined(i.withCredentials)||(m.withCredentials=!!i.withCredentials),u&&"json"!==u&&(m.responseType=i.responseType),h&&([c,d]=ar(h,!0),m.addEventListener("progress",c)),p&&m.upload&&([a,l]=ar(p),m.upload.addEventListener("progress",a),m.upload.addEventListener("loadend",l)),(i.cancelToken||i.signal)&&(s=t=>{m&&(r(!t||t.type?new nr(null,e,m):t),m.abort(),m=null)},i.cancelToken&&i.cancelToken.subscribe(s),i.signal&&(i.signal.aborted?s():i.signal.addEventListener("abort",s)));const y=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(i.url);y&&-1===Gt.protocols.indexOf(y)?r(new Ct("Unsupported protocol "+y+":",Ct.ERR_BAD_REQUEST,e)):m.send(o||null)})},yr=(e,t)=>{const{length:r}=e=e?e.filter(Boolean):[];if(t||r){let r,i=new AbortController;const o=function(e){if(!r){r=!0,s();const t=e instanceof Error?e:this.reason;i.abort(t instanceof Ct?t:new nr(t instanceof Error?t.message:t))}};let n=t&&setTimeout(()=>{n=null,o(new Ct(`timeout ${t} of ms exceeded`,Ct.ETIMEDOUT))},t);const s=()=>{e&&(n&&clearTimeout(n),n=null,e.forEach(e=>{e.unsubscribe?e.unsubscribe(o):e.removeEventListener("abort",o)}),e=null)};e.forEach(e=>e.addEventListener("abort",o));const{signal:a}=i;return a.unsubscribe=()=>At.asap(s),a}},br=function*(e,t){let r=e.byteLength;if(r<t)return void(yield e);let i,o=0;for(;o<r;)i=o+t,yield e.slice(o,i),o=i},wr=async function*(e){if(e[Symbol.asyncIterator])return void(yield*e);const t=e.getReader();try{for(;;){const{done:e,value:r}=await t.read();if(e)break;yield r}}finally{await t.cancel()}},Ir=(e,t,r,i)=>{const o=async function*(e,t){for await(const r of wr(e))yield*br(r,t)}(e,t);let n,s=0,a=e=>{n||(n=!0,i&&i(e))};return new ReadableStream({async pull(e){try{const{done:t,value:i}=await o.next();if(t)return a(),void e.close();let n=i.byteLength;if(r){let e=s+=n;r(e)}e.enqueue(new Uint8Array(i))}catch(t){throw a(t),t}},cancel:e=>(a(e),o.return())},{highWaterMark:2})},Tr="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,Sr=Tr&&"function"==typeof ReadableStream,kr=Tr&&("function"==typeof TextEncoder?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),Er=(e,...t)=>{try{return!!e(...t)}catch(r){return!1}},vr=Sr&&Er(()=>{let e=!1;const t=new Request(Gt.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),Ar=Sr&&Er(()=>At.isReadableStream(new Response("").body)),Cr={stream:Ar&&(e=>e.body)};var xr;Tr&&(xr=new Response,["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!Cr[e]&&(Cr[e]=At.isFunction(xr[e])?t=>t[e]():(t,r)=>{throw new Ct(`Response type '${e}' is not supported`,Ct.ERR_NOT_SUPPORT,r)})}));const Rr=async(e,t)=>{const r=At.toFiniteNumber(e.getContentLength());return null==r?(async e=>{if(null==e)return 0;if(At.isBlob(e))return e.size;if(At.isSpecCompliantForm(e)){const t=new Request(Gt.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return At.isArrayBufferView(e)||At.isArrayBuffer(e)?e.byteLength:(At.isURLSearchParams(e)&&(e+=""),At.isString(e)?(await kr(e)).byteLength:void 0)})(t):r},Nr={http:null,xhr:fr,fetch:Tr&&(async e=>{let{url:t,method:r,data:i,signal:o,cancelToken:n,timeout:s,onDownloadProgress:a,onUploadProgress:c,responseType:l,headers:d,withCredentials:u="same-origin",fetchOptions:p}=mr(e);l=l?(l+"").toLowerCase():"text";let h,g=yr([o,n&&n.toAbortSignal()],s);const m=g&&g.unsubscribe&&(()=>{g.unsubscribe()});let f;try{if(c&&vr&&"get"!==r&&"head"!==r&&0!==(f=await Rr(d,i))){let e,r=new Request(t,{method:"POST",body:i,duplex:"half"});if(At.isFormData(i)&&(e=r.headers.get("content-type"))&&d.setContentType(e),r.body){const[e,t]=cr(f,ar(lr(c)));i=Ir(r.body,65536,e,t)}}At.isString(u)||(u=u?"include":"omit");const o="credentials"in Request.prototype;h=new Request(t,{...p,signal:g,method:r.toUpperCase(),headers:d.normalize().toJSON(),body:i,duplex:"half",credentials:o?u:void 0});let n=await fetch(h,p);const s=Ar&&("stream"===l||"response"===l);if(Ar&&(a||s&&m)){const e={};["status","statusText","headers"].forEach(t=>{e[t]=n[t]});const t=At.toFiniteNumber(n.headers.get("content-length")),[r,i]=a&&cr(t,ar(lr(a),!0))||[];n=new Response(Ir(n.body,65536,r,()=>{i&&i(),m&&m()}),e)}l=l||"text";let y=await Cr[At.findKey(Cr,l)||"text"](n,e);return!s&&m&&m(),await new Promise((t,r)=>{sr(t,r,{data:y,headers:rr.from(n.headers),status:n.status,statusText:n.statusText,config:e,request:h})})}catch(y){if(m&&m(),y&&"TypeError"===y.name&&/Load failed|fetch/i.test(y.message))throw Object.assign(new Ct("Network Error",Ct.ERR_NETWORK,e,h),{cause:y.cause||y});throw Ct.from(y,y&&y.code,e,h)}})};At.forEach(Nr,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(r){}Object.defineProperty(e,"adapterName",{value:t})}});const _r=e=>`- ${e}`,Pr=e=>At.isFunction(e)||null===e||!1===e,Fr=e=>{e=At.isArray(e)?e:[e];const{length:t}=e;let r,i;const o={};for(let n=0;n<t;n++){let t;if(r=e[n],i=r,!Pr(r)&&(i=Nr[(t=String(r)).toLowerCase()],void 0===i))throw new Ct(`Unknown adapter '${t}'`);if(i)break;o[t||"#"+n]=i}if(!i){const e=Object.entries(o).map(([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build"));throw new Ct("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(_r).join("\n"):" "+_r(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return i};function Or(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new nr(null,e)}function Dr(e){Or(e),e.headers=rr.from(e.headers),e.data=ir.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return Fr(e.adapter||Yt.adapter)(e).then(function(t){return Or(e),t.data=ir.call(e,e.transformResponse,t),t.headers=rr.from(t.headers),t},function(t){return or(t)||(Or(e),t&&t.response&&(t.response.data=ir.call(e,e.transformResponse,t.response),t.response.headers=rr.from(t.response.headers))),Promise.reject(t)})}const zr="1.11.0",Br={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Br[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const Mr={};Br.transitional=function(e,t,r){function i(e,t){return"[Axios v"+zr+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,o,n)=>{if(!1===e)throw new Ct(i(o," has been removed"+(t?" in "+t:"")),Ct.ERR_DEPRECATED);return t&&!Mr[o]&&(Mr[o]=!0,console.warn(i(o," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,o,n)}},Br.spelling=function(e){return(t,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};const Kr={assertOptions:function(e,t,r){if("object"!=typeof e)throw new Ct("options must be an object",Ct.ERR_BAD_OPTION_VALUE);const i=Object.keys(e);let o=i.length;for(;o-- >0;){const n=i[o],s=t[n];if(s){const t=e[n],r=void 0===t||s(t,n,e);if(!0!==r)throw new Ct("option "+n+" must be "+r,Ct.ERR_BAD_OPTION_VALUE);continue}if(!0!==r)throw new Ct("Unknown option "+n,Ct.ERR_BAD_OPTION)}},validators:Br},Ur=Kr.validators;let Lr=class{constructor(e){this.defaults=e||{},this.interceptors={request:new Ut,response:new Ut}}async request(e,t){try{return await this._request(e,t)}catch(r){if(r instanceof Error){let e={};Error.captureStackTrace?Error.captureStackTrace(e):e=new Error;const t=e.stack?e.stack.replace(/^.+\n/,""):"";try{r.stack?t&&!String(r.stack).endsWith(t.replace(/^.+\n.+\n/,""))&&(r.stack+="\n"+t):r.stack=t}catch(i){}}throw r}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=gr(this.defaults,t);const{transitional:r,paramsSerializer:i,headers:o}=t;void 0!==r&&Kr.assertOptions(r,{silentJSONParsing:Ur.transitional(Ur.boolean),forcedJSONParsing:Ur.transitional(Ur.boolean),clarifyTimeoutError:Ur.transitional(Ur.boolean)},!1),null!=i&&(At.isFunction(i)?t.paramsSerializer={serialize:i}:Kr.assertOptions(i,{encode:Ur.function,serialize:Ur.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Kr.assertOptions(t,{baseUrl:Ur.spelling("baseURL"),withXsrfToken:Ur.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let n=o&&At.merge(o.common,o[t.method]);o&&At.forEach(["delete","get","head","post","put","patch","common"],e=>{delete o[e]}),t.headers=rr.concat(n,o);const s=[];let a=!0;this.interceptors.request.forEach(function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,s.unshift(e.fulfilled,e.rejected))});const c=[];let l;this.interceptors.response.forEach(function(e){c.push(e.fulfilled,e.rejected)});let d,u=0;if(!a){const e=[Dr.bind(this),void 0];for(e.unshift(...s),e.push(...c),d=e.length,l=Promise.resolve(t);u<d;)l=l.then(e[u++],e[u++]);return l}d=s.length;let p=t;for(u=0;u<d;){const e=s[u++],t=s[u++];try{p=e(p)}catch(h){t.call(this,h);break}}try{l=Dr.call(this,p)}catch(h){return Promise.reject(h)}for(u=0,d=c.length;u<d;)l=l.then(c[u++],c[u++]);return l}getUri(e){return Kt(pr((e=gr(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};At.forEach(["delete","get","head","options"],function(e){Lr.prototype[e]=function(t,r){return this.request(gr(r||{},{method:e,url:t,data:(r||{}).data}))}}),At.forEach(["post","put","patch"],function(e){function t(t){return function(r,i,o){return this.request(gr(o||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:i}))}}Lr.prototype[e]=t(),Lr.prototype[e+"Form"]=t(!0)});const $r={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries($r).forEach(([e,t])=>{$r[t]=e});const Hr=function e(t){const r=new Lr(t),i=Me(Lr.prototype.request,r);return At.extend(i,Lr.prototype,r,{allOwnKeys:!0}),At.extend(i,r,null,{allOwnKeys:!0}),i.create=function(r){return e(gr(t,r))},i}(Yt);Hr.Axios=Lr,Hr.CanceledError=nr,Hr.CancelToken=class e{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(e){t=e});const r=this;this.promise.then(e=>{if(!r._listeners)return;let t=r._listeners.length;for(;t-- >0;)r._listeners[t](e);r._listeners=null}),this.promise.then=e=>{let t;const i=new Promise(e=>{r.subscribe(e),t=e}).then(e);return i.cancel=function(){r.unsubscribe(t)},i},e(function(e,i,o){r.reason||(r.reason=new nr(e,i,o),t(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let t;return{token:new e(function(e){t=e}),cancel:t}}},Hr.isCancel=or,Hr.VERSION=zr,Hr.toFormData=Ot,Hr.AxiosError=Ct,Hr.Cancel=Hr.CanceledError,Hr.all=function(e){return Promise.all(e)},Hr.spread=function(e){return function(t){return e.apply(null,t)}},Hr.isAxiosError=function(e){return At.isObject(e)&&!0===e.isAxiosError},Hr.mergeConfig=gr,Hr.AxiosHeaders=rr,Hr.formToJSON=e=>Jt(At.isHTMLForm(e)?new FormData(e):e),Hr.getAdapter=Fr,Hr.HttpStatusCode=$r,Hr.default=Hr;const{Axios:qr,AxiosError:jr,CanceledError:Wr,isCancel:Vr,CancelToken:Gr,VERSION:Jr,all:Yr,Cancel:Xr,isAxiosError:Zr,spread:Qr,toFormData:ei,AxiosHeaders:ti,HttpStatusCode:ri,formToJSON:ii,getAdapter:oi,mergeConfig:ni}=Hr,si=class e{constructor(){se(this,"isProduction"),this.isProduction="production"===Be.env.NODE_ENV}static getInstance(){return e.instance||(e.instance=new e),e.instance}debug(e,...t){this.isProduction||console.debug(e,...t)}info(e,...t){this.isProduction||console.info(e,...t)}warn(e,...t){console.warn(e,...t)}error(e,...t){console.error(e,...t)}};se(si,"instance");let ai=si;class ci extends Error{constructor(e){super(e),this.name="ValidationError"}}class li{constructor(e){if(se(this,"accountId"),se(this,"privateKey"),se(this,"baseUrl"),se(this,"network"),this.accountId=e.accountId,"string"==typeof e.privateKey){const t=s.detectKeyTypeFromString(e.privateKey);this.privateKey=t.privateKey}else this.privateKey=e.privateKey;this.network=e.network||"mainnet",this.baseUrl=e.baseUrl||"https://kiloscribe.com"}async authenticate(){var e,t,r;const i=await Hr.get(`${this.baseUrl}/api/auth/request-signature`,{headers:{"x-session":this.accountId}});if(!(null==(e=i.data)?void 0:e.message))throw new Error("Failed to get signature message");const o=i.data.message,n=await this.signMessage(o),s=await Hr.post(`${this.baseUrl}/api/auth/authenticate`,{authData:{id:this.accountId,signature:n,data:o,network:this.network},include:"apiKey"});if(!(null==(r=null==(t=s.data)?void 0:t.user)?void 0:r.sessionToken))throw new Error("Authentication failed");return{apiKey:s.data.apiKey}}async signMessage(e){const t=(new TextEncoder).encode(e),r=await this.privateKey.sign(t);return we.from(r).toString("hex")}}class di{constructor(e){se(this,"accountId"),se(this,"signer"),se(this,"baseUrl"),se(this,"network"),se(this,"logger"),this.accountId=e.accountId,this.signer=e.signer,this.network=e.network||"mainnet",this.baseUrl=e.baseUrl||"https://kiloscribe.com",this.logger=e.logger}async authenticate(){var e,t,r;const i=await Hr.get(`${this.baseUrl}/api/auth/request-signature`,{headers:{"x-session":this.accountId}});if(!(null==(e=i.data)?void 0:e.message))throw new Error("Failed to get signature message");const o=i.data.message,n=await this.signMessage(JSON.stringify(o)),s=await Hr.post(`${this.baseUrl}/api/auth/authenticate`,{authData:{id:this.accountId,signature:n,data:o,network:this.network},include:"apiKey"});if(!(null==(r=null==(t=s.data)?void 0:t.user)?void 0:r.sessionToken))throw new Error("Authentication failed");return{apiKey:s.data.apiKey}}async signMessage(e){try{const t=(new TextEncoder).encode(e);this.logger.debug("signing message");const r=await this.signer.sign([t],{encoding:"utf-8"});return we.from(null==r?void 0:r[0].signature).toString("hex")}catch(t){throw this.logger.error("Failed to sign message",t),new Error("Failed to sign message")}}}function ui(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function pi(e){return new DataView(e.buffer,e.byteOffset)}const hi={len:1,get:(e,t)=>pi(e).getUint8(t),put:(e,t,r)=>(pi(e).setUint8(t,r),t+1)},gi={len:2,get:(e,t)=>pi(e).getUint16(t,!0),put:(e,t,r)=>(pi(e).setUint16(t,r,!0),t+2)},mi={len:2,get:(e,t)=>pi(e).getUint16(t),put:(e,t,r)=>(pi(e).setUint16(t,r),t+2)},fi={len:4,get:(e,t)=>pi(e).getUint32(t,!0),put:(e,t,r)=>(pi(e).setUint32(t,r,!0),t+4)},yi={len:4,get:(e,t)=>pi(e).getUint32(t),put:(e,t,r)=>(pi(e).setUint32(t,r),t+4)},bi={len:4,get:(e,t)=>pi(e).getInt32(t),put:(e,t,r)=>(pi(e).setInt32(t,r),t+4)},wi={len:8,get:(e,t)=>pi(e).getBigUint64(t,!0),put:(e,t,r)=>(pi(e).setBigUint64(t,r,!0),t+8)};class Ii{constructor(e,t){if(this.len=e,t&&"windows-1252"===t.toLowerCase())this.decoder=Ii.decodeWindows1252;else{const e=new TextDecoder(t);this.decoder=t=>e.decode(t)}}get(e,t=0){const r=e.subarray(t,t+this.len);return this.decoder(r)}static decodeWindows1252(e){let t="";for(let r=0;r<e.length;r++){const i=e[r];t+=i<128||i>=160?String.fromCharCode(i):Ii.win1252Map[i-128]}return t}}Ii.win1252Map="€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ";class Ti extends Error{constructor(){super("End-Of-Stream"),this.name="EndOfStreamError"}}class Si extends Error{constructor(e="The operation was aborted"){super(e),this.name="AbortError"}}class ki{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(e,t=!1){const r=await this.read(e,t);return this.peekQueue.push(e.subarray(0,r)),r}async read(e,t=!1){if(0===e.length)return 0;let r=this.readFromPeekBuffer(e);if(this.endOfStream||(r+=await this.readRemainderFromStream(e.subarray(r),t)),0===r&&!t)throw new Ti;return r}readFromPeekBuffer(e){let t=e.length,r=0;for(;this.peekQueue.length>0&&t>0;){const i=this.peekQueue.pop();if(!i)throw new Error("peekData should be defined");const o=Math.min(i.length,t);e.set(i.subarray(0,o),r),r+=o,t-=o,o<i.length&&this.peekQueue.push(i.subarray(o))}return r}async readRemainderFromStream(e,t){let r=0;for(;r<e.length&&!this.endOfStream;){if(this.interrupted)throw new Si;const i=await this.readFromStream(e.subarray(r),t);if(0===i)break;r+=i}if(!t&&r<e.length)throw new Ti;return r}}class Ei extends ki{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}}class vi extends Ei{async readFromStream(e,t){if(0===e.length)return 0;const r=await this.reader.read(new Uint8Array(e.length),{min:t?void 0:e.length});return r.done&&(this.endOfStream=r.done),r.value?(e.set(r.value),r.value.length):0}}class Ai extends ki{constructor(e){super(),this.reader=e,this.buffer=null}writeChunk(e,t){const r=Math.min(t.length,e.length);return e.set(t.subarray(0,r)),r<t.length?this.buffer=t.subarray(r):this.buffer=null,r}async readFromStream(e,t){if(0===e.length)return 0;let r=0;for(this.buffer&&(r+=this.writeChunk(e,this.buffer));r<e.length&&!this.endOfStream;){const t=await this.reader.read();if(t.done){this.endOfStream=!0;break}t.value&&(r+=this.writeChunk(e.subarray(r),t.value))}if(!t&&0===r&&this.endOfStream)throw new Ti;return r}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}}class Ci{constructor(e){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=null==e?void 0:e.onClose,(null==e?void 0:e.abortSignal)&&e.abortSignal.addEventListener("abort",()=>{this.abort()})}async readToken(e,t=this.position){const r=new Uint8Array(e.len);if(await this.readBuffer(r,{position:t})<e.len)throw new Ti;return e.get(r,0)}async peekToken(e,t=this.position){const r=new Uint8Array(e.len);if(await this.peekBuffer(r,{position:t})<e.len)throw new Ti;return e.get(r,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new Ti;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new Ti;return e.get(this.numBuffer,0)}async ignore(e){if(void 0!==this.fileInfo.size){const t=this.fileInfo.size-this.position;if(e>t)return this.position+=t,t}return this.position+=e,e}async close(){var e;await this.abort(),await(null==(e=this.onClose)?void 0:e.call(this))}normalizeOptions(e,t){if(!this.supportsRandomAccess()&&t&&void 0!==t.position&&t.position<this.position)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");return{mayBeLess:!1,offset:0,length:e.length,position:this.position,...t}}abort(){return Promise.resolve()}}class xi extends Ci{constructor(e,t){super(t),this.streamReader=e,this.fileInfo=(null==t?void 0:t.fileInfo)??{}}async readBuffer(e,t){const r=this.normalizeOptions(e,t),i=r.position-this.position;if(i>0)return await this.ignore(i),this.readBuffer(e,t);if(i<0)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");if(0===r.length)return 0;const o=await this.streamReader.read(e.subarray(0,r.length),r.mayBeLess);if(this.position+=o,(!t||!t.mayBeLess)&&o<r.length)throw new Ti;return o}async peekBuffer(e,t){const r=this.normalizeOptions(e,t);let i=0;if(r.position){const t=r.position-this.position;if(t>0){const o=new Uint8Array(r.length+t);return i=await this.peekBuffer(o,{mayBeLess:r.mayBeLess}),e.set(o.subarray(t)),i-t}if(t<0)throw new Error("Cannot peek from a negative offset in a stream")}if(r.length>0){try{i=await this.streamReader.peek(e.subarray(0,r.length),r.mayBeLess)}catch(o){if((null==t?void 0:t.mayBeLess)&&o instanceof Ti)return 0;throw o}if(!r.mayBeLess&&i<r.length)throw new Ti}return i}async ignore(e){const t=Math.min(256e3,e),r=new Uint8Array(t);let i=0;for(;i<e;){const o=e-i,n=await this.readBuffer(r,{length:Math.min(t,o)});if(n<0)return n;i+=n}return i}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}}class Ri extends Ci{constructor(e,t){super(t),this.uint8Array=e,this.fileInfo={...(null==t?void 0:t.fileInfo)??{},size:e.length}}async readBuffer(e,t){(null==t?void 0:t.position)&&(this.position=t.position);const r=await this.peekBuffer(e,t);return this.position+=r,r}async peekBuffer(e,t){const r=this.normalizeOptions(e,t),i=Math.min(this.uint8Array.length-r.position,r.length);if(!r.mayBeLess&&i<r.length)throw new Ti;return e.set(this.uint8Array.subarray(r.position,r.position+i)),i}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}}function Ni(e,t){const r=function(e){try{const t=e.getReader({mode:"byob"});return t instanceof ReadableStreamDefaultReader?new Ai(t):new vi(t)}catch(t){if(t instanceof TypeError)return new Ai(e.getReader());throw t}}(e),i=t??{},o=i.onClose;return i.onClose=async()=>{if(await r.close(),o)return o()},new xi(r,i)}var _i=Uint8Array,Pi=Uint16Array,Fi=Int32Array,Oi=new _i([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Di=new _i([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),zi=new _i([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Bi=function(e,t){for(var r=new Pi(31),i=0;i<31;++i)r[i]=t+=1<<e[i-1];var o=new Fi(r[30]);for(i=1;i<30;++i)for(var n=r[i];n<r[i+1];++n)o[n]=n-r[i]<<5|i;return{b:r,r:o}},Mi=Bi(Oi,2),Ki=Mi.b,Ui=Mi.r;Ki[28]=258,Ui[258]=28;for(var Li=Bi(Di,0).b,$i=new Pi(32768),Hi=0;Hi<32768;++Hi){var qi=(43690&Hi)>>1|(21845&Hi)<<1;qi=(61680&(qi=(52428&qi)>>2|(13107&qi)<<2))>>4|(3855&qi)<<4,$i[Hi]=((65280&qi)>>8|(255&qi)<<8)>>1}var ji=function(e,t,r){for(var i=e.length,o=0,n=new Pi(t);o<i;++o)e[o]&&++n[e[o]-1];var s,a=new Pi(t);for(o=1;o<t;++o)a[o]=a[o-1]+n[o-1]<<1;s=new Pi(1<<t);var c=15-t;for(o=0;o<i;++o)if(e[o])for(var l=o<<4|e[o],d=t-e[o],u=a[e[o]-1]++<<d,p=u|(1<<d)-1;u<=p;++u)s[$i[u]>>c]=l;return s},Wi=new _i(288);for(Hi=0;Hi<144;++Hi)Wi[Hi]=8;for(Hi=144;Hi<256;++Hi)Wi[Hi]=9;for(Hi=256;Hi<280;++Hi)Wi[Hi]=7;for(Hi=280;Hi<288;++Hi)Wi[Hi]=8;var Vi=new _i(32);for(Hi=0;Hi<32;++Hi)Vi[Hi]=5;var Gi=ji(Wi,9),Ji=ji(Vi,5),Yi=function(e){for(var t=e[0],r=1;r<e.length;++r)e[r]>t&&(t=e[r]);return t},Xi=function(e,t,r){var i=t/8|0;return(e[i]|e[i+1]<<8)>>(7&t)&r},Zi=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(7&t)},Qi=function(e){return(e+7)/8|0},eo=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],to=function(e,t,r){var i=new Error(t||eo[e]);if(i.code=e,Error.captureStackTrace&&Error.captureStackTrace(i,to),!r)throw i;return i},ro=function(e,t,r,i){var o=e.length;if(!o||t.f&&!t.l)return r||new _i(0);var n=!r,s=n||2!=t.i,a=t.i;n&&(r=new _i(3*o));var c=function(e){var t=r.length;if(e>t){var i=new _i(Math.max(2*t,e));i.set(r),r=i}},l=t.f||0,d=t.p||0,u=t.b||0,p=t.l,h=t.d,g=t.m,m=t.n,f=8*o;do{if(!p){l=Xi(e,d,1);var y=Xi(e,d+1,3);if(d+=3,!y){var b=e[(R=Qi(d)+4)-4]|e[R-3]<<8,w=R+b;if(w>o){a&&to(0);break}s&&c(u+b),r.set(e.subarray(R,w),u),t.b=u+=b,t.p=d=8*w,t.f=l;continue}if(1==y)p=Gi,h=Ji,g=9,m=5;else if(2==y){var I=Xi(e,d,31)+257,T=Xi(e,d+10,15)+4,S=I+Xi(e,d+5,31)+1;d+=14;for(var k=new _i(S),E=new _i(19),v=0;v<T;++v)E[zi[v]]=Xi(e,d+3*v,7);d+=3*T;var A=Yi(E),C=(1<<A)-1,x=ji(E,A);for(v=0;v<S;){var R,N=x[Xi(e,d,C)];if(d+=15&N,(R=N>>4)<16)k[v++]=R;else{var _=0,P=0;for(16==R?(P=3+Xi(e,d,3),d+=2,_=k[v-1]):17==R?(P=3+Xi(e,d,7),d+=3):18==R&&(P=11+Xi(e,d,127),d+=7);P--;)k[v++]=_}}var F=k.subarray(0,I),O=k.subarray(I);g=Yi(F),m=Yi(O),p=ji(F,g),h=ji(O,m)}else to(1);if(d>f){a&&to(0);break}}s&&c(u+131072);for(var D=(1<<g)-1,z=(1<<m)-1,B=d;;B=d){var M=(_=p[Zi(e,d)&D])>>4;if((d+=15&_)>f){a&&to(0);break}if(_||to(2),M<256)r[u++]=M;else{if(256==M){B=d,p=null;break}var K=M-254;if(M>264){var U=Oi[v=M-257];K=Xi(e,d,(1<<U)-1)+Ki[v],d+=U}var L=h[Zi(e,d)&z],$=L>>4;L||to(3),d+=15&L;O=Li[$];if($>3){U=Di[$];O+=Zi(e,d)&(1<<U)-1,d+=U}if(d>f){a&&to(0);break}s&&c(u+131072);var H=u+K;if(u<O){var q=0-O,j=Math.min(O,H);for(q+u<0&&to(3);u<j;++u)r[u]=i[q+u]}for(;u<H;++u)r[u]=r[u-O]}}t.l=p,t.p=B,t.b=u,t.f=l,p&&(l=1,t.m=g,t.d=h,t.n=m)}while(!l);return u!=r.length&&n?function(e,t,r){return(null==r||r>e.length)&&(r=e.length),new _i(e.subarray(t,r))}(r,0,u):r.subarray(0,u)},io=new _i(0);function oo(e,t){var r,i,o=function(e){31==e[0]&&139==e[1]&&8==e[2]||to(6,"invalid gzip data");var t=e[3],r=10;4&t&&(r+=2+(e[10]|e[11]<<8));for(var i=(t>>3&1)+(t>>4&1);i>0;i-=!e[r++]);return r+(2&t)}(e);return o+8>e.length&&to(6,"invalid gzip data"),ro(e.subarray(o,-8),{i:2},new _i((i=(r=e).length,(r[i-4]|r[i-3]<<8|r[i-2]<<16|r[i-1]<<24)>>>0)),t)}function no(e,t){return ro(e.subarray(((8!=(15&(r=e)[0])||r[0]>>4>7||(r[0]<<8|r[1])%31)&&to(6,"invalid zlib data"),1==(r[1]>>5&1)&&to(6,"invalid zlib data: "+(32&r[1]?"need":"unexpected")+" dictionary"),2+(r[1]>>3&4)),-4),{i:2},t,t);var r}function so(e,t){return 31==e[0]&&139==e[1]&&8==e[2]?oo(e,t):8!=(15&e[0])||e[0]>>4>7||(e[0]<<8|e[1])%31?function(e,t){return ro(e,{i:2},t,t)}(e,t):no(e,t)}var ao="undefined"!=typeof TextDecoder&&new TextDecoder;try{ao.decode(io,{stream:!0})}catch(eg){}var co,lo,uo,po,ho,go={exports:{}};function mo(){if(lo)return co;lo=1;var e=1e3,t=60*e,r=60*t,i=24*r,o=7*i,n=365.25*i;function s(e,t,r,i){var o=t>=1.5*r;return Math.round(e/r)+" "+i+(o?"s":"")}return co=function(a,c){c=c||{};var l=typeof a;if("string"===l&&a.length>0)return function(s){if((s=String(s)).length>100)return;var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(s);if(!a)return;var c=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*n;case"weeks":case"week":case"w":return c*o;case"days":case"day":case"d":return c*i;case"hours":case"hour":case"hrs":case"hr":case"h":return c*r;case"minutes":case"minute":case"mins":case"min":case"m":return c*t;case"seconds":case"second":case"secs":case"sec":case"s":return c*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(a);if("number"===l&&isFinite(a))return c.long?function(o){var n=Math.abs(o);if(n>=i)return s(o,n,i,"day");if(n>=r)return s(o,n,r,"hour");if(n>=t)return s(o,n,t,"minute");if(n>=e)return s(o,n,e,"second");return o+" ms"}(a):function(o){var n=Math.abs(o);if(n>=i)return Math.round(o/i)+"d";if(n>=r)return Math.round(o/r)+"h";if(n>=t)return Math.round(o/t)+"m";if(n>=e)return Math.round(o/e)+"s";return o+"ms"}(a);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(a))}}var fo=(ho||(ho=1,function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let i=0,o=0;t[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(i++,"%c"===e&&(o=i))}),t.splice(o,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(r){}},t.load=function(){let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(r){}return!e&&void 0!==Be&&"env"in Be&&(e=Be.env.DEBUG),e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=(po||(po=1,uo=function(e){function t(e){let i,o,n,s=null;function a(...e){if(!a.enabled)return;const r=a,o=Number(new Date),n=o-(i||o);r.diff=n,r.prev=i,r.curr=o,i=o,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let s=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(i,o)=>{if("%%"===i)return"%";s++;const n=t.formatters[o];if("function"==typeof n){const t=e[s];i=n.call(r,t),e.splice(s,1),s--}return i}),t.formatArgs.call(r,e),(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==s?s:(o!==t.namespaces&&(o=t.namespaces,n=t.enabled(e)),n),set:e=>{s=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const i=t(this.namespace+(void 0===r?":":r)+e);return i.log=this.log,i}function i(e,t){let r=0,i=0,o=-1,n=0;for(;r<e.length;)if(i<t.length&&(t[i]===e[r]||"*"===t[i]))"*"===t[i]?(o=i,n=r,i++):(r++,i++);else{if(-1===o)return!1;i=o+1,n++,r=n}for(;i<t.length&&"*"===t[i];)i++;return i===t.length}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names,...t.skips.map(e=>"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const i of r)"-"===i[0]?t.skips.push(i.slice(1)):t.names.push(i)},t.enabled=function(e){for(const r of t.skips)if(i(e,r))return!1;for(const r of t.names)if(i(e,r))return!0;return!1},t.humanize=mo(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach(r=>{t[r]=e[r]}),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t}),uo)(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}(go,go.exports)),go.exports);const yo=ui(fo),bo=67324752,wo=134695760,Io=33639248,To=101010256,So={get:e=>(gi.get(e,6),{signature:fi.get(e,0),compressedSize:fi.get(e,8),uncompressedSize:fi.get(e,12)}),len:16},ko={get(e){const t=gi.get(e,6);return{signature:fi.get(e,0),minVersion:gi.get(e,4),dataDescriptor:!!(8&t),compressedMethod:gi.get(e,8),compressedSize:fi.get(e,18),uncompressedSize:fi.get(e,22),filenameLength:gi.get(e,26),extraFieldLength:gi.get(e,28),filename:null}},len:30},Eo={get:e=>({signature:fi.get(e,0),nrOfThisDisk:gi.get(e,4),nrOfThisDiskWithTheStart:gi.get(e,6),nrOfEntriesOnThisDisk:gi.get(e,8),nrOfEntriesOfSize:gi.get(e,10),sizeOfCd:fi.get(e,12),offsetOfStartOfCd:fi.get(e,16),zipFileCommentLength:gi.get(e,20)}),len:22},vo={get(e){const t=gi.get(e,8);return{signature:fi.get(e,0),minVersion:gi.get(e,6),dataDescriptor:!!(8&t),compressedMethod:gi.get(e,10),compressedSize:fi.get(e,20),uncompressedSize:fi.get(e,24),filenameLength:gi.get(e,28),extraFieldLength:gi.get(e,30),fileCommentLength:gi.get(e,32),relativeOffsetOfLocalHeader:fi.get(e,42),filename:null}},len:46};function Ao(e){const t=new Uint8Array(fi.len);return fi.put(t,0,e),t}const Co=yo("tokenizer:inflate"),xo=262144,Ro=Ao(wo),No=Ao(To);class _o{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(xo)}async isZip(){return await this.peekSignature()===bo}peekSignature(){return this.tokenizer.peekToken(fi)}async findEndOfCentralDirectoryLocator(){const e=this.tokenizer,t=Math.min(16384,e.fileInfo.size),r=this.syncBuffer.subarray(0,t);await this.tokenizer.readBuffer(r,{position:e.fileInfo.size-t});for(let i=r.length-4;i>=0;i--)if(r[i]===No[0]&&r[i+1]===No[1]&&r[i+2]===No[2]&&r[i+3]===No[3])return e.fileInfo.size-t+i;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess())return void Co("Cannot reading central-directory without random-read support");Co("Reading central-directory...");const e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){Co("Central-directory 32-bit signature found");const r=await this.tokenizer.readToken(Eo,t),i=[];this.tokenizer.setPosition(r.offsetOfStartOfCd);for(let e=0;e<r.nrOfEntriesOfSize;++e){const t=await this.tokenizer.readToken(vo);if(t.signature!==Io)throw new Error("Expected Central-File-Header signature");t.filename=await this.tokenizer.readToken(new Ii(t.filenameLength,"utf-8")),await this.tokenizer.ignore(t.extraFieldLength),await this.tokenizer.ignore(t.fileCommentLength),i.push(t),Co(`Add central-directory file-entry: n=${e+1}/${i.length}: filename=${i[e].filename}`)}return this.tokenizer.setPosition(e),i}this.tokenizer.setPosition(e)}async unzip(e){const t=await this.readCentralDirectory();if(t)return this.iterateOverCentralDirectory(t,e);let r=!1;do{const t=await this.readLocalFileHeader();if(!t)break;const i=e(t);let o;if(r=!!i.stop,await this.tokenizer.ignore(t.extraFieldLength),t.dataDescriptor&&0===t.compressedSize){const e=[];let r=xo;Co("Compressed-file-size unknown, scanning for next data-descriptor-signature....");let o=-1;for(;o<0&&r===xo;){r=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),o=Po(this.syncBuffer.subarray(0,r),Ro);const t=o>=0?o:r;if(i.handler){const r=new Uint8Array(t);await this.tokenizer.readBuffer(r),e.push(r)}else await this.tokenizer.ignore(t)}Co(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),i.handler&&await this.inflate(t,Fo(e),i.handler)}else i.handler?(Co(`Reading compressed-file-data: ${t.compressedSize} bytes`),o=new Uint8Array(t.compressedSize),await this.tokenizer.readBuffer(o),await this.inflate(t,o,i.handler)):(Co(`Ignoring compressed-file-data: ${t.compressedSize} bytes`),await this.tokenizer.ignore(t.compressedSize));if(Co(`Reading data-descriptor at pos=${this.tokenizer.position}`),t.dataDescriptor){if(134695760!==(await this.tokenizer.readToken(So)).signature)throw new Error("Expected data-descriptor-signature at position "+(this.tokenizer.position-So.len))}}while(!r)}async iterateOverCentralDirectory(e,t){for(const r of e){const e=t(r);if(e.handler){this.tokenizer.setPosition(r.relativeOffsetOfLocalHeader);const t=await this.readLocalFileHeader();if(t){await this.tokenizer.ignore(t.extraFieldLength);const i=new Uint8Array(r.compressedSize);await this.tokenizer.readBuffer(i),await this.inflate(t,i,e.handler)}}if(e.stop)break}}inflate(e,t,r){if(0===e.compressedMethod)return r(t);Co(`Decompress filename=${e.filename}, compressed-size=${t.length}`);return r(so(t))}async readLocalFileHeader(){const e=await this.tokenizer.peekToken(fi);if(e===bo){const e=await this.tokenizer.readToken(ko);return e.filename=await this.tokenizer.readToken(new Ii(e.filenameLength,"utf-8")),e}if(e===Io)return!1;if(3759263696===e)throw new Error("Encrypted ZIP");throw new Error("Unexpected signature")}}function Po(e,t){const r=e.length,i=t.length;if(i>r)return-1;for(let o=0;o<=r-i;o++){let r=!0;for(let n=0;n<i;n++)if(e[o+n]!==t[n]){r=!1;break}if(r)return o}return-1}function Fo(e){const t=e.reduce((e,t)=>e+t.length,0),r=new Uint8Array(t);let i=0;for(const o of e)r.set(o,i),i+=o.length;return r}function Oo(e){const{byteLength:t}=e;return 6===t?e.getUint16(0)*2**32+e.getUint32(2):5===t?e.getUint8(0)*2**32+e.getUint32(1):4===t?e.getUint32(0):3===t?65536*e.getUint8(0)+e.getUint16(1):2===t?e.getUint16(0):1===t?e.getUint8(0):void 0}new globalThis.TextDecoder("utf8"),new globalThis.TextEncoder,Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));const Do={get:(e,t)=>127&e[t+3]|e[t+2]<<7|e[t+1]<<14|e[t]<<21,len:4},zo=4100;function Bo(e){switch(e=e.toLowerCase()){case"application/epub+zip":return{ext:"epub",mime:e};case"application/vnd.oasis.opendocument.text":return{ext:"odt",mime:e};case"application/vnd.oasis.opendocument.text-template":return{ext:"ott",mime:e};case"application/vnd.oasis.opendocument.spreadsheet":return{ext:"ods",mime:e};case"application/vnd.oasis.opendocument.spreadsheet-template":return{ext:"ots",mime:e};case"application/vnd.oasis.opendocument.presentation":return{ext:"odp",mime:e};case"application/vnd.oasis.opendocument.presentation-template":return{ext:"otp",mime:e};case"application/vnd.oasis.opendocument.graphics":return{ext:"odg",mime:e};case"application/vnd.oasis.opendocument.graphics-template":return{ext:"otg",mime:e};case"application/vnd.openxmlformats-officedocument.presentationml.slideshow":return{ext:"ppsx",mime:e};case"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":return{ext:"xlsx",mime:e};case"application/vnd.ms-excel.sheet.macroenabled":return{ext:"xlsm",mime:"application/vnd.ms-excel.sheet.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.spreadsheetml.template":return{ext:"xltx",mime:e};case"application/vnd.ms-excel.template.macroenabled":return{ext:"xltm",mime:"application/vnd.ms-excel.template.macroenabled.12"};case"application/vnd.ms-powerpoint.slideshow.macroenabled":return{ext:"ppsm",mime:"application/vnd.ms-powerpoint.slideshow.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.wordprocessingml.document":return{ext:"docx",mime:e};case"application/vnd.ms-word.document.macroenabled":return{ext:"docm",mime:"application/vnd.ms-word.document.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.wordprocessingml.template":return{ext:"dotx",mime:e};case"application/vnd.ms-word.template.macroenabledtemplate":return{ext:"dotm",mime:"application/vnd.ms-word.template.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.presentationml.template":return{ext:"potx",mime:e};case"application/vnd.ms-powerpoint.template.macroenabled":return{ext:"potm",mime:"application/vnd.ms-powerpoint.template.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.presentationml.presentation":return{ext:"pptx",mime:e};case"application/vnd.ms-powerpoint.presentation.macroenabled":return{ext:"pptm",mime:"application/vnd.ms-powerpoint.presentation.macroenabled.12"};case"application/vnd.ms-visio.drawing":return{ext:"vsdx",mime:"application/vnd.visio"};case"application/vnd.ms-package.3dmanufacturing-3dmodel+xml":return{ext:"3mf",mime:"model/3mf"}}}function Mo(e,t,r){r={offset:0,...r};for(const[i,o]of t.entries())if(r.mask){if(o!==(r.mask[i]&e[i+r.offset]))return!1}else if(o!==e[i+r.offset])return!1;return!0}class Ko{constructor(e){se(this,"detectConfident",async e=>{if(this.buffer=new Uint8Array(zo),void 0===e.fileInfo.size&&(e.fileInfo.size=Number.MAX_SAFE_INTEGER),this.tokenizer=e,await e.peekBuffer(this.buffer,{length:12,mayBeLess:!0}),this.check([66,77]))return{ext:"bmp",mime:"image/bmp"};if(this.check([11,119]))return{ext:"ac3",mime:"audio/vnd.dolby.dd-raw"};if(this.check([120,1]))return{ext:"dmg",mime:"application/x-apple-diskimage"};if(this.check([77,90]))return{ext:"exe",mime:"application/x-msdownload"};if(this.check([37,33]))return await e.peekBuffer(this.buffer,{length:24,mayBeLess:!0}),this.checkString("PS-Adobe-",{offset:2})&&this.checkString(" EPSF-",{offset:14})?{ext:"eps",mime:"application/eps"}:{ext:"ps",mime:"application/postscript"};if(this.check([31,160])||this.check([31,157]))return{ext:"Z",mime:"application/x-compress"};if(this.check([199,113]))return{ext:"cpio",mime:"application/x-cpio"};if(this.check([96,234]))return{ext:"arj",mime:"application/x-arj"};if(this.check([239,187,191]))return this.tokenizer.ignore(3),this.detectConfident(e);if(this.check([71,73,70]))return{ext:"gif",mime:"image/gif"};if(this.check([73,73,188]))return{ext:"jxr",mime:"image/vnd.ms-photo"};if(this.check([31,139,8]))return{ext:"gz",mime:"application/gzip"};if(this.check([66,90,104]))return{ext:"bz2",mime:"application/x-bzip2"};if(this.checkString("ID3")){await e.ignore(6);const t=await e.readToken(Do);return e.position+t>e.fileInfo.size?{ext:"mp3",mime:"audio/mpeg"}:(await e.ignore(t),this.fromTokenizer(e))}if(this.checkString("MP+"))return{ext:"mpc",mime:"audio/x-musepack"};if((67===this.buffer[0]||70===this.buffer[0])&&this.check([87,83],{offset:1}))return{ext:"swf",mime:"application/x-shockwave-flash"};if(this.check([255,216,255]))return this.check([247],{offset:3})?{ext:"jls",mime:"image/jls"}:{ext:"jpg",mime:"image/jpeg"};if(this.check([79,98,106,1]))return{ext:"avro",mime:"application/avro"};if(this.checkString("FLIF"))return{ext:"flif",mime:"image/flif"};if(this.checkString("8BPS"))return{ext:"psd",mime:"image/vnd.adobe.photoshop"};if(this.checkString("MPCK"))return{ext:"mpc",mime:"audio/x-musepack"};if(this.checkString("FORM"))return{ext:"aif",mime:"audio/aiff"};if(this.checkString("icns",{offset:0}))return{ext:"icns",mime:"image/icns"};if(this.check([80,75,3,4])){let r;return await new _o(e).unzip(e=>{switch(e.filename){case"META-INF/mozilla.rsa":return r={ext:"xpi",mime:"application/x-xpinstall"},{stop:!0};case"META-INF/MANIFEST.MF":return r={ext:"jar",mime:"application/java-archive"},{stop:!0};case"mimetype":return{async handler(e){const t=new TextDecoder("utf-8").decode(e).trim();r=Bo(t)},stop:!0};case"[Content_Types].xml":return{async handler(e){let t=new TextDecoder("utf-8").decode(e);const i=t.indexOf('.main+xml"');if(-1===i){const e="application/vnd.ms-package.3dmanufacturing-3dmodel+xml";t.includes(`ContentType="${e}"`)&&(r=Bo(e))}else{t=t.slice(0,Math.max(0,i));const e=t.lastIndexOf('"'),o=t.slice(Math.max(0,e+1));r=Bo(o)}},stop:!0};default:return/classes\d*\.dex/.test(e.filename)?(r={ext:"apk",mime:"application/vnd.android.package-archive"},{stop:!0}):{}}}),r??{ext:"zip",mime:"application/zip"}}if(this.checkString("OggS")){await e.ignore(28);const i=new Uint8Array(8);return await e.readBuffer(i),Mo(i,[79,112,117,115,72,101,97,100])?{ext:"opus",mime:"audio/ogg; codecs=opus"}:Mo(i,[128,116,104,101,111,114,97])?{ext:"ogv",mime:"video/ogg"}:Mo(i,[1,118,105,100,101,111,0])?{ext:"ogm",mime:"video/ogg"}:Mo(i,[127,70,76,65,67])?{ext:"oga",mime:"audio/ogg"}:Mo(i,[83,112,101,101,120,32,32])?{ext:"spx",mime:"audio/ogg"}:Mo(i,[1,118,111,114,98,105,115])?{ext:"ogg",mime:"audio/ogg"}:{ext:"ogx",mime:"application/ogg"}}if(this.check([80,75])&&(3===this.buffer[2]||5===this.buffer[2]||7===this.buffer[2])&&(4===this.buffer[3]||6===this.buffer[3]||8===this.buffer[3]))return{ext:"zip",mime:"application/zip"};if(this.checkString("MThd"))return{ext:"mid",mime:"audio/midi"};if(this.checkString("wOFF")&&(this.check([0,1,0,0],{offset:4})||this.checkString("OTTO",{offset:4})))return{ext:"woff",mime:"font/woff"};if(this.checkString("wOF2")&&(this.check([0,1,0,0],{offset:4})||this.checkString("OTTO",{offset:4})))return{ext:"woff2",mime:"font/woff2"};if(this.check([212,195,178,161])||this.check([161,178,195,212]))return{ext:"pcap",mime:"application/vnd.tcpdump.pcap"};if(this.checkString("DSD "))return{ext:"dsf",mime:"audio/x-dsf"};if(this.checkString("LZIP"))return{ext:"lz",mime:"application/x-lzip"};if(this.checkString("fLaC"))return{ext:"flac",mime:"audio/flac"};if(this.check([66,80,71,251]))return{ext:"bpg",mime:"image/bpg"};if(this.checkString("wvpk"))return{ext:"wv",mime:"audio/wavpack"};if(this.checkString("%PDF"))return{ext:"pdf",mime:"application/pdf"};if(this.check([0,97,115,109]))return{ext:"wasm",mime:"application/wasm"};if(this.check([73,73])){const o=await this.readTiffHeader(!1);if(o)return o}if(this.check([77,77])){const n=await this.readTiffHeader(!0);if(n)return n}if(this.checkString("MAC "))return{ext:"ape",mime:"audio/ape"};if(this.check([26,69,223,163])){async function s(){const t=await e.peekNumber(hi);let r=128,i=0;for(;0===(t&r)&&0!==r;)++i,r>>=1;const o=new Uint8Array(i+1);return await e.readBuffer(o),o}async function a(){const e=await s(),t=await s();t[0]^=128>>t.length-1;const r=Math.min(6,t.length),i=new DataView(e.buffer),o=new DataView(t.buffer,t.length-r,r);return{id:Oo(i),len:Oo(o)}}async function c(t){for(;t>0;){const r=await a();if(17026===r.id){return(await e.readToken(new Ii(r.len))).replaceAll(/\00.*$/g,"")}await e.ignore(r.len),--t}}const l=await a();switch(await c(l.len)){case"webm":return{ext:"webm",mime:"video/webm"};case"matroska":return{ext:"mkv",mime:"video/matroska"};default:return}}if(this.checkString("SQLi"))return{ext:"sqlite",mime:"application/x-sqlite3"};if(this.check([78,69,83,26]))return{ext:"nes",mime:"application/x-nintendo-nes-rom"};if(this.checkString("Cr24"))return{ext:"crx",mime:"application/x-google-chrome-extension"};if(this.checkString("MSCF")||this.checkString("ISc("))return{ext:"cab",mime:"application/vnd.ms-cab-compressed"};if(this.check([237,171,238,219]))return{ext:"rpm",mime:"application/x-rpm"};if(this.check([197,208,211,198]))return{ext:"eps",mime:"application/eps"};if(this.check([40,181,47,253]))return{ext:"zst",mime:"application/zstd"};if(this.check([127,69,76,70]))return{ext:"elf",mime:"application/x-elf"};if(this.check([33,66,68,78]))return{ext:"pst",mime:"application/vnd.ms-outlook"};if(this.checkString("PAR1")||this.checkString("PARE"))return{ext:"parquet",mime:"application/vnd.apache.parquet"};if(this.checkString("ttcf"))return{ext:"ttc",mime:"font/collection"};if(this.check([207,250,237,254]))return{ext:"macho",mime:"application/x-mach-binary"};if(this.check([4,34,77,24]))return{ext:"lz4",mime:"application/x-lz4"};if(this.check([79,84,84,79,0]))return{ext:"otf",mime:"font/otf"};if(this.checkString("#!AMR"))return{ext:"amr",mime:"audio/amr"};if(this.checkString("{\\rtf"))return{ext:"rtf",mime:"application/rtf"};if(this.check([70,76,86,1]))return{ext:"flv",mime:"video/x-flv"};if(this.checkString("IMPM"))return{ext:"it",mime:"audio/x-it"};if(this.checkString("-lh0-",{offset:2})||this.checkString("-lh1-",{offset:2})||this.checkString("-lh2-",{offset:2})||this.checkString("-lh3-",{offset:2})||this.checkString("-lh4-",{offset:2})||this.checkString("-lh5-",{offset:2})||this.checkString("-lh6-",{offset:2})||this.checkString("-lh7-",{offset:2})||this.checkString("-lzs-",{offset:2})||this.checkString("-lz4-",{offset:2})||this.checkString("-lz5-",{offset:2})||this.checkString("-lhd-",{offset:2}))return{ext:"lzh",mime:"application/x-lzh-compressed"};if(this.check([0,0,1,186])){if(this.check([33],{offset:4,mask:[241]}))return{ext:"mpg",mime:"video/MP1S"};if(this.check([68],{offset:4,mask:[196]}))return{ext:"mpg",mime:"video/MP2P"}}if(this.checkString("ITSF"))return{ext:"chm",mime:"application/vnd.ms-htmlhelp"};if(this.check([202,254,186,190]))return{ext:"class",mime:"application/java-vm"};if(this.checkString(".RMF"))return{ext:"rm",mime:"application/vnd.rn-realmedia"};if(this.checkString("DRACO"))return{ext:"drc",mime:"application/vnd.google.draco"};if(this.check([253,55,122,88,90,0]))return{ext:"xz",mime:"application/x-xz"};if(this.checkString("<?xml "))return{ext:"xml",mime:"application/xml"};if(this.check([55,122,188,175,39,28]))return{ext:"7z",mime:"application/x-7z-compressed"};if(this.check([82,97,114,33,26,7])&&(0===this.buffer[6]||1===this.buffer[6]))return{ext:"rar",mime:"application/x-rar-compressed"};if(this.checkString("solid "))return{ext:"stl",mime:"model/stl"};if(this.checkString("AC")){const d=new Ii(4,"latin1").get(this.buffer,2);if(d.match("^d*")&&d>=1e3&&d<=1050)return{ext:"dwg",mime:"image/vnd.dwg"}}if(this.checkString("070707"))return{ext:"cpio",mime:"application/x-cpio"};if(this.checkString("BLENDER"))return{ext:"blend",mime:"application/x-blender"};if(this.checkString("!<arch>")){await e.ignore(8);return"debian-binary"===await e.readToken(new Ii(13,"ascii"))?{ext:"deb",mime:"application/x-deb"}:{ext:"ar",mime:"application/x-unix-archive"}}if(this.checkString("WEBVTT")&&["\n","\r","\t"," ","\0"].some(e=>this.checkString(e,{offset:6})))return{ext:"vtt",mime:"text/vtt"};if(this.check([137,80,78,71,13,10,26,10])){async function u(){return{length:await e.readToken(bi),type:await e.readToken(new Ii(4,"latin1"))}}await e.ignore(8);do{const p=await u();if(p.length<0)return;switch(p.type){case"IDAT":return{ext:"png",mime:"image/png"};case"acTL":return{ext:"apng",mime:"image/apng"};default:await e.ignore(p.length+4)}}while(e.position+8<e.fileInfo.size);return{ext:"png",mime:"image/png"}}if(this.check([65,82,82,79,87,49,0,0]))return{ext:"arrow",mime:"application/vnd.apache.arrow.file"};if(this.check([103,108,84,70,2,0,0,0]))return{ext:"glb",mime:"model/gltf-binary"};if(this.check([102,114,101,101],{offset:4})||this.check([109,100,97,116],{offset:4})||this.check([109,111,111,118],{offset:4})||this.check([119,105,100,101],{offset:4}))return{ext:"mov",mime:"video/quicktime"};if(this.check([73,73,82,79,8,0,0,0,24]))return{ext:"orf",mime:"image/x-olympus-orf"};if(this.checkString("gimp xcf "))return{ext:"xcf",mime:"image/x-xcf"};if(this.checkString("ftyp",{offset:4})&&96&this.buffer[8]){const h=new Ii(4,"latin1").get(this.buffer,8).replace("\0"," ").trim();switch(h){case"avif":case"avis":return{ext:"avif",mime:"image/avif"};case"mif1":return{ext:"heic",mime:"image/heif"};case"msf1":return{ext:"heic",mime:"image/heif-sequence"};case"heic":case"heix":return{ext:"heic",mime:"image/heic"};case"hevc":case"hevx":return{ext:"heic",mime:"image/heic-sequence"};case"qt":return{ext:"mov",mime:"video/quicktime"};case"M4V":case"M4VH":case"M4VP":return{ext:"m4v",mime:"video/x-m4v"};case"M4P":return{ext:"m4p",mime:"video/mp4"};case"M4B":return{ext:"m4b",mime:"audio/mp4"};case"M4A":return{ext:"m4a",mime:"audio/x-m4a"};case"F4V":return{ext:"f4v",mime:"video/mp4"};case"F4P":return{ext:"f4p",mime:"video/mp4"};case"F4A":return{ext:"f4a",mime:"audio/mp4"};case"F4B":return{ext:"f4b",mime:"audio/mp4"};case"crx":return{ext:"cr3",mime:"image/x-canon-cr3"};default:return h.startsWith("3g")?h.startsWith("3g2")?{ext:"3g2",mime:"video/3gpp2"}:{ext:"3gp",mime:"video/3gpp"}:{ext:"mp4",mime:"video/mp4"}}}if(this.check([82,73,70,70])){if(this.checkString("WEBP",{offset:8}))return{ext:"webp",mime:"image/webp"};if(this.check([65,86,73],{offset:8}))return{ext:"avi",mime:"video/vnd.avi"};if(this.check([87,65,86,69],{offset:8}))return{ext:"wav",mime:"audio/wav"};if(this.check([81,76,67,77],{offset:8}))return{ext:"qcp",mime:"audio/qcelp"}}if(this.check([73,73,85,0,24,0,0,0,136,231,116,216]))return{ext:"rw2",mime:"image/x-panasonic-rw2"};if(this.check([48,38,178,117,142,102,207,17,166,217])){async function g(){const t=new Uint8Array(16);return await e.readBuffer(t),{id:t,size:Number(await e.readToken(wi))}}for(await e.ignore(30);e.position+24<e.fileInfo.size;){const m=await g();let f=m.size-24;if(Mo(m.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){const y=new Uint8Array(16);if(f-=await e.readBuffer(y),Mo(y,[64,158,105,248,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:"asf",mime:"audio/x-ms-asf"};if(Mo(y,[192,239,25,188,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:"asf",mime:"video/x-ms-asf"};break}await e.ignore(f)}return{ext:"asf",mime:"application/vnd.ms-asf"}}if(this.check([171,75,84,88,32,49,49,187,13,10,26,10]))return{ext:"ktx",mime:"image/ktx"};if((this.check([126,16,4])||this.check([126,24,4]))&&this.check([48,77,73,69],{offset:4}))return{ext:"mie",mime:"application/x-mie"};if(this.check([39,10,0,0,0,0,0,0,0,0,0,0],{offset:2}))return{ext:"shp",mime:"application/x-esri-shape"};if(this.check([255,79,255,81]))return{ext:"j2c",mime:"image/j2c"};if(this.check([0,0,0,12,106,80,32,32,13,10,135,10])){await e.ignore(20);switch(await e.readToken(new Ii(4,"ascii"))){case"jp2 ":return{ext:"jp2",mime:"image/jp2"};case"jpx ":return{ext:"jpx",mime:"image/jpx"};case"jpm ":return{ext:"jpm",mime:"image/jpm"};case"mjp2":return{ext:"mj2",mime:"image/mj2"};default:return}}if(this.check([255,10])||this.check([0,0,0,12,74,88,76,32,13,10,135,10]))return{ext:"jxl",mime:"image/jxl"};if(this.check([254,255]))return this.check([0,60,0,63,0,120,0,109,0,108],{offset:2})?{ext:"xml",mime:"application/xml"}:void 0;if(this.check([208,207,17,224,161,177,26,225]))return{ext:"cfb",mime:"application/x-cfb"};if(await e.peekBuffer(this.buffer,{length:Math.min(256,e.fileInfo.size),mayBeLess:!0}),this.check([97,99,115,112],{offset:36}))return{ext:"icc",mime:"application/vnd.iccprofile"};if(this.checkString("**ACE",{offset:7})&&this.checkString("**",{offset:12}))return{ext:"ace",mime:"application/x-ace-compressed"};if(this.checkString("BEGIN:")){if(this.checkString("VCARD",{offset:6}))return{ext:"vcf",mime:"text/vcard"};if(this.checkString("VCALENDAR",{offset:6}))return{ext:"ics",mime:"text/calendar"}}if(this.checkString("FUJIFILMCCD-RAW"))return{ext:"raf",mime:"image/x-fujifilm-raf"};if(this.checkString("Extended Module:"))return{ext:"xm",mime:"audio/x-xm"};if(this.checkString("Creative Voice File"))return{ext:"voc",mime:"audio/x-voc"};if(this.check([4,0,0,0])&&this.buffer.length>=16){const b=new DataView(this.buffer.buffer).getUint32(12,!0);if(b>12&&this.buffer.length>=b+16)try{const w=(new TextDecoder).decode(this.buffer.subarray(16,b+16));if(JSON.parse(w).files)return{ext:"asar",mime:"application/x-asar"}}catch{}}return this.check([6,14,43,52,2,5,1,1,13,1,2,1,1,2])?{ext:"mxf",mime:"application/mxf"}:this.checkString("SCRM",{offset:44})?{ext:"s3m",mime:"audio/x-s3m"}:this.check([71])&&this.check([71],{offset:188})||this.check([71],{offset:4})&&this.check([71],{offset:196})?{ext:"mts",mime:"video/mp2t"}:this.check([66,79,79,75,77,79,66,73],{offset:60})?{ext:"mobi",mime:"application/x-mobipocket-ebook"}:this.check([68,73,67,77],{offset:128})?{ext:"dcm",mime:"application/dicom"}:this.check([76,0,0,0,1,20,2,0,0,0,0,0,192,0,0,0,0,0,0,70])?{ext:"lnk",mime:"application/x.ms.shortcut"}:this.check([98,111,111,107,0,0,0,0,109,97,114,107,0,0,0,0])?{ext:"alias",mime:"application/x.apple.alias"}:this.checkString("Kaydara FBX Binary \0")?{ext:"fbx",mime:"application/x.autodesk.fbx"}:this.check([76,80],{offset:34})&&(this.check([0,0,1],{offset:8})||this.check([1,0,2],{offset:8})||this.check([2,0,2],{offset:8}))?{ext:"eot",mime:"application/vnd.ms-fontobject"}:this.check([6,6,237,245,216,29,70,229,189,49,239,231,254,116,183,29])?{ext:"indd",mime:"application/x-indesign"}:(await e.peekBuffer(this.buffer,{length:Math.min(512,e.fileInfo.size),mayBeLess:!0}),this.checkString("ustar",{offset:257})&&(this.checkString("\0",{offset:262})||this.checkString(" ",{offset:262}))||this.check([0,0,0,0,0,0],{offset:257})&&function(e,t=0){const r=Number.parseInt(new Ii(6).get(e,148).replace(/\0.*$/,"").trim(),8);if(Number.isNaN(r))return!1;let i=256;for(let o=t;o<t+148;o++)i+=e[o];for(let o=t+156;o<t+512;o++)i+=e[o];return r===i}(this.buffer)?{ext:"tar",mime:"application/x-tar"}:this.check([255,254])?this.check([60,0,63,0,120,0,109,0,108,0],{offset:2})?{ext:"xml",mime:"application/xml"}:this.check([255,14,83,0,107,0,101,0,116,0,99,0,104,0,85,0,112,0,32,0,77,0,111,0,100,0,101,0,108,0],{offset:2})?{ext:"skp",mime:"application/vnd.sketchup.skp"}:void 0:this.checkString("-----BEGIN PGP MESSAGE-----")?{ext:"pgp",mime:"application/pgp-encrypted"}:void 0)}),se(this,"detectImprecise",async e=>{if(this.buffer=new Uint8Array(zo),await e.peekBuffer(this.buffer,{length:Math.min(8,e.fileInfo.size),mayBeLess:!0}),this.check([0,0,1,186])||this.check([0,0,1,179]))return{ext:"mpg",mime:"video/mpeg"};if(this.check([0,1,0,0,0]))return{ext:"ttf",mime:"font/ttf"};if(this.check([0,0,1,0]))return{ext:"ico",mime:"image/x-icon"};if(this.check([0,0,2,0]))return{ext:"cur",mime:"image/x-icon"};if(await e.peekBuffer(this.buffer,{length:Math.min(2+this.options.mpegOffsetTolerance,e.fileInfo.size),mayBeLess:!0}),this.buffer.length>=2+this.options.mpegOffsetTolerance)for(let t=0;t<=this.options.mpegOffsetTolerance;++t){const e=this.scanMpeg(t);if(e)return e}}),this.options={mpegOffsetTolerance:0,...e},this.detectors=[...(null==e?void 0:e.customDetectors)??[],{id:"core",detect:this.detectConfident},{id:"core.imprecise",detect:this.detectImprecise}],this.tokenizerOptions={abortSignal:null==e?void 0:e.signal}}async fromTokenizer(e){const t=e.position;for(const r of this.detectors){const i=await r.detect(e);if(i)return i;if(t!==e.position)return}}async fromBuffer(e){if(!(e instanceof Uint8Array||e instanceof ArrayBuffer))throw new TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``);const t=e instanceof Uint8Array?e:new Uint8Array(e);var r,i;if((null==t?void 0:t.length)>1)return this.fromTokenizer((r=t,i=this.tokenizerOptions,new Ri(r,i)))}async fromBlob(e){return this.fromStream(e.stream())}async fromStream(e){const t=await Ni(e,this.tokenizerOptions);try{return await this.fromTokenizer(t)}finally{await t.close()}}async toDetectionStream(e,t){const{sampleSize:r=zo}=t;let i,o;const n=e.getReader({mode:"byob"});try{const{value:e,done:t}=await n.read(new Uint8Array(r));if(o=e,!t&&e)try{i=await this.fromBuffer(e.subarray(0,r))}catch(c){if(!(c instanceof Ti))throw c;i=void 0}o=e}finally{n.releaseLock()}const s=new TransformStream({async start(e){e.enqueue(o)},transform(e,t){t.enqueue(e)}}),a=e.pipeThrough(s);return a.fileType=i,a}check(e,t){return Mo(this.buffer,e,t)}checkString(e,t){return this.check((r=e,[...r].map(e=>e.charCodeAt(0))),t);var r}async readTiffTag(e){const t=await this.tokenizer.readToken(e?mi:gi);switch(this.tokenizer.ignore(10),t){case 50341:return{ext:"arw",mime:"image/x-sony-arw"};case 50706:return{ext:"dng",mime:"image/x-adobe-dng"}}}async readTiffIFD(e){const t=await this.tokenizer.readToken(e?mi:gi);for(let r=0;r<t;++r){const t=await this.readTiffTag(e);if(t)return t}}async readTiffHeader(e){const t=(e?mi:gi).get(this.buffer,2),r=(e?yi:fi).get(this.buffer,4);if(42===t){if(r>=6){if(this.checkString("CR",{offset:8}))return{ext:"cr2",mime:"image/x-canon-cr2"};if(r>=8){const t=(e?mi:gi).get(this.buffer,8),r=(e?mi:gi).get(this.buffer,10);if(28===t&&254===r||31===t&&11===r)return{ext:"nef",mime:"image/x-nikon-nef"}}}await this.tokenizer.ignore(r);return await this.readTiffIFD(e)??{ext:"tif",mime:"image/tiff"}}if(43===t)return{ext:"tif",mime:"image/tiff"}}scanMpeg(e){if(this.check([255,224],{offset:e,mask:[255,224]})){if(this.check([16],{offset:e+1,mask:[22]}))return this.check([8],{offset:e+1,mask:[8]}),{ext:"aac",mime:"audio/aac"};if(this.check([2],{offset:e+1,mask:[6]}))return{ext:"mp3",mime:"audio/mpeg"};if(this.check([4],{offset:e+1,mask:[6]}))return{ext:"mp2",mime:"audio/mpeg"};if(this.check([6],{offset:e+1,mask:[6]}))return{ext:"mp1",mime:"audio/mpeg"}}}}new Set(["jpg","png","apng","gif","webp","flif","xcf","cr2","cr3","orf","arw","dng","nef","rw2","raf","tif","bmp","icns","jxr","psd","indd","zip","tar","rar","gz","bz2","7z","dmg","mp4","mid","mkv","webm","mov","avi","mpg","mp2","mp3","m4a","oga","ogg","ogv","opus","flac","wav","spx","amr","pdf","epub","elf","macho","exe","swf","rtf","wasm","woff","woff2","eot","ttf","otf","ttc","ico","flv","ps","xz","sqlite","nes","crx","xpi","cab","deb","ar","rpm","Z","lz","cfb","mxf","mts","blend","bpg","docx","pptx","xlsx","3gp","3g2","j2c","jp2","jpm","jpx","mj2","aif","qcp","odt","ods","odp","xml","mobi","heic","cur","ktx","ape","wv","dcm","ics","glb","pcap","dsf","lnk","alias","voc","ac3","m4v","m4p","m4b","f4v","f4p","f4b","f4a","mie","asf","ogm","ogx","mpc","arrow","shp","aac","mp1","it","s3m","xm","skp","avif","eps","lzh","pgp","asar","stl","chm","3mf","zst","jxl","vcf","jls","pst","dwg","parquet","class","arj","cpio","ace","avro","icc","fbx","vsdx","vtt","apk","drc","lz4","potx","xltx","dotx","xltm","ott","ots","otp","odg","otg","xlsm","docm","dotm","potm","pptm","jar","rm","ppsm","ppsx"]),new Set(["image/jpeg","image/png","image/gif","image/webp","image/flif","image/x-xcf","image/x-canon-cr2","image/x-canon-cr3","image/tiff","image/bmp","image/vnd.ms-photo","image/vnd.adobe.photoshop","application/x-indesign","application/epub+zip","application/x-xpinstall","application/vnd.ms-powerpoint.slideshow.macroenabled.12","application/vnd.oasis.opendocument.text","application/vnd.oasis.opendocument.spreadsheet","application/vnd.oasis.opendocument.presentation","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.openxmlformats-officedocument.presentationml.slideshow","application/zip","application/x-tar","application/x-rar-compressed","application/gzip","application/x-bzip2","application/x-7z-compressed","application/x-apple-diskimage","application/vnd.apache.arrow.file","video/mp4","audio/midi","video/matroska","video/webm","video/quicktime","video/vnd.avi","audio/wav","audio/qcelp","audio/x-ms-asf","video/x-ms-asf","application/vnd.ms-asf","video/mpeg","video/3gpp","audio/mpeg","audio/mp4","video/ogg","audio/ogg","audio/ogg; codecs=opus","application/ogg","audio/flac","audio/ape","audio/wavpack","audio/amr","application/pdf","application/x-elf","application/x-mach-binary","application/x-msdownload","application/x-shockwave-flash","application/rtf","application/wasm","font/woff","font/woff2","application/vnd.ms-fontobject","font/ttf","font/otf","font/collection","image/x-icon","video/x-flv","application/postscript","application/eps","application/x-xz","application/x-sqlite3","application/x-nintendo-nes-rom","application/x-google-chrome-extension","application/vnd.ms-cab-compressed","application/x-deb","application/x-unix-archive","application/x-rpm","application/x-compress","application/x-lzip","application/x-cfb","application/x-mie","application/mxf","video/mp2t","application/x-blender","image/bpg","image/j2c","image/jp2","image/jpx","image/jpm","image/mj2","audio/aiff","application/xml","application/x-mobipocket-ebook","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/icns","image/ktx","application/dicom","audio/x-musepack","text/calendar","text/vcard","text/vtt","model/gltf-binary","application/vnd.tcpdump.pcap","audio/x-dsf","application/x.ms.shortcut","application/x.apple.alias","audio/x-voc","audio/vnd.dolby.dd-raw","audio/x-m4a","image/apng","image/x-olympus-orf","image/x-sony-arw","image/x-adobe-dng","image/x-nikon-nef","image/x-panasonic-rw2","image/x-fujifilm-raf","video/x-m4v","video/3gpp2","application/x-esri-shape","audio/aac","audio/x-it","audio/x-s3m","audio/x-xm","video/MP1S","video/MP2P","application/vnd.sketchup.skp","image/avif","application/x-lzh-compressed","application/pgp-encrypted","application/x-asar","model/stl","application/vnd.ms-htmlhelp","model/3mf","image/jxl","application/zstd","image/jls","application/vnd.ms-outlook","image/vnd.dwg","application/vnd.apache.parquet","application/java-vm","application/x-arj","application/x-cpio","application/x-ace-compressed","application/avro","application/vnd.iccprofile","application/x.autodesk.fbx","application/vnd.visio","application/vnd.android.package-archive","application/vnd.google.draco","application/x-lz4","application/vnd.openxmlformats-officedocument.presentationml.template","application/vnd.openxmlformats-officedocument.spreadsheetml.template","application/vnd.openxmlformats-officedocument.wordprocessingml.template","application/vnd.ms-excel.template.macroenabled.12","application/vnd.oasis.opendocument.text-template","application/vnd.oasis.opendocument.spreadsheet-template","application/vnd.oasis.opendocument.presentation-template","application/vnd.oasis.opendocument.graphics","application/vnd.oasis.opendocument.graphics-template","application/vnd.ms-excel.sheet.macroenabled.12","application/vnd.ms-word.document.macroenabled.12","application/vnd.ms-word.template.macroenabled.12","application/vnd.ms-powerpoint.template.macroenabled.12","application/vnd.ms-powerpoint.presentation.macroenabled.12","application/java-archive","application/vnd.rn-realmedia"]);const Uo=Object.create(null);Uo.open="0",Uo.close="1",Uo.ping="2",Uo.pong="3",Uo.message="4",Uo.upgrade="5",Uo.noop="6";const Lo=Object.create(null);Object.keys(Uo).forEach(e=>{Lo[Uo[e]]=e});const $o={type:"error",data:"parser error"},Ho="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),qo="function"==typeof ArrayBuffer,jo=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Wo=({type:e,data:t},r,i)=>Ho&&t instanceof Blob?r?i(t):Vo(t,i):qo&&(t instanceof ArrayBuffer||jo(t))?r?i(t):Vo(new Blob([t]),i):i(Uo[e]+(t||"")),Vo=(e,t)=>{const r=new FileReader;return r.onload=function(){const e=r.result.split(",")[1];t("b"+(e||""))},r.readAsDataURL(e)};function Go(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let Jo;const Yo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Xo="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let rg=0;rg<64;rg++)Xo[Yo.charCodeAt(rg)]=rg;const Zo="function"==typeof ArrayBuffer,Qo=(e,t)=>{if("string"!=typeof e)return{type:"message",data:tn(e,t)};const r=e.charAt(0);if("b"===r)return{type:"message",data:en(e.substring(1),t)};return Lo[r]?e.length>1?{type:Lo[r],data:e.substring(1)}:{type:Lo[r]}:$o},en=(e,t)=>{if(Zo){const r=(e=>{let t,r,i,o,n,s=.75*e.length,a=e.length,c=0;"="===e[e.length-1]&&(s--,"="===e[e.length-2]&&s--);const l=new ArrayBuffer(s),d=new Uint8Array(l);for(t=0;t<a;t+=4)r=Xo[e.charCodeAt(t)],i=Xo[e.charCodeAt(t+1)],o=Xo[e.charCodeAt(t+2)],n=Xo[e.charCodeAt(t+3)],d[c++]=r<<2|i>>4,d[c++]=(15&i)<<4|o>>2,d[c++]=(3&o)<<6|63&n;return l})(e);return tn(r,t)}return{base64:!0,data:e}},tn=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,rn=String.fromCharCode(30);function on(){return new TransformStream({transform(e,t){!function(e,t){Ho&&e.data instanceof Blob?e.data.arrayBuffer().then(Go).then(t):qo&&(e.data instanceof ArrayBuffer||jo(e.data))?t(Go(e.data)):Wo(e,!1,e=>{Jo||(Jo=new TextEncoder),t(Jo.encode(e))})}(e,r=>{const i=r.length;let o;if(i<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,i);else if(i<65536){o=new Uint8Array(3);const e=new DataView(o.buffer);e.setUint8(0,126),e.setUint16(1,i)}else{o=new Uint8Array(9);const e=new DataView(o.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(i))}e.data&&"string"!=typeof e.data&&(o[0]|=128),t.enqueue(o),t.enqueue(r)})}})}let nn;function sn(e){return e.reduce((e,t)=>e+t.length,0)}function an(e,t){if(e[0].length===t)return e.shift();const r=new Uint8Array(t);let i=0;for(let o=0;o<t;o++)r[o]=e[0][i++],i===e[0].length&&(e.shift(),i=0);return e.length&&i<e[0].length&&(e[0]=e[0].slice(i)),r}function cn(e){if(e)return function(e){for(var t in cn.prototype)e[t]=cn.prototype[t];return e}(e)}cn.prototype.on=cn.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},cn.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},cn.prototype.off=cn.prototype.removeListener=cn.prototype.removeAllListeners=cn.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,i=this._callbacks["$"+e];if(!i)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var o=0;o<i.length;o++)if((r=i[o])===t||r.fn===t){i.splice(o,1);break}return 0===i.length&&delete this._callbacks["$"+e],this},cn.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),r=this._callbacks["$"+e],i=1;i<arguments.length;i++)t[i-1]=arguments[i];if(r){i=0;for(var o=(r=r.slice(0)).length;i<o;++i)r[i].apply(this,t)}return this},cn.prototype.emitReserved=cn.prototype.emit,cn.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},cn.prototype.hasListeners=function(e){return!!this.listeners(e).length};const ln="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),dn="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function un(e,...t){return t.reduce((t,r)=>(e.hasOwnProperty(r)&&(t[r]=e[r]),t),{})}const pn=dn.setTimeout,hn=dn.clearTimeout;function gn(e,t){t.useNativeTimers?(e.setTimeoutFn=pn.bind(dn),e.clearTimeoutFn=hn.bind(dn)):(e.setTimeoutFn=dn.setTimeout.bind(dn),e.clearTimeoutFn=dn.clearTimeout.bind(dn))}function mn(e){return"string"==typeof e?function(e){let t=0,r=0;for(let i=0,o=e.length;i<o;i++)t=e.charCodeAt(i),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(i++,r+=4);return r}(e):Math.ceil(1.33*(e.byteLength||e.size))}function fn(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class yn extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}}class bn extends cn{constructor(e){super(),this.writable=!1,gn(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,r){return super.emitReserved("error",new yn(e,t,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=Qo(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t}(e);return t.length?"?"+t:""}}class wn extends bn{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once("pollComplete",function(){--e||t()})),this.writable||(e++,this.once("drain",function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const r=e.split(rn),i=[];for(let o=0;o<r.length;o++){const e=Qo(r[o],t);if(i.push(e),"error"===e.type)break}return i})(e,this.socket.binaryType).forEach(e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)}),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const r=e.length,i=new Array(r);let o=0;e.forEach((e,n)=>{Wo(e,!1,e=>{i[n]=e,++o===r&&t(i.join(rn))})})})(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=fn()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let In=!1;try{In="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(tg){}const Tn=In;function Sn(){}class kn extends wn{constructor(e){if(super(e),"undefined"!=typeof location){const t="https:"===location.protocol;let r=location.port;r||(r=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||r!==e.port}}doWrite(e,t){const r=this.request({method:"POST",data:e});r.on("success",t),r.on("error",(e,t)=>{this.onError("xhr post error",e,t)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(e,t)=>{this.onError("xhr poll error",e,t)}),this.pollXhr=e}}let En=class e extends cn{constructor(e,t,r){super(),this.createRequest=e,gn(this,r),this._opts=r,this._method=r.method||"GET",this._uri=t,this._data=void 0!==r.data?r.data:null,this._create()}_create(){var t;const r=un(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");r.xdomain=!!this._opts.xd;const i=this._xhr=this.createRequest(r);try{i.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){i.setDisableHeaderCheck&&i.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&i.setRequestHeader(e,this._opts.extraHeaders[e])}}catch(eg){}if("POST"===this._method)try{i.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(eg){}try{i.setRequestHeader("Accept","*/*")}catch(eg){}null===(t=this._opts.cookieJar)||void 0===t||t.addCookies(i),"withCredentials"in i&&(i.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(i.timeout=this._opts.requestTimeout),i.onreadystatechange=()=>{var e;3===i.readyState&&(null===(e=this._opts.cookieJar)||void 0===e||e.parseCookies(i.getResponseHeader("set-cookie"))),4===i.readyState&&(200===i.status||1223===i.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof i.status?i.status:0)},0))},i.send(this._data)}catch(eg){return void this.setTimeoutFn(()=>{this._onError(eg)},0)}"undefined"!=typeof document&&(this._index=e.requestsCount++,e.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(t){if(void 0!==this._xhr&&null!==this._xhr){if(this._xhr.onreadystatechange=Sn,t)try{this._xhr.abort()}catch(eg){}"undefined"!=typeof document&&delete e.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};if(En.requestsCount=0,En.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",vn);else if("function"==typeof addEventListener){addEventListener("onpagehide"in dn?"pagehide":"unload",vn,!1)}function vn(){for(let e in En.requests)En.requests.hasOwnProperty(e)&&En.requests[e].abort()}const An=function(){const e=Cn({xdomain:!1});return e&&null!==e.responseType}();function Cn(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||Tn))return new XMLHttpRequest}catch(eg){}if(!t)try{return new(dn[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(eg){}}const xn="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class Rn extends bn{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,r=xn?{}:un(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,r)}catch(tg){return this.emitReserved("error",tg)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],i=t===e.length-1;Wo(r,this.supportsBinary,e=>{try{this.doWrite(r,e)}catch(eg){}i&&ln(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=fn()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const Nn=dn.WebSocket||dn.MozWebSocket;const _n={websocket:class extends Rn{createSocket(e,t,r){return xn?new Nn(e,t,r):t?new Nn(e,t):new Nn(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends bn{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(tg){return this.emitReserved("error",tg)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=function(e,t){nn||(nn=new TextDecoder);const r=[];let i=0,o=-1,n=!1;return new TransformStream({transform(s,a){for(r.push(s);;){if(0===i){if(sn(r)<1)break;const e=an(r,1);n=!(128&~e[0]),o=127&e[0],i=o<126?3:126===o?1:2}else if(1===i){if(sn(r)<2)break;const e=an(r,2);o=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),i=3}else if(2===i){if(sn(r)<8)break;const e=an(r,8),t=new DataView(e.buffer,e.byteOffset,e.length),n=t.getUint32(0);if(n>Math.pow(2,21)-1){a.enqueue($o);break}o=n*Math.pow(2,32)+t.getUint32(4),i=3}else{if(sn(r)<o)break;const e=an(r,o);a.enqueue(Qo(n?e:nn.decode(e),t)),i=0}if(0===o||o>e){a.enqueue($o);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),i=on();i.readable.pipeTo(e.writable),this._writer=i.writable.getWriter();const o=()=>{r.read().then(({done:e,value:t})=>{e||(this.onPacket(t),o())}).catch(e=>{})};o();const n={type:"open"};this.query.sid&&(n.data=`{"sid":"${this.query.sid}"}`),this._writer.write(n).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],i=t===e.length-1;this._writer.write(r).then(()=>{i&&ln(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this._transport)||void 0===e||e.close()}},polling:class extends kn{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=An&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new En(Cn,this.uri(),e)}}},Pn=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Fn=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function On(e){if(e.length>8e3)throw"URI too long";const t=e,r=e.indexOf("["),i=e.indexOf("]");-1!=r&&-1!=i&&(e=e.substring(0,r)+e.substring(r,i).replace(/:/g,";")+e.substring(i,e.length));let o=Pn.exec(e||""),n={},s=14;for(;s--;)n[Fn[s]]=o[s]||"";return-1!=r&&-1!=i&&(n.source=t,n.host=n.host.substring(1,n.host.length-1).replace(/;/g,":"),n.authority=n.authority.replace("[","").replace("]","").replace(/;/g,":"),n.ipv6uri=!0),n.pathNames=function(e,t){const r=/\/{2,9}/g,i=t.replace(r,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||i.splice(0,1);"/"==t.slice(-1)&&i.splice(i.length-1,1);return i}(0,n.path),n.queryKey=function(e,t){const r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,i){t&&(r[t]=i)}),r}(0,n.query),n}const Dn="function"==typeof addEventListener&&"function"==typeof removeEventListener,zn=[];Dn&&addEventListener("offline",()=>{zn.forEach(e=>e())},!1);class Bn extends cn{constructor(e,t){if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&"object"==typeof e&&(t=e,e=null),e){const r=On(e);t.hostname=r.host,t.secure="https"===r.protocol||"wss"===r.protocol,t.port=r.port,r.query&&(t.query=r.query)}else t.host&&(t.hostname=On(t.host).host);gn(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{const t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},r=e.split("&");for(let i=0,o=r.length;i<o;i++){let e=r[i].split("=");t[decodeURIComponent(e[0])]=decodeURIComponent(e[1])}return t}(this.opts.query)),Dn&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},zn.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const r=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](r)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const e=this.opts.rememberUpgrade&&Bn.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",e=>this._onClose("transport close",e))}onOpen(){this.readyState="open",Bn.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){const r=this.writeBuffer[t].data;if(r&&(e+=mn(r)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,ln(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,r){return this._sendPacket("message",e,t,r),this}send(e,t,r){return this._sendPacket("message",e,t,r),this}_sendPacket(e,t,r,i){if("function"==typeof t&&(i=t,t=void 0),"function"==typeof r&&(i=r,r=null),"closing"===this.readyState||"closed"===this.readyState)return;(r=r||{}).compress=!1!==r.compress;const o={type:e,data:t,options:r};this.emitReserved("packetCreate",o),this.writeBuffer.push(o),i&&this.once("flush",i),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},r=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():e()}):this.upgrading?r():e()),this}_onError(e){if(Bn.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Dn&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const e=zn.indexOf(this._offlineEventListener);-1!==e&&zn.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}Bn.protocol=4;class Mn extends Bn{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),r=!1;Bn.priorWebsocketSuccess=!1;const i=()=>{r||(t.send([{type:"ping",data:"probe"}]),t.once("packet",e=>{if(!r)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Bn.priorWebsocketSuccess="websocket"===t.name,this.transport.pause(()=>{r||"closed"!==this.readyState&&(l(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}}))};function o(){r||(r=!0,l(),t.close(),t=null)}const n=e=>{const r=new Error("probe error: "+e);r.transport=t.name,o(),this.emitReserved("upgradeError",r)};function s(){n("transport closed")}function a(){n("socket closed")}function c(e){t&&e.name!==t.name&&o()}const l=()=>{t.removeListener("open",i),t.removeListener("error",n),t.removeListener("close",s),this.off("close",a),this.off("upgrading",c)};t.once("open",i),t.once("error",n),t.once("close",s),this.once("close",a),this.once("upgrading",c),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn(()=>{r||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let r=0;r<e.length;r++)~this.transports.indexOf(e[r])&&t.push(e[r]);return t}}let Kn=class extends Mn{constructor(e,t={}){const r="object"==typeof e?e:t;(!r.transports||r.transports&&"string"==typeof r.transports[0])&&(r.transports=(r.transports||["polling","websocket","webtransport"]).map(e=>_n[e]).filter(e=>!!e)),super(e,r)}};const Un="function"==typeof ArrayBuffer,Ln=Object.prototype.toString,$n="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Ln.call(Blob),Hn="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Ln.call(File);function qn(e){return Un&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||$n&&e instanceof Blob||Hn&&e instanceof File}function jn(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if(jn(e[t]))return!0;return!1}if(qn(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return jn(e.toJSON(),!0);for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&jn(e[r]))return!0;return!1}function Wn(e){const t=[],r=e.data,i=e;return i.data=Vn(r,t),i.attachments=t.length,{packet:i,buffers:t}}function Vn(e,t){if(!e)return e;if(qn(e)){const r={_placeholder:!0,num:t.length};return t.push(e),r}if(Array.isArray(e)){const r=new Array(e.length);for(let i=0;i<e.length;i++)r[i]=Vn(e[i],t);return r}if("object"==typeof e&&!(e instanceof Date)){const r={};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=Vn(e[i],t));return r}return e}function Gn(e,t){return e.data=Jn(e.data,t),delete e.attachments,e}function Jn(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let r=0;r<e.length;r++)e[r]=Jn(e[r],t);else if("object"==typeof e)for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=Jn(e[r],t));return e}const Yn=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Xn,Zn;(Zn=Xn||(Xn={}))[Zn.CONNECT=0]="CONNECT",Zn[Zn.DISCONNECT=1]="DISCONNECT",Zn[Zn.EVENT=2]="EVENT",Zn[Zn.ACK=3]="ACK",Zn[Zn.CONNECT_ERROR=4]="CONNECT_ERROR",Zn[Zn.BINARY_EVENT=5]="BINARY_EVENT",Zn[Zn.BINARY_ACK=6]="BINARY_ACK";function Qn(e){return"[object Object]"===Object.prototype.toString.call(e)}class es extends cn{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const r=t.type===Xn.BINARY_EVENT;r||t.type===Xn.BINARY_ACK?(t.type=r?Xn.EVENT:Xn.ACK,this.reconstructor=new ts(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!qn(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const r={type:Number(e.charAt(0))};if(void 0===Xn[r.type])throw new Error("unknown packet type "+r.type);if(r.type===Xn.BINARY_EVENT||r.type===Xn.BINARY_ACK){const i=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const o=e.substring(i,t);if(o!=Number(o)||"-"!==e.charAt(t))throw new Error("Illegal attachments");r.attachments=Number(o)}if("/"===e.charAt(t+1)){const i=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}r.nsp=e.substring(i,t)}else r.nsp="/";const i=e.charAt(t+1);if(""!==i&&Number(i)==i){const i=t+1;for(;++t;){const r=e.charAt(t);if(null==r||Number(r)!=r){--t;break}if(t===e.length)break}r.id=Number(e.substring(i,t+1))}if(e.charAt(++t)){const i=this.tryParse(e.substr(t));if(!es.isPayloadValid(r.type,i))throw new Error("invalid payload");r.data=i}return r}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(eg){return!1}}static isPayloadValid(e,t){switch(e){case Xn.CONNECT:return Qn(t);case Xn.DISCONNECT:return void 0===t;case Xn.CONNECT_ERROR:return"string"==typeof t||Qn(t);case Xn.EVENT:case Xn.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===Yn.indexOf(t[0]));case Xn.ACK:case Xn.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ts{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=Gn(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const rs=Object.freeze(Object.defineProperty({__proto__:null,Decoder:es,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==Xn.EVENT&&e.type!==Xn.ACK||!jn(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===Xn.EVENT?Xn.BINARY_EVENT:Xn.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==Xn.BINARY_EVENT&&e.type!==Xn.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=Wn(e),r=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(r),i}},get PacketType(){return Xn},protocol:5},Symbol.toStringTag,{value:"Module"}));function is(e,t,r){return e.on(t,r),function(){e.off(t,r)}}const os=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class ns extends cn{constructor(e,t,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[is(e,"open",this.onopen.bind(this)),is(e,"packet",this.onpacket.bind(this)),is(e,"error",this.onerror.bind(this)),is(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var r,i,o;if(os.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const n={type:Xn.EVENT,data:t,options:{}};if(n.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,r=t.pop();this._registerAckCallback(e,r),n.id=e}const s=null===(i=null===(r=this.io.engine)||void 0===r?void 0:r.transport)||void 0===i?void 0:i.writable,a=this.connected&&!(null===(o=this.io.engine)||void 0===o?void 0:o._hasPingExpired());return this.flags.volatile&&!s||(a?(this.notifyOutgoingListeners(n),this.packet(n)):this.sendBuffer.push(n)),this.flags={},this}_registerAckCallback(e,t){var r;const i=null!==(r=this.flags.timeout)&&void 0!==r?r:this._opts.ackTimeout;if(void 0===i)return void(this.acks[e]=t);const o=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))},i),n=(...e)=>{this.io.clearTimeoutFn(o),t.apply(this,e)};n.withError=!0,this.acks[e]=n}emitWithAck(e,...t){return new Promise((r,i)=>{const o=(e,t)=>e?i(e):r(t);o.withError=!0,t.push(o),this.emit(e,...t)})}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...i)=>{if(r!==this._queue[0])return;return null!==e?r.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...i)),r.pending=!1,this._drainQueue()}),this._queue.push(r),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Xn.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){const t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Xn.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Xn.EVENT:case Xn.BINARY_EVENT:this.onevent(e);break;case Xn.ACK:case Xn.BINARY_ACK:this.onack(e);break;case Xn.DISCONNECT:this.ondisconnect();break;case Xn.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const r of t)r.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let r=!1;return function(...i){r||(r=!0,t.packet({type:Xn.ACK,id:e,data:i}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Xn.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const r of t)r.apply(this,e.data)}}}function ss(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}ss.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*e);e=1&Math.floor(10*t)?e+r:e-r}return 0|Math.min(e,this.max)},ss.prototype.reset=function(){this.attempts=0},ss.prototype.setMin=function(e){this.ms=e},ss.prototype.setMax=function(e){this.max=e},ss.prototype.setJitter=function(e){this.jitter=e};class as extends cn{constructor(e,t){var r;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,gn(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(r=t.randomizationFactor)&&void 0!==r?r:.5),this.backoff=new ss({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const i=t.parser||rs;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new Kn(this.uri,this.opts);const t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const i=is(t,"open",function(){r.onopen(),e&&e()}),o=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},n=is(t,"error",o);if(!1!==this._timeout){const e=this._timeout,r=this.setTimeoutFn(()=>{i(),o(new Error("timeout")),t.close()},e);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}return this.subs.push(i),this.subs.push(n),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(is(e,"ping",this.onping.bind(this)),is(e,"data",this.ondata.bind(this)),is(e,"error",this.onerror.bind(this)),is(e,"close",this.onclose.bind(this)),is(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(eg){this.onclose("parse error",eg)}}ondecoded(e){ln(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new ns(this,e,t),this.nsps[e]=r),r}_destroy(e){const t=Object.keys(this.nsps);for(const r of t){if(this.nsps[r].active)return}this._close()}_packet(e){const t=this.encoder.encode(e);for(let r=0;r<t.length;r++)this.engine.write(t[r],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var r;this.cleanup(),null===(r=this.engine)||void 0===r||r.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()}))},t);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const cs={};function ls(e,t){"object"==typeof e&&(t=e,e=void 0);const r=function(e,t="",r){let i=e;r=r||"undefined"!=typeof location&&location,null==e&&(e=r.protocol+"//"+r.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?r.protocol+e:r.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==r?r.protocol+"//"+e:"https://"+e),i=On(e)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";const o=-1!==i.host.indexOf(":")?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+o+":"+i.port+t,i.href=i.protocol+"://"+o+(r&&r.port===i.port?"":":"+i.port),i}(e,(t=t||{}).path||"/socket.io"),i=r.source,o=r.id,n=r.path,s=cs[o]&&n in cs[o].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||s?a=new as(i,t):(cs[o]||(cs[o]=new as(i,t)),a=cs[o]),r.query&&!t.query&&(t.query=r.queryKey),a.socket(r.path,t)}Object.assign(ls,{Manager:as,Socket:ns,io:ls,connect:ls});const ds=class e{constructor(e){if(se(this,"client"),se(this,"config"),se(this,"logger",ai.getInstance()),se(this,"socket",null),se(this,"socketConnected",!1),se(this,"connectionMode","auto"),se(this,"wsBaseUrl",null),this.config=e,!e.apiKey)throw new ci("API key is required");if(!e.network)throw new ci("Network is required");const t={"x-api-key":e.apiKey,"Content-Type":"application/json"};this.client=Hr.create({baseURL:"https://v2-api.tier.bot/api",headers:t}),this.logger=ai.getInstance(),e.wsBaseUrl&&(this.wsBaseUrl=e.wsBaseUrl),this.connectionMode=e.connectionMode||"websocket",this.wsBaseUrl||"http"===this.connectionMode||this.fetchWebSocketServers().catch(e=>this.logger.warn("Failed to fetch WebSocket servers:",e))}async getFileMetadata(e){try{const t=await Hr.get(e),r=t.headers["content-type"]||"";return{size:parseInt(t.headers["content-length"]||"0",10),mimeType:r}}catch(t){throw this.logger.error("Error fetching file metadata:",t),new ci("Unable to fetch file metadata")}}getMimeType(t){const r=t.toLowerCase().split(".").pop();if(!r)throw new ci("File must have an extension");const i=e.VALID_MIME_TYPES[r];if(!i)throw new ci(`Unsupported file type: ${r}`);return i}validateRequest(t){if(this.logger.debug("Validating request:",t),!t.holderId||""===t.holderId.trim())throw this.logger.warn("holderId is missing or empty"),new ci("holderId is required");if(!e.VALID_MODES.includes(t.mode))throw new ci(`Invalid mode: ${t.mode}. Must be one of: ${e.VALID_MODES.join(", ")}`);if("hashinal"===t.mode&&!t.jsonFileURL&&!t.metadataObject)throw new ci("Hashinal mode requires either jsonFileURL or metadataObject");if(t.onlyJSONCollection&&"hashinal-collection"!==t.mode)throw new ci("onlyJSONCollection can only be used with hashinal-collection mode");this.validateFileInput(t.file)}normalizeMimeType(e){return"image/vnd.microsoft.icon"===e?(this.logger.debug("Normalizing MIME type from image/vnd.microsoft.icon to image/x-icon"),"image/x-icon"):e}validateMimeType(t){return!!Object.values(e.VALID_MIME_TYPES).includes(t)||"image/vnd.microsoft.icon"===t&&(this.logger.debug("Accepting alternative MIME type for ICO: image/vnd.microsoft.icon"),!0)}validateFileInput(t){if("base64"===t.type){if(!t.base64)throw new ci("Base64 data is required");const r=t.base64.replace(/^data:.*?;base64,/,"");if(Math.ceil(.75*r.length)>e.MAX_BASE64_SIZE)throw new ci(`File size exceeds maximum limit of ${e.MAX_BASE64_SIZE/1024/1024}MB`);const i=t.mimeType||this.getMimeType(t.fileName);if(!this.validateMimeType(i))throw new ci("File must have one of the supported MIME types");"image/vnd.microsoft.icon"===t.mimeType&&(t.mimeType=this.normalizeMimeType(t.mimeType))}else if("url"===t.type&&!t.url)throw new ci("URL is required")}async detectMimeTypeFromBase64(e){if(e.startsWith("data:")){const t=e.match(/^data:([^;]+);base64,/);if(t&&t.length>1)return t[1]}try{const t=e.replace(/\s/g,""),r=be.from(t,"base64"),i=await async function(e,t){return new Ko(t).fromBuffer(e)}(r);return(null==i?void 0:i.mime)||"application/octet-stream"}catch(tg){return this.logger.warn("Failed to detect MIME type from buffer"),"application/octet-stream"}}async startInscription(t){var r,i;try{this.validateRequest(t);let r=t.file.mimeType;if("url"===t.file.type){const i=await this.getFileMetadata(t.file.url);if(r=i.mimeType||r,i.size>e.MAX_URL_FILE_SIZE)throw new ci(`File size exceeds maximum URL file limit of ${e.MAX_URL_FILE_SIZE/1024/1024}MB`)}else"base64"===t.file.type&&(r=await this.detectMimeTypeFromBase64(t.file.base64));if("image/vnd.microsoft.icon"===r&&(r=this.normalizeMimeType(r)),t.jsonFileURL){if("application/json"!==(await this.getFileMetadata(t.jsonFileURL)).mimeType)throw new ci("JSON file must be of type application/json")}const i={holderId:t.holderId,mode:t.mode,network:this.config.network,onlyJSONCollection:t.onlyJSONCollection?1:0,creator:t.creator,description:t.description,fileStandard:t.fileStandard,metadataObject:t.metadataObject,jsonFileURL:t.jsonFileURL};let o;return o="url"===t.file.type?await this.client.post("/inscriptions/start-inscription",{...i,fileURL:t.file.url}):await this.client.post("/inscriptions/start-inscription",{...i,fileBase64:t.file.base64,fileName:t.file.fileName,fileMimeType:r||this.getMimeType(t.file.fileName)}),o.data}catch(o){if(o instanceof ci)throw o;if(Hr.isAxiosError(o))throw new Error((null==(i=null==(r=o.response)?void 0:r.data)?void 0:i.message)||"Failed to start inscription");throw o}}async executeTransaction(e,t){var r,o;try{const n="mainnet"===t.network?i.Client.forMainnet():i.Client.forTestnet(),a=new s.HederaMirrorNode(t.network),c=await a.requestAccount(t.accountId),l=null==(r=null==c?void 0:c.key)?void 0:r._type,d="string"==typeof t.privateKey;let u;if(l&&d)u=(null==(o=null==l?void 0:l.toLowerCase())?void 0:o.includes("ecdsa"))?i.PrivateKey.fromStringECDSA(t.privateKey):i.PrivateKey.fromStringED25519(t.privateKey);else if(!l&&d){const e=d?s.detectKeyTypeFromString(t.privateKey):void 0;u="ed25519"===(null==e?void 0:e.detectedType)?i.PrivateKey.fromStringED25519(t.privateKey):i.PrivateKey.fromStringECDSA(t.privateKey)}else u=t.privateKey;n.setOperator(t.accountId,u);const p=i.TransferTransaction.fromBytes(be.from(e,"base64")),h=await p.sign(u),g=await h.execute(n),m=(await g.getReceipt(n)).status.toString();if("SUCCESS"!==m)throw new Error(`Transaction failed with status: ${m}`);return g.transactionId.toString()}catch(n){throw new Error(`Failed to execute transaction: ${n instanceof Error?n.message:"Unknown error"}`)}}async executeTransactionWithSigner(e,t){try{const r=i.TransferTransaction.fromBytes(be.from(e,"base64")),o=await r.executeWithSigner(t),n=(await o.getReceiptWithSigner(t)).status.toString();if("SUCCESS"!==n)throw new Error(`Transaction failed with status: ${n}`);return o.transactionId.toString()}catch(r){throw new Error(`Failed to execute transaction: ${r instanceof Error?r.message:"Unknown error"}`)}}async inscribeAndExecute(e,t,r,i){const o=(null==i?void 0:i.waitForCompletion)??!0,n=(null==i?void 0:i.maxWaitTime)??12e4,s=(null==i?void 0:i.checkInterval)??2e3;if(this.logger.debug("inscribeAndExecute called",{hasProgressCallback:!!r,connectionMode:this.connectionMode,wsBaseUrl:this.wsBaseUrl}),"http"!==this.connectionMode){const i="websocket"===this.connectionMode||"auto"===this.connectionMode&&await this.detectBestConnection();if(i)try{return await this.inscribeViaWebSocket(e,t,r)}catch(d){throw this.logger.error("WebSocket inscription failed, falling back to HTTP:",d),d}else this.logger.info(`Not using WebSocket: useWebSocket=${i}, wsBaseUrl=${this.wsBaseUrl}`)}else this.logger.info(`Not using WebSocket: hasCallback=${!!r}, connectionMode=${this.connectionMode}`);const a=await this.startInscription(e);if(!a.transactionBytes)throw this.logger.error("No transaction bytes returned from inscription request",a),new Error("No transaction bytes returned from inscription request");this.logger.info("executing transaction");const c=await this.executeTransaction(a.transactionBytes,t),l={jobId:a.tx_id,transactionId:c};if(o){r&&r({stage:"confirming",message:"Transaction executed, waiting for inscription to complete",progressPercent:5});const e=Math.floor(n/s),t=await this.waitForInscription(c,e,s,!0,r);return{...l,topicId:t.topic_id,status:t.status,completed:t.completed}}return l}async fetchWebSocketServers(){try{const e=await this.client.get("/inscriptions/websocket-servers"),{servers:t,recommended:r}=e.data;if(r)this.wsBaseUrl=r;else if(t&&t.length>0){const e=t.filter(e=>"active"===e.status);if(e.length>0){const t=e[0];this.wsBaseUrl=t.url}}}catch(e){this.logger.debug("Could not fetch WebSocket servers, will use HTTP only")}}async detectBestConnection(){if(!this.wsBaseUrl)return!1;try{const e=ls(this.wsBaseUrl,{auth:{apiKey:this.config.apiKey},transports:["websocket"],timeout:3e3});return new Promise(t=>{const r=setTimeout(()=>{e.disconnect(),t(!1)},3e3);e.on("connect",()=>{clearTimeout(r),e.disconnect(),t(!0)}),e.on("connect_error",()=>{clearTimeout(r),e.disconnect(),t(!1)})})}catch(eg){return!1}}async inscribeViaWebSocket(e,t,r){if(!this.wsBaseUrl){const e=(await this.client.get("/inscriptions/websocket-servers")).data.recommended;if(!e)throw new Error("No WebSocket servers available");this.wsBaseUrl=e}return await this.connectWebSocket(),new Promise((i,o)=>{if(!this.socket)return o(new Error("WebSocket not connected"));let n,s,a,c;const l=()=>{var e,t,r;c&&clearTimeout(c),null==(e=this.socket)||e.off("inscription-progress",p),null==(t=this.socket)||t.off("inscription-complete",d),null==(r=this.socket)||r.off("inscription-error",u)};c=setTimeout(()=>{this.logger.error("WebSocket inscription timeout after 60 seconds",{jobId:n,transactionId:s,lastTopicId:a}),l(),i({jobId:n,transactionId:s,topicId:a,topic_id:a,status:"timeout",completed:!1})},6e4);const d=e=>{l(),i({jobId:n,transactionId:s,topicId:e.topicId||e.topic_id,topic_id:e.topicId||e.topic_id,status:"completed",completed:!0})},u=e=>{l(),o(new Error(e.error||"Inscription failed"))},p=e=>{this.logger.debug("Progress event received:",{jobId:e.jobId,status:e.status,progress:e.progress,topicId:e.topicId||e.topic_id,topic_id:e.topicId||e.topic_id}),(e.topicId||e.topic_id)&&(a=e.topicId||e.topic_id),r&&r({stage:"completed"===e.status?"completed":"confirming",message:`Processing inscription: ${e.status}`,progressPercent:e.progress||0,details:e}),"completed"!==e.status&&100!==e.progress||(this.logger.info("Inscription completed via progress handler",{status:e.status,progress:e.progress,topicId:e.topicId||e.topic_id||a,topic_id:e.topicId||e.topic_id||a}),l(),i({jobId:n,transactionId:s,topicId:e.topicId||e.topic_id||a,topic_id:e.topicId||e.topic_id||a,status:"completed",completed:!0}))};this.socket.on("inscription-progress",p),this.socket.on("inscription-complete",d),this.socket.on("inscription-error",u),this.socket.emit("start-inscription",{...e,network:this.config.network},async e=>{if(!e.success)return l(),o(new Error(e.error||"Inscription failed"));try{if(!e.transactionBytes)throw new Error("No transaction bytes returned from WebSocket inscription");if(s=await this.executeTransaction(e.transactionBytes,t),n=e.jobId||e.tx_id,!n)throw new Error("No job ID returned from WebSocket inscription");r&&r({stage:"confirming",message:"Transaction executed, inscribing to HCS...",progressPercent:5}),this.logger.info("Transaction executed, waiting for inscription completion...",{jobId:n,transactionId:s})}catch(i){l(),o(i)}})})}async connectWebSocket(){if(!this.socketConnected||!this.socket){if(!this.wsBaseUrl)throw new Error("WebSocket URL not configured");return new Promise((e,t)=>{this.socket=ls(this.wsBaseUrl,{auth:{apiKey:this.config.apiKey},transports:["websocket","polling"]});const r=setTimeout(()=>{t(new Error("WebSocket connection timeout"))},1e4);this.socket.on("connect",()=>{clearTimeout(r),this.socketConnected=!0,this.logger.info("WebSocket connected"),e()}),this.socket.on("connect_error",e=>{clearTimeout(r),this.socketConnected=!1,t(new Error(`WebSocket connection failed: ${e.message}`))}),this.socket.on("disconnect",()=>{this.socketConnected=!1,this.logger.info("WebSocket disconnected")})})}}disconnect(){this.socket&&(this.socket.disconnect(),this.socket=null,this.socketConnected=!1)}async inscribe(e,t){const r=await this.startInscription(e);if(!r.transactionBytes)throw this.logger.error("No transaction bytes returned from inscription request",r),new Error("No transaction bytes returned from inscription request");this.logger.info("executing transaction");const i=await this.executeTransactionWithSigner(r.transactionBytes,t);return{jobId:r.tx_id,transactionId:i}}async retryWithBackoff(e,t=3,r=1e3){for(let o=0;o<t;o++)try{return await e()}catch(i){if(o===t-1)throw i;const e=r*Math.pow(2,o);await new Promise(t=>setTimeout(t,e)),this.logger.debug(`Retry attempt ${o+1}/${t} after ${e}ms delay`)}throw new Error("Retry operation failed")}async retrieveInscription(e){if(!e)throw new ci("Transaction ID is required");try{return await this.retryWithBackoff(async()=>{const t=(await this.client.get(`/inscriptions/retrieve-inscription?id=${e}`)).data;return{...t,jobId:t.id}})}catch(t){throw this.logger.error("Failed to retrieve inscription:",t),t}}async getInscriptionNumbers(e={}){try{return(await this.client.get("/inscriptions/numbers",{params:e})).data}catch(t){throw this.logger.error("Failed to fetch inscription numbers:",t),t}}static async authenticate(e){return new li(e).authenticate()}static async createWithAuth(t){const r="client"===t.type?new di({...t,logger:ai.getInstance()}):new li(t),{apiKey:i}=await r.authenticate();return new e({apiKey:i,network:t.network||"mainnet",wsBaseUrl:t.wsBaseUrl,connectionMode:t.connectionMode||"websocket"})}async waitForInscription(e,t=30,r=4e3,i=!1,o){var n;let s=0,a=0;const c=(r,i,n,c)=>{if(o)try{a=Math.max(a,n),o({stage:r,message:i,progressPercent:a,details:{...c,txId:e,currentAttempt:s,maxAttempts:t}})}catch(tg){this.logger.warn(`Error in progress callback: ${tg}`)}};for(c("confirming","Starting inscription verification",0);s<t;){c("confirming",`Verifying inscription status (attempt ${s+1}/${t})`,5,{attempt:s+1});const o=await this.retrieveInscription(e);if(o.error)throw c("verifying",`Error: ${o.error}`,100,{error:o.error}),new Error(o.error);let a=5;void 0!==o.messages&&void 0!==o.maxMessages&&o.maxMessages>0?(a=Math.min(95,5+o.messages/o.maxMessages*90),o.completed&&(a=100)):"processing"===o.status?a=10:o.completed&&(a=100),c(o.completed?"completed":"confirming",o.completed?"Inscription completed successfully":`Processing inscription (${o.status})`,a,{status:o.status,messagesProcessed:o.messages,maxMessages:o.maxMessages,messageCount:o.messages,completed:o.completed,confirmedMessages:o.confirmedMessages,result:o});const l="hashinal"===o.mode,d="6"===(null==(n=o.fileStandard)?void 0:n.toString());if(l&&o.topic_id&&o.jsonTopicId&&(!i||o.completed))return c("completed","Inscription verification complete",100,{result:o}),o;if(!l&&!d&&o.topic_id&&(!i||o.completed))return c("completed","Inscription verification complete",100,{result:o}),o;if(d&&o.topic_id&&o.jsonTopicId&&o.registryTopicId&&(!i||o.completed))return c("completed","Inscription verification complete",100,{result:o}),o;await new Promise(e=>setTimeout(e,r)),s++}throw c("verifying",`Inscription ${e} did not complete within ${t} attempts`,100,{timedOut:!0}),new Error(`Inscription ${e} did not complete within ${t} attempts`)}async getHolderInscriptions(e){var t,r;if(!e.holderId)throw new ci("Holder ID is required");try{const t={holderId:e.holderId};e.includeCollections&&(t.includeCollections="1");return(await this.client.get("/inscriptions/holder-inscriptions",{params:t})).data}catch(i){if(this.logger.error("Failed to fetch holder inscriptions:",i),Hr.isAxiosError(i))throw new Error((null==(r=null==(t=i.response)?void 0:t.data)?void 0:r.message)||"Failed to fetch holder inscriptions");throw i}}};se(ds,"VALID_MODES",["file","upload","hashinal","hashinal-collection"]),se(ds,"MAX_BASE64_SIZE",2097152),se(ds,"MAX_URL_FILE_SIZE",104857600),se(ds,"VALID_MIME_TYPES",{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",ico:"image/x-icon",heic:"image/heic",heif:"image/heif",bmp:"image/bmp",webp:"image/webp",tiff:"image/tiff",tif:"image/tiff",svg:"image/svg+xml",mp4:"video/mp4",webm:"video/webm",mp3:"audio/mpeg",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",html:"text/html",htm:"text/html",css:"text/css",php:"application/x-httpd-php",java:"text/x-java-source",js:"application/javascript",mjs:"application/javascript",csv:"text/csv",json:"application/json",txt:"text/plain",glb:"model/gltf-binary",wav:"audio/wav",ogg:"audio/ogg",oga:"audio/ogg",flac:"audio/flac",aac:"audio/aac",m4a:"audio/mp4",avi:"video/x-msvideo",mov:"video/quicktime",mkv:"video/x-matroska",m4v:"video/mp4",mpg:"video/mpeg",mpeg:"video/mpeg",ts:"application/typescript",zip:"application/zip",rar:"application/vnd.rar",tar:"application/x-tar",gz:"application/gzip","7z":"application/x-7z-compressed",xml:"application/xml",yaml:"application/yaml",yml:"application/yaml",md:"text/markdown",markdown:"text/markdown",rtf:"application/rtf",gltf:"model/gltf+json",usdz:"model/vnd.usdz+zip",obj:"model/obj",stl:"model/stl",fbx:"application/octet-stream",ttf:"font/ttf",otf:"font/otf",woff:"font/woff",woff2:"font/woff2",eot:"application/vnd.ms-fontobject",psd:"application/vnd.adobe.photoshop",ai:"application/postscript",eps:"application/postscript",ps:"application/postscript",sqlite:"application/x-sqlite3",db:"application/x-sqlite3",apk:"application/vnd.android.package-archive",ics:"text/calendar",vcf:"text/vcard",py:"text/x-python",rb:"text/x-ruby",go:"text/x-go",rs:"text/x-rust",typescript:"application/typescript",jsx:"text/jsx",tsx:"text/tsx",sql:"application/sql",toml:"application/toml",avif:"image/avif",jxl:"image/jxl",weba:"audio/webm",wasm:"application/wasm"});let us=ds;class ps{constructor(e={}){this.module=e.module||"Progress",this.callback=e.callback,this.logger=e.logger||new z({level:"info",module:"ProgressReporter"}),this.logProgress=e.logProgress??!0,this.minPercent=e.minPercent??0,this.maxPercent=e.maxPercent??100,this.lastReportedPercent=-1,this.lastReportedTime=0,this.throttleMs=100}static getInstance(e={}){return ps.instance?(e.callback&&ps.instance.setCallback(e.callback),e.module&&ps.instance.setModule(e.module),e.logger&&ps.instance.setLogger(e.logger),void 0!==e.minPercent&&ps.instance.setMinPercent(e.minPercent),void 0!==e.maxPercent&&ps.instance.setMaxPercent(e.maxPercent)):ps.instance=new ps(e),ps.instance}setCallback(e){this.callback=e}setModule(e){this.module=e}setLogger(e){this.logger=e}setMinPercent(e){this.minPercent=e}setMaxPercent(e){this.maxPercent=e}createSubProgress(e){const t=new ps({module:this.module,logger:this.logger,logProgress:this.logProgress,minPercent:e.minPercent,maxPercent:e.maxPercent}),r=e.logPrefix||"";return t.setCallback(t=>{const i=this.scalePercent(t.progressPercent,e.minPercent,e.maxPercent);let o=t.message;r&&!o.startsWith(r)&&(o=`${r}: ${o}`),this.report({stage:t.stage,message:o,progressPercent:i,details:t.details})}),t}report(e){const t=e.progressPercent,r=Math.max(0,Math.min(100,t)),i=this.scalePercent(r,0,100),o=Date.now();if(i===this.lastReportedPercent&&o-this.lastReportedTime<this.throttleMs&&"completed"!==e.stage&&"failed"!==e.stage)return;this.lastReportedPercent=i,this.lastReportedTime=o;const n={...e,progressPercent:i};if(this.logProgress&&this.logger.debug(`[${this.module}] [${e.stage.toUpperCase()}] ${e.message} (${i.toFixed(1)}%)`,e.details),this.callback)try{this.callback(n)}catch(tg){this.logger.warn(`Error in progress callback: ${tg}`)}}scalePercent(e,t,r){const i=(this.maxPercent-this.minPercent)/(r-t);return this.minPercent+(e-t)*i}preparing(e,t,r){this.report({stage:"preparing",message:e,progressPercent:t,details:r})}submitting(e,t,r){this.report({stage:"submitting",message:e,progressPercent:t,details:r})}confirming(e,t,r){this.report({stage:"confirming",message:e,progressPercent:t,details:r})}verifying(e,t,r){this.report({stage:"verifying",message:e,progressPercent:t,details:r})}completed(e,t){this.report({stage:"completed",message:e,progressPercent:100,details:t})}failed(e,t){this.report({stage:"failed",message:e,progressPercent:this.lastReportedPercent,details:t})}}class hs extends Error{constructor(e,t="PARSING_FAILED",r,i){super(e),this.name="TransactionParsingError",this.code=t,this.originalError=r,this.transactionBytes=i,Error.captureStackTrace&&Error.captureStackTrace(this,hs)}}const gs=(e,t)=>e.replace(/\{([^}]+)\}/g,(e,r)=>{const i=((e,t)=>{const r=t.split(".");let i=e;for(const o of r){if(null==i)return;i=i[o]}return i})(t,String(r).trim());return null==i?"(Unknown)":String(i)}),ms=e=>{const t=[],r=[];if(Array.isArray(e.transfers))for(const i of e.transfers){const e=parseFloat(i.amount);let o=i.amount;o.startsWith("-")&&(o=o.substring(1)),o=o.replace(/\s*ℏ$/,""),e<0?t.push(`${i.accountId} (${o} ℏ)`):e>0&&r.push(`${i.accountId} (${o} ℏ)`)}return t.length>0&&r.length>0?`Transfer of HBAR from ${t.join(", ")} to ${r.join(", ")}`:e.humanReadableType},fs=e=>{if(!e.contractCall)return e.humanReadableType;let t=`Contract call to ${e.contractCall.contractId} with ${e.contractCall.gas} gas`;return e.contractCall.amount>0&&(t+=` and ${e.contractCall.amount} HBAR`),e.contractCall.functionName&&(t+=` calling function ${e.contractCall.functionName}`),t},ys=e=>e.tokenMint?`Mint ${e.tokenMint.amount} tokens for token ${e.tokenMint.tokenId}`:e.humanReadableType,bs=e=>e.tokenBurn?`Burn ${e.tokenBurn.amount} tokens for token ${e.tokenBurn.tokenId}`:e.humanReadableType,ws=e=>{if(!e.tokenCreation)return e.humanReadableType;let t=`Create token ${e.tokenCreation.tokenName||"(No Name)"} (${e.tokenCreation.tokenSymbol||"(No Symbol)"})`;return e.tokenCreation.initialSupply&&(t+=` with initial supply ${e.tokenCreation.initialSupply}`),e.tokenCreation.customFees&&e.tokenCreation.customFees.length>0&&(t+=` including ${e.tokenCreation.customFees.length} custom fee(s)`),t},Is=e=>{if(!e.consensusCreateTopic)return e.humanReadableType;let t="Create new topic";return e.consensusCreateTopic.memo&&(t+=` with memo "${e.consensusCreateTopic.memo}"`),e.consensusCreateTopic.autoRenewAccountId&&(t+=`, auto-renew by ${e.consensusCreateTopic.autoRenewAccountId}`),t},Ts=e=>{if(!e.consensusSubmitMessage)return e.humanReadableType;let t="Submit message";if(e.consensusSubmitMessage.topicId&&(t+=` to topic ${e.consensusSubmitMessage.topicId}`),e.consensusSubmitMessage.message)if("utf8"===e.consensusSubmitMessage.messageEncoding){t+=`: "${e.consensusSubmitMessage.message.substring(0,70)}${e.consensusSubmitMessage.message.length>70?"...":""}"`}else{t+=` (binary message data, length: ${globalThis.Buffer.from(e.consensusSubmitMessage.message,"base64").length} bytes)`}return e.consensusSubmitMessage.chunkInfoNumber&&e.consensusSubmitMessage.chunkInfoTotal&&(t+=` (chunk ${e.consensusSubmitMessage.chunkInfoNumber}/${e.consensusSubmitMessage.chunkInfoTotal})`),t},Ss=e=>{if(!e.fileCreate)return e.humanReadableType;let t="Create File";return e.fileCreate.memo&&(t+=` with memo "${e.fileCreate.memo}"`),e.fileCreate.contents&&(t+=" (includes content)"),t},ks=e=>e.fileAppend?`Append to File ${e.fileAppend.fileId||"(Unknown ID)"}`:e.humanReadableType,Es=e=>e.fileUpdate?`Update File ${e.fileUpdate.fileId||"(Unknown ID)"}`:e.humanReadableType,vs=e=>e.fileDelete?`Delete File ${e.fileDelete.fileId||"(Unknown ID)"}`:e.humanReadableType,As=e=>e.consensusUpdateTopic?`Update Topic ${e.consensusUpdateTopic.topicId||"(Unknown ID)"}`:e.humanReadableType,Cs=e=>e.consensusDeleteTopic?`Delete Topic ${e.consensusDeleteTopic.topicId||"(Unknown ID)"}`:e.humanReadableType,xs=e=>e.tokenFreeze?`Freeze Token ${e.tokenFreeze.tokenId} for Account ${e.tokenFreeze.accountId}`:e.humanReadableType,Rs=e=>e.tokenUnfreeze?`Unfreeze Token ${e.tokenUnfreeze.tokenId} for Account ${e.tokenUnfreeze.accountId}`:e.humanReadableType,Ns=e=>e.tokenGrantKyc?`Grant KYC for Token ${e.tokenGrantKyc.tokenId} to Account ${e.tokenGrantKyc.accountId}`:e.humanReadableType,_s=e=>e.tokenRevokeKyc?`Revoke KYC for Token ${e.tokenRevokeKyc.tokenId} from Account ${e.tokenRevokeKyc.accountId}`:e.humanReadableType,Ps=e=>e.tokenPause?`Pause Token ${e.tokenPause.tokenId}`:e.humanReadableType,Fs=e=>e.tokenUnpause?`Unpause Token ${e.tokenUnpause.tokenId}`:e.humanReadableType,Os=e=>{if(e.tokenWipeAccount){let t=`Wipe Token ${e.tokenWipeAccount.tokenId} from Account ${e.tokenWipeAccount.accountId}`;return e.tokenWipeAccount.serialNumbers&&e.tokenWipeAccount.serialNumbers.length>0&&(t+=` (Serials: ${e.tokenWipeAccount.serialNumbers.join(", ")})`),e.tokenWipeAccount.amount&&(t+=` (Amount: ${e.tokenWipeAccount.amount})`),t}return e.humanReadableType},Ds=e=>e.tokenDelete?`Delete Token ${e.tokenDelete.tokenId}`:e.humanReadableType,zs=e=>e.tokenAssociate?`Associate Account ${e.tokenAssociate.accountId} with Tokens: ${(e.tokenAssociate.tokenIds||[]).join(", ")}`:e.humanReadableType,Bs=e=>e.tokenDissociate?`Dissociate Account ${e.tokenDissociate.accountId} from Tokens: ${(e.tokenDissociate.tokenIds||[]).join(", ")}`:e.humanReadableType,Ms=e=>e.cryptoDelete?`Delete Account ${e.cryptoDelete.deleteAccountId}`:e.humanReadableType,Ks=e=>{if(!e.cryptoCreateAccount)return e.humanReadableType;let t="Create Account";return e.cryptoCreateAccount.initialBalance&&"0"!==e.cryptoCreateAccount.initialBalance&&(t+=` with balance ${e.cryptoCreateAccount.initialBalance}`),e.cryptoCreateAccount.alias&&(t+=` (Alias: ${e.cryptoCreateAccount.alias})`),t},Us=e=>e.cryptoUpdateAccount?`Update Account ${e.cryptoUpdateAccount.accountIdToUpdate||"(Unknown ID)"}`:e.humanReadableType,Ls=e=>{if(e.cryptoApproveAllowance){let t=0;return e.cryptoApproveAllowance.hbarAllowances&&(t+=e.cryptoApproveAllowance.hbarAllowances.length),e.cryptoApproveAllowance.tokenAllowances&&(t+=e.cryptoApproveAllowance.tokenAllowances.length),e.cryptoApproveAllowance.nftAllowances&&(t+=e.cryptoApproveAllowance.nftAllowances.length),`Approve ${t} Crypto Allowance(s)`}return e.humanReadableType},$s=e=>{if(e.cryptoDeleteAllowance){return`Delete ${(e.cryptoDeleteAllowance.nftAllowancesToRemove||[]).length} NFT Crypto Allowance(s)`}return e.humanReadableType},Hs=e=>{if(e.contractCreate){let t="Create Contract";return e.contractCreate.memo&&(t+=` (Memo: ${e.contractCreate.memo})`),t}return e.humanReadableType},qs=e=>e.contractUpdate?`Update Contract ${e.contractUpdate.contractIdToUpdate||"(Unknown ID)"}`:e.humanReadableType,js=e=>{if(e.contractDelete){let t=`Delete Contract ${e.contractDelete.contractIdToDelete||"(Unknown ID)"}`;return e.contractDelete.transferAccountId?t+=` (Transfer to Account: ${e.contractDelete.transferAccountId})`:e.contractDelete.transferContractId&&(t+=` (Transfer to Contract: ${e.contractDelete.transferContractId})`),t}return e.humanReadableType},Ws=e=>e.tokenUpdate?`Update Token ${e.tokenUpdate.tokenId||"(Unknown ID)"}`:e.humanReadableType,Vs=e=>e.tokenFeeScheduleUpdate?`Update Fee Schedule for Token ${e.tokenFeeScheduleUpdate.tokenId||"(Unknown ID)"}`:e.humanReadableType,Gs=e=>{if(!e.tokenAirdrop||!e.tokenAirdrop.tokenTransfers)return e.humanReadableType;let t=0,r=0;for(const i of e.tokenAirdrop.tokenTransfers)t+=1,r+=Array.isArray(i.transfers)?i.transfers.length:0;return`Token Airdrop across ${t} token(s), ${r} transfer(s)`},Js=e=>{if(!e.scheduleCreate)return e.humanReadableType;let t="Create Schedule";return e.scheduleCreate.memo&&(t+=` (Memo: ${e.scheduleCreate.memo})`),t},Ys=e=>e.scheduleSign?"Sign Schedule":e.humanReadableType,Xs=e=>e.scheduleDelete?"Delete Schedule":e.humanReadableType,Zs=e=>e.systemDelete?e.systemDelete.fileId?`System Delete File ${e.systemDelete.fileId}`:e.systemDelete.contractId?`System Delete Contract ${e.systemDelete.contractId}`:"System Delete":e.humanReadableType,Qs=e=>e.systemUndelete?e.systemUndelete.fileId?`System Undelete File ${e.systemUndelete.fileId}`:e.systemUndelete.contractId?`System Undelete Contract ${e.systemUndelete.contractId}`:"System Undelete":e.humanReadableType,ea=e=>"Network Freeze",ta=e=>"Ethereum Transaction",ra=e=>e.uncheckedSubmit&&e.uncheckedSubmit.topicId?`Unchecked Submit to topic ${e.uncheckedSubmit.topicId}`:"Unchecked Submit",ia=e=>"Create Node",oa=e=>"Update Node",na=e=>"Delete Node",sa=e=>`Atomic Batch (${Array.isArray(e.atomicBatch?.transactions)?e.atomicBatch.transactions.length:0} transaction(s))`,aa={CRYPTOTRANSFER:{fn:ms},cryptoTransfer:{fn:ms},CONTRACTCALL:{fn:fs},contractCall:{fn:fs},TOKENMINT:{fn:ys},tokenMint:{fn:ys},TOKENBURN:{fn:bs},tokenBurn:{fn:bs},TOKENCREATE:{fn:ws},tokenCreation:{fn:ws},TOPICCREATE:{fn:Is},consensusCreateTopic:{fn:Is},CONSENSUSSUBMITMESSAGE:{fn:Ts},consensusSubmitMessage:{fn:Ts},TOPICUPDATE:{fn:As},consensusUpdateTopic:{fn:As},TOPICDELETE:{fn:Cs},consensusDeleteTopic:{fn:Cs},FILECREATE:{fn:Ss},fileCreate:{fn:Ss},FILEAPPEND:{fn:ks},fileAppend:{fn:ks},FILEUPDATE:{fn:Es},fileUpdate:{fn:Es},FILEDELETE:{fn:vs},fileDelete:{fn:vs},TOKENUPDATE:{fn:Ws},tokenUpdate:{fn:Ws},TOKENFEESCHEDULEUPDATE:{fn:Vs},tokenFeeScheduleUpdate:{fn:Vs},TOKENFREEZE:{fn:xs},tokenFreeze:{fn:xs},TOKENUNFREEZE:{fn:Rs},tokenUnfreeze:{fn:Rs},TOKENGRANTKYC:{fn:Ns},tokenGrantKyc:{fn:Ns},TOKENREVOKEKYC:{fn:_s},tokenRevokeKyc:{fn:_s},TOKENPAUSE:{fn:Ps},tokenPause:{fn:Ps},TOKENUNPAUSE:{fn:Fs},tokenUnpause:{fn:Fs},TOKENWIPE:{fn:Os},TOKENWIPEACCOUNT:{fn:Os},tokenWipe:{fn:Os},tokenWipeAccount:{fn:Os},TOKENDELETE:{fn:Ds},tokenDelete:{fn:Ds},TOKENASSOCIATE:{fn:zs},tokenAssociate:{fn:zs},TOKENDISSOCIATE:{fn:Bs},tokenDissociate:{fn:Bs},ACCOUNTDELETE:{fn:Ms},cryptoDelete:{fn:Ms},ACCOUNTCREATE:{fn:Ks},cryptoCreateAccount:{fn:Ks},ACCOUNTUPDATE:{fn:Us},cryptoUpdateAccount:{fn:Us},APPROVEALLOWANCE:{fn:Ls},cryptoApproveAllowance:{fn:Ls},DELETEALLOWANCE:{fn:$s},cryptoDeleteAllowance:{fn:$s},CONTRACTCREATE:{fn:Hs},contractCreate:{fn:Hs},CONTRACTUPDATE:{fn:qs},contractUpdate:{fn:qs},CONTRACTDELETE:{fn:js},contractDelete:{fn:js},TOKENAIRDROP:{fn:Gs},tokenAirdrop:{fn:Gs},SCHEDULECREATE:{fn:Js},scheduleCreate:{fn:Js},SCHEDULESIGN:{fn:Ys},scheduleSign:{fn:Ys},SCHEDULEDELETE:{fn:Xs},scheduleDelete:{fn:Xs},SYSTEMDELETE:{fn:Zs},systemDelete:{fn:Zs},SYSTEMUNDELETE:{fn:Qs},systemUndelete:{fn:Qs},FREEZE:{fn:ea},freeze:{fn:ea},ETHEREUMTRANSACTION:{fn:ta},ethereumTransaction:{fn:ta},UNCHECKEDSUBMIT:{fn:ra},uncheckedSubmit:{fn:ra},NODECREATE:{fn:ia},nodeCreate:{fn:ia},NODEUPDATE:{fn:oa},nodeUpdate:{fn:oa},NODEDELETE:{fn:na},nodeDelete:{fn:na},ATOMICBATCH:{fn:sa},atomicBatch:{fn:sa}},ca=e=>{const t=aa[e.type];if(t){if(t.fn)return t.fn(e);if(t.template)return gs(t.template,e)}const r=aa[e.humanReadableType];if(r){if(r.fn)return r.fn(e);if(r.template)return gs(r.template,e)}return"cryptoTransfer"===e.type||"CRYPTOTRANSFER"===e.type?ms(e):e.contractCall?fs(e):Array.isArray(e.tokenTransfers)&&e.tokenTransfers.length>0?(e=>{const t=[],r=(e=>{const t={};for(const r of e)t[r.tokenId]||(t[r.tokenId]=[]),t[r.tokenId].push(r);return t})(e.tokenTransfers||[]);for(const[i,o]of Object.entries(r)){const e=[],r=[];for(const t of o){const i=parseFloat(String(t.amount));i<0?e.push(`${t.accountId} (${Math.abs(i)})`):i>0&&r.push(`${t.accountId} (${i})`)}e.length>0&&r.length>0&&t.push(`Transfer of token ${i} from ${e.join(", ")} to ${r.join(", ")}`)}return t.length>0?t.join("; "):e.humanReadableType})(e):e.humanReadableType&&"Unknown Transaction"!==e.humanReadableType?e.humanReadableType:"Unknown Transaction"};function la(e){if(e){if(e.contractID)return`ContractID: ${new i.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()}`;if(e.ed25519)return`ED25519: ${a.Buffer.from(e.ed25519).toString("hex")}`;if(e.ECDSASecp256k1)return`ECDSA_secp256k1: ${a.Buffer.from(e.ECDSASecp256k1).toString("hex")}`;if(e?.keyList?.keys?.length>0){const t=e.keyList.keys.map(e=>la(e)).filter(Boolean);return`KeyList (${t.length} keys): [${t.join(", ")}]`}if(e?.thresholdKey?.keys?.keys?.length>0){const t=e.thresholdKey.keys.keys.map(e=>la(e)).filter(Boolean);return`ThresholdKey (${e.thresholdKey.threshold} of ${t.length}): [${t.join(", ")}]`}return e.delegatableContractId?`DelegatableContractID: ${new i.ContractId(e.delegatableContractId.shardNum??0,e.delegatableContractId.realmNum??0,e.delegatableContractId.contractNum??0).toString()}`:0===Object.keys(e).length?"Empty Key Structure":"Unknown or Unset Key Type"}}function da(e){try{const t=e.toBytes?e.toBytes():void 0;if(!t)return null;const r=n.proto.TransactionList.decode(t);if(!r.transactionList||0===r.transactionList.length)return null;const i=r.transactionList[0];if(i.bodyBytes&&i.bodyBytes.length>0)return n.proto.TransactionBody.decode(i.bodyBytes);if(i.signedTransactionBytes&&i.signedTransactionBytes.length>0){const e=n.proto.SignedTransaction.decode(i.signedTransactionBytes);if(e.bodyBytes)return n.proto.TransactionBody.decode(e.bodyBytes)}return null}catch(t){return null}}function ua(e,t){const r=da(e);return!(!r||!r[t])}class pa{static parseHTSTransaction(e){try{const t=e._transactionBody;if(!t)return{};if(t.tokenCreation){const e=this.parseTokenCreate(t.tokenCreation);if(e)return{type:"TOKENCREATE",humanReadableType:"Token Creation",tokenCreation:e}}if(t.tokenMint){const e=this.parseTokenMint(t.tokenMint);if(e)return{type:"TOKENMINT",humanReadableType:"Token Mint",tokenMint:e}}if(t.tokenBurn){const e=this.parseTokenBurn(t.tokenBurn);if(e)return{type:"TOKENBURN",humanReadableType:"Token Burn",tokenBurn:e}}if(t.tokenUpdate){const e=this.parseTokenUpdate(t.tokenUpdate);if(e)return{type:"TOKENUPDATE",humanReadableType:"Token Update",tokenUpdate:e}}if(t.tokenFreeze){const e=this.parseTokenFreeze(t.tokenFreeze);if(e)return{type:"TOKENFREEZE",humanReadableType:"Token Freeze",tokenFreeze:e}}if(t.tokenUnfreeze){const e=this.parseTokenUnfreeze(t.tokenUnfreeze);if(e)return{type:"TOKENUNFREEZE",humanReadableType:"Token Unfreeze",tokenUnfreeze:e}}if(t.tokenGrantKyc){const e=this.parseTokenGrantKyc(t.tokenGrantKyc);if(e)return{type:"TOKENGRANTKYC",humanReadableType:"Token Grant KYC",tokenGrantKyc:e}}if(t.tokenRevokeKyc){const e=this.parseTokenRevokeKyc(t.tokenRevokeKyc);if(e)return{type:"TOKENREVOKEKYC",humanReadableType:"Token Revoke KYC",tokenRevokeKyc:e}}if(t.tokenPause){const e=this.parseTokenPause(t.tokenPause);if(e)return{type:"TOKENPAUSE",humanReadableType:"Token Pause",tokenPause:e}}if(t.tokenUnpause){const e=this.parseTokenUnpause(t.tokenUnpause);if(e)return{type:"TOKENUNPAUSE",humanReadableType:"Token Unpause",tokenUnpause:e}}if(t.tokenWipe){const e=this.parseTokenWipeAccount(t.tokenWipe);if(e)return{type:"TOKENWIPEACCOUNT",humanReadableType:"Token Wipe Account",tokenWipeAccount:e}}if(t.tokenDeletion){const e=this.parseTokenDelete(t.tokenDeletion);if(e)return{type:"TOKENDELETE",humanReadableType:"Token Delete",tokenDelete:e}}if(t.tokenAssociate){const e=this.parseTokenAssociate(t.tokenAssociate);if(e)return{type:"TOKENASSOCIATE",humanReadableType:"Token Associate",tokenAssociate:e}}if(t.tokenDissociate){const e=this.parseTokenDissociate(t.tokenDissociate);if(e)return{type:"TOKENDISSOCIATE",humanReadableType:"Token Dissociate",tokenDissociate:e}}if(t.tokenFeeScheduleUpdate){const e=this.parseTokenFeeScheduleUpdate(t.tokenFeeScheduleUpdate);if(e)return{type:"TOKENFEESCHEDULEUPDATE",humanReadableType:"Token Fee Schedule Update",tokenFeeScheduleUpdate:e}}const r=this.parseTokenAirdrop(e);return r?{type:"TOKENAIRDROP",humanReadableType:"Token Airdrop",tokenAirdrop:r}:{}}catch(t){return console.warn("[HTSParser] Failed to parse HTS transaction:",t),{}}}static parseTokenCreate(e){if(!e)return;const t={};return e.name&&(t.tokenName=e.name),e.symbol&&(t.tokenSymbol=e.symbol),e.treasury&&(t.treasuryAccountId=new i.AccountId(e.treasury.shardNum??0,e.treasury.realmNum??0,e.treasury.accountNum??0).toString()),e.initialSupply&&(t.initialSupply=i.Long.fromValue(e.initialSupply).toString()),void 0!==e.decimals&&null!==e.decimals&&(t.decimals=i.Long.fromValue(e.decimals).toNumber()),e.maxSupply&&(t.maxSupply=i.Long.fromValue(e.maxSupply).toString()),e.memo&&(t.memo=e.memo),null!==e.tokenType&&void 0!==e.tokenType&&(t.tokenType=n.proto.TokenType[e.tokenType]),null!==e.supplyType&&void 0!==e.supplyType&&(t.supplyType=n.proto.TokenSupplyType[e.supplyType]),t.adminKey=la(e.adminKey),t.kycKey=la(e.kycKey),t.freezeKey=la(e.freezeKey),t.wipeKey=la(e.wipeKey),t.supplyKey=la(e.supplyKey),t.feeScheduleKey=la(e.feeScheduleKey),t.pauseKey=la(e.pauseKey),e.autoRenewAccount&&(t.autoRenewAccount=new i.AccountId(e.autoRenewAccount.shardNum??0,e.autoRenewAccount.realmNum??0,e.autoRenewAccount.accountNum??0).toString()),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=i.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.customFees&&e.customFees.length>0&&(t.customFees=e.customFees.map(e=>{const t={feeCollectorAccountId:e.feeCollectorAccountId?new i.AccountId(e.feeCollectorAccountId.shardNum??0,e.feeCollectorAccountId.realmNum??0,e.feeCollectorAccountId.accountNum??0).toString():"Not Set",allCollectorsAreExempt:e.allCollectorsAreExempt||!1};if(e.fixedFee)return{...t,feeType:"FIXED_FEE",fixedFee:{amount:i.Long.fromValue(e.fixedFee.amount||0).toString(),denominatingTokenId:e.fixedFee.denominatingTokenId?new i.TokenId(e.fixedFee.denominatingTokenId.shardNum??0,e.fixedFee.denominatingTokenId.realmNum??0,e.fixedFee.denominatingTokenId.tokenNum??0).toString():void 0}};if(e.fractionalFee)return{...t,feeType:"FRACTIONAL_FEE",fractionalFee:{numerator:i.Long.fromValue(e.fractionalFee.fractionalAmount?.numerator||0).toString(),denominator:i.Long.fromValue(e.fractionalFee.fractionalAmount?.denominator||1).toString(),minimumAmount:i.Long.fromValue(e.fractionalFee.minimumAmount||0).toString(),maximumAmount:i.Long.fromValue(e.fractionalFee.maximumAmount||0).toString(),netOfTransfers:e.fractionalFee.netOfTransfers||!1}};if(e.royaltyFee){let r;return e.royaltyFee.fallbackFee&&(r={amount:i.Long.fromValue(e.royaltyFee.fallbackFee.amount||0).toString(),denominatingTokenId:e.royaltyFee.fallbackFee.denominatingTokenId?new i.TokenId(e.royaltyFee.fallbackFee.denominatingTokenId.shardNum??0,e.royaltyFee.fallbackFee.denominatingTokenId.realmNum??0,e.royaltyFee.fallbackFee.denominatingTokenId.tokenNum??0).toString():void 0}),{...t,feeType:"ROYALTY_FEE",royaltyFee:{numerator:i.Long.fromValue(e.royaltyFee.exchangeValueFraction?.numerator||0).toString(),denominator:i.Long.fromValue(e.royaltyFee.exchangeValueFraction?.denominator||1).toString(),fallbackFee:r}}}return{...t,feeType:"FIXED_FEE",fixedFee:{amount:"0"}}})),t}static parseTokenMint(e){if(!e||!e.token||null===e.amount||void 0===e.amount)return;const t={tokenId:new i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString(),amount:i.Long.fromValue(e.amount).toNumber()};return e.metadata&&e.metadata.length>0&&(t.metadata=e.metadata.map(e=>a.Buffer.from(e).toString("base64"))),t}static parseTokenBurn(e){if(!e||!e.token||null===e.amount||void 0===e.amount)return;const t={tokenId:new i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString(),amount:i.Long.fromValue(e.amount).toNumber()};return e.serialNumbers&&e.serialNumbers.length>0&&(t.serialNumbers=e.serialNumbers.map(e=>i.Long.fromValue(e).toNumber())),t}static parseTokenUpdate(e){if(!e)return;const t={};return e.token&&(t.tokenId=new i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.name&&(t.name=e.name),e.symbol&&(t.symbol=e.symbol),e.treasury&&(t.treasuryAccountId=new i.AccountId(e.treasury.shardNum??0,e.treasury.realmNum??0,e.treasury.accountNum??0).toString()),t.adminKey=la(e.adminKey),t.kycKey=la(e.kycKey),t.freezeKey=la(e.freezeKey),t.wipeKey=la(e.wipeKey),t.supplyKey=la(e.supplyKey),t.feeScheduleKey=la(e.feeScheduleKey),t.pauseKey=la(e.pauseKey),e.autoRenewAccount&&(t.autoRenewAccountId=new i.AccountId(e.autoRenewAccount.shardNum??0,e.autoRenewAccount.realmNum??0,e.autoRenewAccount.accountNum??0).toString()),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=i.Long.fromValue(e.autoRenewPeriod.seconds).toString()),void 0!==e.memo?.value&&(t.memo=e.memo.value),e.expiry?.seconds&&(t.expiry=`${i.Long.fromValue(e.expiry.seconds).toString()}.${e.expiry.nanos}`),t}static parseTokenFeeScheduleUpdate(e){if(!e)return;const t={};return e.tokenId&&(t.tokenId=new i.TokenId(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString()),e.customFees&&e.customFees.length>0&&(t.customFees=e.customFees.map(e=>{const t={feeCollectorAccountId:e.feeCollectorAccountId?new i.AccountId(e.feeCollectorAccountId.shardNum??0,e.feeCollectorAccountId.realmNum??0,e.feeCollectorAccountId.accountNum??0).toString():"Not Set",allCollectorsAreExempt:e.allCollectorsAreExempt||!1};if(e.fixedFee)return{...t,feeType:"FIXED_FEE",fixedFee:{amount:i.Long.fromValue(e.fixedFee.amount||0).toString(),denominatingTokenId:e.fixedFee.denominatingTokenId?new i.TokenId(e.fixedFee.denominatingTokenId.shardNum??0,e.fixedFee.denominatingTokenId.realmNum??0,e.fixedFee.denominatingTokenId.tokenNum??0).toString():void 0}};if(e.fractionalFee)return{...t,feeType:"FRACTIONAL_FEE",fractionalFee:{numerator:i.Long.fromValue(e.fractionalFee.fractionalAmount?.numerator||0).toString(),denominator:i.Long.fromValue(e.fractionalFee.fractionalAmount?.denominator||1).toString(),minimumAmount:i.Long.fromValue(e.fractionalFee.minimumAmount||0).toString(),maximumAmount:i.Long.fromValue(e.fractionalFee.maximumAmount||0).toString(),netOfTransfers:e.fractionalFee.netOfTransfers||!1}};if(e.royaltyFee){let r;return e.royaltyFee.fallbackFee&&(r={amount:i.Long.fromValue(e.royaltyFee.fallbackFee.amount||0).toString(),denominatingTokenId:e.royaltyFee.fallbackFee.denominatingTokenId?new i.TokenId(e.royaltyFee.fallbackFee.denominatingTokenId.shardNum??0,e.royaltyFee.fallbackFee.denominatingTokenId.realmNum??0,e.royaltyFee.fallbackFee.denominatingTokenId.tokenNum??0).toString():void 0}),{...t,feeType:"ROYALTY_FEE",royaltyFee:{numerator:i.Long.fromValue(e.royaltyFee.exchangeValueFraction?.numerator||0).toString(),denominator:i.Long.fromValue(e.royaltyFee.exchangeValueFraction?.denominator||1).toString(),fallbackFee:r}}}return{...t,feeType:"FIXED_FEE",fixedFee:{amount:"0"}}})),t}static parseTokenFreeze(e){if(!e)return;const t={};return e.token&&(t.tokenId=new i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new i.AccountId(e.account.shardNum??0,e.account.realmNum??0,e.account.accountNum??0).toString()),t}static parseTokenUnfreeze(e){if(!e)return;const t={};return e.token&&(t.tokenId=new i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new i.AccountId(e.account.shardNum??0,e.account.realmNum??0,e.account.accountNum??0).toString()),t}static parseTokenGrantKyc(e){if(!e)return;const t={};return e.token&&(t.tokenId=new i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new i.AccountId(e.account.shardNum??0,e.account.realmNum??0,e.account.accountNum??0).toString()),t}static parseTokenRevokeKyc(e){if(!e)return;const t={};return e.token&&(t.tokenId=new i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new i.AccountId(e.account.shardNum??0,e.account.realmNum??0,e.account.accountNum??0).toString()),t}static parseTokenPause(e){if(!e)return;const t={};return e.token&&(t.tokenId=new i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),t}static parseTokenUnpause(e){if(!e)return;const t={};return e.token&&(t.tokenId=new i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),t}static parseTokenWipeAccount(e){if(!e)return;const t={};return e.token&&(t.tokenId=new i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new i.AccountId(e.account.shardNum??0,e.account.realmNum??0,e.account.accountNum??0).toString()),e.serialNumbers&&e.serialNumbers.length>0&&(t.serialNumbers=e.serialNumbers.map(e=>i.Long.fromValue(e).toString())),e.amount&&(t.amount=i.Long.fromValue(e.amount).toString()),t}static parseTokenDelete(e){if(!e)return;const t={};return e.token&&(t.tokenId=new i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),t}static parseTokenAssociate(e){if(!e)return;const t={};return e.account&&(t.accountId=new i.AccountId(e.account.shardNum??0,e.account.realmNum??0,e.account.accountNum??0).toString()),e.tokens&&e.tokens.length>0&&(t.tokenIds=e.tokens.map(e=>new i.TokenId(e.shardNum??0,e.realmNum??0,e.tokenNum??0).toString())),t}static parseTokenDissociate(e){if(!e)return;const t={};return e.account&&(t.accountId=new i.AccountId(e.account.shardNum??0,e.account.realmNum??0,e.account.accountNum??0).toString()),e.tokens&&e.tokens.length>0&&(t.tokenIds=e.tokens.map(e=>new i.TokenId(e.shardNum??0,e.realmNum??0,e.tokenNum??0).toString())),t}static parseTokenAirdrop(e){try{const t=e._transactionBody;if(t?.tokenAirdrop){return{tokenTransfers:(t.tokenAirdrop.tokenTransfers||[]).map(e=>({tokenId:e.token?.toString()||"Unknown",transfers:(e.transfers||[]).map(e=>({accountId:e.accountID?.toString()||"Unknown",amount:e.amount?.toString()||"0",serialNumbers:e.serialNumbers?.map(e=>e.toString())}))}))}}if(ua(e,"tokenAirdrop")){const t=da(e);if(t?.tokenAirdrop)return this.parseTokenAirdropFromProto(t.tokenAirdrop)}const r=e._tokenTransfers||[];return r.length>0?{tokenTransfers:r.map(e=>({tokenId:e.tokenId?.toString()||"Unknown",transfers:(e.transfers||[]).map(e=>({accountId:e.accountId?.toString()||"Unknown",amount:e.amount?.toString()||"0",serialNumbers:e.serialNumbers?.map(e=>e.toString())}))}))}:null}catch(t){return console.warn("[HTSParser] Failed to parse token airdrop:",t),null}}static parseTokenAirdropFromProto(e){const t=[];if(e.tokenTransfers)for(const r of e.tokenTransfers){const e=r.token?new i.TokenId(r.token.shardNum??0,r.token.realmNum??0,r.token.tokenNum??0):null,o=[];if(r.transfers)for(const t of r.transfers){const e=t.accountID?new i.AccountId(t.accountID.shardNum??0,t.accountID.realmNum??0,t.accountID.accountNum??0):null;o.push({accountId:e?.toString()||"Unknown",amount:t.amount?i.Long.fromValue(t.amount).toString():"0",serialNumbers:t.serialNumbers?.map(e=>i.Long.fromValue(e).toString())})}t.push({tokenId:e?.toString()||"Unknown",transfers:o})}return{tokenTransfers:t}}static extractTokenCreationFromTransaction(e){try{const t=e;if(t._tokenName||t._tokenSymbol){const e={tokenName:t._tokenName||"Unknown Token",tokenSymbol:t._tokenSymbol||"UNKNOWN",initialSupply:t._initialSupply?.toString()||"0",decimals:Number(t._decimals||0),treasuryAccountId:t._treasuryAccountId?.toString()||"Unknown"};return t._maxSupply&&(e.maxSupply=t._maxSupply.toString()),t._tokenType&&(e.tokenType=t._tokenType.toString?t._tokenType.toString():String(t._tokenType)),t._supplyType&&(e.supplyType=t._supplyType.toString?t._supplyType.toString():String(t._supplyType)),t._tokenMemo&&(e.memo=t._tokenMemo),t._adminKey&&(e.adminKey=t._adminKey.toString()),t._kycKey&&(e.kycKey=t._kycKey.toString()),t._freezeKey&&(e.freezeKey=t._freezeKey.toString()),t._wipeKey&&(e.wipeKey=t._wipeKey.toString()),t._supplyKey&&(e.supplyKey=t._supplyKey.toString()),t._feeScheduleKey&&(e.feeScheduleKey=t._feeScheduleKey.toString()),t._pauseKey&&(e.pauseKey=t._pauseKey.toString()),t._metadataKey&&(e.metadataKey=t._metadataKey.toString()),t._autoRenewAccountId&&(e.autoRenewAccount=t._autoRenewAccountId.toString()),t._autoRenewPeriod&&(e.autoRenewPeriod=t._autoRenewPeriod.seconds?.toString()||t._autoRenewPeriod.toString()),t._expirationTime&&(e.expiry=t._expirationTime.seconds?.toString()||t._expirationTime.toString()),t._customFees&&Array.isArray(t._customFees)&&t._customFees.length>0&&(e.customFees=t._customFees.map(e=>{const t={feeCollectorAccountId:e.feeCollectorAccountId?.toString()||"",feeType:"FIXED_FEE"};return e.fixedFee?(t.feeType="FIXED_FEE",t.fixedFee={amount:e.fixedFee.amount?.toString()||"0",denominatingTokenId:e.fixedFee.denominatingTokenId?.toString()}):e.fractionalFee?(t.feeType="FRACTIONAL_FEE",t.fractionalFee={numerator:e.fractionalFee.numerator?.toString()||"0",denominator:e.fractionalFee.denominator?.toString()||"1",minimumAmount:e.fractionalFee.minimumAmount?.toString()||"0",maximumAmount:e.fractionalFee.maximumAmount?.toString()||"0",netOfTransfers:e.fractionalFee.netOfTransfers||!1}):e.royaltyFee&&(t.feeType="ROYALTY_FEE",t.royaltyFee={numerator:e.royaltyFee.numerator?.toString()||"0",denominator:e.royaltyFee.denominator?.toString()||"1",fallbackFee:e.royaltyFee.fallbackFee?{amount:e.royaltyFee.fallbackFee.amount?.toString()||"0",denominatingTokenId:e.royaltyFee.fallbackFee.denominatingTokenId?.toString()}:void 0}),t.allCollectorsAreExempt=e.allCollectorsAreExempt||!1,t})),e}return null}catch(t){return null}}static extractTokenAirdropFromTransaction(e){try{const t=e;if(t._tokenAirdrops&&Array.isArray(t._tokenAirdrops)){return{tokenTransfers:t._tokenAirdrops.map(e=>({tokenId:e.tokenId?.toString()||"Unknown",transfers:(e.transfers||[]).map(e=>({accountId:e.accountId?.toString()||"Unknown",amount:e.amount?.toString()||"0",serialNumbers:e.serialNumbers?.map(e=>e.toString())||[]}))}))}}return null}catch(t){return null}}static parseFromTransactionObject(e){try{try{const t=e.toBytes?e.toBytes():void 0;if(t){const e=n.proto.TransactionList.decode(t);if(e.transactionList&&e.transactionList.length>0){const t=e.transactionList[0];let r=null;if(t.bodyBytes&&t.bodyBytes.length>0)r=n.proto.TransactionBody.decode(t.bodyBytes);else if(t.signedTransactionBytes&&t.signedTransactionBytes.length>0){const e=n.proto.SignedTransaction.decode(t.signedTransactionBytes);e.bodyBytes&&(r=n.proto.TransactionBody.decode(e.bodyBytes))}if(r){if(r.tokenCreation){const e=this.parseTokenCreate(r.tokenCreation);if(e)return{type:"TOKENCREATE",humanReadableType:"Token Creation",tokenCreation:e}}if(r.tokenMint){const e=this.parseTokenMint(r.tokenMint);if(e)return{type:"TOKENMINT",humanReadableType:"Token Mint",tokenMint:e}}if(r.tokenBurn){const e=this.parseTokenBurn(r.tokenBurn);if(e)return{type:"TOKENBURN",humanReadableType:"Token Burn",tokenBurn:e}}if(r.tokenUpdate){const e=this.parseTokenUpdate(r.tokenUpdate);if(e)return{type:"TOKENUPDATE",humanReadableType:"Token Update",tokenUpdate:e}}if(r.tokenFreeze){const e=this.parseTokenFreeze(r.tokenFreeze);if(e)return{type:"TOKENFREEZE",humanReadableType:"Token Freeze",tokenFreeze:e}}if(r.tokenUnfreeze){const e=this.parseTokenUnfreeze(r.tokenUnfreeze);if(e)return{type:"TOKENUNFREEZE",humanReadableType:"Token Unfreeze",tokenUnfreeze:e}}if(r.tokenGrantKyc){const e=this.parseTokenGrantKyc(r.tokenGrantKyc);if(e)return{type:"TOKENGRANTKYC",humanReadableType:"Token Grant KYC",tokenGrantKyc:e}}if(r.tokenRevokeKyc){const e=this.parseTokenRevokeKyc(r.tokenRevokeKyc);if(e)return{type:"TOKENREVOKEKYC",humanReadableType:"Token Revoke KYC",tokenRevokeKyc:e}}if(r.tokenPause){const e=this.parseTokenPause(r.tokenPause);if(e)return{type:"TOKENPAUSE",humanReadableType:"Token Pause",tokenPause:e}}if(r.tokenUnpause){const e=this.parseTokenUnpause(r.tokenUnpause);if(e)return{type:"TOKENUNPAUSE",humanReadableType:"Token Unpause",tokenUnpause:e}}if(r.tokenWipe){const e=this.parseTokenWipeAccount(r.tokenWipe);if(e)return{type:"TOKENWIPEACCOUNT",humanReadableType:"Token Wipe Account",tokenWipeAccount:e}}if(r.tokenDeletion){const e=this.parseTokenDelete(r.tokenDeletion);if(e)return{type:"TOKENDELETE",humanReadableType:"Token Delete",tokenDelete:e}}if(r.tokenAssociate){const e=this.parseTokenAssociate(r.tokenAssociate);if(e)return{type:"TOKENASSOCIATE",humanReadableType:"Token Associate",tokenAssociate:e}}if(r.tokenDissociate){const e=this.parseTokenDissociate(r.tokenDissociate);if(e)return{type:"TOKENDISSOCIATE",humanReadableType:"Token Dissociate",tokenDissociate:e}}if(r.tokenFeeScheduleUpdate){const e=this.parseTokenFeeScheduleUpdate(r.tokenFeeScheduleUpdate);if(e)return{type:"TOKENFEESCHEDULEUPDATE",humanReadableType:"Token Fee Schedule Update",tokenFeeScheduleUpdate:e}}if(r.tokenAirdrop){const e=this.parseTokenAirdropFromProto(r.tokenAirdrop);if(e)return{type:"TOKENAIRDROP",humanReadableType:"Token Airdrop",tokenAirdrop:e}}}}}}catch(eg){}const t=this.parseHTSTransaction(e);if(t.type)return t;const r=this.extractTokenCreationFromTransaction(e),i=this.extractTokenAirdropFromTransaction(e);return r?{type:"TOKENCREATE",humanReadableType:"Token Creation",tokenCreation:r}:i?{type:"TOKENAIRDROP",humanReadableType:"Token Airdrop",tokenAirdrop:i}:{}}catch(t){return{}}}}class ha{static parseConsensusCreateTopic(e){if(!e)return;const t={};return e.memo&&(t.memo=e.memo),t.adminKey=la(e.adminKey),t.submitKey=la(e.submitKey),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=i.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.autoRenewAccount&&(t.autoRenewAccountId=new i.AccountId(e.autoRenewAccount.shardNum??0,e.autoRenewAccount.realmNum??0,e.autoRenewAccount.accountNum??0).toString()),t}static parseConsensusSubmitMessage(e){if(!e)return;const t={};if(e.topicID&&(t.topicId=`${e.topicID.shardNum??0}.${e.topicID.realmNum??0}.${e.topicID.topicNum??0}`),e.message?.length>0){const r=a.Buffer.from(e.message),i=r.toString("utf8");/[\x00-\x08\x0B\x0E-\x1F\x7F]/.test(i)||i.includes("�")?(t.message=r.toString("base64"),t.messageEncoding="base64"):(t.message=i,t.messageEncoding="utf8")}if(e.chunkInfo){if(e.chunkInfo.initialTransactionID){const r=e.chunkInfo.initialTransactionID.accountID,i=e.chunkInfo.initialTransactionID.transactionValidStart;r&&i&&(t.chunkInfoInitialTransactionID=`${r.shardNum??0}.${r.realmNum??0}.${r.accountNum??0}@${i.seconds??0}.${i.nanos??0}`)}void 0!==e.chunkInfo.number&&null!==e.chunkInfo.number&&(t.chunkInfoNumber=e.chunkInfo.number),void 0!==e.chunkInfo.total&&null!==e.chunkInfo.total&&(t.chunkInfoTotal=e.chunkInfo.total)}return t}static parseConsensusUpdateTopic(e){if(!e)return;const t={};return e.topicID&&(t.topicId=`${e.topicID.shardNum}.${e.topicID.realmNum}.${e.topicID.topicNum}`),void 0!==e.memo?.value&&(t.memo=e.memo.value),null===e.adminKey?(t.clearAdminKey=!0,t.adminKey=void 0):e.adminKey?t.adminKey=la(e.adminKey):t.adminKey=void 0,null===e.submitKey?(t.clearSubmitKey=!0,t.submitKey=void 0):e.submitKey?t.submitKey=la(e.submitKey):t.submitKey=void 0,e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=i.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.autoRenewAccount&&(t.autoRenewAccountId=new i.AccountId(e.autoRenewAccount.shardNum??0,e.autoRenewAccount.realmNum??0,e.autoRenewAccount.accountNum??0).toString()),t}static parseConsensusDeleteTopic(e){if(!e)return;const t={};return e.topicID&&(t.topicId=`${e.topicID.shardNum}.${e.topicID.realmNum??0}.${e.topicID.topicNum??0}`),t}static parseFromTransactionObject(e){try{const t=e._transactionBody;if(!t)return{};if(t.consensusCreateTopic){const e=this.parseConsensusCreateTopic(t.consensusCreateTopic);if(e)return{type:"TOPICCREATE",humanReadableType:"Topic Create",consensusCreateTopic:e}}if(t.consensusSubmitMessage){const e=this.parseConsensusSubmitMessage(t.consensusSubmitMessage);if(e)return{type:"CONSENSUSSUBMITMESSAGE",humanReadableType:"Submit Message",consensusSubmitMessage:e}}if(t.consensusUpdateTopic){const e=this.parseConsensusUpdateTopic(t.consensusUpdateTopic);if(e)return{type:"TOPICUPDATE",humanReadableType:"Topic Update",consensusUpdateTopic:e}}if(t.consensusDeleteTopic){const e=this.parseConsensusDeleteTopic(t.consensusDeleteTopic);if(e)return{type:"TOPICDELETE",humanReadableType:"Topic Delete",consensusDeleteTopic:e}}return{}}catch(t){return{}}}}class ga{static parseFileTransaction(e,t){try{if(t||e.toBytes)try{const r=t||e.toBytes(),i=n.proto.TransactionList.decode(r);if(i.transactionList&&i.transactionList.length>0){const e=i.transactionList[0];let t=null;if(e.bodyBytes&&e.bodyBytes.length>0)t=n.proto.TransactionBody.decode(e.bodyBytes);else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const r=n.proto.SignedTransaction.decode(e.signedTransactionBytes);r.bodyBytes&&(t=n.proto.TransactionBody.decode(r.bodyBytes))}if(t){const e=this.parseFromProtobufTxBody(t);if(e.type&&"UNKNOWN"!==e.type)return e}}}catch(r){}return this.parseFromTransactionInternals(e)}catch(i){return{type:"UNKNOWN",humanReadableType:"Unknown File Transaction"}}}static parseFromProtobufTxBody(e){if(e.fileCreate){const t=this.parseFileCreate(e.fileCreate);if(t)return{type:"FILECREATE",humanReadableType:"File Create",fileCreate:t}}if(e.fileAppend){const t=this.parseFileAppend(e.fileAppend);if(t)return{type:"FILEAPPEND",humanReadableType:"File Append",fileAppend:t}}if(e.fileUpdate){const t=this.parseFileUpdate(e.fileUpdate);if(t)return{type:"FILEUPDATE",humanReadableType:"File Update",fileUpdate:t}}if(e.fileDelete){const t=this.parseFileDelete(e.fileDelete);if(t)return{type:"FILEDELETE",humanReadableType:"File Delete",fileDelete:t}}return{}}static parseFromTransactionInternals(e){try{const t=e;if(ua(e,"fileCreate")){const e={};if(t._contents){const r=this.analyzeContent(t._contents);e.contents=r.encoded,r.contentType&&(e.contentType=r.contentType),r.size&&(e.contentSize=r.size)}if(t._keys&&t._keys.length>0){const r={keys:t._keys};e.keys=la({keyList:r})}return t._expirationTime&&(e.expirationTime=t._expirationTime.toString()),t._memo&&(e.memo=t._memo),{type:"FILECREATE",humanReadableType:"File Create",fileCreate:e}}if(ua(e,"fileAppend")){const e={fileId:t._fileId.toString()};if(t._contents){const r=this.analyzeContent(t._contents);e.contents=r.encoded,r.size&&(e.contentSize=r.size)}return{type:"FILEAPPEND",humanReadableType:"File Append",fileAppend:e}}if(ua(e,"fileUpdate")){const e={fileId:t._fileId.toString()};if(t._contents){const r=this.analyzeContent(t._contents);e.contents=r.encoded,r.size&&(e.contentSize=r.size)}if(t._keys&&t._keys.length>0){const r={keys:t._keys};e.keys=la({keyList:r})}return t._expirationTime&&(e.expirationTime=t._expirationTime.toString()),t._memo&&(e.memo=t._memo),{type:"FILEUPDATE",humanReadableType:"File Update",fileUpdate:e}}if(ua(e,"fileDelete")){return{type:"FILEDELETE",humanReadableType:"File Delete",fileDelete:{fileId:t._fileId.toString()}}}return{}}catch(t){return{}}}static analyzeContent(e){const t=e.length,r=a.Buffer.from(e);let i,o;if(t>=4){i={"89504e47":"image/png",ffd8ffe0:"image/jpeg",ffd8ffe1:"image/jpeg",47494638:"image/gif",25504446:"application/pdf","504b0304":"application/zip","7f454c46":"application/x-executable",d0cf11e0:"application/msoffice"}[r.subarray(0,4).toString("hex").toLowerCase()]}if(!i)try{const e=r.toString("utf8"),t=/[\x00-\x08\x0B\x0E-\x1F\x7F]/.test(e),o=e.includes("�");i=t||o?"application/octet-stream":e.trim().startsWith("{")&&e.trim().endsWith("}")?"application/json":e.includes("<?xml")||e.includes("<html")?"text/xml":e.includes("<!DOCTYPE html")?"text/html":"text/plain"}catch{i="application/octet-stream"}if(i?.startsWith("text/")||"application/json"===i)try{o=r.toString("utf8"),(o.includes("�")||/[\x00-\x08\x0B\x0E-\x1F\x7F]/.test(o))&&(o=r.toString("base64"))}catch{o=r.toString("base64")}else o=r.toString("base64");return{encoded:o,contentType:i,size:t}}static parseFileCreate(e){if(!e)return;const t={};return e.expirationTime?.seconds&&(t.expirationTime=`${i.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.keys&&(t.keys=la({keyList:e.keys})),e.contents&&(t.contents=a.Buffer.from(e.contents).toString("base64")),e.memo&&(t.memo=e.memo),t}static parseFileAppend(e){if(!e)return;const t={};return e.fileID&&(t.fileId=`${e.fileID.shardNum??0}.${e.fileID.realmNum??0}.${e.fileID.fileNum??0}`),e.contents&&(t.contents=a.Buffer.from(e.contents).toString("base64")),t}static parseFileUpdate(e){if(!e)return;const t={};return e.fileID&&(t.fileId=`${e.fileID.shardNum??0}.${e.fileID.realmNum??0}.${e.fileID.fileNum??0}`),e.expirationTime?.seconds&&(t.expirationTime=`${i.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.keys&&(t.keys=la({keyList:e.keys})),e.contents&&(t.contents=a.Buffer.from(e.contents).toString("base64")),void 0!==e.memo?.value&&(t.memo=e.memo.value),t}static parseFileDelete(e){if(!e)return;const t={};return e.fileID&&(t.fileId=`${e.fileID.shardNum??0}.${e.fileID.realmNum??0}.${e.fileID.fileNum??0}`),t}static parseFromTransactionObject(e){return this.parseFileTransaction(e)}}class ma{static parseCryptoTransfers(e,t){if(e.transfers?.accountAmounts&&(t.transfers=e.transfers.accountAmounts.map(e=>{const t=new i.AccountId(e.accountID.shardNum??0,e.accountID.realmNum??0,e.accountID.accountNum??0),r=i.Hbar.fromTinybars(i.Long.fromValue(e.amount));return{accountId:t.toString(),amount:r.toString(i.HbarUnit.Hbar),isDecimal:!0}})),e.tokenTransfers)for(const r of e.tokenTransfers){const e=new i.TokenId(r.token.shardNum??0,r.token.realmNum??0,r.token.tokenNum??0);if(r.transfers)for(const o of r.transfers){const r=new i.AccountId(o.accountID.shardNum??0,o.accountID.realmNum??0,o.accountID.accountNum??0),n=i.Long.fromValue(o.amount).toNumber();t.tokenTransfers.push({tokenId:e.toString(),accountId:r.toString(),amount:n})}}}static parseCryptoDelete(e){if(!e)return;const t={};return e.deleteAccountID&&(t.deleteAccountId=new i.AccountId(e.deleteAccountID.shardNum??0,e.deleteAccountID.realmNum??0,e.deleteAccountID.accountNum??0).toString()),e.transferAccountID&&(t.transferAccountId=new i.AccountId(e.transferAccountID.shardNum??0,e.transferAccountID.realmNum??0,e.transferAccountID.accountNum??0).toString()),t}static parseCryptoCreateAccount(e){if(!e)return;const t={};return e.initialBalance&&(t.initialBalance=i.Hbar.fromTinybars(i.Long.fromValue(e.initialBalance)).toString(i.HbarUnit.Hbar)),e.key&&(t.key=la(e.key)),void 0!==e.receiverSigRequired&&(t.receiverSigRequired=e.receiverSigRequired),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=i.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.memo&&(t.memo=e.memo),void 0!==e.maxAutomaticTokenAssociations&&(t.maxAutomaticTokenAssociations=e.maxAutomaticTokenAssociations),e.stakedAccountId?t.stakedAccountId=new i.AccountId(e.stakedAccountId.shardNum??0,e.stakedAccountId.realmNum??0,e.stakedAccountId.accountNum??0).toString():null!==e.stakedNodeId&&void 0!==e.stakedNodeId&&(t.stakedNodeId=i.Long.fromValue(e.stakedNodeId).toString()),void 0!==e.declineReward&&(t.declineReward=e.declineReward),e.alias&&e.alias.length>0&&(t.alias=globalThis.Buffer.from(e.alias).toString("hex")),t}static parseCryptoUpdateAccount(e){if(!e)return;const t={};return e.accountIDToUpdate&&(t.accountIdToUpdate=new i.AccountId(e.accountIDToUpdate.shardNum??0,e.accountIDToUpdate.realmNum??0,e.accountIDToUpdate.accountNum??0).toString()),e.key&&(t.key=la(e.key)),e.expirationTime?.seconds&&(t.expirationTime=`${i.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),null!==e.receiverSigRequired&&void 0!==e.receiverSigRequired&&(t.receiverSigRequired=Boolean(e.receiverSigRequired)),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=i.Long.fromValue(e.autoRenewPeriod.seconds).toString()),void 0!==e.memo?.value&&(t.memo=e.memo.value),void 0!==e.maxAutomaticTokenAssociations?.value&&(t.maxAutomaticTokenAssociations=e.maxAutomaticTokenAssociations.value),e.stakedAccountId?(t.stakedAccountId=new i.AccountId(e.stakedAccountId.shardNum??0,e.stakedAccountId.realmNum??0,e.stakedAccountId.accountNum??0).toString(),t.stakedNodeId=void 0):null!==e.stakedNodeId&&void 0!==e.stakedNodeId?(t.stakedNodeId=i.Long.fromValue(e.stakedNodeId).toString(),t.stakedAccountId=void 0):(t.stakedAccountId=void 0,t.stakedNodeId=void 0),null!==e.declineReward&&void 0!==e.declineReward&&(t.declineReward=Boolean(e.declineReward)),t}static parseCryptoApproveAllowance(e){if(!e)return;const t={};return e.cryptoAllowances&&e.cryptoAllowances.length>0&&(t.hbarAllowances=e.cryptoAllowances.map(e=>({ownerAccountId:new i.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),spenderAccountId:new i.AccountId(e.spender.shardNum??0,e.spender.realmNum??0,e.spender.accountNum??0).toString(),amount:i.Hbar.fromTinybars(i.Long.fromValue(e.amount)).toString(i.HbarUnit.Hbar)}))),e.tokenAllowances&&e.tokenAllowances.length>0&&(t.tokenAllowances=e.tokenAllowances.map(e=>({tokenId:new i.TokenId(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString(),ownerAccountId:new i.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),spenderAccountId:new i.AccountId(e.spender.shardNum??0,e.spender.realmNum??0,e.spender.accountNum??0).toString(),amount:i.Long.fromValue(e.amount).toString()}))),e.nftAllowances&&e.nftAllowances.length>0&&(t.nftAllowances=e.nftAllowances.map(e=>{const t={};return e.tokenId&&(t.tokenId=new i.TokenId(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString()),e.owner&&(t.ownerAccountId=new i.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString()),e.spender&&(t.spenderAccountId=new i.AccountId(e.spender.shardNum??0,e.spender.realmNum??0,e.spender.accountNum??0).toString()),e.serialNumbers&&e.serialNumbers.length>0&&(t.serialNumbers=e.serialNumbers.map(e=>i.Long.fromValue(e).toString())),void 0!==e.approvedForAll?.value&&(t.approvedForAll=e.approvedForAll.value),e.delegatingSpender&&(t.delegatingSpender=new i.AccountId(e.delegatingSpender.shardNum??0,e.delegatingSpender.realmNum??0,e.delegatingSpender.accountNum??0).toString()),t})),t}static parseCryptoDeleteAllowance(e){if(!e)return;const t={};return e.nftAllowances&&e.nftAllowances.length>0&&(t.nftAllowancesToRemove=e.nftAllowances.map(e=>({ownerAccountId:new i.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),tokenId:new i.TokenId(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString(),serialNumbers:e.serialNumbers?e.serialNumbers.map(e=>i.Long.fromValue(e).toString()):[]}))),t}static extractHbarTransfersFromTransaction(e){const t=[];try{const r=e._hbarTransfers;Array.isArray(r)&&r.forEach(e=>{if(e.accountId&&e.amount){const r=e.amount.toTinybars(),i=Number(r)/1e8;t.push({accountId:e.accountId.toString(),amount:i})}})}catch(r){}return t}static extractTokenTransfersFromTransaction(e){const t=[];try{const r=e._tokenTransfers;Array.isArray(r)&&r.forEach(e=>{if(e.tokenId&&Array.isArray(e.transfers)){const r=e.transfers.map(e=>({accountId:e.accountId?.toString()||"Unknown",amount:Number(e.amount||0)}));t.push({tokenId:e.tokenId.toString(),transfers:r})}})}catch(r){}return t}static parseFromTransactionObject(e){try{const t=this.extractHbarTransfersFromTransaction(e),r=this.extractTokenTransfersFromTransaction(e);if(t.length>0||r.length>0){const e=t.map(e=>({accountId:e.accountId,amount:e.amount.toString()+" ℏ",isDecimal:!0})),i=r.flatMap(e=>e.transfers.map(t=>({tokenId:e.tokenId,accountId:t.accountId,amount:t.amount})));if(t.length>0)return{type:"CRYPTOTRANSFER",humanReadableType:"Crypto Transfer",transfers:e,tokenTransfers:i};if(r.length>0)return{type:"TOKENTRANSFER",humanReadableType:"Token Transfer",transfers:e,tokenTransfers:i}}return{}}catch(t){return{}}}}class fa{static parseSCSTransaction(e,t){try{if(t||e.toBytes)try{const r=t||e.toBytes(),i=n.proto.TransactionList.decode(r);if(i.transactionList&&i.transactionList.length>0){const e=i.transactionList[0];let t=null;if(e.bodyBytes&&e.bodyBytes.length>0)t=n.proto.TransactionBody.decode(e.bodyBytes);else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const r=n.proto.SignedTransaction.decode(e.signedTransactionBytes);r.bodyBytes&&(t=n.proto.TransactionBody.decode(r.bodyBytes))}if(t){const e=this.parseFromProtobufTxBody(t);if(e.type&&"UNKNOWN"!==e.type)return e}}}catch(r){}return this.parseFromTransactionInternals(e)}catch(i){return{type:"UNKNOWN",humanReadableType:"Unknown Contract Transaction"}}}static parseFromProtobufTxBody(e){if(e.contractCall){const t=this.parseContractCall(e.contractCall);if(t)return{type:"CONTRACTCALL",humanReadableType:"Contract Call",contractCall:t}}if(e.contractCreateInstance){const t=this.parseContractCreate(e.contractCreateInstance);if(t)return{type:"CONTRACTCREATE",humanReadableType:"Contract Create",contractCreate:t}}if(e.contractUpdateInstance){const t=this.parseContractUpdate(e.contractUpdateInstance);if(t)return{type:"CONTRACTUPDATE",humanReadableType:"Contract Update",contractUpdate:t}}if(e.contractDeleteInstance){const t=this.parseContractDelete(e.contractDeleteInstance);if(t)return{type:"CONTRACTDELETE",humanReadableType:"Contract Delete",contractDelete:t}}if(e.ethereumTransaction){const t=this.parseEthereumTransaction(e.ethereumTransaction);if(t)return{type:"ETHEREUMTRANSACTION",humanReadableType:"Ethereum Transaction",ethereumTransaction:t}}return{}}static parseFromTransactionInternals(e){try{const t=e;if(t._contractId&&t._gas){const e={contractId:t._contractId.toString(),gas:"number"==typeof t._gas?t._gas:i.Long.fromValue(t._gas).toNumber(),amount:t._amount?parseFloat(t._amount.toString()):0};if(t._functionParameters){const r=a.Buffer.from(t._functionParameters).toString("hex");e.functionParameters=r,e.functionName=this.extractFunctionName(r)}return{type:"CONTRACTCALL",humanReadableType:"Contract Call",contractCall:e}}if(ua(e,"contractCreateInstance")){const e={gas:t._gas.toString(),initialBalance:t._initialBalance?.toString()||"0"};return t._fileId?(e.initcodeSource="fileID",e.initcode=t._fileId.toString()):t._bytecode&&(e.initcodeSource="bytes",e.initcode=a.Buffer.from(t._bytecode).toString("hex")),t._constructorParameters&&(e.constructorParameters=a.Buffer.from(t._constructorParameters).toString("hex")),t._memo&&(e.memo=t._memo),t._adminKey&&(e.adminKey=la(t._adminKey)),void 0!==t._maxAutomaticTokenAssociations&&(e.maxAutomaticTokenAssociations=t._maxAutomaticTokenAssociations),t._stakedAccountId?e.stakedAccountId=t._stakedAccountId.toString():null!==t._stakedNodeId&&void 0!==t._stakedNodeId&&(e.stakedNodeId=i.Long.fromValue(t._stakedNodeId).toString()),void 0!==t._declineReward&&(e.declineReward=t._declineReward),t._autoRenewPeriod&&(e.autoRenewPeriod=t._autoRenewPeriod.toString()),{type:"CONTRACTCREATE",humanReadableType:"Contract Create",contractCreate:e}}if(ua(e,"contractUpdateInstance")){const e={contractIdToUpdate:t._contractId.toString()};return t._memo&&(e.memo=t._memo),t._adminKey&&(e.adminKey=la(t._adminKey)),void 0!==t._maxAutomaticTokenAssociations&&(e.maxAutomaticTokenAssociations=t._maxAutomaticTokenAssociations),t._stakedAccountId?e.stakedAccountId=t._stakedAccountId.toString():null!==t._stakedNodeId&&void 0!==t._stakedNodeId&&(e.stakedNodeId=i.Long.fromValue(t._stakedNodeId).toString()),void 0!==t._declineReward&&(e.declineReward=t._declineReward),t._autoRenewPeriod&&(e.autoRenewPeriod=t._autoRenewPeriod.toString()),{type:"CONTRACTUPDATE",humanReadableType:"Contract Update",contractUpdate:e}}if(ua(e,"contractDeleteInstance")){const e={contractIdToDelete:t._contractId.toString()};return t._transferAccountId?e.transferAccountId=t._transferAccountId.toString():t._transferContractId&&(e.transferContractId=t._transferContractId.toString()),{type:"CONTRACTDELETE",humanReadableType:"Contract Delete",contractDelete:e}}return{}}catch(t){return{}}}static extractFunctionName(e){if(e.length<8)return"unknown";const t=e.substring(0,8);return{a9059cbb:"transfer","095ea7b3":"approve","23b872dd":"transferFrom","70a08231":"balanceOf",dd62ed3e:"allowance","18160ddd":"totalSupply","06fdde03":"name","95d89b41":"symbol","313ce567":"decimals","42842e0e":"safeTransferFrom",b88d4fde:"safeTransferFrom",e985e9c5:"isApprovedForAll",a22cb465:"setApprovalForAll","6352211e":"ownerOf",c87b56dd:"tokenURI","01ffc9a7":"supportsInterface","40c10f19":"mint","42966c68":"burn",f2fde38b:"transferOwnership","715018a6":"renounceOwnership","8da5cb5b":"owner"}[t]||t}static parseEthereumTransaction(e){if(!e)return;const t={contractId:"EVM",gas:e.maxGasAllowance?i.Long.fromValue(e.maxGasAllowance).toNumber():0,amount:0};if(e.ethereumData&&e.ethereumData.length>0){const r=a.Buffer.from(e.ethereumData).toString("hex");t.functionParameters=r,r.length>=8&&(t.functionName=this.extractFunctionName(r))}return t}static parseContractCall(e){if(!e)return;const t=i.Hbar.fromTinybars(i.Long.fromValue(e.amount??0)),r={contractId:new i.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString(),gas:i.Long.fromValue(e.gas??0).toNumber(),amount:parseFloat(t.toString(i.HbarUnit.Hbar))};return e.functionParameters&&(r.functionParameters=a.Buffer.from(e.functionParameters).toString("hex"),r.functionParameters.length>=8&&(r.functionName=this.extractFunctionName(r.functionParameters))),r}static parseContractCreate(e){if(!e)return;const t={};return e.initialBalance&&(t.initialBalance=i.Hbar.fromTinybars(i.Long.fromValue(e.initialBalance)).toString(i.HbarUnit.Hbar)),e.gas&&(t.gas=i.Long.fromValue(e.gas).toString()),e.adminKey&&(t.adminKey=la(e.adminKey)),e.constructorParameters&&(t.constructorParameters=a.Buffer.from(e.constructorParameters).toString("hex")),e.memo&&(t.memo=e.memo),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=i.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.stakedAccountId?t.stakedAccountId=new i.AccountId(e.stakedAccountId.shardNum??0,e.stakedAccountId.realmNum??0,e.stakedAccountId.accountNum??0).toString():null!==e.stakedNodeId&&void 0!==e.stakedNodeId&&(t.stakedNodeId=i.Long.fromValue(e.stakedNodeId).toString()),void 0!==e.declineReward&&(t.declineReward=e.declineReward),void 0!==e.maxAutomaticTokenAssociations&&(t.maxAutomaticTokenAssociations=e.maxAutomaticTokenAssociations),e.fileID?(t.initcodeSource="fileID",t.initcode=new i.FileId(e.fileID.shardNum??0,e.fileID.realmNum??0,e.fileID.fileNum??0).toString()):e.initcode&&e.initcode.length>0&&(t.initcodeSource="bytes",t.initcode=a.Buffer.from(e.initcode).toString("hex")),t}static parseContractUpdate(e){if(!e)return;const t={};if(e.contractID&&(t.contractIdToUpdate=new i.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),e.adminKey&&(t.adminKey=la(e.adminKey)),e.expirationTime?.seconds&&(t.expirationTime=`${i.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=i.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.memo){const r=e.memo;if(r&&"object"==typeof r&&Object.prototype.hasOwnProperty.call(r,"value")){const e=r.value;t.memo=null==e?void 0:String(e)}else t.memo="string"==typeof r?r:void 0}else t.memo=void 0;return e.stakedAccountId?(t.stakedAccountId=new i.AccountId(e.stakedAccountId.shardNum??0,e.stakedAccountId.realmNum??0,e.stakedAccountId.accountNum??0).toString(),t.stakedNodeId=void 0):null!==e.stakedNodeId&&void 0!==e.stakedNodeId&&i.Long.fromValue(e.stakedNodeId).notEquals(-1)?(t.stakedNodeId=i.Long.fromValue(e.stakedNodeId).toString(),t.stakedAccountId=void 0):(t.stakedNodeId=void 0,t.stakedAccountId=void 0),void 0!==e.declineReward?.value&&(t.declineReward=e.declineReward.value),void 0!==e.maxAutomaticTokenAssociations?.value&&(t.maxAutomaticTokenAssociations=e.maxAutomaticTokenAssociations.value),e.autoRenewAccountId&&(t.autoRenewAccountId=new i.AccountId(e.autoRenewAccountId.shardNum??0,e.autoRenewAccountId.realmNum??0,e.autoRenewAccountId.accountNum??0).toString()),t}static parseContractDelete(e){if(!e)return;const t={};return e.contractID&&(t.contractIdToDelete=new i.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),e.transferAccountID?t.transferAccountId=new i.AccountId(e.transferAccountID.shardNum??0,e.transferAccountID.realmNum??0,e.transferAccountID.accountNum??0).toString():e.transferContractID&&(t.transferContractId=new i.ContractId(e.transferContractID.shardNum??0,e.transferContractID.realmNum??0,e.transferContractID.contractNum??0).toString()),t}static parseFromTransactionObject(e){return this.parseSCSTransaction(e)}}class ya{static parseUtilTransaction(e,t){try{if(t||e.toBytes)try{const r=t||e.toBytes(),i=n.proto.TransactionList.decode(r);if(i.transactionList&&i.transactionList.length>0){const e=i.transactionList[0];let t=null;if(e.bodyBytes&&e.bodyBytes.length>0)t=n.proto.TransactionBody.decode(e.bodyBytes);else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const r=n.proto.SignedTransaction.decode(e.signedTransactionBytes);r.bodyBytes&&(t=n.proto.TransactionBody.decode(r.bodyBytes))}if(t){const e=this.parseFromProtobufTxBody(t);if(e.type&&"UNKNOWN"!==e.type)return e}}}catch(r){}return this.parseFromTransactionInternals(e)}catch(i){return{type:"UNKNOWN",humanReadableType:"Unknown Utility Transaction"}}}static parseFromProtobufTxBody(e){if(e.utilPrng){const t=this.parseUtilPrng(e.utilPrng);if(t)return{type:"PRNG",humanReadableType:"Pseudo Random Number",utilPrng:t}}if(e.freeze){const t=this.parseNetworkFreezeFromProto(e.freeze);if(t)return{type:"FREEZE",humanReadableType:"Network Freeze",freeze:t}}if(e.systemDelete){const t=this.parseSystemDeleteFromProto(e.systemDelete);if(t)return{type:"SYSTEMDELETE",humanReadableType:"System Delete",systemDelete:t}}if(e.systemUndelete){const t=this.parseSystemUndeleteFromProto(e.systemUndelete);if(t)return{type:"SYSTEMUNDELETE",humanReadableType:"System Undelete",systemUndelete:t}}if(e.nodeCreate){const t=this.parseNodeCreateFromProto(e.nodeCreate);if(t)return{type:"NODECREATE",humanReadableType:"Node Create",nodeCreate:t}}if(e.nodeUpdate){const t=this.parseNodeUpdateFromProto(e.nodeUpdate);if(t)return{type:"NODEUPDATE",humanReadableType:"Node Update",nodeUpdate:t}}if(e.nodeDelete){const t=this.parseNodeDeleteFromProto(e.nodeDelete);if(t)return{type:"NODEDELETE",humanReadableType:"Node Delete",nodeDelete:t}}return{}}static parseFromTransactionInternals(e){try{const t=e;if(ua(e,"utilPrng")){const e={};return t._range&&0!==t._range&&(e.range=t._range),{type:"PRNG",humanReadableType:"Pseudo Random Number",utilPrng:e}}if(ua(e,"freeze")){const e={};return t._startTime&&(e.startTime=t._startTime.toString()),t._endTime&&(e.endTime=t._endTime.toString()),t._updateFile&&(e.updateFile=t._updateFile.toString()),t._fileHash&&(e.fileHash=globalThis.Buffer.from(t._fileHash).toString("hex")),t._freezeType&&(e.freezeType=t._freezeType),{type:"FREEZE",humanReadableType:"Network Freeze",freeze:e}}if(ua(e,"systemDelete")){const e={};return t._fileId?e.fileId=t._fileId.toString():t._contractId&&(e.contractId=t._contractId.toString()),t._expirationTime&&(e.expirationTime=t._expirationTime.toString()),{type:"SYSTEMDELETE",humanReadableType:"System Delete",systemDelete:e}}if(ua(e,"systemUndelete")){const e={};return t._fileId?e.fileId=t._fileId.toString():t._contractId&&(e.contractId=t._contractId.toString()),{type:"SYSTEMUNDELETE",humanReadableType:"System Undelete",systemUndelete:e}}return{}}catch(t){return{}}}static parseNetworkFreezeFromProto(e){if(!e)return;const t={};if(e.startTime?.seconds&&(t.startTime=`${i.Long.fromValue(e.startTime.seconds).toString()}.${e.startTime.nanos??0}`),e.updateFile&&(t.updateFile=new i.FileId(e.updateFile.shardNum??0,e.updateFile.realmNum??0,e.updateFile.fileNum??0).toString()),e.fileHash&&e.fileHash.length>0&&(t.fileHash=globalThis.Buffer.from(e.fileHash).toString("hex")),void 0!==e.freezeType){const r=["FREEZE_ONLY","PREPARE_UPGRADE","FREEZE_UPGRADE","FREEZE_ABORT"];t.freezeType=r[e.freezeType]||"FREEZE_ONLY"}return t}static parseSystemDeleteFromProto(e){if(!e)return;const t={};return e.fileID?t.fileId=new i.FileId(e.fileID.shardNum??0,e.fileID.realmNum??0,e.fileID.fileNum??0).toString():e.contractID&&(t.contractId=new i.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),e.expirationTime?.seconds&&(t.expirationTime=i.Long.fromValue(e.expirationTime.seconds).toString()),t}static parseSystemUndeleteFromProto(e){if(!e)return;const t={};return e.fileID?t.fileId=new i.FileId(e.fileID.shardNum??0,e.fileID.realmNum??0,e.fileID.fileNum??0).toString():e.contractID&&(t.contractId=new i.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),t}static parseNodeCreateFromProto(e){if(!e)return;const t={};return void 0!==e.nodeId&&(t.nodeId=i.Long.fromValue(e.nodeId).toNumber()),t}static parseNodeUpdateFromProto(e){if(!e)return;const t={};return void 0!==e.nodeId&&(t.nodeId=i.Long.fromValue(e.nodeId).toNumber()),t}static parseNodeDeleteFromProto(e){if(!e)return;const t={};return void 0!==e.nodeId&&(t.nodeId=i.Long.fromValue(e.nodeId).toNumber()),t}static parseUtilPrng(e){if(!e)return;const t={};return e.range&&0!==e.range&&(t.range=e.range),t}static parseFreeze(e){return this.parseNetworkFreezeFromProto(e)}static parseFromTransactionObject(e){return this.parseUtilTransaction(e)}}class ba{static parseScheduleTransaction(e,t){try{if(t||e.toBytes)try{const r=t||e.toBytes(),i=n.proto.TransactionList.decode(r);if(i.transactionList&&i.transactionList.length>0){const e=i.transactionList[0];let t=null;if(e.bodyBytes&&e.bodyBytes.length>0)t=n.proto.TransactionBody.decode(e.bodyBytes);else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const r=n.proto.SignedTransaction.decode(e.signedTransactionBytes);r.bodyBytes&&(t=n.proto.TransactionBody.decode(r.bodyBytes))}if(t){const e=this.parseFromProtobufTxBody(t);if(e.type&&"UNKNOWN"!==e.type)return e}}}catch(r){}return this.parseFromTransactionInternals(e)}catch(i){return{type:"UNKNOWN",humanReadableType:"Unknown Schedule Transaction"}}}static parseFromProtobufTxBody(e){if(e.scheduleCreate){const t=this.parseScheduleCreateFromProto(e.scheduleCreate);if(t)return{type:"SCHEDULECREATE",humanReadableType:"Schedule Create",scheduleCreate:t}}if(e.scheduleSign){const t=this.parseScheduleSignFromProto(e.scheduleSign);if(t)return{type:"SCHEDULESIGN",humanReadableType:"Schedule Sign",scheduleSign:t}}if(e.scheduleDelete){const t=this.parseScheduleDeleteFromProto(e.scheduleDelete);if(t)return{type:"SCHEDULEDELETE",humanReadableType:"Schedule Delete",scheduleDelete:t}}return{}}static parseFromTransactionInternals(e){try{const t=e;if(ua(e,"scheduleCreate")){return{type:"SCHEDULECREATE",humanReadableType:"Schedule Create",scheduleCreate:{scheduledTransactionBody:globalThis.Buffer.from(t._scheduledTransaction).toString("base64"),memo:t._scheduleMemo,adminKey:t._adminKey?la(t._adminKey):void 0,payerAccountId:t._payerAccountId?.toString(),expirationTime:t._expirationTime?.toString(),waitForExpiry:t._waitForExpiry||!1}}}if(ua(e,"scheduleSign")){return{type:"SCHEDULESIGN",humanReadableType:"Schedule Sign",scheduleSign:{scheduleId:t._scheduleId.toString()}}}if(ua(e,"scheduleDelete")){return{type:"SCHEDULEDELETE",humanReadableType:"Schedule Delete",scheduleDelete:{scheduleId:t._scheduleId.toString()}}}return{}}catch(t){return{}}}static parseScheduleCreateFromProto(e){if(!e)return;const t={};if(e.scheduledTransactionBody){const r=n.proto.SchedulableTransactionBody.encode(n.proto.SchedulableTransactionBody.create(e.scheduledTransactionBody)).finish();t.scheduledTransactionBody=globalThis.Buffer.from(r).toString("base64")}return e.memo&&(t.memo=e.memo),e.adminKey&&(t.adminKey=la(e.adminKey)),e.payerAccountID&&(t.payerAccountId=new i.AccountId(e.payerAccountID.shardNum??0,e.payerAccountID.realmNum??0,e.payerAccountID.accountNum??0).toString()),e.expirationTime?.seconds&&(t.expirationTime=`${i.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos??0}`),void 0!==e.waitForExpiry&&(t.waitForExpiry=e.waitForExpiry),t}static parseScheduleSignFromProto(e){if(!e)return;const t={};return e.scheduleID&&(t.scheduleId=new i.ScheduleId(e.scheduleID.shardNum??0,e.scheduleID.realmNum??0,e.scheduleID.scheduleNum??0).toString()),t}static parseScheduleDeleteFromProto(e){if(!e)return;const t={};return e.scheduleID&&(t.scheduleId=new i.ScheduleId(e.scheduleID.shardNum??0,e.scheduleID.realmNum??0,e.scheduleID.scheduleNum??0).toString()),t}static parseScheduleCreate(e){try{return this.parseScheduleTransaction(e).scheduleCreate||null}catch(t){return console.warn("[ScheduleParser] Failed to parse schedule create:",t),null}}static parseScheduleSign(e){try{return this.parseScheduleTransaction(e).scheduleSign||null}catch(t){return console.warn("[ScheduleParser] Failed to parse schedule sign:",t),null}}static parseScheduleDelete(e){try{return this.parseScheduleTransaction(e).scheduleDelete||null}catch(t){return console.warn("[ScheduleParser] Failed to parse schedule delete:",t),null}}static extractScheduleInfo(e){try{const t=e._transactionBody;if(t?.scheduleRef)return{isScheduled:!0,scheduleRef:t.scheduleRef.toString()};const r=e;return r._scheduleId||r.scheduleId?{isScheduled:!0,scheduleRef:(r._scheduleId||r.scheduleId)?.toString()}:{isScheduled:!1}}catch(t){return{isScheduled:!1}}}static parseScheduledTransactionBody(e){try{let t;if(e.startsWith("0x")){const r=e.slice(2);t=new Uint8Array(globalThis.Buffer.from(r,"hex"))}else t=new Uint8Array(globalThis.Buffer.from(e,"base64"));const r=n.proto.SchedulableTransactionBody.decode(t),i=Object.keys(r).find(e=>null!==r[e]&&"transactionFee"!==e&&"memo"!==e);return i?{type:i.toUpperCase(),body:r[i],memo:r.memo,transactionFee:r.transactionFee?.toString()}:null}catch(t){return console.warn("[ScheduleParser] Failed to parse scheduled transaction body:",t),null}}static parseFromTransactionObject(e){return this.parseScheduleTransaction(e)}}const wa={TOKENCREATE:{bodyField:"tokenCreation",parser:pa.parseTokenCreate,resultField:"tokenCreation"},TOKENMINT:{bodyField:"tokenMint",parser:pa.parseTokenMint,resultField:"tokenMint"},TOKENBURN:{bodyField:"tokenBurn",parser:pa.parseTokenBurn,resultField:"tokenBurn"},TOKENUPDATE:{bodyField:"tokenUpdate",parser:pa.parseTokenUpdate,resultField:"tokenUpdate"},TOKENDELETE:{bodyField:"tokenDeletion",parser:pa.parseTokenDelete,resultField:"tokenDelete"},TOKENASSOCIATE:{bodyField:"tokenAssociate",parser:pa.parseTokenAssociate,resultField:"tokenAssociate"},TOKENDISSOCIATE:{bodyField:"tokenDissociate",parser:pa.parseTokenDissociate,resultField:"tokenDissociate"},TOKENFREEZE:{bodyField:"tokenFreeze",parser:pa.parseTokenFreeze,resultField:"tokenFreeze"},TOKENUNFREEZE:{bodyField:"tokenUnfreeze",parser:pa.parseTokenUnfreeze,resultField:"tokenUnfreeze"},TOKENGRANTKYC:{bodyField:"tokenGrantKyc",parser:pa.parseTokenGrantKyc,resultField:"tokenGrantKyc"},TOKENREVOKEKYC:{bodyField:"tokenRevokeKyc",parser:pa.parseTokenRevokeKyc,resultField:"tokenRevokeKyc"},TOKENPAUSE:{bodyField:"tokenPause",parser:pa.parseTokenPause,resultField:"tokenPause"},TOKENUNPAUSE:{bodyField:"tokenUnpause",parser:pa.parseTokenUnpause,resultField:"tokenUnpause"},TOKENWIPEACCOUNT:{bodyField:"tokenWipe",parser:pa.parseTokenWipeAccount,resultField:"tokenWipeAccount"},TOKENFEESCHEDULEUPDATE:{bodyField:"tokenFeeScheduleUpdate",parser:pa.parseTokenFeeScheduleUpdate,resultField:"tokenFeeScheduleUpdate"},TOKENAIRDROP:{bodyField:"tokenAirdrop",parser:pa.parseTokenAirdropFromProto,resultField:"tokenAirdrop"},TOPICCREATE:{bodyField:"consensusCreateTopic",parser:ha.parseConsensusCreateTopic,resultField:"consensusCreateTopic"},CONSENSUSSUBMITMESSAGE:{bodyField:"consensusSubmitMessage",parser:ha.parseConsensusSubmitMessage,resultField:"consensusSubmitMessage"},TOPICUPDATE:{bodyField:"consensusUpdateTopic",parser:ha.parseConsensusUpdateTopic,resultField:"consensusUpdateTopic"},TOPICDELETE:{bodyField:"consensusDeleteTopic",parser:ha.parseConsensusDeleteTopic,resultField:"consensusDeleteTopic"},ACCOUNTCREATE:{bodyField:"cryptoCreateAccount",parser:ma.parseCryptoCreateAccount,resultField:"cryptoCreateAccount"},ACCOUNTUPDATE:{bodyField:"cryptoUpdateAccount",parser:ma.parseCryptoUpdateAccount,resultField:"cryptoUpdateAccount"},ACCOUNTDELETE:{bodyField:"cryptoDelete",parser:ma.parseCryptoDelete,resultField:"cryptoDelete"},CRYPTOTRANSFER:{bodyField:"cryptoTransfer",parser:e=>{const t={transfers:[],tokenTransfers:[]};return ma.parseCryptoTransfers(e,t),t},resultField:"transfers",spreadResult:!0},APPROVEALLOWANCE:{bodyField:"cryptoApproveAllowance",parser:ma.parseCryptoApproveAllowance,resultField:"cryptoApproveAllowance"},DELETEALLOWANCE:{bodyField:"cryptoDeleteAllowance",parser:ma.parseCryptoDeleteAllowance,resultField:"cryptoDeleteAllowance"},FILECREATE:{bodyField:"fileCreate",parser:ga.parseFileCreate,resultField:"fileCreate"},FILEUPDATE:{bodyField:"fileUpdate",parser:ga.parseFileUpdate,resultField:"fileUpdate"},FILEDELETE:{bodyField:"fileDelete",parser:ga.parseFileDelete,resultField:"fileDelete"},FILEAPPEND:{bodyField:"fileAppend",parser:ga.parseFileAppend,resultField:"fileAppend"},CONTRACTCREATE:{bodyField:"contractCreateInstance",parser:fa.parseContractCreate,resultField:"contractCreate"},CONTRACTUPDATE:{bodyField:"contractUpdateInstance",parser:fa.parseContractUpdate,resultField:"contractUpdate"},CONTRACTDELETE:{bodyField:"contractDeleteInstance",parser:fa.parseContractDelete,resultField:"contractDelete"},CONTRACTCALL:{bodyField:"contractCall",parser:fa.parseContractCall,resultField:"contractCall"},ETHEREUMTRANSACTION:{bodyField:"ethereumTransaction",parser:fa.parseEthereumTransaction,resultField:"ethereumTransaction"},SCHEDULECREATE:{bodyField:"scheduleCreate",parser:ba.parseScheduleCreateFromProto,resultField:"scheduleCreate"},SCHEDULESIGN:{bodyField:"scheduleSign",parser:ba.parseScheduleSignFromProto,resultField:"scheduleSign"},SCHEDULEDELETE:{bodyField:"scheduleDelete",parser:ba.parseScheduleDeleteFromProto,resultField:"scheduleDelete"},PRNG:{bodyField:"utilPrng",parser:ya.parseUtilPrng,resultField:"utilPrng"},FREEZE:{bodyField:"freeze",parser:ya.parseFreeze,resultField:"freeze"},SYSTEMDELETE:{bodyField:"systemDelete",parser:e=>({fileId:e.fileID?`${e.fileID.shardNum}.${e.fileID.realmNum}.${e.fileID.fileNum}`:void 0,contractId:e.contractID?`${e.contractID.shardNum}.${e.contractID.realmNum}.${e.contractID.contractNum}`:void 0,expirationTime:e.expirationTime?.seconds?e.expirationTime.seconds.toString():void 0}),resultField:"systemDelete"},SYSTEMUNDELETE:{bodyField:"systemUndelete",parser:e=>({fileId:e.fileID?`${e.fileID.shardNum}.${e.fileID.realmNum}.${e.fileID.fileNum}`:void 0,contractId:e.contractID?`${e.contractID.shardNum}.${e.contractID.realmNum}.${e.contractID.contractNum}`:void 0}),resultField:"systemUndelete"},TOKENCANCELAIRDROP:{bodyField:"tokenCancelAirdrop",parser:e=>({pendingAirdrops:e.pendingAirdrops||[]}),resultField:"tokenCancelAirdrop"},TOKENCLAIMAIRDROP:{bodyField:"tokenClaimAirdrop",parser:e=>({pendingAirdrops:e.pendingAirdrops||[]}),resultField:"tokenClaimAirdrop"},TOKENREJECT:{bodyField:"tokenReject",parser:e=>({owner:e.owner?`${e.owner.shardNum}.${e.owner.realmNum}.${e.owner.accountNum}`:void 0,rejections:e.rejections||[]}),resultField:"tokenReject"},TOKENUPDATENFTS:{bodyField:"tokenUpdateNfts",parser:e=>({tokenId:e.token?`${e.token.shardNum}.${e.token.realmNum}.${e.token.tokenNum}`:void 0,serialNumbers:e.serialNumbers||[],metadata:e.metadata}),resultField:"tokenUpdateNfts"},TOKENWIPE:{bodyField:"tokenWipe",parser:pa.parseTokenWipeAccount,resultField:"tokenWipeAccount"},CRYPTOADDLIVEHASH:{bodyField:"cryptoAddLiveHash",parser:e=>({accountId:e.accountID?`${e.accountID.shardNum}.${e.accountID.realmNum}.${e.accountID.accountNum}`:void 0,liveHash:e.liveHash}),resultField:"cryptoAddLiveHash"},CRYPTODELETELIVEHASH:{bodyField:"cryptoDeleteLiveHash",parser:e=>({accountId:e.accountOfLiveHash?`${e.accountOfLiveHash.shardNum}.${e.accountOfLiveHash.realmNum}.${e.accountOfLiveHash.accountNum}`:void 0,liveHashToDelete:e.liveHashToDelete}),resultField:"cryptoDeleteLiveHash"},UNCHECKEDSUBMIT:{bodyField:"uncheckedSubmit",parser:e=>({topicId:e.topicID?`${e.topicID.shardNum}.${e.topicID.realmNum}.${e.topicID.topicNum}`:void 0,message:e.message}),resultField:"uncheckedSubmit"},NODECREATE:{bodyField:"nodeCreate",parser:e=>({accountId:e.accountId?`${e.accountId.shardNum}.${e.accountId.realmNum}.${e.accountId.accountNum}`:void 0,description:e.description,gossipEndpoint:e.gossipEndpoint,serviceEndpoint:e.serviceEndpoint,gossipCaCertificate:e.gossipCaCertificate,grpcCertificateHash:e.grpcCertificateHash,adminKey:e.adminKey}),resultField:"nodeCreate"},NODEUPDATE:{bodyField:"nodeUpdate",parser:e=>({nodeId:e.nodeId?.toString(),accountId:e.accountId?`${e.accountId.shardNum}.${e.accountId.realmNum}.${e.accountId.accountNum}`:void 0,description:e.description,gossipEndpoint:e.gossipEndpoint,serviceEndpoint:e.serviceEndpoint,gossipCaCertificate:e.gossipCaCertificate,grpcCertificateHash:e.grpcCertificateHash,adminKey:e.adminKey}),resultField:"nodeUpdate"},NODEDELETE:{bodyField:"nodeDelete",parser:e=>({nodeId:e.nodeId?.toString()}),resultField:"nodeDelete"},NODESTAKEUPDATE:{bodyField:"nodeStakeUpdate",parser:e=>({nodeId:e.nodeId?.toString(),maxStake:e.maxStake?.toString(),minStake:e.minStake?.toString(),rewardRate:e.rewardRate?.toString()}),resultField:"nodeStakeUpdate"},ATOMICBATCH:{bodyField:"atomicBatch",parser:e=>({transactions:e.transactions||[]}),resultField:"atomicBatch"},STATESIGNATURETRANSACTION:{bodyField:"stateSignatureTransaction",parser:e=>({signature:e.signature,round:e.round?.toString()}),resultField:"stateSignatureTransaction"},HISTORYPROOFSIGNATURE:{bodyField:"historyProofSignature",parser:e=>({signature:e.signature,round:e.round?.toString()}),resultField:"historyProofSignature"},HISTORYPROOFKEYPUBLICATION:{bodyField:"historyProofKeyPublication",parser:e=>({publicKey:e.publicKey,round:e.round?.toString()}),resultField:"historyProofKeyPublication"},HISTORYPROOFVOTE:{bodyField:"historyProofVote",parser:e=>({vote:e.vote,round:e.round?.toString()}),resultField:"historyProofVote"},HINTSPREPROCESSINGVOTE:{bodyField:"hintsPreprocessingVote",parser:e=>({vote:e.vote,round:e.round?.toString()}),resultField:"hintsPreprocessingVote"},HINTSKEYPUBLICATION:{bodyField:"hintsKeyPublication",parser:e=>({publicKey:e.publicKey,round:e.round?.toString()}),resultField:"hintsKeyPublication"},HINTSPARTIALSIGNATURE:{bodyField:"hintsPartialSignature",parser:e=>({signature:e.signature,round:e.round?.toString()}),resultField:"hintsPartialSignature"},CRSPUBLICATION:{bodyField:"crsPublication",parser:e=>({crs:e.crs,round:e.round?.toString()}),resultField:"crsPublication"}};const Ia={tokenCreation:{type:"TOKENCREATE",humanReadableType:"Token Creation"},tokenAirdrop:{type:"TOKENAIRDROP",humanReadableType:"Token Airdrop"},tokenMint:{type:"TOKENMINT",humanReadableType:"Token Mint"},tokenBurn:{type:"TOKENBURN",humanReadableType:"Token Burn"},tokenUpdate:{type:"TOKENUPDATE",humanReadableType:"Token Update"},tokenDeletion:{type:"TOKENDELETE",humanReadableType:"Token Deletion"},tokenAssociate:{type:"TOKENASSOCIATE",humanReadableType:"Token Association"},tokenDissociate:{type:"TOKENDISSOCIATE",humanReadableType:"Token Dissociation"},tokenFreeze:{type:"TOKENFREEZE",humanReadableType:"Token Freeze"},tokenUnfreeze:{type:"TOKENUNFREEZE",humanReadableType:"Token Unfreeze"},tokenGrantKyc:{type:"TOKENGRANTKYC",humanReadableType:"Token Grant KYC"},tokenRevokeKyc:{type:"TOKENREVOKEKYC",humanReadableType:"Token Revoke KYC"},tokenPause:{type:"TOKENPAUSE",humanReadableType:"Token Pause"},tokenUnpause:{type:"TOKENUNPAUSE",humanReadableType:"Token Unpause"},tokenWipe:{type:"TOKENWIPE",humanReadableType:"Token Wipe"},tokenFeeScheduleUpdate:{type:"TOKENFEESCHEDULEUPDATE",humanReadableType:"Token Fee Schedule Update"},tokenCancelAirdrop:{type:"TOKENCANCELAIRDROP",humanReadableType:"Cancel Token Airdrop"},tokenClaimAirdrop:{type:"TOKENCLAIMAIRDROP",humanReadableType:"Claim Token Airdrop"},tokenReject:{type:"TOKENREJECT",humanReadableType:"Token Reject"},tokenUpdateNfts:{type:"TOKENUPDATENFTS",humanReadableType:"Update NFT Metadata"},cryptoTransfer:{type:"CRYPTOTRANSFER",humanReadableType:"Crypto Transfer"},cryptoCreateAccount:{type:"ACCOUNTCREATE",humanReadableType:"Account Creation"},cryptoUpdateAccount:{type:"ACCOUNTUPDATE",humanReadableType:"Account Update"},cryptoDelete:{type:"ACCOUNTDELETE",humanReadableType:"Account Deletion"},cryptoApproveAllowance:{type:"APPROVEALLOWANCE",humanReadableType:"Approve Allowance"},cryptoDeleteAllowance:{type:"DELETEALLOWANCE",humanReadableType:"Delete Allowance"},cryptoAddLiveHash:{type:"CRYPTOADDLIVEHASH",humanReadableType:"Add Live Hash"},cryptoDeleteLiveHash:{type:"CRYPTODELETELIVEHASH",humanReadableType:"Delete Live Hash"},consensusCreateTopic:{type:"TOPICCREATE",humanReadableType:"Topic Creation"},consensusSubmitMessage:{type:"CONSENSUSSUBMITMESSAGE",humanReadableType:"Submit Message"},consensusUpdateTopic:{type:"TOPICUPDATE",humanReadableType:"Topic Update"},consensusDeleteTopic:{type:"TOPICDELETE",humanReadableType:"Topic Deletion"},uncheckedSubmit:{type:"UNCHECKEDSUBMIT",humanReadableType:"Unchecked Submit"},contractCall:{type:"CONTRACTCALL",humanReadableType:"Contract Call"},contractCreateInstance:{type:"CONTRACTCREATE",humanReadableType:"Contract Creation"},contractUpdateInstance:{type:"CONTRACTUPDATE",humanReadableType:"Contract Update"},contractDeleteInstance:{type:"CONTRACTDELETE",humanReadableType:"Contract Deletion"},ethereumTransaction:{type:"ETHEREUMTRANSACTION",humanReadableType:"Ethereum Transaction"},fileCreate:{type:"FILECREATE",humanReadableType:"File Creation"},fileUpdate:{type:"FILEUPDATE",humanReadableType:"File Update"},fileDelete:{type:"FILEDELETE",humanReadableType:"File Deletion"},fileAppend:{type:"FILEAPPEND",humanReadableType:"File Append"},scheduleCreate:{type:"SCHEDULECREATE",humanReadableType:"Schedule Creation"},scheduleSign:{type:"SCHEDULESIGN",humanReadableType:"Schedule Sign"},scheduleDelete:{type:"SCHEDULEDELETE",humanReadableType:"Schedule Deletion"},freeze:{type:"FREEZE",humanReadableType:"Network Freeze"},systemDelete:{type:"SYSTEMDELETE",humanReadableType:"System Delete"},systemUndelete:{type:"SYSTEMUNDELETE",humanReadableType:"System Undelete"},nodeCreate:{type:"NODECREATE",humanReadableType:"Node Creation"},nodeUpdate:{type:"NODEUPDATE",humanReadableType:"Node Update"},nodeDelete:{type:"NODEDELETE",humanReadableType:"Node Deletion"},nodeStakeUpdate:{type:"NODESTAKEUPDATE",humanReadableType:"Node Stake Update"},utilPrng:{type:"PRNG",humanReadableType:"Pseudo Random Number"},atomicBatch:{type:"ATOMICBATCH",humanReadableType:"Atomic Batch"},stateSignatureTransaction:{type:"STATESIGNATURETRANSACTION",humanReadableType:"State Signature"},historyProofSignature:{type:"HISTORYPROOFSIGNATURE",humanReadableType:"History Proof Signature"},historyProofKeyPublication:{type:"HISTORYPROOFKEYPUBLICATION",humanReadableType:"History Proof Key Publication"},historyProofVote:{type:"HISTORYPROOFVOTE",humanReadableType:"History Proof Vote"},hintsPreprocessingVote:{type:"HINTSPREPROCESSINGVOTE",humanReadableType:"Hints Preprocessing Vote"},hintsKeyPublication:{type:"HINTSKEYPUBLICATION",humanReadableType:"Hints Key Publication"},hintsPartialSignature:{type:"HINTSPARTIALSIGNATURE",humanReadableType:"Hints Partial Signature"},crsPublication:{type:"CRSPUBLICATION",humanReadableType:"CRS Publication"},transactionID:{type:"UNKNOWN",humanReadableType:"Unknown Transaction"},nodeAccountID:{type:"UNKNOWN",humanReadableType:"Unknown Transaction"},transactionFee:{type:"UNKNOWN",humanReadableType:"Unknown Transaction"},transactionValidDuration:{type:"UNKNOWN",humanReadableType:"Unknown Transaction"},generateRecord:{type:"UNKNOWN",humanReadableType:"Unknown Transaction"},memo:{type:"UNKNOWN",humanReadableType:"Unknown Transaction"},batchKey:{type:"UNKNOWN",humanReadableType:"Unknown Transaction"},maxCustomFees:{type:"UNKNOWN",humanReadableType:"Unknown Transaction"}},Ta={cryptoTransfer:"HBAR Transfer",CRYPTOTRANSFER:"HBAR Transfer",cryptoCreateAccount:"Create Account",ACCOUNTCREATE:"Create Account",cryptoUpdateAccount:"Update Account",ACCOUNTUPDATE:"Update Account",cryptoDeleteAccount:"Delete Account",cryptoDelete:"Delete Account",ACCOUNTDELETE:"Delete Account",cryptoApproveAllowance:"Approve Allowance",APPROVEALLOWANCE:"Approve Allowance",cryptoDeleteAllowance:"Delete Allowance",DELETEALLOWANCE:"Delete Allowance",CRYPTOADDLIVEHASH:"Add Live Hash",CRYPTODELETELIVEHASH:"Delete Live Hash",consensusCreateTopic:"Create Topic",TOPICCREATE:"Create Topic",consensusUpdateTopic:"Update Topic",TOPICUPDATE:"Update Topic",consensusSubmitMessage:"Submit Message",CONSENSUSSUBMITMESSAGE:"Submit Message",consensusDeleteTopic:"Delete Topic",TOPICDELETE:"Delete Topic",UNCHECKEDSUBMIT:"Unchecked Submit",fileCreate:"Create File",FILECREATE:"Create File",fileAppend:"Append File",FILEAPPEND:"Append File",fileUpdate:"Update File",FILEUPDATE:"Update File",fileDelete:"Delete File",FILEDELETE:"Delete File",contractCall:"Contract Call",CONTRACTCALL:"Contract Call",contractCreate:"Create Contract",CONTRACTCREATE:"Create Contract",contractUpdate:"Update Contract",CONTRACTUPDATE:"Update Contract",contractDelete:"Delete Contract",CONTRACTDELETE:"Delete Contract",ethereumTransaction:"Ethereum Transaction",ETHEREUMTRANSACTION:"Ethereum Transaction",tokenCreate:"Create Token",TOKENCREATE:"Create Token",tokenUpdate:"Update Token",TOKENUPDATE:"Update Token",tokenDelete:"Delete Token",TOKENDELETE:"Delete Token",tokenAssociate:"Associate Token",TOKENASSOCIATE:"Associate Token",tokenDissociate:"Dissociate Token",TOKENDISSOCIATE:"Dissociate Token",tokenMint:"Mint Token",TOKENMINT:"Mint Token",tokenBurn:"Burn Token",TOKENBURN:"Burn Token",tokenFeeScheduleUpdate:"Update Token Fee Schedule",TOKENFEESCHEDULEUPDATE:"Update Token Fee Schedule",tokenFreeze:"Freeze Token",TOKENFREEZE:"Freeze Token",tokenUnfreeze:"Unfreeze Token",TOKENUNFREEZE:"Unfreeze Token",tokenGrantKyc:"Grant KYC",TOKENGRANTKYC:"Grant KYC",tokenRevokeKyc:"Revoke KYC",TOKENREVOKEKYC:"Revoke KYC",tokenPause:"Pause Token",TOKENPAUSE:"Pause Token",tokenUnpause:"Unpause Token",TOKENUNPAUSE:"Unpause Token",tokenWipe:"Wipe Token",TOKENWIPE:"Wipe Token",tokenAirdrop:"Token Airdrop",TOKENAIRDROP:"Token Airdrop",TOKENCANCELAIRDROP:"Cancel Token Airdrop",TOKENCLAIMAIRDROP:"Claim Token Airdrop",TOKENREJECT:"Token Reject",TOKENUPDATENFTS:"Update NFT Metadata",scheduleCreate:"Create Schedule",SCHEDULECREATE:"Create Schedule",scheduleSign:"Sign Schedule",SCHEDULESIGN:"Sign Schedule",SCHEDULEDELETE:"Delete Schedule",FREEZE:"Network Freeze",SYSTEMDELETE:"System Delete",SYSTEMUNDELETE:"System Undelete",NODECREATE:"Create Node",NODEUPDATE:"Update Node",NODEDELETE:"Delete Node",NODESTAKEUPDATE:"Update Node Stake",utilPrng:"Generate Random Number",PRNG:"Generate Random Number",ATOMICBATCH:"Atomic Batch",STATESIGNATURETRANSACTION:"State Signature",HISTORYPROOFSIGNATURE:"History Proof Signature",HISTORYPROOFKEYPUBLICATION:"History Proof Key Publication",HISTORYPROOFVOTE:"History Proof Vote",HINTSPREPROCESSINGVOTE:"Hints Preprocessing Vote",HINTSKEYPUBLICATION:"Hints Key Publication",HINTSPARTIALSIGNATURE:"Hints Partial Signature",CRSPUBLICATION:"CRS Publication",unknown:"Unknown Transaction",UNKNOWN:"Unknown Transaction"},Sa={tokenCreation:"tokenCreate",tokenAirdrop:"tokenAirdrop",cryptoTransfer:"cryptoTransfer",consensusSubmitMessage:"consensusSubmitMessage",contractCall:"contractCall",cryptoCreateAccount:"cryptoCreateAccount",cryptoUpdateAccount:"cryptoUpdateAccount",cryptoApproveAllowance:"cryptoApproveAllowance",cryptoDeleteAllowance:"cryptoDeleteAllowance",cryptoDelete:"cryptoDelete",consensusCreateTopic:"consensusCreateTopic",consensusUpdateTopic:"consensusUpdateTopic",consensusDeleteTopic:"consensusDeleteTopic",fileCreate:"fileCreate",fileAppend:"fileAppend",fileUpdate:"fileUpdate",fileDelete:"fileDelete",contractCreateInstance:"contractCreate",contractUpdateInstance:"contractUpdate",contractDeleteInstance:"contractDelete",tokenUpdate:"tokenUpdate",tokenDeletion:"tokenDelete",tokenAssociate:"tokenAssociate",tokenDissociate:"tokenDissociate",tokenMint:"tokenMint",tokenBurn:"tokenBurn",tokenFeeScheduleUpdate:"tokenFeeScheduleUpdate",tokenFreeze:"tokenFreeze",tokenUnfreeze:"tokenUnfreeze",tokenGrantKyc:"tokenGrantKyc",tokenRevokeKyc:"tokenRevokeKyc",tokenPause:"tokenPause",tokenUnpause:"tokenUnpause",tokenWipe:"tokenWipe",utilPrng:"utilPrng"};function ka(e){for(const[t,r]of Object.entries(Ia))if(e[t])return r;return{type:"UNKNOWN",humanReadableType:"Unknown Transaction"}}function Ea(e){return Ta[e]||"Unknown Transaction"}class va{static async parseTransactionBytes(e,t={}){const{enableFallback:r=!0,strictMode:i=!1,includeRaw:o=!0,maxRetries:n=2}=t,s=this.validateTransactionBytes(e);if(!s.isValid&&i)throw new hs(`Invalid transaction bytes format: ${s.error}`,"INVALID_FORMAT",void 0,e);let a,c=0;for(;c<=n;)try{const r=await this.parseTransaction(e,t);return r.formatDetection={originalFormat:s.format||"base64",wasConverted:"hex"===s.format,length:e.length},r}catch(d){if(a=d instanceof Error?d:new Error(String(d)),c++,!r||c>n){if(i)throw new hs("Failed to parse transaction after all attempts","PARSING_FAILED",a,e);break}try{const r=this.parseScheduledTransaction(e,t);return r.formatDetection={originalFormat:s.format||"base64",wasConverted:!1,length:e.length},r}catch(u){}}const l=this.createFallbackResult(e,a,void 0);return l.details&&(l.details.parseAttempts=Math.max(c,1)),l}static parseTransactionObject(e,t,r={}){let i,o;!t||a.Buffer.isBuffer(t)||t instanceof Uint8Array?(i=t,o=r):(o=t,i=void 0);try{const t=this.extractTransactionMetadata(e),r=pa.parseFromTransactionObject(e),a=ma.parseFromTransactionObject(e),c=ha.parseFromTransactionObject(e),l=ga.parseFromTransactionObject(e),d=fa.parseFromTransactionObject(e),u=ba.parseFromTransactionObject(e),p=ya.parseFromTransactionObject(e),h=[r,a,c,l,d,u,p].find(e=>e.type&&"UNKNOWN"!==e.type)||{};let g,m="UNKNOWN",f="Unknown Transaction",y={};if(i||e.toBytes)try{const t=i||e.toBytes(),r=n.proto.TransactionList.decode(t);if(r.transactionList&&r.transactionList.length>0){const e=r.transactionList[0];if(e.bodyBytes&&e.bodyBytes.length>0){const t=n.proto.TransactionBody.decode(e.bodyBytes),r=this.detectTransactionTypeFromBody(t);m=r.type,f=r.humanReadableType,y=this.parseTransactionBodyDetails(t,m),y.tokenCreation&&(g=y.tokenCreation)}else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const t=n.proto.SignedTransaction.decode(e.signedTransactionBytes);if(t.bodyBytes){const e=n.proto.TransactionBody.decode(t.bodyBytes),r=this.detectTransactionTypeFromBody(e);m=r.type,f=r.humanReadableType,y=this.parseTransactionBodyDetails(e,m),y.tokenCreation&&(g=y.tokenCreation)}}}}catch(s){}"UNKNOWN"===m&&h.type&&(m=h.type,f=h.humanReadableType||f);const b={type:m,humanReadableType:f,transfers:[],tokenTransfers:[],...t,...h,raw:o.includeRaw?e._transactionBody||{}:void 0};return this.mergeProtoParsingResults(b,y,r,e,i),b.transfers=a.transfers||b.transfers||[],b.tokenTransfers=a.tokenTransfers||b.tokenTransfers||[],b}catch(c){return{type:"UNKNOWN",humanReadableType:"Unknown Transaction",transfers:[],tokenTransfers:[],raw:o.includeRaw?{}:void 0,details:{error:`Failed to parse Transaction object: ${c instanceof Error?c.message:String(c)}`}}}}static parseTransactionBody(e){try{const t=c.ethers.decodeBase64(e),r=n.proto.SchedulableTransactionBody.decode(t),o=this.getTransactionType(r),s={type:o,humanReadableType:this.getHumanReadableType(o),transfers:[],tokenTransfers:[],raw:r};if(r.memo&&(s.memo=r.memo),r.transactionFee){const e=i.Hbar.fromTinybars(i.Long.fromValue(r.transactionFee));s.transactionFee=e.toString(i.HbarUnit.Hbar)}return this.applySchedulableTransactionParsing(r,s),s}catch(t){return{type:"UNKNOWN",humanReadableType:"Unknown Transaction",transfers:[],tokenTransfers:[],raw:void 0,details:{error:`Failed to parse transaction body: ${t instanceof Error?t.message:String(t)}`}}}}static detectTransactionTypeFromBody(e){return ka(e)}static parseScheduleResponse(e){if(!e.transaction_body)return{type:"UNKNOWN",humanReadableType:"Unknown Transaction",transfers:[],tokenTransfers:[],raw:void 0,details:{error:"Schedule response missing transaction_body"}};const t=this.parseTransactionBody(e.transaction_body);return e.memo&&(t.memo=e.memo),t}static getTransactionType(e){return ka(e).type}static getHumanReadableType(e){return Ea(e)}static getTransactionSummary(e){return ca(e)}static validateTransactionBytes(e){if(!e||"string"!=typeof e)return{isValid:!1,error:"Transaction bytes must be a non-empty string"};const t=this.detectTransactionFormat(e),r=/^[A-Za-z0-9+/]*={0,2}$/;let i,o=!1;return"hex"===t?(o=/^0x[0-9a-fA-F]+$/.test(e)&&e.length>2,o||(i="Invalid hex format")):(o=r.test(e)&&e.length>0,o||(i="Invalid base64 format")),{isValid:o,format:t,error:i,length:e.length}}static detectTransactionFormat(e){return e.startsWith("0x")?"hex":"base64"}static decodeTransactionBytes(e){try{if("hex"===this.detectTransactionFormat(e)){const t=e.slice(2);return new Uint8Array(a.Buffer.from(t,"hex"))}return new Uint8Array(a.Buffer.from(e,"base64"))}catch(t){throw new hs("Failed to decode transaction bytes","DECODE_ERROR",t instanceof Error?t:void 0,e)}}static async isValidHederaTransaction(e){try{if(!this.validateTransactionBytes(e).isValid)return!1;const t=this.decodeTransactionBytes(e);return i.Transaction.fromBytes(t),!0}catch{return!1}}static decodeBytesLegacy(e){return this.decodeTransactionBytes(e)}static async parseTransaction(e,t={}){try{const r=this.decodeTransactionBytes(e),o=i.Transaction.fromBytes(r),n=this.extractTransactionMetadataEnhanced(o),s=this.runAllParsers(o),a=s.find(e=>e.type&&"UNKNOWN"!==e.type)||{},c=this.parseFromProtobuf(r),l=c.type||a.type||"UNKNOWN",d={type:l,humanReadableType:c.humanReadableType||a.humanReadableType||"Unknown Transaction",transfers:[],tokenTransfers:[],details:{...n},memo:"string"==typeof n.memo?n.memo:void 0,transactionId:"string"==typeof n.transactionId?n.transactionId:void 0,nodeAccountIds:Array.isArray(n.nodeAccountIds)?n.nodeAccountIds:[],maxTransactionFee:"string"==typeof n.maxTransactionFee?n.maxTransactionFee:void 0,validStart:"string"==typeof n.validStart?n.validStart:void 0,validDuration:"string"==typeof n.validDuration?n.validDuration:void 0,raw:t.includeRaw?{}:void 0};return this.mergeAllResults(d,c,a,s),d}catch(r){throw new hs("Failed to parse as regular transaction","REGULAR_PARSING_FAILED",r instanceof Error?r:void 0,e)}}static parseScheduledTransaction(e,t={}){try{const t=this.parseTransactionBody(e),r=this.validateTransactionBytes(e);return{...t,details:{...t.details||{},parseMethod:"scheduled",validation:r,parseAttempts:t.details?.parseAttempts||1},formatDetection:{originalFormat:r.format||"base64",wasConverted:!1,length:e.length}}}catch(r){throw new hs("Failed to parse as scheduled transaction","SCHEDULED_PARSING_FAILED",r instanceof Error?r:void 0,e)}}static extractTransactionMetadata(e){return{transactionId:e.transactionId?.toString(),nodeAccountIds:e.nodeAccountIds?.map(e=>e.toString())||[],maxTransactionFee:e.maxTransactionFee?.toTinybars().toString()||"0",memo:e._transactionMemo||void 0,transfers:[],tokenTransfers:[]}}static extractTransactionMetadataEnhanced(e){return{transactionId:e.transactionId?.toString(),nodeAccountIds:e.nodeAccountIds?.map(e=>e.toString())||[],maxTransactionFee:e.maxTransactionFee?.toTinybars().toString()||"0",memo:e._transactionMemo||void 0,validStart:e._transactionValidStart?.toString(),validDuration:e._transactionValidDuration?.toString()}}static runAllParsers(e){return[pa.parseFromTransactionObject(e),ma.parseFromTransactionObject(e),ha.parseFromTransactionObject(e),ga.parseFromTransactionObject(e),fa.parseFromTransactionObject(e),ba.parseFromTransactionObject(e),ya.parseFromTransactionObject(e)]}static parseFromProtobuf(e){const t={};try{const r=n.proto.TransactionList.decode(e);if(r.transactionList&&r.transactionList.length>0){const e=r.transactionList[0];let i=null;if(e.bodyBytes&&e.bodyBytes.length>0)i=n.proto.TransactionBody.decode(e.bodyBytes);else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const t=n.proto.SignedTransaction.decode(e.signedTransactionBytes);t.bodyBytes&&(i=n.proto.TransactionBody.decode(t.bodyBytes))}if(i){const e=this.detectTransactionTypeFromBody(i);t.type=e.type,t.humanReadableType=e.humanReadableType;const r=this.parseTransactionBodyDetails(i,e.type);Object.assign(t,r)}}}catch(r){}return t}static mergeAllResults(e,t,r,i){const o=i.find(e=>e.transfers||e.tokenTransfers)||{};e.transfers=o.transfers||e.transfers||[],e.tokenTransfers=o.tokenTransfers||e.tokenTransfers||[],Object.keys(t).forEach(r=>{void 0!==t[r]&&"type"!==r&&"humanReadableType"!==r&&(e[r]=t[r])}),Object.keys(r).forEach(t=>{void 0===r[t]||t in e||"type"===t||"humanReadableType"===t||(e[t]=r[t])})}static applySchedulableTransactionParsing(e,t){e.cryptoTransfer&&ma.parseCryptoTransfers(e.cryptoTransfer,t),e.cryptoDelete&&(t.cryptoDelete=ma.parseCryptoDelete(e.cryptoDelete)),e.cryptoCreateAccount&&(t.cryptoCreateAccount=ma.parseCryptoCreateAccount(e.cryptoCreateAccount)),e.cryptoUpdateAccount&&(t.cryptoUpdateAccount=ma.parseCryptoUpdateAccount(e.cryptoUpdateAccount)),e.cryptoApproveAllowance&&(t.cryptoApproveAllowance=ma.parseCryptoApproveAllowance(e.cryptoApproveAllowance)),e.cryptoDeleteAllowance&&(t.cryptoDeleteAllowance=ma.parseCryptoDeleteAllowance(e.cryptoDeleteAllowance)),e.contractCall&&(t.contractCall=fa.parseContractCall(e.contractCall)),e.contractCreateInstance&&(t.contractCreate=fa.parseContractCreate(e.contractCreateInstance)),e.contractUpdateInstance&&(t.contractUpdate=fa.parseContractUpdate(e.contractUpdateInstance)),e.contractDeleteInstance&&(t.contractDelete=fa.parseContractDelete(e.contractDeleteInstance)),e.tokenCreation&&(t.tokenCreation=pa.parseTokenCreate(e.tokenCreation)),e.tokenMint&&(t.tokenMint=pa.parseTokenMint(e.tokenMint)),e.tokenBurn&&(t.tokenBurn=pa.parseTokenBurn(e.tokenBurn)),e.tokenUpdate&&(t.tokenUpdate=pa.parseTokenUpdate(e.tokenUpdate)),e.tokenFeeScheduleUpdate&&(t.tokenFeeScheduleUpdate=pa.parseTokenFeeScheduleUpdate(e.tokenFeeScheduleUpdate)),e.tokenFreeze&&(t.tokenFreeze=pa.parseTokenFreeze(e.tokenFreeze)),e.tokenUnfreeze&&(t.tokenUnfreeze=pa.parseTokenUnfreeze(e.tokenUnfreeze)),e.tokenGrantKyc&&(t.tokenGrantKyc=pa.parseTokenGrantKyc(e.tokenGrantKyc)),e.tokenRevokeKyc&&(t.tokenRevokeKyc=pa.parseTokenRevokeKyc(e.tokenRevokeKyc)),e.tokenPause&&(t.tokenPause=pa.parseTokenPause(e.tokenPause)),e.tokenUnpause&&(t.tokenUnpause=pa.parseTokenUnpause(e.tokenUnpause)),e.tokenWipe&&(t.tokenWipeAccount=pa.parseTokenWipeAccount(e.tokenWipe)),e.tokenDeletion&&(t.tokenDelete=pa.parseTokenDelete(e.tokenDeletion)),e.tokenAssociate&&(t.tokenAssociate=pa.parseTokenAssociate(e.tokenAssociate)),e.tokenDissociate&&(t.tokenDissociate=pa.parseTokenDissociate(e.tokenDissociate)),e.tokenAirdrop&&(t.tokenAirdrop=pa.parseTokenAirdropFromProto(e.tokenAirdrop)),e.consensusCreateTopic&&(t.consensusCreateTopic=ha.parseConsensusCreateTopic(e.consensusCreateTopic)),e.consensusSubmitMessage&&(t.consensusSubmitMessage=ha.parseConsensusSubmitMessage(e.consensusSubmitMessage)),e.consensusUpdateTopic&&(t.consensusUpdateTopic=ha.parseConsensusUpdateTopic(e.consensusUpdateTopic)),e.consensusDeleteTopic&&(t.consensusDeleteTopic=ha.parseConsensusDeleteTopic(e.consensusDeleteTopic)),e.fileCreate&&(t.fileCreate=ga.parseFileCreate(e.fileCreate)),e.fileAppend&&(t.fileAppend=ga.parseFileAppend(e.fileAppend)),e.fileUpdate&&(t.fileUpdate=ga.parseFileUpdate(e.fileUpdate)),e.fileDelete&&(t.fileDelete=ga.parseFileDelete(e.fileDelete)),e.utilPrng&&(t.utilPrng=ya.parseUtilPrng(e.utilPrng))}static parseTransactionBodyDetails(e,t){const r={},i=wa[t];if(i){const t=e[i.bodyField];if(t){const e=i.parser(t);i.spreadResult?Object.assign(r,e):r[i.resultField]=e}}return r}static mergeProtoParsingResults(e,t,r,i,o){const n=Object.values(wa).map(e=>e.resultField);for(const s of n){const o=t[s],n=r[s];void 0!==o?e[s]=o:void 0!==n?e[s]=n:this.handleSpecialFieldExtraction(e,s,i)}}static handleSpecialFieldExtraction(e,t,r){if("tokenCreation"===t&&"TOKENCREATE"===e.type){const i=pa.extractTokenCreationFromTransaction(r);i&&(e[t]=i)}else if("tokenAirdrop"===t&&"TOKENAIRDROP"===e.type){const i=pa.extractTokenAirdropFromTransaction(r);i&&(e[t]=i)}}static createFallbackResult(e,t,r){const i=this.validateTransactionBytes(e);return{type:"UNKNOWN",humanReadableType:"Unknown Transaction",transfers:[],tokenTransfers:[],details:{rawBytes:e.length>100?e.substring(0,100)+"...":e,primaryError:t?.message,secondaryError:r?.message,parseAttempts:r?2:1,validation:i},formatDetection:{originalFormat:i.format||"base64",wasConverted:!1,length:e.length},raw:{}}}}const Aa="undefined"!=typeof window&&void 0!==window.document;const Ca=new class{constructor(){this.cache=new Map,this.maxSize=100,this.defaultTtlMs=3e5}generateKey(e){return`${e.inputHash}-${e.clientConfigHash}-${e.optionsHash}`}hashObject(e){return globalThis.Buffer.from(JSON.stringify(e)).toString("base64").slice(0,16)}createCacheKey(e,t,r){return{inputHash:this.hashObject(e),clientConfigHash:this.hashObject({accountId:t.accountId,network:t.network}),optionsHash:this.hashObject({mode:r.mode,apiKey:r.apiKey?"present":"absent",network:r.network,metadata:r.metadata})}}get(e){const t=this.generateKey(e),r=this.cache.get(t);if(!r)return null;return Date.now()-r.timestamp>r.ttlMs?(this.cache.delete(t),null):(this.cache.delete(t),this.cache.set(t,r),r.quote)}set(e,t,r=this.defaultTtlMs){const i=this.generateKey(e);if(this.cache.size>=this.maxSize){const e=this.cache.keys().next().value;e&&this.cache.delete(e)}this.cache.set(i,{quote:t,timestamp:Date.now(),ttlMs:r})}clear(){this.cache.clear()}},xa=new class{constructor(){this.cache=new Map,this.maxSize=10,this.defaultTtlMs=18e5}generateConfigKey(e){return globalThis.Buffer.from(JSON.stringify(e)).toString("base64")}get(e){const t=this.generateConfigKey(e),r=this.cache.get(t);if(!r)return null;return Date.now()-r.timestamp>this.defaultTtlMs?(this.cache.delete(t),null):r.sdk}set(e,t){const r=this.generateConfigKey(e);if(this.cache.size>=this.maxSize){const e=this.cache.keys().next().value;e&&this.cache.delete(e)}this.cache.set(r,{sdk:t,timestamp:Date.now(),config:r})}clear(){this.cache.clear()}};async function Ra(e,t,r){if(r)return r;const i={apiKey:t.apiKey,accountId:e.accountId,network:e.network||"mainnet",authType:t.apiKey?"api":"server"},o=xa.get(i);if(o)return o;let n;return n=t.apiKey?new us({apiKey:t.apiKey,network:e.network||"mainnet"}):await us.createWithAuth({type:"server",accountId:e.accountId,privateKey:"string"==typeof e.privateKey?e.privateKey:e.privateKey.toString(),network:e.network||"mainnet"}),xa.set(i,n),n}let Na={};async function _a(e){if(Aa)throw new Error("File path operations are not supported in browser environment. Use buffer input type instead.");if(await async function(){if(!Aa&&!Na.readFileSync)try{const e="undefined"!=typeof global?global:globalThis,t=e.process?.mainModule?.require||e.require;if("function"!=typeof t)throw new Error("require function not available");{const e=t("fs"),r=t("path");Na.readFileSync=e.readFileSync,Na.basename=r.basename,Na.extname=r.extname}}catch(e){console.warn("Node.js modules not available, file path operations will be disabled")}}(),!Na.readFileSync||!Na.basename||!Na.extname)throw new Error("Node.js file system modules are not available. Cannot read file from path.");try{const r=Na.readFileSync(e),i=r.toString("base64"),o=Na.basename(e);let n="application/octet-stream";try{const e=await l.fileTypeFromBuffer(r);e&&(n=e.mime)}catch(t){const r=Na.extname(e).toLowerCase();n={".txt":"text/plain",".json":"application/json",".html":"text/html",".css":"text/css",".js":"application/javascript",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".pdf":"application/pdf"}[r]||"application/octet-stream"}return{base64:i,fileName:o,mimeType:n}}catch(t){throw new Error(`Failed to read file ${e}: ${t.message}`)}}function Pa(e){return{accountId:e.accountId,privateKey:"string"==typeof e.privateKey?e.privateKey:e.privateKey.toString(),network:e.network}}async function Fa(e,t,r,i){const o=z.getInstance({module:"Inscriber",...r.logging});o.info("Starting inscription process",{type:e.type,mode:r.mode||"file",quoteOnly:r.quoteOnly||!1,..."url"===e.type?{url:e.url}:{},..."file"===e.type?{path:e.path}:{},..."buffer"===e.type?{fileName:e.fileName,bufferSize:e.buffer.byteLength}:{}});try{if(r.quoteOnly)return o.debug("Quote-only mode requested, generating quote"),await Ba(e,t,r,i);let n;if("hashinal"===r.mode&&r.metadata&&za(r.metadata,o),i)o.debug("Using existing InscriptionSDK instance"),n=i;else if(r.apiKey)o.debug("Initializing InscriptionSDK with API key"),n=new us({apiKey:r.apiKey,network:t.network||"mainnet"});else{o.debug("Initializing InscriptionSDK with server auth");const e=Pa(t);n=await us.createWithAuth({type:"server",accountId:e.accountId,privateKey:e.privateKey,network:e.network||"mainnet"})}const s={holderId:t.accountId,metadata:r.metadata||{},tags:r.tags||[],mode:r.mode||"file",fileStandard:r.fileStandard,chunkSize:r.chunkSize};let a;switch(e.type){case"url":a={...s,file:{type:"url",url:e.url}};break;case"file":{const t=await _a(e.path);a={...s,file:{type:"base64",base64:t.base64,fileName:t.fileName,mimeType:t.mimeType}};break}case"buffer":a={...s,file:{type:"base64",base64:globalThis.Buffer.from(e.buffer instanceof ArrayBuffer?new Uint8Array(e.buffer):e.buffer).toString("base64"),fileName:e.fileName,mimeType:e.mimeType}}}"hashinal"===r.mode&&(a.metadataObject=r.metadata,a.creator=r.metadata?.creator||t.accountId,a.description=r.metadata?.description,r.jsonFileURL&&(a.jsonFileURL=r.jsonFileURL)),o.debug("Preparing to inscribe content",{type:e.type,mode:r.mode||"file",holderId:t.accountId});const c=Pa(t),l=await n.inscribeAndExecute(a,c);if(o.info("Starting to inscribe.",{type:e.type,mode:r.mode||"file",transactionId:l.jobId}),r.waitForConfirmation){o.debug("Waiting for inscription confirmation",{transactionId:l.jobId,maxAttempts:r.waitMaxAttempts,intervalMs:r.waitIntervalMs});const e=await Ma(n,l.jobId,r.waitMaxAttempts,r.waitIntervalMs,r.progressCallback);return o.info("Inscription confirmation received",{transactionId:l.jobId}),{confirmed:!0,result:l,inscription:e,sdk:n}}return{confirmed:!1,result:l,sdk:n}}catch(n){throw o.error("Error during inscription process",n),n}}async function Oa(e,t,r,i){const o=z.getInstance({module:"Inscriber",...r.logging});o.info("Starting inscription process with signer",{type:e.type,mode:r.mode||"file",quoteOnly:r.quoteOnly||!1,..."url"===e.type?{url:e.url}:{},..."file"===e.type?{path:e.path}:{},..."buffer"===e.type?{fileName:e.fileName,bufferSize:e.buffer.byteLength}:{}});try{if(r.quoteOnly){o.debug("Quote-only mode requested with signer, generating quote");const n={accountId:t.getAccountId().toString(),privateKey:"",network:r.network||"mainnet"};return await Ba(e,n,r,i)}"hashinal"===r.mode&&r.metadata&&za(r.metadata,o);const n=t.getAccountId().toString();let s;o.debug("Using account ID from signer",{accountId:n}),i?(o.debug("Using existing InscriptionSDK instance"),s=i):r.apiKey?(o.debug("Initializing InscriptionSDK with API key"),s=new us({apiKey:r.apiKey,network:r.network||"mainnet",connectionMode:"websocket"})):(o.debug("Initializing InscriptionSDK with client auth (websocket)"),s=await us.createWithAuth({type:"client",accountId:n,signer:t,network:r.network||"mainnet",connectionMode:"websocket"}));const a={holderId:n,metadata:r.metadata||{},tags:r.tags||[],mode:r.mode||"file",fileStandard:r.fileStandard,chunkSize:r.chunkSize};let c;switch(e.type){case"url":c={...a,file:{type:"url",url:e.url}};break;case"file":{const t=await _a(e.path);c={...a,file:{type:"base64",base64:t.base64,fileName:t.fileName,mimeType:t.mimeType}};break}case"buffer":c={...a,file:{type:"base64",base64:globalThis.Buffer.from(e.buffer instanceof ArrayBuffer?new Uint8Array(e.buffer):e.buffer).toString("base64"),fileName:e.fileName,mimeType:e.mimeType}}}"hashinal"===r.mode&&(c.metadataObject=r.metadata,c.creator=r.metadata?.creator||n,c.description=r.metadata?.description,r.jsonFileURL&&(c.jsonFileURL=r.jsonFileURL)),o.debug("Starting inscription via startInscription (websocket)",{type:e.type,mode:r.mode||"file",holderId:n,usesStartInscription:!0});const l=await s.startInscription({...c,holderId:n,network:r.network||"mainnet"});if(o.info("about to start inscription",{type:e.type,mode:r.mode||"file",jobId:l.id||l.tx_id,...l}),"string"==typeof l?.transactionBytes?(o.debug("Executing inscription transaction with signer from bytes"),await s.executeTransactionWithSigner(l.transactionBytes,t)):"Buffer"===l?.transactionBytes?.type&&(o.debug("Executing inscription transaction with signer from buffer"),await s.executeTransactionWithSigner(globalThis.Buffer.from(l.transactionBytes.data).toString("base64"),t)),r.waitForConfirmation){o.debug("Waiting for inscription confirmation (websocket)",{jobId:l.id||l.tx_id,maxAttempts:r.waitMaxAttempts,intervalMs:r.waitIntervalMs});const e=l.tx_id||l.id,t=await Ma(s,e,r.waitMaxAttempts,r.waitIntervalMs,r.progressCallback);return o.info("Inscription confirmation received",{jobId:e}),{confirmed:!0,result:{jobId:l.id||l.tx_id,transactionId:l.tx_id||"",topic_id:l.topic_id,status:l.status,completed:l.completed},inscription:t,sdk:s}}return{confirmed:!1,result:{jobId:l.id||l.tx_id,transactionId:l.tx_id||"",topic_id:l.topic_id,status:l.status,completed:l.completed},sdk:s}}catch(n){throw o.error("Error during inscription process",n),n}}async function Da(e,t){const r=z.getInstance({module:"Inscriber",...t?.logging||{}}),i=e.includes("@")?`${e.split("@")[0]}-${e.split("@")[1].replace(/\./g,"-")}`:e;r.info("Retrieving inscription",{originalTransactionId:e,formattedTransactionId:i});try{let e;if(t?.apiKey)r.debug("Initializing InscriptionSDK with API key"),e=new us({apiKey:t.apiKey,network:t.network||"mainnet"});else{if(!t?.accountId||!t?.privateKey){const e=new Error("Either API key or account ID and private key are required for retrieving inscriptions");throw r.error("Missing authentication credentials",{hasApiKey:Boolean(t?.apiKey),hasAccountId:Boolean(t?.accountId),hasPrivateKey:Boolean(t?.privateKey)}),e}r.debug("Initializing InscriptionSDK with server auth"),e=await us.createWithAuth({type:"server",accountId:t.accountId,privateKey:t.privateKey,network:t.network||"mainnet"})}r.debug("Initialized SDK for inscription retrieval",{formattedTransactionId:i,network:t.network||"mainnet"});const o=await e.retrieveInscription(i);return r.info("Successfully retrieved inscription",{formattedTransactionId:i}),o}catch(o){throw r.error("Error retrieving inscription",{formattedTransactionId:i,error:o}),o}}function za(e,t){const r=["name","creator","description","type"].filter(t=>!e[t]);if(r.length>0){const e=new Error(`Missing required Hashinal metadata fields: ${r.join(", ")}`);throw t.error("Hashinal metadata validation failed",{missingFields:r}),e}t.debug("Hashinal metadata validation passed",{name:e.name,creator:e.creator,description:e.description,type:e.type,hasAttributes:!!e.attributes,hasProperties:!!e.properties})}async function Ba(e,t,r,i){const o=z.getInstance({module:"Inscriber",...r.logging});o.info("Generating inscription quote",{type:e.type,mode:r.mode||"file",..."url"===e.type?{url:e.url}:{},..."file"===e.type?{path:e.path}:{},..."buffer"===e.type?{fileName:e.fileName,bufferSize:e.buffer.byteLength}:{}});try{!function(e,t,r){if(!e||"object"!=typeof e||!("type"in e))throw new Error("Invalid inscription input: type is required");if(!t||!t.accountId)throw new Error("Invalid client config: accountId is required");if(!r)throw new Error("Options are required");if("hashinal"===r.mode){if(!r.metadata)throw new Error("Hashinal mode requires metadata");const e=["name","creator","description","type"].filter(e=>!r.metadata||!r.metadata[e]);if(e.length>0)throw new Error(`Missing required Hashinal metadata fields: ${e.join(", ")}`)}}(e,t,r);const n=function(e,t,r){const i=Ca.createCacheKey(e,t,r);return Ca.get(i)}(e,t,r);if(n)return o.debug("Returning cached quote"),{confirmed:!1,quote:!0,result:n};"hashinal"===r.mode&&r.metadata&&za(r.metadata,o);const s=await Ra(t,r,i),a={holderId:t.accountId,metadata:r.metadata||{},tags:r.tags||[],mode:r.mode||"file",fileStandard:r.fileStandard,chunkSize:r.chunkSize};let c;switch(e.type){case"url":c={...a,file:{type:"url",url:e.url}};break;case"file":{const t=await _a(e.path);c={...a,file:{type:"base64",base64:t.base64,fileName:t.fileName,mimeType:t.mimeType}};break}case"buffer":c={...a,file:{type:"base64",base64:globalThis.Buffer.from(e.buffer instanceof ArrayBuffer?new Uint8Array(e.buffer):e.buffer).toString("base64"),fileName:e.fileName,mimeType:e.mimeType}}}"hashinal"===r.mode&&(c.metadataObject=r.metadata,c.creator=r.metadata?.creator||t.accountId,c.description=r.metadata?.description,r.jsonFileURL&&(c.jsonFileURL=r.jsonFileURL)),o.debug("Calling inscription SDK startInscription for quote",{type:e.type,mode:r.mode||"file",holderId:t.accountId});const l=await s.startInscription(c);o.debug("Received inscription response for quote parsing",{hasTransactionBytes:!!l.transactionBytes,bytesLength:l.transactionBytes?.length||0,transactionBytesType:typeof l.transactionBytes,totalCost:l.totalCost});const d=await async function(e,t){try{let i="0.001";if(e.totalCost&&"number"==typeof e.totalCost){i=(e.totalCost/1e8).toString(),t.debug("Using totalCost from inscription response",{totalCostTinybars:e.totalCost,totalCostHbar:i})}else if(e.transactionBytes){t.debug("Parsing transaction bytes for cost information");try{let r;if("string"==typeof e.transactionBytes)r=e.transactionBytes;else{if(!e.transactionBytes||"object"!=typeof e.transactionBytes||!("data"in e.transactionBytes))throw new Error("Invalid transactionBytes format");r=globalThis.Buffer.from(e.transactionBytes.data).toString("base64")}t.debug("About to parse transaction bytes",{bytesLength:r.length,bytesPreview:r.slice(0,100)});const o=await va.parseTransactionBytes(r,{includeRaw:!1});t.debug("Parsed transaction for quote",{type:o.type,hasTransfers:!!o.transfers,transferCount:o.transfers?.length||0,transfers:o.transfers});let n=0;if(o.transfers&&o.transfers.length>0)for(const e of o.transfers){const r="string"==typeof e.amount?parseFloat(e.amount):e.amount;if(r<0){const i=Math.abs(r);n+=i,t.debug("Found HBAR transfer",{from:e.accountId,to:"service",amount:i})}}n>0&&(i=n.toString(),t.debug("Using parsed transaction transfer amount",{totalTransferAmount:n,totalCostHbar:i}))}catch(r){t.warn("Could not parse transaction bytes, using totalCost fallback",{error:r,errorMessage:r instanceof Error?r.message:String(r)})}}const o=[{to:"Inscription Service",amount:i,description:`Inscription fee (${i} HBAR)`}],n={totalCostHbar:i,validUntil:new Date(Date.now()+9e5).toISOString(),breakdown:{transfers:o}};return t.debug("Successfully parsed transaction for quote",{totalCostHbar:n.totalCostHbar,transferCount:o.length,hasTransactionBytes:!!e.transactionBytes,hasTotalCost:!!e.totalCost}),n}catch(i){throw t.error("Error parsing transaction for quote",i),i}}(l,o);return function(e,t,r,i){const o=Ca.createCacheKey(e,t,r);Ca.set(o,i,6e5)}(e,t,r,d),o.info("Successfully generated inscription quote",{totalCostHbar:d.totalCostHbar}),{confirmed:!1,quote:!0,result:d}}catch(n){throw o.error("Error generating inscription quote",n),n}}async function Ma(e,t,r=30,i=4e3,o){const n=z.getInstance({module:"Inscriber"}),s=new ps({module:"Inscriber",logger:n,callback:o});try{n.debug("Waiting for inscription confirmation",{transactionId:t,maxAttempts:r,intervalMs:i}),s.preparing("Preparing for inscription confirmation",5,{transactionId:t,maxAttempts:r,intervalMs:i});try{const o=e.waitForInscription.bind(e),n=e=>{const t=e.stage||"confirming",r=["preparing","submitting","confirming","verifying","completed","failed"].includes(t)?t:"confirming",i=e.message||"Processing inscription",o=e.progressPercent||50;s.report({stage:r,message:i,progressPercent:o,details:e.details})};return await o(t,r,i,!0,n)}catch(eg){return n.debug("Falling back to standard waitForInscription method",{error:eg}),s.verifying("Verifying inscription status",50,{error:eg}),await e.waitForInscription(t,r,i,!0)}}catch(a){throw n.error("Error waiting for inscription confirmation",{transactionId:t,maxAttempts:r,intervalMs:i,error:a}),s.failed("Inscription confirmation failed",{transactionId:t,error:a}),a}}function Ka(e){if(!e||"object"!=typeof e)return;const t=e,r=t.topicId||t.topic_id;if("string"==typeof r&&r.trim())return r;const i=t,o=i.topicId;if("string"==typeof o&&o.trim())return o;const n=i.topic_id;return"string"==typeof n&&n.trim()?n:void 0}var Ua=(e=>(e.REGISTER_CONFIG="register-config",e.REGISTER="register",e))(Ua||{}),La=(e=>(e.EVM="evm",e.WASM="wasm",e))(La||{});const $a=r.z.object({name:r.z.string().optional(),type:r.z.string()}),Ha=r.z.object({name:r.z.string(),inputs:r.z.array($a),outputs:r.z.array($a),stateMutability:r.z.enum(["view","pure"]),type:r.z.literal("function")}),qa=r.z.enum(["number","string","bool"]),ja=r.z.object({p:r.z.literal("hcs-7"),m:r.z.string().optional()}),Wa=ja.extend({op:r.z.literal("register-config"),t:r.z.literal("evm"),c:r.z.object({contractAddress:r.z.string().regex(/^0x[a-fA-F0-9]{40}$/,"Invalid contract address"),abi:Ha})}),Va=ja.extend({op:r.z.literal("register-config"),t:r.z.literal("wasm"),c:r.z.object({wasmTopicId:r.z.string(),inputType:r.z.object({stateData:r.z.record(qa)}),outputType:r.z.object({type:r.z.literal("string"),format:r.z.literal("topic-id")})})}),Ga=ja.extend({op:r.z.literal("register"),t_id:r.z.string(),d:r.z.object({weight:r.z.number(),tags:r.z.array(r.z.string()).nonempty()}).catchall(r.z.unknown())}),Ja=r.z.union([Wa,Va,Ga]);class Ya{constructor(e){this.network=e.network,this.logger=e.logger||z.getInstance({level:e.logLevel||"info",module:"HCS7Client",silent:e.silent}),this.mirrorNode=new G(this.network,this.logger,e.mirrorNodeUrl?{customUrl:e.mirrorNodeUrl}:void 0)}generateRegistryMemo(e){return`hcs-7:indexed:${e}`}createConfigMessage(e){return e.config.type===La.EVM?{p:"hcs-7",op:Ua.REGISTER_CONFIG,t:La.EVM,c:{contractAddress:e.config.contractAddress,abi:e.config.abi},m:e.memo}:{p:"hcs-7",op:Ua.REGISTER_CONFIG,t:La.WASM,c:{wasmTopicId:e.config.wasmTopicId,inputType:e.config.inputType,outputType:e.config.outputType},m:e.memo}}createMetadataMessage(e){return{p:"hcs-7",op:Ua.REGISTER,t_id:e.metadataTopicId,m:e.memo,d:{weight:e.weight,tags:e.tags,...e.data||{}}}}validateMessage(e){const t=Ja.safeParse(e);if(t.success)return{valid:!0,errors:[]};const r=t.error.errors.map(e=>{const t=e.path.join(".");return t?`${t}: ${e.message}`:e.message});return this.logger.debug(`HCS-7 message validation failed: ${r.join(", ")}`),{valid:!1,errors:r}}async getRegistry(e,t){const r=[];try{const i=await this.mirrorNode.getTopicMessages(e,{limit:t?.limit,order:t?.order,sequenceNumber:t?.next});for(const e of i){if("hcs-7"!==e.p)continue;const t=Ja.safeParse(e);if(!t.success)continue;const i=t.data;r.push({sequenceNumber:Number(e.sequence_number),timestamp:e.consensus_timestamp||"",payer:e.payer||"",message:i})}}catch(i){this.logger.error("Failed to query HCS-7 registry",i)}return{topicId:e,entries:r}}}function Xa(e){const t=e.topicSequenceNumber;return"number"==typeof t?t:"function"==typeof t?.toNumber?t.toNumber():"number"==typeof t?.low?t.low:void 0}function Za(e){return Y({memo:`hcs-7:indexed:${e.ttl}`,submitKey:e.submitKey,adminKey:e.adminKey,operatorPublicKey:e.operatorPublicKey})}function Qa(e){const t={p:"hcs-7",...e.message};return X({topicId:e.topicId,message:JSON.stringify(t),transactionMemo:e.transactionMemo})}class ec{constructor(){this.cache=new Map}get(e){return this.cache.get(e)}set(e,t){this.cache.set(e,t)}delete(e){this.cache.delete(e)}clear(){this.cache.clear()}}function tc(e,t){return null==e?"0":e._isBigNumber?e.toString():t.startsWith("uint")||t.startsWith("int")?String(e):"bool"===t?e?"true":"false":"string"===t?e:"address"===t?String(e).toLowerCase():t.endsWith("[]")?Array.isArray(e)?e.map(e=>String(e)).join(","):"":String(e)}function rc(e){const t=Object.create(z.prototype);return t.debug=(...t)=>e.debug(...t),t.info=(...t)=>e.info(...t),t.warn=(...t)=>e.warn(...t),t.error=(...t)=>e.error(...t),t.trace=(...t)=>e.trace(...t),t.setLogLevel=t=>e.setLogLevel(t),t.getLevel=()=>e.getLevel(),t.setSilent=t=>e.setSilent(t),t.setModule=t=>e.setModule(t),t.logger={level:e.getLevel()},t.moduleContext="",t.formatArgs=()=>({msg:""}),t}function ic(e){return e instanceof z}async function oc(e,t,r){const i=new G(t,r),o=[];for(const s of e)try{const e=await i.getPublicKey(s);o.push(e)}catch(n){r&&r.warn(`Could not get public key for account ${s}: ${n}`)}return o}const nc=e=>e.trim().toLowerCase(),sc=new Map([["hedera:mainnet",{canonical:"hedera:mainnet",hederaNetwork:"mainnet"}],["mainnet",{canonical:"hedera:mainnet",hederaNetwork:"mainnet"}],["hedera-mainnet",{canonical:"hedera:mainnet",hederaNetwork:"mainnet"}],["hedera_mainnet",{canonical:"hedera:mainnet",hederaNetwork:"mainnet"}],["hedera:testnet",{canonical:"hedera:testnet",hederaNetwork:"testnet"}],["testnet",{canonical:"hedera:testnet",hederaNetwork:"testnet"}],["hedera-testnet",{canonical:"hedera:testnet",hederaNetwork:"testnet"}],["hedera_testnet",{canonical:"hedera:testnet",hederaNetwork:"testnet"}]]),ac={abstract:2741,"abstract-testnet":11124,base:8453,"base-sepolia":84532,avalanche:43114,"avalanche-fuji":43113,iotex:4689,sei:1329,"sei-testnet":1328,polygon:137,"polygon-amoy":80002,peaq:3338},cc=new Map(Object.entries(ac).map(([e,t])=>[t,e])),lc=e=>{const t=nc(e);let r,i=(e=>/^eip155:\d+$/i.test(e)?Number.parseInt(e.split(":")[1],10):/^\d+$/.test(e)?Number.parseInt(e,10):void 0)(t);if(void 0===i){const e=ac[t];void 0!==e&&(i=e,r=t)}else cc.has(i)&&(r=cc.get(i));if(void 0===i)throw new Error('Unsupported EVM ledger network. Provide an alias like "base-sepolia" or a canonical eip155:<chainId> string.');return{canonical:`eip155:${i}`,kind:"evm",chainId:i,legacyName:r}},dc=e=>{if("string"!=typeof e||0===e.trim().length)throw new Error("Ledger network is required.");const t=nc(e);return t.startsWith("hedera:")||t.includes("hedera-")||t.includes("hedera_")||"mainnet"===t||"testnet"===t?(e=>{const t=nc(e),r=sc.get(t);if(!r)throw new Error('Unsupported Hedera network. Use hedera:mainnet or hedera:testnet (legacy "mainnet"/"testnet" also accepted).');return{canonical:r.canonical,kind:"hedera",hederaNetwork:r.hederaNetwork}})(t):lc(t)};var uc=(e=>(e[e.PERSONAL=0]="PERSONAL",e[e.AI_AGENT=1]="AI_AGENT",e[e.MCP_SERVER=2]="MCP_SERVER",e[e.FLORA=3]="FLORA",e))(uc||{}),pc=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTONOMOUS=1]="AUTONOMOUS",e))(pc||{}),hc=(e=>(e[e.REST=0]="REST",e[e.WEBSOCKET=1]="WEBSOCKET",e[e.GRPC=2]="GRPC",e))(hc||{}),gc=(e=>(e[e.TEXT_GENERATION=0]="TEXT_GENERATION",e[e.IMAGE_GENERATION=1]="IMAGE_GENERATION",e[e.AUDIO_GENERATION=2]="AUDIO_GENERATION",e[e.VIDEO_GENERATION=3]="VIDEO_GENERATION",e[e.CODE_GENERATION=4]="CODE_GENERATION",e[e.LANGUAGE_TRANSLATION=5]="LANGUAGE_TRANSLATION",e[e.SUMMARIZATION_EXTRACTION=6]="SUMMARIZATION_EXTRACTION",e[e.KNOWLEDGE_RETRIEVAL=7]="KNOWLEDGE_RETRIEVAL",e[e.DATA_INTEGRATION=8]="DATA_INTEGRATION",e[e.MARKET_INTELLIGENCE=9]="MARKET_INTELLIGENCE",e[e.TRANSACTION_ANALYTICS=10]="TRANSACTION_ANALYTICS",e[e.SMART_CONTRACT_AUDIT=11]="SMART_CONTRACT_AUDIT",e[e.GOVERNANCE_FACILITATION=12]="GOVERNANCE_FACILITATION",e[e.SECURITY_MONITORING=13]="SECURITY_MONITORING",e[e.COMPLIANCE_ANALYSIS=14]="COMPLIANCE_ANALYSIS",e[e.FRAUD_DETECTION=15]="FRAUD_DETECTION",e[e.MULTI_AGENT_COORDINATION=16]="MULTI_AGENT_COORDINATION",e[e.API_INTEGRATION=17]="API_INTEGRATION",e[e.WORKFLOW_AUTOMATION=18]="WORKFLOW_AUTOMATION",e))(gc||{}),mc=(e=>(e[e.RESOURCE_PROVIDER=0]="RESOURCE_PROVIDER",e[e.TOOL_PROVIDER=1]="TOOL_PROVIDER",e[e.PROMPT_TEMPLATE_PROVIDER=2]="PROMPT_TEMPLATE_PROVIDER",e[e.LOCAL_FILE_ACCESS=3]="LOCAL_FILE_ACCESS",e[e.DATABASE_INTEGRATION=4]="DATABASE_INTEGRATION",e[e.API_INTEGRATION=5]="API_INTEGRATION",e[e.WEB_ACCESS=6]="WEB_ACCESS",e[e.KNOWLEDGE_BASE=7]="KNOWLEDGE_BASE",e[e.MEMORY_PERSISTENCE=8]="MEMORY_PERSISTENCE",e[e.CODE_ANALYSIS=9]="CODE_ANALYSIS",e[e.CONTENT_GENERATION=10]="CONTENT_GENERATION",e[e.COMMUNICATION=11]="COMMUNICATION",e[e.DOCUMENT_PROCESSING=12]="DOCUMENT_PROCESSING",e[e.CALENDAR_SCHEDULE=13]="CALENDAR_SCHEDULE",e[e.SEARCH=14]="SEARCH",e[e.ASSISTANT_ORCHESTRATION=15]="ASSISTANT_ORCHESTRATION",e))(mc||{}),fc=(e=>(e.DNS="dns",e.SIGNATURE="signature",e.CHALLENGE="challenge",e))(fc||{}),yc=(e=>(e.PUBLIC="PUBLIC",e.CONTROLLED="CONTROLLED",e.FEE_BASED="FEE_BASED",e))(yc||{});const bc={text_generation:0,image_generation:1,audio_generation:2,video_generation:3,code_generation:4,language_translation:5,summarization:6,extraction:6,knowledge_retrieval:7,data_integration:8,data_visualization:8,market_intelligence:9,transaction_analytics:10,smart_contract_audit:11,governance:12,security_monitoring:13,compliance_analysis:14,fraud_detection:15,multi_agent:16,api_integration:17,workflow_automation:18},wc=r.z.nativeEnum(gc),Ic=r.z.union([wc,r.z.string()]),Tc=r.z.union([r.z.string(),r.z.number(),r.z.boolean(),r.z.null()]),Sc=r.z.lazy(()=>r.z.union([Tc,r.z.array(Sc),r.z.record(Sc)])),kc=r.z.object({version:r.z.string(),type:r.z.number(),display_name:r.z.string(),alias:r.z.string().optional(),bio:r.z.string().optional(),socials:r.z.array(Sc).optional(),aiAgent:r.z.object({type:r.z.nativeEnum(pc),creator:r.z.string().optional(),model:r.z.string().optional(),capabilities:r.z.array(wc).optional()}).optional(),uaid:r.z.string().optional()}).catchall(Sc),Ec=r.z.object({uaid:r.z.string().optional(),ledgerAccountId:r.z.string().optional(),userId:r.z.string().optional(),email:r.z.string().optional(),encryptedShare:r.z.string()}),vc=r.z.object({algorithm:r.z.string(),ciphertext:r.z.string(),nonce:r.z.string(),associatedData:r.z.string().optional(),keyLocator:r.z.object({sessionId:r.z.string().optional(),revision:r.z.number().optional()}).optional(),recipients:r.z.array(Ec)}),Ac=r.z.object({keyType:r.z.string(),publicKey:r.z.string(),uaid:r.z.string().optional(),ledgerAccountId:r.z.string().optional(),userId:r.z.string().optional(),email:r.z.string().optional()}),Cc=r.z.object({role:r.z.enum(["requester","responder"]),uaid:r.z.string().optional(),userId:r.z.string().optional(),ledgerAccountId:r.z.string().optional(),keyType:r.z.string(),longTermPublicKey:r.z.string().optional(),ephemeralPublicKey:r.z.string(),signature:r.z.string().optional(),metadata:r.z.record(Sc).optional(),submittedAt:r.z.string()}),xc=r.z.object({sessionId:r.z.string(),algorithm:r.z.string(),createdAt:r.z.string(),expiresAt:r.z.number(),status:r.z.enum(["pending","complete"]),requester:Cc.optional(),responder:Cc.optional()}),Rc=r.z.object({enabled:r.z.boolean(),algorithm:r.z.string(),requireCiphertext:r.z.boolean(),requester:Ac.nullable().optional(),responder:Ac.nullable().optional(),handshake:xc.nullable().optional()}),Nc=r.z.object({messageId:r.z.string(),role:r.z.enum(["user","agent"]),content:r.z.string(),timestamp:r.z.string(),cipherEnvelope:vc.optional(),metadata:r.z.record(Sc).optional()}),_c=r.z.record(r.z.array(Sc)).optional(),Pc=r.z.object({id:r.z.string(),uaid:r.z.string(),registry:r.z.string(),name:r.z.string(),description:r.z.string().optional(),capabilities:r.z.array(Ic),endpoints:r.z.union([r.z.record(Sc),r.z.array(r.z.string())]).optional(),metadata:r.z.record(Sc).optional(),metadataFacet:_c,profile:kc.optional(),protocols:r.z.array(r.z.string()).optional(),adapter:r.z.string().optional(),originalId:r.z.string().optional(),communicationSupported:r.z.boolean().optional(),routingSupported:r.z.boolean().optional(),available:r.z.boolean().optional(),availabilityStatus:r.z.string().optional(),availabilityCheckedAt:r.z.string().optional(),availabilitySource:r.z.string().optional(),availabilityLatencyMs:r.z.number().optional(),availabilityScore:r.z.number().optional(),capabilityLabels:r.z.array(r.z.string()).optional(),capabilityTokens:r.z.array(r.z.string()).optional(),image:r.z.string().optional(),createdAt:r.z.string().optional(),updatedAt:r.z.string().optional(),lastSeen:r.z.string().optional(),lastIndexed:r.z.string().optional()}).passthrough(),Fc=r.z.object({hits:r.z.array(Pc),total:r.z.number(),page:r.z.number(),limit:r.z.number()}),Oc=r.z.object({totalAgents:r.z.number(),registries:r.z.record(r.z.number()),capabilities:r.z.record(r.z.number()),lastUpdate:r.z.string(),status:r.z.string()}),Dc=r.z.object({registries:r.z.array(r.z.string())}),zc=r.z.object({searches:r.z.array(r.z.string())}),Bc=r.z.object({agent:Pc}),Mc=r.z.object({sessionId:r.z.string(),uaid:r.z.string().nullable().optional(),agent:r.z.object({name:r.z.string(),description:r.z.string().optional(),capabilities:r.z.record(Sc).nullable().optional(),skills:r.z.array(r.z.string()).optional()}),history:r.z.array(Nc),historyTtlSeconds:r.z.number().nullable().optional(),encryption:Rc.nullable().optional()}),Kc=r.z.object({sessionId:r.z.string(),uaid:r.z.string().nullable().optional(),message:r.z.string(),timestamp:r.z.string(),rawResponse:Sc.optional(),content:r.z.string().optional(),history:r.z.array(Nc).optional(),historyTtlSeconds:r.z.number().nullable().optional(),encrypted:r.z.boolean().optional()}),Uc=r.z.object({sessionId:r.z.string(),history:r.z.array(Nc),historyTtlSeconds:r.z.number()});r.z.object({preserveEntries:r.z.number().int().min(0).optional()}).strict();const Lc=r.z.object({sessionId:r.z.string(),history:r.z.array(Nc),summaryEntry:Nc,preservedEntries:r.z.array(Nc),historyTtlSeconds:r.z.number(),creditsDebited:r.z.number(),metadata:r.z.record(Sc).optional()}),$c=r.z.object({sessionId:r.z.string(),encryption:Rc.nullable()}),Hc=r.z.object({sessionId:r.z.string(),handshake:xc}),qc=r.z.object({id:r.z.string(),keyType:r.z.string(),publicKey:r.z.string(),uaid:r.z.string().nullable(),ledgerAccountId:r.z.string().nullable(),ledgerNetwork:r.z.string().nullable().optional(),userId:r.z.string().nullable().optional(),email:r.z.string().nullable().optional(),createdAt:r.z.string(),updatedAt:r.z.string()}),jc=r.z.object({challengeId:r.z.string(),message:r.z.string(),expiresAt:r.z.string()}),Wc=r.z.object({id:r.z.string(),label:r.z.string().optional(),prefix:r.z.string(),lastFour:r.z.string(),createdAt:r.z.string(),lastUsedAt:r.z.string().nullable().optional(),ownerType:r.z.literal("ledger"),ledgerAccountId:r.z.string().optional(),ledgerNetwork:r.z.string().optional(),ledgerNetworkCanonical:r.z.string().optional()}),Vc=r.z.object({key:r.z.string(),apiKey:Wc,accountId:r.z.string(),network:r.z.string(),networkCanonical:r.z.string().optional()}),Gc=r.z.object({protocols:r.z.array(r.z.string())}),Jc=r.z.object({protocol:r.z.string().nullable()}),Yc=r.z.object({hits:r.z.array(Pc),total:r.z.number(),page:r.z.number().optional(),limit:r.z.number().optional()}),Xc=r.z.union([r.z.string(),r.z.number()]),Zc=r.z.object({capabilities:r.z.array(Xc).optional(),type:r.z.enum(["ai-agents","mcp-servers"]).optional(),registry:r.z.string().optional(),protocols:r.z.array(r.z.string()).optional(),adapter:r.z.array(r.z.string()).optional()}).strict();r.z.object({query:r.z.string(),filter:Zc.optional(),limit:r.z.number().int().min(1).max(100).optional(),offset:r.z.number().int().min(0).optional()}).strict();const Qc=r.z.object({agent:Pc,score:r.z.number().optional(),highlights:r.z.record(r.z.array(r.z.string())).optional()}),el=r.z.object({hits:r.z.array(Qc),total:r.z.number(),took:r.z.number(),totalAvailable:r.z.number().optional(),visible:r.z.number().optional(),limited:r.z.boolean().optional(),credits_used:r.z.number().optional()}),tl=r.z.object({enabled:r.z.boolean(),healthy:r.z.boolean(),mode:r.z.enum(["disabled","initializing","healthy","degraded","error"]),lastUpdated:r.z.string(),details:r.z.record(r.z.any()).optional(),lastError:r.z.object({message:r.z.string(),stack:r.z.string().optional(),timestamp:r.z.string().optional()}).optional()}),rl=r.z.object({storageMode:r.z.string(),vectorStatus:tl}),il=r.z.object({clients:r.z.number(),stats:r.z.object({totalClients:r.z.number().optional(),clientsByRegistry:r.z.record(r.z.number()).optional(),clientsByEventType:r.z.record(r.z.number()).optional()}).passthrough()}),ol=r.z.object({p50:r.z.number(),p90:r.z.number(),p95:r.z.number(),p99:r.z.number()}),nl=r.z.object({http:r.z.object({requestsTotal:r.z.number(),activeConnections:r.z.number(),requestDuration:ol}),search:r.z.object({queriesTotal:r.z.number(),queryDuration:ol}),indexing:r.z.object({agentsTotal:r.z.number(),crawlErrors:r.z.number()}),registration:r.z.object({total:r.z.number(),failures:r.z.number(),duration:ol}),cache:r.z.object({hits:r.z.number(),misses:r.z.number(),hitRate:r.z.number()}),websocket:r.z.object({connections:r.z.number()})}),sl=r.z.object({uaid:r.z.string(),valid:r.z.boolean(),formats:r.z.array(r.z.string())}),al=r.z.object({id:r.z.string(),agentId:r.z.string(),protocol:r.z.string(),endpoint:r.z.string(),status:r.z.enum(["connected","disconnected","error"]),metadata:r.z.record(Tc).optional(),createdAt:r.z.string()}),cl=r.z.object({connected:r.z.boolean(),connection:al.optional(),adapter:r.z.string().optional(),agentId:r.z.string().optional()}),ll=r.z.object({operatorId:r.z.string().optional(),adapters:r.z.array(r.z.object({name:r.z.string(),version:r.z.string(),status:r.z.string(),agentCount:r.z.number(),lastDiscovery:r.z.string(),registryType:r.z.string(),health:r.z.string()})).optional(),totalAgents:r.z.number().optional(),elasticsearchDocumentCount:r.z.number().optional(),agentsByAdapter:r.z.record(r.z.number()).optional(),agentsByRegistry:r.z.record(r.z.number()).optional(),systemInfo:r.z.object({uptime:r.z.number().optional(),version:r.z.string().optional(),network:r.z.string().optional()}).optional()}),dl=r.z.object({id:r.z.string(),name:r.z.string(),type:r.z.string(),endpoint:r.z.string().optional(),capabilities:r.z.array(Ic),registry:r.z.string().optional(),protocol:r.z.string().optional(),profile:kc.optional(),nativeId:r.z.string().optional(),metadata:r.z.record(Sc).optional()}),ul=r.z.object({tId:r.z.string().nullable(),sizeBytes:r.z.number().optional()}),pl=r.z.object({topicId:r.z.string().optional(),sequenceNumber:r.z.number().optional(),profileReference:r.z.string().optional(),profileTopicId:r.z.string().optional()}).passthrough().nullable().optional(),hl=r.z.object({registry:r.z.string(),status:r.z.enum(["created","duplicate","skipped","error","updated","pending"]),agentId:r.z.string().nullable().optional(),agentUri:r.z.string().nullable().optional(),error:r.z.string().optional(),metadata:r.z.record(Sc).optional(),registryKey:r.z.string().optional(),networkId:r.z.string().optional(),networkName:r.z.string().optional(),chainId:r.z.number().optional(),estimatedCredits:r.z.number().nullable().optional(),gasEstimateCredits:r.z.number().nullable().optional(),gasEstimateUsd:r.z.number().nullable().optional(),gasPriceGwei:r.z.number().nullable().optional(),gasLimit:r.z.number().nullable().optional(),creditMode:r.z.enum(["fixed","gas"]).nullable().optional(),minCredits:r.z.number().nullable().optional(),consumedCredits:r.z.number().nullable().optional(),cost:r.z.object({credits:r.z.number(),usd:r.z.number(),eth:r.z.number(),gasUsedWei:r.z.string(),effectiveGasPriceWei:r.z.string().nullable().optional(),transactions:r.z.array(r.z.object({hash:r.z.string(),gasUsedWei:r.z.string(),effectiveGasPriceWei:r.z.string().nullable().optional(),costWei:r.z.string()})).optional()}).optional()}),gl=r.z.object({base:r.z.number(),additional:r.z.number(),total:r.z.number()}),ml=r.z.object({status:r.z.string(),uaid:r.z.string().optional(),transactionId:r.z.string().optional(),consensusTimestamp:r.z.string().optional(),registryTopicId:r.z.string().optional(),topicSequenceNumber:r.z.number().optional(),payloadHash:r.z.string().optional(),profileReference:r.z.string().optional(),tId:r.z.string().optional(),profileSizeBytes:r.z.number().optional(),error:r.z.string().optional()}).passthrough(),fl=r.z.object({key:r.z.string(),registryId:r.z.string().optional(),networkId:r.z.string().optional(),name:r.z.string().optional(),chainId:r.z.number().optional(),label:r.z.string().optional(),estimatedCredits:r.z.number().nullable().optional(),baseCredits:r.z.number().nullable().optional(),gasPortionCredits:r.z.number().nullable().optional(),gasPortionUsd:r.z.number().nullable().optional(),gasEstimateCredits:r.z.number().nullable().optional(),gasEstimateUsd:r.z.number().nullable().optional(),gasPriceGwei:r.z.number().nullable().optional(),gasLimit:r.z.number().nullable().optional(),minCredits:r.z.number().nullable().optional(),creditMode:r.z.string().nullable().optional()}).passthrough(),yl=r.z.object({id:r.z.string(),label:r.z.string(),networks:r.z.array(fl)}),bl=r.z.object({registries:r.z.array(yl)}),wl=r.z.object({success:r.z.literal(!0),status:r.z.enum(["created","duplicate","updated"]).optional(),uaid:r.z.string(),agentId:r.z.string(),message:r.z.string().optional(),registry:r.z.string().optional(),attemptId:r.z.string().nullable().optional(),agent:dl,openConvAI:r.z.object({compatible:r.z.boolean(),hcs11Profile:kc.optional(),bridgeEndpoint:r.z.string().optional()}).optional(),profile:ul.optional(),profileRegistry:pl.nullable().optional(),hcs10Registry:ml.nullable().optional(),credits:gl.optional(),additionalRegistries:r.z.array(hl).optional(),additionalRegistryCredits:r.z.array(hl).optional(),additionalRegistryCostPerRegistry:r.z.number().optional()}),Il=r.z.object({success:r.z.literal(!0),status:r.z.literal("pending"),message:r.z.string(),uaid:r.z.string(),agentId:r.z.string(),registry:r.z.string().optional(),attemptId:r.z.string().nullable(),agent:dl,openConvAI:r.z.object({compatible:r.z.boolean(),hcs11Profile:kc.optional(),bridgeEndpoint:r.z.string().optional()}).optional(),profile:ul.optional(),profileRegistry:pl.nullable().optional(),hcs10Registry:ml.nullable().optional(),credits:gl,additionalRegistries:r.z.array(hl),additionalRegistryCredits:r.z.array(hl).optional(),additionalRegistryCostPerRegistry:r.z.number().optional()}),Tl=r.z.object({success:r.z.literal(!1),status:r.z.literal("partial"),message:r.z.string(),uaid:r.z.string(),agentId:r.z.string(),registry:r.z.string().optional(),attemptId:r.z.string().nullable().optional(),agent:dl,openConvAI:r.z.object({compatible:r.z.boolean(),hcs11Profile:kc.optional(),bridgeEndpoint:r.z.string().optional()}).optional(),profile:ul.optional(),profileRegistry:pl.nullable().optional(),hcs10Registry:ml.nullable().optional(),credits:gl.optional(),additionalRegistries:r.z.array(hl).optional(),additionalRegistryCredits:r.z.array(hl).optional(),additionalRegistryCostPerRegistry:r.z.number().optional(),errors:r.z.array(r.z.object({registry:r.z.string(),registryKey:r.z.string().nullable().optional(),error:r.z.string()})).min(1)}),Sl=r.z.union([wl,Il,Tl]),kl=r.z.object({registryId:r.z.string(),registryKey:r.z.string(),networkId:r.z.string().optional(),networkName:r.z.string().optional(),chainId:r.z.number().optional(),label:r.z.string().optional(),status:r.z.enum(["pending","in_progress","completed","failed"]),error:r.z.string().optional(),credits:r.z.number().nullable().optional(),agentId:r.z.string().nullable().optional(),agentUri:r.z.string().nullable().optional(),metadata:r.z.record(Sc).optional(),lastUpdated:r.z.string()}),El=r.z.object({attemptId:r.z.string(),mode:r.z.enum(["register","update"]),status:r.z.enum(["pending","partial","completed","failed"]),uaid:r.z.string().optional(),agentId:r.z.string().optional(),registryNamespace:r.z.string(),accountId:r.z.string().optional(),startedAt:r.z.string(),completedAt:r.z.string().optional(),primary:r.z.object({status:r.z.enum(["pending","completed","failed"]),finishedAt:r.z.string().optional(),error:r.z.string().optional()}),additionalRegistries:r.z.record(r.z.string(),kl),errors:r.z.array(r.z.string()).optional()}),vl=r.z.object({progress:El}),Al=r.z.object({accountId:r.z.string().nullable().optional(),registry:r.z.string().optional(),protocol:r.z.string().optional(),requiredCredits:r.z.number(),availableCredits:r.z.number().nullable().optional(),shortfallCredits:r.z.number().nullable().optional(),creditsPerHbar:r.z.number().nullable().optional(),estimatedHbar:r.z.number().nullable().optional()}),Cl=r.z.object({success:r.z.boolean().optional(),purchaser:r.z.string(),credits:r.z.number(),hbarAmount:r.z.number(),transactionId:r.z.string(),consensusTimestamp:r.z.string().nullable().optional()}),xl=r.z.object({success:r.z.boolean().optional(),transaction:r.z.string().optional(),network:r.z.string().optional(),payer:r.z.string().optional(),errorReason:r.z.string().optional()}).strict(),Rl=r.z.object({success:r.z.boolean(),accountId:r.z.string(),creditedCredits:r.z.number(),usdAmount:r.z.number(),balance:r.z.number(),payment:r.z.object({payer:r.z.string().optional(),requirement:r.z.record(Sc).optional(),settlement:xl.optional()}).optional()}),Nl=r.z.object({minimums:r.z.record(r.z.object({network:r.z.string().optional(),gasLimit:r.z.number().optional(),gasPriceWei:r.z.string().optional(),gasUsd:r.z.number().optional(),minUsd:r.z.number().optional(),ethUsd:r.z.number().optional(),fetchedAt:r.z.string().optional(),source:r.z.string().optional()})).optional(),creditUnitUsd:r.z.number().optional()}),_l=r.z.object({adapters:r.z.array(r.z.string())}),Pl=r.z.object({supportsChat:r.z.boolean(),delivery:r.z.string().optional(),transport:r.z.string().optional(),streaming:r.z.boolean().optional(),requiresAuth:r.z.array(r.z.string()).optional(),notes:r.z.string().optional()}),Fl=r.z.object({discovery:r.z.boolean(),routing:r.z.boolean(),communication:r.z.boolean(),translation:r.z.boolean(),protocols:r.z.array(r.z.string())}),Ol=r.z.object({id:r.z.string(),name:r.z.string(),version:r.z.string(),author:r.z.string(),description:r.z.string(),supportedProtocols:r.z.array(r.z.string()),registryType:r.z.enum(["web2","web3","hybrid"]),chatProfile:Pl.optional(),capabilities:Fl,enabled:r.z.boolean(),priority:r.z.number(),status:r.z.enum(["running","stopped"])}),Dl=r.z.object({adapters:r.z.array(Ol)}),zl=r.z.object({value:r.z.union([r.z.string(),r.z.number(),r.z.boolean()]),label:r.z.string()}),Bl=r.z.object({key:r.z.string(),label:r.z.string(),description:r.z.string().optional(),type:r.z.enum(["string","boolean","number"]),adapters:r.z.array(r.z.string()).optional(),options:r.z.array(zl).optional()}),Ml=r.z.object({facets:r.z.array(Bl)}),Kl=e=>new Error(`${e} is not supported by the in-memory signer`),Ul=e=>{if(!e.privateKey)throw new Error("privateKey is required to create a ledger signer.");if(!e.accountId)throw new Error("accountId is required to create a ledger signer.");const t=i.AccountId.fromString(e.accountId),r=i.PrivateKey.fromString(e.privateKey),o=i.LedgerId.fromString(e.network);return{getLedgerId:()=>o,getAccountId:()=>t,getAccountKey:()=>r.publicKey,getNetwork:()=>({}),getMirrorNetwork:()=>[],sign:async e=>Promise.all(e.map(async e=>{const o=await r.sign(e);return new i.SignerSignature({publicKey:r.publicKey,signature:o,accountId:t})})),getAccountBalance:async()=>{throw Kl("getAccountBalance")},getAccountInfo:async()=>{throw Kl("getAccountInfo")},getAccountRecords:async()=>{throw Kl("getAccountRecords")},signTransaction:async e=>{throw Kl("signTransaction")},checkTransaction:async e=>{throw Kl("checkTransaction")},populateTransaction:async e=>{throw Kl("populateTransaction")},call:async e=>{throw Kl("call")}}},Ll=()=>"function"==typeof DOMException?new DOMException("Aborted","AbortError"):new Error("The operation was aborted"),$l=/application\/json/i,Hl=e=>{if(null===e)return null;if(e instanceof Date)return e.toISOString();if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(Array.isArray(e))return e.map(e=>void 0===e?null:Hl(e));if("object"==typeof e){const t={};return Object.entries(e).forEach(([e,r])=>{void 0!==r&&(t[e]=Hl(r))}),t}throw new TypeError("Only JSON-compatible values are supported")},ql=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),jl=e=>{const t=Hl(e);if(ql(t))return t;throw new TypeError("Expected JSON object value")},Wl=e=>{const t={};return e.type&&(t.type=e.type),e.token&&(t.token=e.token),e.username&&(t.username=e.username),e.password&&(t.password=e.password),e.headerName&&(t.headerName=e.headerName),e.headerValue&&(t.headerValue=e.headerValue),e.headers&&(t.headers={...e.headers}),t},Vl=e=>{const t={profile:jl(e.profile)};return void 0!==e.endpoint&&(t.endpoint=e.endpoint),void 0!==e.protocol&&(t.protocol=e.protocol),void 0!==e.communicationProtocol&&(t.communicationProtocol=e.communicationProtocol),void 0!==e.registry&&(t.registry=e.registry),void 0!==e.additionalRegistries&&(t.additionalRegistries=e.additionalRegistries),void 0!==e.metadata&&(t.metadata=jl(e.metadata)),t};class Gl extends Error{constructor(e,t){super(e),this.status=t.status,this.statusText=t.statusText,this.body=t.body}}class Jl extends Error{constructor(e,t,r){super(e),this.cause=t,this.rawValue=r}}class Yl{constructor(e={}){this.conversationContexts=new Map,this.request=async(e,t)=>{const r=new Headers;Object.entries(this.defaultHeaders).forEach(([e,t])=>{r.set(e,t)}),t.headers&&Object.entries(t.headers).forEach(([e,t])=>{r.set(e,t)}),r.has("accept")||r.set("accept","application/json"),r.has("user-agent")||"undefined"!=typeof window&&"function"==typeof window.fetch||r.set("user-agent","@hashgraphonline/standards-sdk/registry-broker-client");const i={method:t.method??"GET",headers:r};void 0!==t.body&&(i.body=JSON.stringify(t.body),r.has("content-type")||r.set("content-type","application/json"));const o=await this.fetchImpl(this.buildUrl(e),i);if(o.ok)return o;const n=await this.extractErrorBody(o);throw new Gl("Registry broker request failed",{status:o.status,statusText:o.statusText,body:n})},this.baseUrl=function(e){const t=e?.trim();let r=t&&t.length>0?t:"https://hol.org/registry/api/v1";try{const e=new URL(r.replace(/\/+$/,"")),t=e.hostname.toLowerCase(),i=()=>{e.pathname.startsWith("/registry")||(e.pathname="/"===e.pathname?"/registry":`/registry${e.pathname}`)};"hol.org"===t?(i(),r=e.toString()):"registry.hashgraphonline.com"!==t&&"hashgraphonline.com"!==t||(i(),e.hostname="hol.org",r=e.toString())}catch{}const i=r.replace(/\/+$/,"");return/\/api\/v\d+$/i.test(i)?i:/\/api$/i.test(i)?`${i}/v1`:`${i}/api/v1`}(e.baseUrl);const t=e.fetchImplementation??globalThis.fetch;if(!t)throw new Error("A fetch implementation is required for RegistryBrokerClient");this.fetchImpl=t,this.defaultHeaders={},e.defaultHeaders&&Object.entries(e.defaultHeaders).forEach(([e,t])=>{"string"==typeof t&&this.setDefaultHeader(e,t)}),e.apiKey&&e.apiKey.trim().length>0&&this.setApiKey(e.apiKey),e.ledgerApiKey&&e.ledgerApiKey.trim().length>0&&this.setLedgerApiKey(e.ledgerApiKey),this.registrationAutoTopUp=e.registrationAutoTopUp,this.historyAutoTopUp=e.historyAutoTopUp,this.encryptedChatManager=new Xl(this),this.encryptionOptions=e.encryption,this.encryptionBootstrapPromise=this.bootstrapEncryptionOptions(e.encryption),this.chat={start:e=>this.startChat(e),createSession:e=>this.createSession(e),sendMessage:e=>this.sendMessage(e),endSession:e=>this.endSession(e),getHistory:(e,t)=>this.fetchHistorySnapshot(e,t),compactHistory:e=>this.compactHistory(e),getEncryptionStatus:e=>this.fetchEncryptionStatus(e),submitEncryptionHandshake:(e,t)=>this.postEncryptionHandshake(e,t),startConversation:e=>this.startConversation(e),acceptConversation:e=>this.acceptConversation(e)},this.encryption={registerKey:e=>this.registerEncryptionKey(e),generateEphemeralKeyPair:()=>this.createEphemeralKeyPair(),deriveSharedSecret:e=>this.deriveSharedSecret(e),encryptCipherEnvelope:e=>this.buildCipherEnvelope(e),decryptCipherEnvelope:e=>this.openCipherEnvelope(e),ensureAgentKey:e=>this.ensureAgentEncryptionKey(e)},this.chat.createEncryptedSession=e=>this.encryptedChatManager.startSession(e),this.chat.acceptEncryptedSession=e=>this.encryptedChatManager.acceptSession(e)}static async initializeAgent(e){const{uaid:t,ensureEncryptionKey:r=!0,...i}=e,o=new Yl(i);let n=null;if(r){const e="object"==typeof r?r:{generateIfMissing:!0};n=await o.encryption.ensureAgentKey({uaid:t,...e})}return{client:o,encryption:n}}setApiKey(e){this.setDefaultHeader("x-api-key",e)}setLedgerApiKey(e){this.setDefaultHeader("x-ledger-api-key",e)}setDefaultHeader(e,t){if(!e||0===e.trim().length)return;const r=(e=>e.trim().toLowerCase())(e);t&&0!==t.trim().length?this.defaultHeaders[r]=t.trim():delete this.defaultHeaders[r]}getDefaultHeaders(){return{...this.defaultHeaders}}async encryptionReady(){this.encryptionBootstrapPromise&&await this.encryptionBootstrapPromise}async search(e={}){const t=function(e){const t=new URLSearchParams,r=(e,r)=>{r&&r.forEach(r=>{if("string"==typeof r){const i=r.trim();i.length>0&&t.append(e,i)}})};if(e.q){const r=e.q.trim();r.length>0&&t.set("q",r)}if("number"==typeof e.page&&t.set("page",e.page.toString()),"number"==typeof e.limit&&t.set("limit",e.limit.toString()),e.registry){const r=e.registry.trim();r.length>0&&t.set("registry",r)}if(r("registries",e.registries),"number"==typeof e.minTrust&&t.set("minTrust",e.minTrust.toString()),r("capabilities",e.capabilities),r("protocols",e.protocols),r("adapters",e.adapters),e.metadata&&Object.entries(e.metadata).forEach(([e,r])=>{if(!e||!Array.isArray(r)||0===r.length)return;const i=e.trim();0!==i.length&&r.forEach(e=>{null!=e&&t.append(`metadata.${i}`,String(e))})}),e.type){const r=e.type.trim();r.length>0&&"all"!==r.toLowerCase()&&t.set("type",r)}if(!0===e.verified&&t.set("verified","true"),!0===e.online&&t.set("online","true"),e.sortBy){const r=e.sortBy.trim();r.length>0&&t.set("sortBy",r)}if(e.sortOrder){const r=e.sortOrder.toLowerCase();"asc"!==r&&"desc"!==r||t.set("sortOrder",r)}const i=t.toString();return i.length>0?`?${i}`:""}(e),r=await this.requestJson(`/search${t}`,{method:"GET"});return this.parseWithSchema(r,Fc,"search response")}async stats(){const e=await this.requestJson("/stats",{method:"GET"});return this.parseWithSchema(e,Oc,"stats response")}async registries(){const e=await this.requestJson("/registries",{method:"GET"});return this.parseWithSchema(e,Dc,"registries response")}async getAdditionalRegistries(){const e=await this.requestJson("/register/additional-registries",{method:"GET"});return this.parseWithSchema(e,bl,"additional registry catalog response")}bootstrapEncryptionOptions(e){return e?.autoRegister&&!1!==e.autoRegister.enabled?this.autoRegisterEncryptionKey(e.autoRegister).then(()=>{}):null}async autoRegisterEncryptionKey(e){const t=this.normalizeAutoRegisterIdentity(e);if(!t)throw new Error("Auto-registration requires uaid, ledgerAccountId, or email");const r=await this.resolveAutoRegisterKeyMaterial(e);if(!r)throw new Error("Unable to resolve encryption public key for auto-registration");return await this.registerEncryptionKey({keyType:e.keyType??"secp256k1",publicKey:r.publicKey,...t}),r}normalizeAutoRegisterIdentity(e){const t={};return e.uaid&&(t.uaid=e.uaid),e.ledgerAccountId&&(t.ledgerAccountId=e.ledgerAccountId,e.ledgerNetwork&&(t.ledgerNetwork=e.ledgerNetwork)),e.email&&(t.email=e.email),t.uaid||t.ledgerAccountId||t.email?t:null}async resolveAutoRegisterKeyMaterial(e){if(e.publicKey?.trim())return{publicKey:e.publicKey.trim()};let t=e.privateKey?.trim();const r=e.envVar??"RB_ENCRYPTION_PRIVATE_KEY";if(!t&&r&&process?.env?.[r]?.trim()&&(t=process.env[r]?.trim()),!t&&e.generateIfMissing){const t=await this.generateEncryptionKeyPair({keyType:e.keyType??"secp256k1",envVar:r,envPath:e.envPath,overwrite:e.overwriteEnv});return r&&(process.env[r]=t.privateKey),{publicKey:t.publicKey,privateKey:t.privateKey}}if(t){return{publicKey:this.derivePublicKeyFromPrivateKey(t),privateKey:t}}return null}derivePublicKeyFromPrivateKey(e){const t=this.hexToBuffer(e),r=h.secp256k1.getPublicKey(t,!0);return u.Buffer.from(r).toString("hex")}ensureAgentEncryptionKey(e){return this.autoRegisterEncryptionKey({...e,uaid:e.uaid,enabled:!0})}async popularSearches(){const e=await this.requestJson("/popular",{method:"GET"});return this.parseWithSchema(e,zc,"popular searches response")}async resolveUaid(e){const t=await this.requestJson(`/resolve/${encodeURIComponent(e)}`,{method:"GET"});return this.parseWithSchema(t,Bc,"resolve UAID response")}async performRegisterAgent(e){const t=await this.requestJson("/register",{method:"POST",body:Vl(e),headers:{"content-type":"application/json"}});return this.parseWithSchema(t,Sl,"register agent response")}async registerAgent(e,t){const r=t?.autoTopUp??this.registrationAutoTopUp;if(!r)return this.performRegisterAgent(e);await this.ensureCreditsForRegistration(e,r);let i=!1;for(;;)try{return await this.performRegisterAgent(e)}catch(o){if(this.extractInsufficientCreditsDetails(o)&&!i){await this.ensureCreditsForRegistration(e,r),i=!0;continue}throw o}}async getRegistrationQuote(e){const t=await this.requestJson("/register/quote",{method:"POST",body:Vl(e),headers:{"content-type":"application/json"}});return this.parseWithSchema(t,Al,"registration quote response")}async updateAgent(e,t){const r=await this.requestJson(`/register/${encodeURIComponent(e)}`,{method:"PUT",body:Vl(t),headers:{"content-type":"application/json"}});return this.parseWithSchema(r,Sl,"update agent response")}async getRegistrationProgress(e){const t=e.trim();if(!t)throw new Error("attemptId is required");try{const e=await this.requestJson(`/register/progress/${encodeURIComponent(t)}`,{method:"GET"});return this.parseWithSchema(e,vl,"registration progress response").progress}catch(r){if(r instanceof Gl&&404===r.status)return null;throw r}}async waitForRegistrationCompletion(e,t={}){const r=e.trim();if(!r)throw new Error("attemptId is required");const i=Math.max(250,t.intervalMs??1500),o=t.timeoutMs??3e5,n=t.throwOnFailure??!0,s=t.signal,a=Date.now();for(;;){if(s?.aborted)throw Ll();const e=await this.getRegistrationProgress(r);if(e){if(t.onProgress?.(e),"completed"===e.status)return e;if("partial"===e.status||"failed"===e.status){if(n)throw new Gl("Registration did not complete successfully",{status:409,statusText:e.status,body:e});return e}}if(Date.now()-a>=o)throw new Error(`Registration progress polling timed out after ${o}ms`);await this.delay(i,s)}}async purchaseCreditsWithHbar(e){const t={accountId:e.accountId,payerKey:e.privateKey,hbarAmount:this.calculateHbarAmountParam(e.hbarAmount)};e.memo&&(t.memo=e.memo),e.metadata&&(t.metadata=e.metadata);const r=await this.requestJson("/credits/purchase",{method:"POST",headers:{"content-type":"application/json"},body:t});return this.parseWithSchema(r,Cl,"credit purchase response")}async getX402Minimums(){const e=await this.requestJson("/credits/purchase/x402/minimums",{method:"GET"});return this.parseWithSchema(e,Nl,"x402 minimums response")}async purchaseCreditsWithX402(e){if(!Number.isFinite(e.credits)||e.credits<=0)throw new Error("credits must be a positive number");if(void 0!==e.usdAmount&&(!Number.isFinite(e.usdAmount)||e.usdAmount<=0))throw new Error("usdAmount must be a positive number when provided");const t={accountId:e.accountId,credits:e.credits};void 0!==e.usdAmount&&(t.usdAmount=e.usdAmount),e.description&&(t.description=e.description),e.metadata&&(t.metadata=e.metadata);const r=o.create({baseURL:this.baseUrl,headers:{...this.getDefaultHeaders(),"content-type":"application/json"}}),i=m.withPaymentInterceptor(r,e.walletClient),n=await i.post("/credits/purchase/x402",t),s=this.parseWithSchema(n.data,Rl,"x402 credit purchase response"),a="string"==typeof n.headers["x-payment-response"]?n.headers["x-payment-response"]:void 0;return{...s,paymentResponseHeader:a,paymentResponse:void 0!==a?m.decodeXPaymentResponse(a):void 0}}async buyCreditsWithX402(e){const t=e.network??"base",r=(e=>{const t=e.trim();if(!t)throw new Error("evmPrivateKey is required");return t.startsWith("0x")?t:`0x${t}`})(e.evmPrivateKey),i=await f.createSigner(t,r);return this.purchaseCreditsWithX402({accountId:e.accountId,credits:e.credits,usdAmount:e.usdAmount,description:e.description,metadata:e.metadata,walletClient:i})}calculateHbarAmount(e,t){if(t<=0)throw new Error("creditsPerHbar must be positive");if(e<=0)throw new Error("creditsToPurchase must be positive");const r=e/t;return Math.ceil(1e8*r)/1e8}resolveCreditsToPurchase(e){return!Number.isFinite(e)||e<=0?0:Math.max(Math.ceil(e),1)}calculateHbarAmountParam(e){const t=Math.ceil(1e8*e);if(t<=0)throw new Error("Calculated purchase amount must be positive");return t/1e8}shouldAutoTopUpHistory(e,t){if(!this.historyAutoTopUp||void 0===e.historyTtlSeconds)return!1;if(!(t instanceof Gl))return!1;if(402!==t.status)return!1;const r=this.extractErrorMessage(t.body);if(!r)return!0;const i=r.toLowerCase();return i.includes("history")||i.includes("chat history")}extractErrorMessage(e){return"string"==typeof e?e:ql(e)&&"string"==typeof e.error?e.error:ql(e)&&"string"==typeof e.message?e.message:void 0}async executeHistoryAutoTopUp(e){if(!this.historyAutoTopUp)return;const t=this.historyAutoTopUp.hbarAmount&&this.historyAutoTopUp.hbarAmount>0?this.historyAutoTopUp.hbarAmount:.25;await this.purchaseCreditsWithHbar({accountId:this.historyAutoTopUp.accountId,privateKey:this.historyAutoTopUp.privateKey,hbarAmount:t,memo:this.historyAutoTopUp.memo??"registry-broker-client:chat-history-topup",metadata:{purpose:"chat-history",reason:e}})}async ensureCreditsForRegistration(e,t){const r=t??null;if(!r)return;if(!r.accountId||!r.accountId.trim())throw new Error("autoTopUp.accountId is required");if(!r.privateKey||!r.privateKey.trim())throw new Error("autoTopUp.privateKey is required");for(let i=0;i<3;i+=1){const t=await this.getRegistrationQuote(e),i=t.shortfallCredits??0;if(i<=0)return;const o=this.resolveCreditsToPurchase(i);if(o<=0)return;const n=t.creditsPerHbar??null;if(!n||n<=0)throw new Error("Unable to determine credits per HBAR for auto top-up");const s=this.calculateHbarAmount(o,n);await this.purchaseCreditsWithHbar({accountId:r.accountId.trim(),privateKey:r.privateKey.trim(),hbarAmount:s,memo:r.memo??"Registry Broker auto top-up",metadata:{shortfallCredits:i,requiredCredits:t.requiredCredits,purchasedCredits:o}})}if(((await this.getRegistrationQuote(e)).shortfallCredits??0)>0)throw new Error("Unable to purchase sufficient credits for registration")}extractInsufficientCreditsDetails(e){if(!(e instanceof Gl)||402!==e.status)return null;const t=e.body;if(!t||"object"!=typeof t||Array.isArray(t))return null;const r=t.shortfallCredits;return"number"!=typeof r||r<=0?null:{shortfallCredits:r}}async createLedgerChallenge(e){const t=dc(e.network),r="hedera"===t.kind?t.hederaNetwork??t.canonical:t.canonical,i=await this.requestJson("/auth/ledger/challenge",{method:"POST",headers:{"content-type":"application/json"},body:{accountId:e.accountId,network:r}});return this.parseWithSchema(i,jc,"ledger challenge response")}async verifyLedgerChallenge(e){const t=dc(e.network),r="hedera"===t.kind?t.hederaNetwork??t.canonical:t.canonical,i={challengeId:e.challengeId,accountId:e.accountId,network:r,signature:e.signature};e.signatureKind&&(i.signatureKind=e.signatureKind),e.publicKey&&(i.publicKey=e.publicKey),"number"==typeof e.expiresInMinutes&&(i.expiresInMinutes=e.expiresInMinutes);const o=await this.requestJson("/auth/ledger/verify",{method:"POST",headers:{"content-type":"application/json"},body:i}),n=this.parseWithSchema(o,Vc,"ledger verification response");return this.setLedgerApiKey(n.key),n}async authenticateWithLedger(e){const t=await this.createLedgerChallenge({accountId:e.accountId,network:e.network}),r=await this.resolveLedgerAuthSignature(t.message,e);return await this.verifyLedgerChallenge({challengeId:t.challengeId,accountId:e.accountId,network:e.network,signature:r.signature,signatureKind:r.signatureKind,publicKey:r.publicKey,expiresInMinutes:e.expiresInMinutes})}async resolveLedgerAuthSignature(e,t){if("function"==typeof t.sign){const r=await t.sign(e);if(!r||"string"!=typeof r.signature||0===r.signature.length)throw new Error("Custom ledger signer failed to produce a signature.");return r}if(!t.signer||"function"!=typeof t.signer.sign)throw new Error("Ledger authentication requires a Hedera Signer or custom sign function.");const r=u.Buffer.from(e,"utf8"),i=await t.signer.sign([r]),o=i?.[0];if(!o)throw new Error("Signer did not return any signatures.");let n;if(o.publicKey)n=o.publicKey.toString();else if("function"==typeof t.signer.getAccountKey){const e=await t.signer.getAccountKey();e&&"function"==typeof e.toString&&(n=e.toString())}return{signature:u.Buffer.from(o.signature).toString("base64"),signatureKind:"raw",publicKey:n}}async authenticateWithLedgerCredentials(e){const{accountId:t,network:r,signer:i,sign:o,hederaPrivateKey:n,evmPrivateKey:s,expiresInMinutes:a,setAccountHeader:c=!0,label:l,logger:d}=e,u=dc(r),p=l?` for ${l}`:"",h={accountId:t,network:u.canonical,expiresInMinutes:a};if(o)h.sign=o;else if(i)h.signer=i;else if(n){if("hedera"!==u.kind||!u.hederaNetwork)throw new Error("hederaPrivateKey can only be used with hedera:mainnet or hedera:testnet networks.");h.signer=Ul({accountId:t,privateKey:n,network:u.hederaNetwork})}else{if(!s)throw new Error("Provide a signer, sign function, hederaPrivateKey, or evmPrivateKey to authenticate with the ledger.");{if("evm"!==u.kind)throw new Error("evmPrivateKey can only be used with CAIP-2 EVM networks (eip155:<chainId>).");const e=s.startsWith("0x")?s:`0x${s}`,t=g.privateKeyToAccount(e);h.sign=async e=>({signature:await t.signMessage({message:e}),signatureKind:"evm",publicKey:t.publicKey})}}d?.info?.(`Authenticating ledger account ${t} (${u.canonical})${p}...`);const m=await this.authenticateWithLedger(h);return c&&this.setDefaultHeader("x-account-id",m.accountId),d?.info?.(`Ledger authentication complete${p}. Issued key prefix: ${m.apiKey.prefix}…${m.apiKey.lastFour}`),m}async listProtocols(){const e=await this.requestJson("/protocols",{method:"GET"});return this.parseWithSchema(e,Gc,"protocols response")}async detectProtocol(e){const t=await this.requestJson("/detect-protocol",{method:"POST",body:{message:e},headers:{"content-type":"application/json"}});return this.parseWithSchema(t,Jc,"detect protocol response")}async registrySearchByNamespace(e,t){const r=new URLSearchParams;t&&r.set("q",t);const i=r.size>0?`?${r.toString()}`:"",o=await this.requestJson(`/registries/${encodeURIComponent(e)}/search${i}`,{method:"GET"});return this.parseWithSchema(o,Yc,"registry search response")}async vectorSearch(e){try{const t=await this.requestJson("/search",{method:"POST",body:e,headers:{"content-type":"application/json"}});return this.parseWithSchema(t,el,"vector search response")}catch(t){if(t instanceof Gl&&501===t.status){const t=await this.search(this.buildVectorFallbackSearchParams(e));return this.convertSearchResultToVectorResponse(t)}throw t}}async searchStatus(){const e=await this.requestJson("/search/status",{method:"GET"});return this.parseWithSchema(e,rl,"search status response")}async adaptersDetailed(){const e=await this.requestJson("/adapters/details",{method:"GET"});return this.parseWithSchema(e,Dl,"adapter details response")}async websocketStats(){const e=await this.requestJson("/websocket/stats",{method:"GET"});return this.parseWithSchema(e,il,"websocket stats response")}async metricsSummary(){const e=await this.requestJson("/metrics",{method:"GET"});return this.parseWithSchema(e,nl,"metrics summary response")}async validateUaid(e){const t=await this.requestJson(`/uaids/validate/${encodeURIComponent(e)}`,{method:"GET"});return this.parseWithSchema(t,sl,"UAID validation response")}async getUaidConnectionStatus(e){const t=await this.requestJson(`/uaids/connections/${encodeURIComponent(e)}/status`,{method:"GET"});return this.parseWithSchema(t,cl,"UAID connection status")}async closeUaidConnection(e){await this.request(`/uaids/connections/${encodeURIComponent(e)}`,{method:"DELETE"})}async dashboardStats(){const e=await this.requestJson("/dashboard/stats",{method:"GET"});return this.parseWithSchema(e,ll,"dashboard stats response")}async adapters(){const e=await this.requestJson("/adapters",{method:"GET"});return this.parseWithSchema(e,_l,"adapters response")}async facets(e){const t=new URLSearchParams;e&&t.set("adapter",e);const r=t.size>0?`?${t.toString()}`:"",i=await this.requestJson(`/search/facets${r}`,{method:"GET"});return this.parseWithSchema(i,Ml,"search facets response")}async createSession(e,t=!0){const r={};"uaid"in e&&e.uaid&&(r.uaid=e.uaid),"agentUrl"in e&&e.agentUrl&&(r.agentUrl=e.agentUrl),e.auth&&(r.auth=Wl(e.auth)),void 0!==e.historyTtlSeconds&&(r.historyTtlSeconds=e.historyTtlSeconds),void 0!==e.encryptionRequested&&(r.encryptionRequested=e.encryptionRequested),e.senderUaid&&(r.senderUaid=e.senderUaid);try{const e=await this.requestJson("/chat/session",{method:"POST",body:r,headers:{"content-type":"application/json"}});return this.parseWithSchema(e,Mc,"chat session response")}catch(i){if(t&&this.shouldAutoTopUpHistory(e,i))return await this.executeHistoryAutoTopUp("chat.session"),this.createSession(e,!1);throw i}}async startChat(e){if("uaid"in e&&e.uaid)return this.startConversation({uaid:e.uaid,senderUaid:e.senderUaid,historyTtlSeconds:e.historyTtlSeconds,auth:e.auth,encryption:e.encryption,onSessionCreated:e.onSessionCreated});if("agentUrl"in e&&e.agentUrl){const t=await this.createSession({agentUrl:e.agentUrl,auth:e.auth,historyTtlSeconds:e.historyTtlSeconds,senderUaid:e.senderUaid});return e.onSessionCreated?.(t.sessionId),this.createPlaintextConversationHandle(t.sessionId,t.encryption??null,e.auth,{agentUrl:e.agentUrl,uaid:e.uaid})}throw new Error("startChat requires either uaid or agentUrl")}async startConversation(e){const t=e.encryption?.preference??"preferred";if(!("disabled"!==t)){const t=await this.createSession({uaid:e.uaid,auth:e.auth,historyTtlSeconds:e.historyTtlSeconds,senderUaid:e.senderUaid,encryptionRequested:!1});return e.onSessionCreated?.(t.sessionId),this.createPlaintextConversationHandle(t.sessionId,t.encryption??null,e.auth,{uaid:e.uaid})}try{return await this.encryptedChatManager.startSession({uaid:e.uaid,senderUaid:e.senderUaid,historyTtlSeconds:e.historyTtlSeconds,handshakeTimeoutMs:e.encryption?.handshakeTimeoutMs,pollIntervalMs:e.encryption?.pollIntervalMs,onSessionCreated:t=>{e.onSessionCreated?.(t)},auth:e.auth})}catch(r){if(r instanceof Zl){if("required"===t)throw r;return this.createPlaintextConversationHandle(r.sessionId,r.summary??null,e.auth,{uaid:e.uaid})}throw r}}async acceptConversation(e){const t=e.encryption?.preference??"preferred";if("disabled"===t)return this.createPlaintextConversationHandle(e.sessionId,null);try{return await this.encryptedChatManager.acceptSession({sessionId:e.sessionId,responderUaid:e.responderUaid,handshakeTimeoutMs:e.encryption?.handshakeTimeoutMs,pollIntervalMs:e.encryption?.pollIntervalMs})}catch(r){if(r instanceof Zl&&"required"!==t)return this.createPlaintextConversationHandle(e.sessionId,null,void 0,{uaid:e.responderUaid});throw r}}async fetchHistorySnapshot(e,t){if(!e||0===e.trim().length)throw new Error("sessionId is required to fetch chat history");const r=await this.requestJson(`/chat/session/${encodeURIComponent(e)}/history`,{method:"GET"}),i=this.parseWithSchema(r,Uc,"chat history snapshot response");return this.attachDecryptedHistory(e,i,t)}attachDecryptedHistory(e,t,r){if(!(void 0!==r?.decrypt?r.decrypt:!0===this.encryptionOptions?.autoDecryptHistory))return t;const i=this.resolveDecryptionContext(e,r);if(!i)throw new Error("Unable to decrypt chat history: encryption context unavailable");const o=t.history.map(t=>({entry:t,plaintext:this.decryptHistoryEntryFromContext(e,t,i)}));return{...t,decryptedHistory:o}}registerConversationContext(e){const t={sessionId:e.sessionId,sharedSecret:u.Buffer.from(e.sharedSecret),identity:e.identity?{...e.identity}:void 0},r=this.conversationContexts.get(e.sessionId)??[],i=r.findIndex(e=>this.identitiesMatch(e.identity,t.identity));i>=0?r[i]=t:r.push(t),this.conversationContexts.set(e.sessionId,r)}registerConversationContextForEncryption(e){this.registerConversationContext(e)}resolveDecryptionContext(e,t){if(t?.sharedSecret)return{sessionId:e,sharedSecret:this.normalizeSharedSecret(t.sharedSecret),identity:t.identity};const r=this.conversationContexts.get(e);if(!r||0===r.length)return null;if(t?.identity){const e=r.find(e=>this.identitiesMatch(e.identity,t.identity));if(e)return e}return r[0]}decryptHistoryEntryFromContext(e,t,r){const i=t.cipherEnvelope;if(!i)return t.content;const o=u.Buffer.from(r.sharedSecret);try{return this.encryption.decryptCipherEnvelope({envelope:i,sharedSecret:o})}catch(n){return null}}identitiesMatch(e,t){return!e&&!t||!(!e||!t)&&(!(!e.uaid||!t.uaid||e.uaid.toLowerCase()!==t.uaid.toLowerCase())||(!(!e.ledgerAccountId||!t.ledgerAccountId||e.ledgerAccountId.toLowerCase()!==t.ledgerAccountId.toLowerCase())||(!(!e.userId||!t.userId||e.userId!==t.userId)||!(!e.email||!t.email||e.email.toLowerCase()!==t.email.toLowerCase()))))}identityMatchesRecipient(e,t){return!(!t.uaid||e.uaid?.toLowerCase()!==t.uaid.toLowerCase())||(!(!t.ledgerAccountId||e.ledgerAccountId?.toLowerCase()!==t.ledgerAccountId.toLowerCase())||(!(!t.userId||e.userId!==t.userId)||!(!t.email||e.email?.toLowerCase()!==t.email.toLowerCase())))}createPlaintextConversationHandle(e,t,r,i){const o=i?.uaid?.trim(),n=i?.agentUrl?.trim();return{sessionId:e,mode:"plaintext",summary:t??null,send:async t=>{const i=t.plaintext;if(!i||0===i.trim().length)throw new Error("plaintext is required for chat messages");const s=t.message??i;return this.sendMessage({sessionId:e,message:s,streaming:t.streaming,auth:t.auth??r,uaid:o,agentUrl:n})},decryptHistoryEntry:e=>e.content}}async compactHistory(e){if(!e.sessionId||0===e.sessionId.trim().length)throw new Error("sessionId is required to compact chat history");const t={};"number"==typeof e.preserveEntries&&Number.isFinite(e.preserveEntries)&&e.preserveEntries>=0&&(t.preserveEntries=Math.floor(e.preserveEntries));const r=await this.requestJson(`/chat/session/${encodeURIComponent(e.sessionId)}/compact`,{method:"POST",headers:{"content-type":"application/json"},body:t});return this.parseWithSchema(r,Lc,"chat history compaction response")}async fetchEncryptionStatus(e){if(!e||0===e.trim().length)throw new Error("sessionId is required for encryption status");const t=await this.requestJson(`/chat/session/${encodeURIComponent(e)}/encryption`,{method:"GET"});return this.parseWithSchema(t,$c,"session encryption status response")}async postEncryptionHandshake(e,t){if(!e||0===e.trim().length)throw new Error("sessionId is required for encryption handshake");const r=await this.requestJson(`/chat/session/${encodeURIComponent(e)}/encryption-handshake`,{method:"POST",headers:{"content-type":"application/json"},body:{role:t.role,keyType:t.keyType,ephemeralPublicKey:t.ephemeralPublicKey,longTermPublicKey:t.longTermPublicKey,signature:t.signature,uaid:t.uaid,userId:t.userId,ledgerAccountId:t.ledgerAccountId,metadata:t.metadata}});return this.parseWithSchema(r,Hc,"encryption handshake response").handshake}async registerEncryptionKey(e){const t=await this.requestJson("/encryption/keys",{method:"POST",headers:{"content-type":"application/json"},body:e});return this.parseWithSchema(t,qc,"register encryption key response")}async sendMessage(e){const t={message:e.message};void 0!==e.streaming&&(t.streaming=e.streaming),e.auth&&(t.auth=Wl(e.auth)),"uaid"in e&&(t.uaid=e.uaid),"sessionId"in e&&e.sessionId&&(t.sessionId=e.sessionId),"agentUrl"in e&&e.agentUrl&&(t.agentUrl=e.agentUrl);let r=e.cipherEnvelope??null;if(e.encryption){const i=e.encryption.sessionId??("string"==typeof t.sessionId?t.sessionId:void 0);if(!i)throw new Error("sessionId is required when using encrypted chat payloads");if(!e.encryption.recipients?.length)throw new Error("recipients are required for encrypted chat payloads");r=this.encryption.encryptCipherEnvelope({...e.encryption,sessionId:i})}r&&(t.cipherEnvelope=r),delete t.encryption;const i=await this.requestJson("/chat/message",{method:"POST",body:t,headers:{"content-type":"application/json"}});return this.parseWithSchema(i,Kc,"chat message response")}async endSession(e){await this.request(`/chat/session/${encodeURIComponent(e)}`,{method:"DELETE"})}async generateEncryptionKeyPair(e={}){this.assertNodeRuntime("generateEncryptionKeyPair");if("secp256k1"!==(e.keyType??"secp256k1"))throw new Error("Only secp256k1 key generation is supported currently");const t=p.randomBytes(32),r=u.Buffer.from(t).toString("hex"),i=h.secp256k1.getPublicKey(t,!0),o=u.Buffer.from(i).toString("hex"),n=e.envVar??"RB_ENCRYPTION_PRIVATE_KEY",s=e.envPath?S.resolve(e.envPath):void 0;if(s){const t=(()=>{if("function"!=typeof require)return null;try{const e=require("node:fs");if(e&&"function"==typeof e.existsSync&&"function"==typeof e.readFileSync&&"function"==typeof e.writeFileSync&&"function"==typeof e.appendFileSync)return e}catch{}return null})();if(!t)throw new Error("File system module is not available; cannot write encryption key env file");const i=`${n}=${r}`;if(t.existsSync(s)){const r=t.readFileSync(s,"utf-8"),o=new RegExp(`^${n}=.*$`,"m");if(o.test(r)){if(!e.overwrite)throw new Error(`${n} already exists in ${s}; set overwrite=true to replace it`);const a=r.replace(o,i);t.writeFileSync(s,a)}else{const e=!r.endsWith("\n");t.appendFileSync(s,`${e?"\n":""}${i}\n`)}}else t.writeFileSync(s,`${i}\n`)}return{privateKey:r,publicKey:o,envPath:s,envVar:n}}buildUrl(e){const t=e.startsWith("/")?e:`/${e}`;return`${this.baseUrl}${t}`}buildVectorFallbackSearchParams(e){const t={q:e.query};let r;if("number"==typeof e.limit&&Number.isFinite(e.limit)&&(r=e.limit,t.limit=e.limit),"number"==typeof e.offset&&Number.isFinite(e.offset)&&e.offset>0){const i=r&&r>0?r:20;t.limit=i,t.page=Math.floor(e.offset/i)+1}return e.filter?.registry&&(t.registry=e.filter.registry),e.filter?.protocols?.length&&(t.protocols=[...e.filter.protocols]),e.filter?.adapter?.length&&(t.adapters=[...e.filter.adapter]),e.filter?.capabilities?.length&&(t.capabilities=e.filter.capabilities.map(e=>"number"==typeof e?e.toString(10):e)),e.filter?.type&&(t.type=e.filter.type),t}convertSearchResultToVectorResponse(e){const t=e.hits.map(e=>({agent:e,score:0,highlights:{}})),r=e.total,i=e.limit,o=e.page,n=r>o*i||o>1;return{hits:t,total:r,took:0,totalAvailable:r,visible:t.length,limited:n,credits_used:0}}async delay(e,t){if(e<=0){if(t?.aborted)throw Ll()}else await new Promise((r,i)=>{const o=setTimeout(()=>{t&&t.removeEventListener("abort",n),r()},e),n=()=>{clearTimeout(o),t?.removeEventListener("abort",n),i(Ll())};if(t){if(t.aborted)return clearTimeout(o),void i(Ll());t.addEventListener("abort",n,{once:!0})}})}async requestJson(e,t){const r=await this.request(e,t),i=r.headers?.get("content-type")??"";if(!$l.test(i)){const e=await r.text();throw new Jl("Expected JSON response from registry broker",e)}return await r.json()}async extractErrorBody(e){const t=e.headers?.get("content-type")??"";if($l.test(t))try{return await e.json()}catch(r){return{parseError:String(r)}}try{return await e.text()}catch(r){return{parseError:String(r)}}}parseWithSchema(e,t,i){try{return t.parse(e)}catch(o){throw new Jl(`Failed to parse ${i}`,o instanceof r.ZodError||o instanceof Error?o:String(o),e)}}assertNodeRuntime(e){if("undefined"==typeof process||!process.versions?.node)throw new Error(`${e} is only available in Node.js environments`)}createEphemeralKeyPair(){this.assertNodeRuntime("generateEphemeralKeyPair");const e=p.randomBytes(32),t=h.secp256k1.getPublicKey(e,!0);return{privateKey:u.Buffer.from(e).toString("hex"),publicKey:u.Buffer.from(t).toString("hex")}}deriveSharedSecret(e){this.assertNodeRuntime("deriveSharedSecret");const t=this.hexToBuffer(e.privateKey),r=this.hexToBuffer(e.peerPublicKey),i=h.secp256k1.getSharedSecret(t,r,!0);return p.createHash("sha256").update(u.Buffer.from(i)).digest()}buildCipherEnvelope(e){this.assertNodeRuntime("encryptCipherEnvelope");const t=this.normalizeSharedSecret(e.sharedSecret),r=p.randomBytes(12),i=p.createCipheriv("aes-256-gcm",t,r),o=e.associatedData??e.sessionId,n=o?u.Buffer.from(o,"utf8").toString("base64"):void 0;o&&i.setAAD(u.Buffer.from(o,"utf8"));const s=u.Buffer.concat([i.update(u.Buffer.from(e.plaintext,"utf8")),i.final()]),a=i.getAuthTag();return{algorithm:"aes-256-gcm",ciphertext:u.Buffer.concat([s,a]).toString("base64"),nonce:r.toString("base64"),associatedData:n,keyLocator:{sessionId:e.sessionId,revision:e.revision??1},recipients:e.recipients.map(e=>({...e,encryptedShare:""}))}}openCipherEnvelope(e){this.assertNodeRuntime("decryptCipherEnvelope");const t=this.normalizeSharedSecret(e.sharedSecret),r=u.Buffer.from(e.envelope.ciphertext,"base64"),i=u.Buffer.from(e.envelope.nonce,"base64"),o=r.slice(0,r.length-16),n=r.slice(r.length-16),s=p.createDecipheriv("aes-256-gcm",t,i);e.envelope.associatedData&&s.setAAD(u.Buffer.from(e.envelope.associatedData,"base64")),s.setAuthTag(n);return u.Buffer.concat([s.update(o),s.final()]).toString(e.encoding??"utf8")}normalizeSharedSecret(e){if(u.Buffer.isBuffer(e))return u.Buffer.from(e);if(e instanceof Uint8Array)return u.Buffer.from(e);if("string"==typeof e)return this.bufferFromString(e);throw new Error("Unsupported shared secret input")}bufferFromString(e){const t=e.trim();if(!t)throw new Error("sharedSecret string cannot be empty");const r=t.startsWith("0x")?t.slice(2):t;return/^[0-9a-fA-F]+$/.test(r)&&r.length%2==0?u.Buffer.from(r,"hex"):u.Buffer.from(t,"base64")}hexToBuffer(e){const t=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(t)||t.length%2!=0)throw new Error("Expected hex-encoded value");return u.Buffer.from(t,"hex")}}class Xl{constructor(e){this.client=e}registerConversationContext(e){this.client.registerConversationContextForEncryption(e)}async startSession(e){await this.client.encryptionReady();const t=await this.client.chat.createSession({uaid:e.uaid,senderUaid:e.senderUaid,encryptionRequested:!0,historyTtlSeconds:e.historyTtlSeconds,auth:e.auth});e.onSessionCreated?.(t.sessionId);const r=t.encryption;if(!r?.enabled)throw new Zl(t.sessionId,t.encryption??null);return await this.establishRequesterContext({sessionId:t.sessionId,summary:r,senderUaid:e.senderUaid,handshakeTimeoutMs:e.handshakeTimeoutMs,pollIntervalMs:e.pollIntervalMs})}async acceptSession(e){await this.client.encryptionReady();const t=await this.waitForEncryptionSummary(e.sessionId,e.handshakeTimeoutMs,e.pollIntervalMs);return await this.establishResponderContext({sessionId:e.sessionId,summary:t,responderUaid:e.responderUaid,handshakeTimeoutMs:e.handshakeTimeoutMs,pollIntervalMs:e.pollIntervalMs})}async establishRequesterContext(e){const t=this.client.encryption.generateEphemeralKeyPair();await this.client.chat.submitEncryptionHandshake(e.sessionId,{role:"requester",keyType:"secp256k1",ephemeralPublicKey:t.publicKey,uaid:e.senderUaid??e.summary.requester?.uaid??void 0});const{summary:r,record:i}=await this.waitForHandshakeCompletion(e.sessionId,e.handshakeTimeoutMs,e.pollIntervalMs),o=i.responder?.ephemeralPublicKey;if(!o)throw new Error("Responder handshake was not completed in time");const n=this.client.encryption.deriveSharedSecret({privateKey:t.privateKey,peerPublicKey:o}).subarray(),s=this.buildRecipients(r);return this.createHandle({sessionId:e.sessionId,sharedSecret:n,summary:r,recipients:s,identity:r.requester??void 0})}async establishResponderContext(e){const t=this.client.encryption.generateEphemeralKeyPair();await this.client.chat.submitEncryptionHandshake(e.sessionId,{role:"responder",keyType:"secp256k1",ephemeralPublicKey:t.publicKey,uaid:e.responderUaid??e.summary.responder?.uaid??void 0});const{summary:r,record:i}=await this.waitForHandshakeCompletion(e.sessionId,e.handshakeTimeoutMs,e.pollIntervalMs),o=i.requester?.ephemeralPublicKey;if(!o)throw new Error("Requester handshake was not detected in time");const n=this.client.encryption.deriveSharedSecret({privateKey:t.privateKey,peerPublicKey:o}).subarray(),s=this.buildRecipients(r);return this.createHandle({sessionId:e.sessionId,sharedSecret:n,summary:r,recipients:s,identity:r.responder??void 0})}async waitForHandshakeCompletion(e,t=3e4,r=1e3){const i=Date.now()+t;for(;;){const t=(await this.client.chat.getEncryptionStatus(e)).encryption,o=t?.handshake;if(t&&o&&"complete"===o.status)return{summary:t,record:o};if(Date.now()>=i)throw new Error("Timed out waiting for encrypted handshake completion");await this.delay(r)}}async waitForEncryptionSummary(e,t=3e4,r=1e3){const i=await this.client.chat.getEncryptionStatus(e);if(!i.encryption?.enabled)throw new Zl(e,i.encryption??null);return i.encryption}buildRecipients(e){const t=[e.requester,e.responder].filter(Boolean).map(e=>{if(!e)return null;const t={};return e.uaid&&(t.uaid=e.uaid),e.ledgerAccountId&&(t.ledgerAccountId=e.ledgerAccountId),e.userId&&(t.userId=e.userId),e.email&&(t.email=e.email),t}).filter(e=>Boolean(e?.uaid||e?.ledgerAccountId||e?.userId||e?.email));return t.length>0?t:e.responder?.uaid?[{uaid:e.responder.uaid}]:[]}createHandle(e){const t=e.sharedSecret,r=e.summary.requester?.uaid??e.summary.responder?.uaid??e.identity?.uaid,i={sessionId:e.sessionId,mode:"encrypted",summary:e.summary,send:async i=>{const o=i.recipients??e.recipients;return this.client.chat.sendMessage({sessionId:e.sessionId,message:i.message??"[ciphertext omitted]",streaming:i.streaming,auth:i.auth,uaid:r,encryption:{plaintext:i.plaintext,sharedSecret:u.Buffer.from(t),recipients:o}})},decryptHistoryEntry:r=>this.decryptEntry(r,e.identity,t)};return this.registerConversationContext({sessionId:e.sessionId,sharedSecret:t,identity:e.identity}),i}decryptEntry(e,t,r){const i=e.cipherEnvelope;if(!i)return null;const o=u.Buffer.from(r);try{return this.client.encryption.decryptCipherEnvelope({envelope:i,sharedSecret:o})}catch(n){return null}}recipientMatches(e,t){return!(!t.uaid||e.uaid?.toLowerCase()!==t.uaid.toLowerCase())||(!(!t.ledgerAccountId||e.ledgerAccountId?.toLowerCase()!==t.ledgerAccountId.toLowerCase())||(!(!t.userId||e.userId!==t.userId)||!(!t.email||e.email?.toLowerCase()!==t.email.toLowerCase())))}async delay(e){e<=0||await new Promise(t=>setTimeout(t,e))}}class Zl extends Error{constructor(e,t){super("Encryption is not enabled for this session"),this.sessionId=e,this.summary=t}}class Ql{constructor(e="info"){this.defaultEndpoint="https://kiloscribe.com/api/inscription-cdn",this.logger=z.getInstance({level:e,module:"HRLResolver"})}isBinaryContentType(e){return["image/","audio/","video/","application/octet-stream","application/pdf","application/zip","application/gzip","application/x-binary","application/vnd.ms-","application/x-msdownload","application/x-shockwave-flash","font/","application/wasm"].some(t=>e.startsWith(t))}parseHRL(e){if(!e)return null;const t=e.match(/^hcs:\/\/(\d+)\/([0-9]+\.[0-9]+\.[0-9]+)$/);return t?{standard:t[1],topicId:t[2]}:null}isValidHRL(e){if(!e||"string"!=typeof e)return!1;const t=this.parseHRL(e);if(!t)return!1;return!!/^[0-9]+\.[0-9]+\.[0-9]+$/.test(t.topicId)}isValidTopicId(e){return/^[0-9]+\.[0-9]+\.[0-9]+$/.test(e)}async resolve(e,t){if(this.isValidHRL(e))return this.resolveHRL(e,t);if(!this.isValidTopicId(e))throw new Error(`Invalid HRL or topic ID format: ${e}`);try{const r=new G(t.network,this.logger),i=await r.getTopicInfo(e),o=i?.memo||"";let n="1";if(o){const e=o.match(/^hcs-(\d+)/);e&&e[1]&&(n=e[1])}const s=`hcs://${n}/${e}`;return this.resolveHRL(s,t)}catch(r){this.logger.error(`Failed to get topic info for ${e}: ${r.message}`);const i=`hcs://1/${e}`;return this.resolveHRL(i,t)}}async getContentWithType(e,t){if(!this.isValidHRL(e))return{content:e,contentType:"text/plain",isBinary:!1};try{const r=await this.resolveHRL(e,t);return{content:r.content,contentType:r.contentType,isBinary:r.isBinary}}catch(eg){const t=`Error resolving HRL for content and type: ${eg.message}`;throw this.logger.error(t),new Error(t)}}async resolveHRL(e,t){const r=this.parseHRL(e);if(!r)throw new Error(`Invalid HRL format: ${e}`);const{standard:i,topicId:n}=r;this.logger.debug(`Resolving HRL reference: standard=${i}, topicId=${n}`);try{const e=`${t.cdnEndpoint||this.defaultEndpoint}/${n}?network=${t.network}`;this.logger.debug(`Fetching content from CDN: ${e}`);const r=(await o.head(e)).headers["content-type"]||"";if(this.isBinaryContentType(r)||t.returnRaw){return{content:(await o.get(e,{responseType:"arraybuffer"})).data,contentType:r,topicId:n,isBinary:!0}}if("application/json"===r){const t=await o.get(e,{responseType:"json"});if(!t.data)throw new Error(`Failed to fetch content from topic: ${n}`);return{content:t.data,contentType:r,topicId:n,isBinary:!1}}const i=await o.get(e);if(!i.data)throw new Error(`Failed to fetch content from topic: ${n}`);let s;return s="object"==typeof i.data?i.data.content||i.data.text||JSON.stringify(i.data):i.data,{content:s,contentType:r,topicId:n,isBinary:!1}}catch(eg){const t=`Error resolving HRL reference: ${eg.message}`;throw this.logger.error(t),new Error(t)}}}class ed{constructor(e){this.nodeHash=e}update(e){return this.nodeHash.update(e),this}digest(e){return this.nodeHash.digest(e)}}class td{constructor(e){this.algorithm=e,this.data=[]}update(e){const t="string"==typeof e?(new TextEncoder).encode(e):new Uint8Array(e);return this.data.push(t),this}async digest(e){const t=this.concatenateArrays(this.data),r=new Uint8Array(t).buffer,i=await crypto.subtle.digest(this.mapAlgorithm(this.algorithm),r);return"hex"===e?Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,"0")).join(""):globalThis.Buffer.from(i)}concatenateArrays(e){const t=e.reduce((e,t)=>e+t.length,0),r=new Uint8Array(t);let i=0;for(const o of e)r.set(o,i),i+=o.length;return r}mapAlgorithm(e){return{sha256:"SHA-256",sha384:"SHA-384",sha1:"SHA-1",sha512:"SHA-512"}[e.toLowerCase()]||"SHA-256"}}class rd{constructor(e){this.algorithm=e,this.data=[]}update(e){const t="string"==typeof e?globalThis.Buffer.from(e):e;return this.data.push(t),this}digest(e){const t=globalThis.Buffer.concat(this.data),r=this.simpleHash(t);return"hex"===e?r.toString(16).padStart(8,"0"):r.toString()}simpleHash(e){let t=0;for(let r=0;r<e.length;r++)t=(t<<5)-t+e[r]&4294967295;return Math.abs(t)}}function id(){const e="undefined"==typeof window;let t,r=!1,i=!1;try{r="undefined"!=typeof require&&"undefined"!=typeof process&&!!process.versions?.node}catch{r=!1}try{i="undefined"!=typeof crypto&&void 0!==crypto.subtle&&!e}catch{i=!1}return t=r&&e?"node":i&&!e?"web":"none",{hasNodeCrypto:r,hasWebCrypto:i,isSSR:e,preferredAPI:t}}function od(){return"undefined"==typeof window}class nd{constructor(e){this.nodeHmac=e}update(e){return this.nodeHmac.update(e),this}digest(e){return this.nodeHmac.digest(e)}}class sd{constructor(e,t="sha256"){this.key=e,this.algorithm=t,this.data=[]}update(e){return this.data.push(e),this}async digest(e){const t=globalThis.Buffer.concat(this.data),r=new Uint8Array(this.key),i=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:this.mapAlgorithm(this.algorithm)},!1,["sign"]),o=await crypto.subtle.sign("HMAC",i,new Uint8Array(t));return"hex"===e?Array.from(new Uint8Array(o)).map(e=>e.toString(16).padStart(2,"0")).join(""):globalThis.Buffer.from(o)}mapAlgorithm(e){return{sha256:"SHA-256",sha1:"SHA-1",sha512:"SHA-512"}[e.toLowerCase()]||"SHA-256"}}class ad{constructor(e,t="sha256"){this.key=e,this.algorithm=t,this.data=[]}update(e){return this.data.push(e),this}digest(e){const t=globalThis.Buffer.concat(this.data),r=this.simpleHmac(t,this.key);return"hex"===e?r.toString(16).padStart(8,"0"):r.toString()}simpleHmac(e,t){let r=0;for(let i=0;i<e.length;i++){const o=t[i%t.length];r=(r<<5)-r+e[i]+o&4294967295}return Math.abs(r)}}class cd{constructor(){try{const e="crypto";this.crypto=require(e)}catch(e){throw new Error("Node.js crypto module not available")}}createHash(e){return new ed(this.crypto.createHash(e))}createHmac(e,t){return new nd(this.crypto.createHmac(e,t))}async pbkdf2(e,t,r,i,o){return new Promise((n,s)=>{this.crypto.pbkdf2(e,t,r,i,o,(e,t)=>{e?s(e):n(t)})})}timingSafeEqual(e,t){return this.crypto.timingSafeEqual(e,t)}}class ld{createHash(e){return new td(e)}createHmac(e,t){return new sd(t,e)}async pbkdf2(e,t,r,i,o){const n=new TextEncoder,s=await crypto.subtle.importKey("raw",n.encode(e),{name:"PBKDF2"},!1,["deriveBits"]),a=await crypto.subtle.deriveBits({name:"PBKDF2",salt:new Uint8Array(t),iterations:r,hash:this.mapDigest(o)},s,8*i);return globalThis.Buffer.from(a)}timingSafeEqual(e,t){if(e.length!==t.length)return!1;let r=0;for(let i=0;i<e.length;i++)r|=e[i]^t[i];return 0===r}mapDigest(e){return{sha256:"SHA-256",sha1:"SHA-1",sha512:"SHA-512"}[e.toLowerCase()]||"SHA-256"}}class dd{createHash(e){return new rd(e)}createHmac(e,t){return new ad(t,e)}async pbkdf2(e,t,r,i,o){const n=new TextEncoder,s=globalThis.Buffer.from(n.encode(e));let a=globalThis.Buffer.alloc(i);for(let c=0;c<r;c++){const e=globalThis.Buffer.concat([s,t,globalThis.Buffer.from([c])]);let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e[t]&4294967295;a[c%i]^=255&r}return a}timingSafeEqual(e,t){if(e.length!==t.length)return!1;let r=0;for(let i=0;i<e.length;i++)r|=e[i]^t[i];return 0===r}}function ud(){switch(id().preferredAPI){case"node":try{return new cd}catch{return new dd}case"web":return new ld;default:return new dd}}const pd=["mainnet","testnet","previewnet","devnet"];function hd(e){return pd.includes(e)}const gd=/^hedera:(mainnet|testnet|previewnet|devnet):\d+\.\d+\.\d+(?:-[a-zA-Z0-9]{5})?$/;function md(e){return gd.test(e)}function fd(e,t){if(!hd(e))throw new Error("Invalid Hedera network");if(t.startsWith("hedera:")){if(md(t))return t;throw new Error("Invalid Hedera CAIP-10 account")}if(!/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9]{5})?$/.test(t))throw new Error("Invalid Hedera accountId format");return`hedera:${e}:${t}`}function yd(e){if(!md(e))throw new Error("Invalid Hedera CAIP-10");const[,t,r]=e.match(/^hedera:([^:]+):(.+)$/);return{network:t,accountId:r}}const bd=/^eip155:(\d+):(0x[0-9a-fA-F]{39,40})$/;function wd(e){return bd.test(e)}function Id(e,t){const r=`eip155:${"number"==typeof e?String(e):e}:${t.startsWith("0x")?t:`0x${t}`}`;if(!wd(r))throw new Error("Invalid EIP-155 CAIP-10");return r}const Td=r.z.object({platform:r.z.string().min(1),handle:r.z.string().min(1)}),Sd=r.z.object({type:r.z.nativeEnum(pc),capabilities:r.z.array(r.z.nativeEnum(gc)).min(1),model:r.z.string().min(1),creator:r.z.string().optional()}),kd=r.z.object({url:r.z.string().min(1),transport:r.z.enum(["stdio","sse"])}),Ed=r.z.object({type:r.z.nativeEnum(fc),value:r.z.string(),dns_field:r.z.string().optional(),challenge_path:r.z.string().optional()}),vd=r.z.object({minVersion:r.z.string().optional()}),Ad=r.z.object({name:r.z.string().min(1),description:r.z.string().min(1)}),Cd=r.z.object({name:r.z.string().min(1),description:r.z.string().min(1)}),xd=r.z.object({version:r.z.string().min(1),connectionInfo:kd,services:r.z.array(r.z.nativeEnum(mc)).min(1),description:r.z.string().min(1),verification:Ed.optional(),host:vd.optional(),capabilities:r.z.array(r.z.string()).optional(),resources:r.z.array(Ad).optional(),tools:r.z.array(Cd).optional(),maintainer:r.z.string().optional(),repository:r.z.string().optional(),docs:r.z.string().optional()}),Rd=r.z.object({version:r.z.string().min(1),type:r.z.nativeEnum(uc),display_name:r.z.string().min(1),alias:r.z.string().optional(),bio:r.z.string().optional(),socials:r.z.array(Td).optional(),profileImage:r.z.string().optional(),uaid:r.z.string().optional(),properties:r.z.record(r.z.any()).optional(),inboundTopicId:r.z.string().optional(),outboundTopicId:r.z.string().optional(),base_account:r.z.string().optional()}),Nd=Rd.extend({type:r.z.literal(uc.PERSONAL),language:r.z.string().optional(),timezone:r.z.string().optional()}),_d=Rd.extend({type:r.z.literal(uc.AI_AGENT),aiAgent:Sd}),Pd=Rd.extend({type:r.z.literal(uc.MCP_SERVER),mcpServer:xd}),Fd=r.z.object({version:r.z.string(),type:r.z.literal(uc.FLORA),display_name:r.z.string().min(1),members:r.z.array(r.z.object({accountId:r.z.string(),publicKey:r.z.string().optional(),weight:r.z.number().optional()})),threshold:r.z.number().min(1),topics:r.z.object({communication:r.z.string(),transaction:r.z.string(),state:r.z.string()}),inboundTopicId:r.z.string(),outboundTopicId:r.z.string(),bio:r.z.string().optional(),metadata:r.z.record(r.z.any()).optional(),policies:r.z.record(r.z.any()).optional()}),Od=r.z.union([Nd,_d,Pd,Fd]);class Dd{constructor(e){this.client="mainnet"===e.network?i.Client.forMainnet():i.Client.forTestnet(),this.auth=e.auth,this.network=e.network,this.operatorId=e.auth.operatorId,this.logger=z.getInstance({level:e.logLevel||"info",module:"HCS-11",silent:e.silent}),this.mirrorNode=new G(this.network,this.logger),this.auth.privateKey?(this.operatorCtx=oe({network:this.network,operatorId:this.operatorId,operatorKey:this.auth.privateKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:this.client}),this.client=this.operatorCtx.client,this.keyType=this.operatorCtx.keyType,this.operatorCtx.ensureInitialized(),this.client.setOperator(this.operatorId.toString(),this.operatorCtx.operatorKey)):this.keyType=e.keyType||"ed25519"}getClient(){return this.client}getOperatorId(){return this.auth.operatorId}async initializeOperator(){if(this.operatorCtx)try{await this.operatorCtx.ensureInitialized(),this.keyType=this.operatorCtx.keyType,this.client.setOperator(this.operatorId,this.operatorCtx.operatorKey)}catch(e){this.logger.warn(`Failed to verify operator key with mirror node: ${e.message}`)}}createPersonalProfile(e,t){return{version:"1.0",type:uc.PERSONAL,display_name:e,alias:t?.alias,bio:t?.bio,socials:t?.socials,profileImage:t?.profileImage,properties:t?.properties,inboundTopicId:t?.inboundTopicId,outboundTopicId:t?.outboundTopicId,base_account:t?.baseAccount}}createAIAgentProfile(e,t,r,i,o){const n=this.validateProfile({version:"1.0",type:uc.AI_AGENT,display_name:e,alias:o?.alias,bio:o?.bio,socials:o?.socials,profileImage:o?.profileImage,properties:o?.properties,inboundTopicId:o?.inboundTopicId,outboundTopicId:o?.outboundTopicId,base_account:o?.baseAccount,aiAgent:{type:t,capabilities:r,model:i,creator:o?.creator}});if(!n.valid)throw new Error(`Invalid AI Agent Profile: ${n.errors.join(", ")}`);return{version:"1.0",type:uc.AI_AGENT,display_name:e,alias:o?.alias,bio:o?.bio,socials:o?.socials,profileImage:o?.profileImage,properties:o?.properties,inboundTopicId:o?.inboundTopicId,outboundTopicId:o?.outboundTopicId,base_account:o?.baseAccount,aiAgent:{type:t,capabilities:r,model:i,creator:o?.creator}}}createMCPServerProfile(e,t,r){const i=this.validateProfile({version:"1.0",type:uc.MCP_SERVER,display_name:e,alias:r?.alias,bio:r?.bio,socials:r?.socials,profileImage:r?.profileImage,properties:r?.properties,inboundTopicId:r?.inboundTopicId,outboundTopicId:r?.outboundTopicId,mcpServer:t});if(!i.valid)throw new Error(`Invalid MCP Server Profile: ${i.errors.join(", ")}`);return{version:"1.0",type:uc.MCP_SERVER,display_name:e,alias:r?.alias,bio:r?.bio,socials:r?.socials,profileImage:r?.profileImage,properties:r?.properties,inboundTopicId:r?.inboundTopicId,outboundTopicId:r?.outboundTopicId,mcpServer:t}}validateProfile(e){const t=Od.safeParse(e);if(t.success)return{valid:!0,errors:[]};return{valid:!1,errors:t.error.errors.map(e=>{const t=e.path.join(".");let r=e.message;if("invalid_type"===e.code)r=`Expected ${e.expected}, got ${e.received}`;else if("invalid_enum_value"===e.code){const t=e.options?.join(", ");r=`Invalid value. Valid options are: ${t}`}else"too_small"===e.code&&"string"===e.type&&(r="Cannot be empty");return`${t}: ${r}`})}}profileToJSONString(e){return JSON.stringify(e)}parseProfileFromString(e){try{const t=JSON.parse(e),r=this.validateProfile(t);return r.valid?t:(this.logger.error("Invalid profile format:",r.errors),null)}catch(t){return this.logger.error("Error parsing profile:"),null}}setProfileForAccountMemo(e,t=1){return`hcs-11:hcs://${t}/${e}`}async executeTransaction(e){try{if(this.auth.privateKey){const t=await e.signWithOperator(this.client),r=await t.execute(this.client),o=await r.getReceipt(this.client);return o.status.toString()!==i.Status.Success.toString()?{success:!1,error:`Transaction failed: ${o.status.toString()}`}:{success:!0,result:o}}if(!this.auth.signer)throw new Error("No valid authentication method provided");const t=this.auth.signer,r=await e.freezeWithSigner(t),o=await r.executeWithSigner(t),n=await o.getReceiptWithSigner(t);return n.status.toString()!==i.Status.Success.toString()?{success:!1,error:`Transaction failed: ${n.status.toString()}: ${i.Status.Success.toString()}`}:{success:!0,result:n}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Unknown error during transaction execution"}}}async inscribeImage(e,t,r){try{const o=r?.progressCallback,n=new ps({module:"HCS11-Image",logger:this.logger,callback:o});n.preparing("Preparing to inscribe image",0);const s=k.lookup(t)||"application/octet-stream",a=r?.waitForConfirmation??!0;let c;if(this.auth.signer){if(!("accountId"in this.auth.signer))throw n.failed("Signer must be a DAppSigner for inscription"),new Error("Signer must be a DAppSigner for inscription");n.preparing("Using signer for inscription",10),c=await Oa({type:"buffer",buffer:e,fileName:t,mimeType:s},this.auth.signer,{network:this.network,waitForConfirmation:a,waitMaxAttempts:150,waitIntervalMs:4e3,logging:{level:"debug"},progressCallback:e=>{const t=10+.8*(e.progressPercent||0);n.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}})}else{if(!this.auth.privateKey)throw n.failed("Private key is required for inscription"),this.logger.error("Private key is required for inscription"),new Error("Private key is required for inscription");n.preparing("Using private key for inscription",10);const r="ecdsa"===this.keyType?i.PrivateKey.fromStringECDSA(this.auth.privateKey):i.PrivateKey.fromStringED25519(this.auth.privateKey);c=await Fa({type:"buffer",buffer:e,fileName:t,mimeType:s},{accountId:this.auth.operatorId,privateKey:r,network:this.network},{waitForConfirmation:a,waitMaxAttempts:150,waitIntervalMs:2e3,logging:{level:"debug"},progressCallback:e=>{const t=10+.8*(e.progressPercent||0);n.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}})}if(c.confirmed)return n.completed("Image inscription completed",{topicId:Ka(c.inscription)}),{imageTopicId:Ka(c.inscription)||"",transactionId:c.result.jobId,success:!0};{const e=c.quote?"quote-only":c.result.jobId;return n.verifying("Waiting for inscription confirmation",50,{jobId:e}),{imageTopicId:"",transactionId:e,success:!1,error:"Inscription not confirmed"}}}catch(o){return this.logger.error("Error inscribing image:",o),{imageTopicId:"",transactionId:"",success:!1,error:o instanceof Error?o.message:"Error inscribing image"}}}async inscribeProfile(e,t){this.logger.info("Inscribing HCS-11 profile");const r=t?.progressCallback,o=new ps({module:"HCS11-Profile",logger:this.logger,callback:r});await this.attachUaidIfMissing(e),o.preparing("Validating profile data",5);const n=this.validateProfile(e);if(!n.valid)return o.failed(`Invalid profile: ${n.errors.join(", ")}`),{profileTopicId:"",transactionId:"",success:!1,error:`Invalid profile: ${n.errors.join(", ")}`};o.preparing("Formatting profile for inscription",15);const s=this.profileToJSONString(e),a=`profile-${e.display_name.toLowerCase().replace(/\s+/g,"-")}.json`;try{const e=globalThis.Buffer.from(s,"utf-8"),t="application/json";o.preparing("Preparing profile for inscription",20);const r={type:"buffer",buffer:e,fileName:a,mimeType:t},n={waitForConfirmation:!0,mode:"file",network:this.network,waitMaxAttempts:100,waitIntervalMs:2e3,progressCallback:e=>{const t=20+.75*Number(e?.progressPercent||0);o?.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}};let c;if(o.submitting("Submitting profile to Hedera network",30),this.auth.privateKey){const e="ecdsa"===this.keyType?i.PrivateKey.fromStringECDSA(this.auth.privateKey):i.PrivateKey.fromStringED25519(this.auth.privateKey);c=await Fa(r,{accountId:this.auth.operatorId,privateKey:e,network:this.network},n)}else{if(!this.auth.signer)throw new Error("No authentication method available - neither private key nor signer");c=await Oa(r,this.auth.signer,n)}if(!c.confirmed||!Ka(c.inscription))return o.failed("Failed to inscribe profile content"),{profileTopicId:"",transactionId:"",success:!1,error:"Failed to inscribe profile content"};const l=Ka(c.inscription);return o.completed("Profile inscription completed",{topicId:l,transactionId:c.result.transactionId}),{profileTopicId:l,transactionId:c.result.transactionId,success:!0}}catch(c){return o.failed(`Error inscribing profile: ${c.message||"Unknown error"}`),{profileTopicId:"",transactionId:"",success:!1,error:c.message||"Unknown error during inscription"}}}async attachUaidIfMissing(e){if(!e.uaid&&hd(this.network))try{const{HCS14Client:t}=await Promise.resolve().then(()=>dp),r=new t({client:this.client}),i=await r.createDid({method:"hedera",client:this.client}),o=fd(this.network,this.auth.operatorId);let n=this.auth.operatorId;const s=e.inboundTopicId;if(s&&s.trim().length>0)n=`${s}@${this.auth.operatorId}`;else try{const e=await this.fetchProfileByAccountId(this.auth.operatorId,this.network),t=e?.topicInfo?.inboundTopic;t&&t.trim().length>0&&(n=`${t}@${this.auth.operatorId}`)}catch{}const a=r.createUaid(i,{proto:"hcs-10",nativeId:o,uid:n});e.uaid=a}catch(eg){this.logger.warn("Hiero registrar not available; skipping UAID generation for profile",eg)}}async updateAccountMemoWithProfile(e,t){try{this.logger.info(`Updating account memo for ${e} with profile ${t}`);const r=this.setProfileForAccountMemo(t),o=(new i.AccountUpdateTransaction).setAccountMemo(r).setAccountId(e);return this.executeTransaction(o)}catch(r){return this.logger.error(`Error updating account memo: ${r instanceof Error?r.message:"Unknown error"}`),{success:!1,error:r instanceof Error?r.message:"Unknown error updating account memo"}}}async createAndInscribeProfile(e,t=!0,r){const i=r?.progressCallback,o=new ps({module:"HCS11-ProfileCreation",logger:this.logger,callback:i});o.preparing("Starting profile creation process",0);const n=o.createSubProgress({minPercent:0,maxPercent:80,logPrefix:"Inscription"}),s=await this.inscribeProfile(e,{...r,progressCallback:e=>{n.report({stage:e.stage,message:e.message,progressPercent:e.progressPercent,details:e.details})}});if(!s?.success)return o.failed("Profile inscription failed",{error:s?.error}),s;if(o.confirming("Profile inscribed, updating account memo",85),t){const e=await this.updateAccountMemoWithProfile(this.auth.operatorId,s.profileTopicId);if(!e.success)return o.failed("Failed to update account memo",{error:e?.error}),{...s,success:!1,error:e?.error}}return o.completed("Profile creation completed successfully",{profileTopicId:s.profileTopicId,transactionId:s.transactionId}),s}async getCapabilitiesFromTags(e){const t=[];if(0===e.length)return[gc.TEXT_GENERATION];for(const r of e){const e=bc[r.toLowerCase()];void 0===e||t.includes(e)||t.push(e)}return 0===t.length&&t.push(gc.TEXT_GENERATION),t}getAgentTypeFromMetadata(e){return"autonomous"===e.type?pc.AUTONOMOUS:pc.MANUAL}async fetchProfileByAccountId(e,t){try{this.logger.debug(`Fetching profile for account ${e.toString()} on ${this.network}`);const i=await this.mirrorNode.getAccountMemo(e.toString());if(this.logger.debug(`Got account memo: ${i}`),!i?.startsWith("hcs-11:"))return{success:!1,error:`Account ${e.toString()} does not have a valid HCS-11 memo. Current memo: ${i||"empty"}`};this.logger.debug(`Found HCS-11 memo: ${i}`);const o=i.substring(7);if(!o?.startsWith("hcs://")){if(o.startsWith("ipfs://")){this.logger.warn("IPFS protocol references are not fully supported");const e=await fetch(`https://ipfs.io/ipfs/${o.replace("ipfs://","")}`),t=await e.json(),r=Od.safeParse(t);return r.success?{success:!0,profile:r.data,topicInfo:{inboundTopic:r.data.inboundTopicId||"",outboundTopic:r.data.outboundTopicId||"",profileTopicId:""}}:{success:!1,error:`Invalid HCS-11 profile data from IPFS reference ${o}`}}if(o.startsWith("ar://")){const e=o.replace("ar://",""),t=await fetch(`https://arweave.net/${e}`);if(!t.ok)return{success:!1,error:`Failed to fetch profile from Arweave ${e}: ${t.statusText}`};const r=await t.json(),i=Od.safeParse(r);return i.success?{success:!0,profile:i.data,topicInfo:{inboundTopic:i.data.inboundTopicId||"",outboundTopic:i.data.outboundTopicId||"",profileTopicId:""}}:{success:!1,error:`Invalid HCS-11 profile data from Arweave reference ${e}`}}return{success:!1,error:`Invalid protocol reference format: ${o}`}}{const e=o.match(/hcs:\/\/(\d+)\/(.+)/);if(!e)return{success:!1,error:`Invalid HCS protocol reference format: ${o}`};const[i,n,s]=e,a=t||this.network||"mainnet";this.logger.debug(`Retrieving profile from Kiloscribe CDN: ${s}`);const c=`https://kiloscribe.com/api/inscription-cdn/${s}?network=${a}`;try{const e=await fetch(c);if(!e.ok)return{success:!1,error:`Failed to fetch profile from Kiloscribe CDN: ${e.statusText}`};const t=await e.json();if(!t)return{success:!1,error:`No profile data found for topic ${s}`};const r=Od.safeParse(t);return r.success?{success:!0,profile:r.data,topicInfo:{inboundTopic:r.data.inboundTopicId||"",outboundTopic:r.data.outboundTopicId||"",profileTopicId:s}}:{success:!1,error:`Invalid HCS-11 profile data for topic ${s}`}}catch(r){return this.logger.error(`Error retrieving from Kiloscribe CDN: ${r.message}`),{success:!1,error:`Error retrieving from Kiloscribe CDN: ${r.message}`}}}}catch(i){return this.logger.error(`Error fetching profile: ${i.message}`),{success:!1,error:`Error fetching profile: ${i.message}`}}}}class zd{async checkRegistrationStatus(e,t,r,i){try{const o=await fetch(`${r}/api/request-confirm`,{method:"POST",headers:{"Content-Type":"application/json","X-Network":t},body:JSON.stringify({transaction_id:e})});if(!o.ok){const e=`Failed to confirm registration: ${o.statusText}`;throw i&&i.error(e),new Error(e)}return await o.json()}catch(o){throw i&&i.error(`Error checking registration status: ${o.message}`),o}}async waitForRegistrationConfirmation(e,t,r,i=60,o=2e3,n){let s=0;for(;s<i;){n&&n.info(`Checking registration status. Attempt ${s+1}/${i}`);const a=await this.checkRegistrationStatus(e,t,r,n);if("success"===a.status)return n&&n.info("Registration confirmed successfully"),!0;if("failed"===a.status)throw n&&n.error("Registration confirmation failed"),new Error("Registration confirmation failed");n&&n.info(`Registration still pending. Waiting ${o}ms before next attempt`),await new Promise(e=>setTimeout(e,o)),s++}return n&&n.warn(`Registration not confirmed after ${i} attempts`),!1}async executeRegistration(e,t="mainnet",r="https://moonscape.tech",i){try{i&&i.info("Registering agent with guarded registry");try{const r=new Dd({network:t,auth:{operatorId:"0.0.0"}});i?.info(`Fetching profile by account ID ${e} on ${t}`),await B(5e3);const o=await r.fetchProfileByAccountId(e,t);if(i?.info("Profile fetched",o),o?.error)return i?.error("Error fetching profile",o.error),{error:o.error,success:!1};if(!o?.success||!o?.profile)return i&&i.error("Profile not found for agent registration"),{error:"Profile not found for the provided account ID",success:!1};if(!o.profile.inboundTopicId)return i&&i.error("Missing inbound topic ID in profile"),{error:"Profile is missing required inbound topic ID",success:!1};if(!o.profile.outboundTopicId)return i&&i.error("Missing outbound topic ID in profile"),{error:"Profile is missing required outbound topic ID",success:!1};i&&i.info(`Profile validation successful. Inbound topic: ${o.profile.inboundTopicId}, Outbound topic: ${o.profile.outboundTopicId}`)}catch(o){return i&&i.error(`Error validating profile: ${o.message}`),{error:`Error validating profile: ${o.message}`,success:!1}}const n=await fetch(`${r}/api/request-register`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"*/*","Accept-Language":"en;q=0.5",Origin:r,Referer:`${r}/`,"X-Network":t},body:JSON.stringify({accountId:e})}),s=await n.json();return n.ok?(i&&i.info(`Created new registration request. Transaction ID: ${s.transaction_id}`),{transactionId:s.transaction_id,transaction:s.transaction,success:!0}):s.details?.length>0?{validationErrors:s.details,error:s.error||"Validation failed",success:!1}:{error:s.error||"Failed to register agent",success:!1}}catch(n){return{error:`Error during registration request: ${n.message}`,success:!1}}}async findRegistrations(e={},t="https://moonscape.tech"){try{const r=new URLSearchParams;e.tags?.forEach(e=>r.append("tags",e.toString())),e.accountId&&r.append("accountId",e.accountId),e.network&&r.append("network",e.network);const i=await fetch(`${t}/api/registrations?${r}`,{headers:{Accept:"*/*","Accept-Language":"en;q=0.5",Origin:t,Referer:`${t}/`}});if(!i.ok){return{registrations:[],error:await i.text()||"Failed to fetch registrations",success:!1}}const o=await i.json();return o.error?{registrations:[],error:o.error,success:!1}:{registrations:o.registrations||[],success:!0}}catch(eg){return{registrations:[],error:`Error fetching registrations: ${eg.message}`,success:!1}}}}function Bd(e,t){return`hcs-10:op:${e}:${t}`}function Md(e){var t,r;return Y({memo:e.memoOverride??(t=e.ttl,r=e.accountId,`hcs-10:0:${t}:0:${r}`),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function Kd(e){return Y({memo:e.memoOverride??`hcs-10:0:${e.ttl}:1`,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function Ud(e){var t,r,i;return Y({memo:e.memoOverride??(t=e.ttl,r=e.inboundTopicId,i=e.connectionId,`hcs-10:1:${t}:2:${r}:${i}`),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function Ld(e){var t,r;return Y({memo:e.memoOverride??(t=e.ttl,(r=e.metadataTopicId)?`hcs-10:0:${t}:3:${r}`:`hcs-10:0:${t}:3`),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function $d(e){const t={p:"hcs-10",op:"connection_request",operator_id:e.operatorId,m:e.memo};return X({topicId:e.inboundTopicId,message:JSON.stringify(t),transactionMemo:Bd(3,1)})}function Hd(e){const t={p:"hcs-10",op:"connection_created",connection_topic_id:e.connectionTopicId,connected_account_id:e.connectedAccountId,operator_id:e.operatorId,connection_id:e.connectionId,m:e.memo};return X({topicId:e.inboundTopicId,message:JSON.stringify(t),transactionMemo:Bd(4,1)})}function qd(e){const t={p:"hcs-10",op:"connection_request",operator_id:e.operatorId,outbound_topic_id:e.outboundTopicId,connection_request_id:e.connectionRequestId,m:e.memo};return X({topicId:e.outboundTopicId,message:JSON.stringify(t),transactionMemo:Bd(3,2)})}function jd(e){const t={p:"hcs-10",op:"connection_created",connection_topic_id:e.connectionTopicId,outbound_topic_id:e.outboundTopicId,requestor_outbound_topic_id:e.requestorOutboundTopicId,confirmed_request_id:e.confirmedRequestId,connection_request_id:e.connectionRequestId,operator_id:e.operatorId,m:e.memo};return X({topicId:e.outboundTopicId,message:JSON.stringify(t),transactionMemo:Bd(4,2)})}function Wd(e){const t={p:"hcs-10",op:"message",operator_id:e.operatorId,data:e.data,m:e.memo};return X({topicId:e.connectionTopicId,message:JSON.stringify(t),transactionMemo:Bd(6,3)})}function Vd(e){const t={p:"hcs-10",op:"register",account_id:e.accountId,...e.inboundTopicId?{inbound_topic_id:e.inboundTopicId}:{},m:e.memo};return X({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:Bd(0,0)})}var Gd=(e=>(e.INBOUND="inbound",e.OUTBOUND="outbound",e.CONNECTION="connection",e.REGISTRY="registry",e))(Gd||{});class Jd extends zd{constructor(e){super(),this.network=e.network,this.logger=z.getInstance({level:e.logLevel||"info",module:"HCS10-BaseClient",prettyPrint:e.prettyPrint,silent:e.silent}),this.mirrorNode=new G(e.network,this.logger,e.mirrorNode),this.feeAmount=e.feeAmount||.001}configureMirrorNode(e){this.mirrorNode.configureMirrorNode(e),this.logger.info("Mirror node configuration updated")}extractTopicFromOperatorId(e){if(!e)return"";const t=e.split("@");return t.length>0?t[0]:""}extractAccountFromOperatorId(e){if(!e)return"";const t=e.split("@");return t.length>1?t[1]:""}async getMessageStream(e,t){try{const r=await this.mirrorNode.getTopicMessages(e,t),i=["message","close_connection","transaction"];return{messages:r.filter(e=>{if("hcs-10"!==e.p||!i.includes(e.op))return!1;if("message"===e.op||"close_connection"===e.op){if(!e.operator_id)return!1;if(!this.isValidOperatorId(e.operator_id))return!1;if("message"===e.op&&!e.data)return!1}if("transaction"===e.op){if(!e.operator_id||!e.schedule_id)return!1;if(!this.isValidOperatorId(e.operator_id))return!1}return!0})}}catch(r){return this.logger&&this.logger.error(`Error fetching messages: ${r.message}`),{messages:[]}}}async getPublicTopicInfo(e){try{return await this.mirrorNode.getTopicInfo(e)}catch(t){return this.logger.error(`Error getting public topic info for ${e}:`,t),null}}async canSubmitToTopic(e,t){try{const o=await this.mirrorNode.getTopicInfo(e);if(!o)return{canSubmit:!1,requiresFee:!1,reason:"Topic does not exist"};if(!o.submit_key?.key)return{canSubmit:!0,requiresFee:!1};try{const e=await this.mirrorNode.getPublicKey(t);if("ProtobufEncoded"===o.submit_key._type){const t=globalThis.Buffer.from(o.submit_key.key,"hex");if(await this.mirrorNode.checkKeyListAccess(t,e))return{canSubmit:!0,requiresFee:!1}}else{const t=i.PublicKey.fromString(o.submit_key.key);if(e.toString()===t.toString())return{canSubmit:!0,requiresFee:!1}}}catch(r){this.logger.error(`Key validation error: ${r instanceof Error?r.message:String(r)}`)}return o.fee_schedule_key?.key&&o.custom_fees?.fixed_fees?.length>0?{canSubmit:!0,requiresFee:!0,reason:"Requires fee payment via HIP-991"}:{canSubmit:!1,requiresFee:!1,reason:"User does not have submit permission for this topic"}}catch(r){const e=r instanceof Error?r.message:String(r);return this.logger.error(`Topic submission validation error: ${e}`),{canSubmit:!1,requiresFee:!1,reason:`Error: ${e}`}}}async getMessages(e,t){try{const r=await this.mirrorNode.getTopicMessages(e,t);return{messages:r.filter(e=>{if("hcs-10"!==e.p)return!1;if("message"===e.op){if(!e.data)return!1;if(e.operator_id&&!this.isValidOperatorId(e.operator_id))return!1}return!0})}}catch(r){return this.logger&&this.logger.error(`Error fetching messages: ${r.message}`),{messages:[]}}}async requestAccount(e){try{if(!e)throw new Error("Account ID is required");return await this.mirrorNode.requestAccount(e)}catch(eg){throw this.logger.error("Failed to fetch account",eg),eg}}async getAccountMemo(e){return await this.mirrorNode.getAccountMemo(e)}async retrieveProfile(e,t,r){const i=r?.maxRetries??0,o=r?.retryDelay??3e3;let n=0;for(;n<=i;){this.logger.debug(`Retrieving profile for account: ${e}${n>0?` (attempt ${n+1}/${i+1})`:""}`);const r=`${e}-${this.network}`;if(!t&&0===n){const t=Yd.getInstance().get(r);if(t)return this.logger.debug(`Cache hit for profile: ${e}`),t}try{const t=new Dd({network:this.network,auth:{operatorId:"0.0.0"},logLevel:this.logger.getLevel()}),s=await t.fetchProfileByAccountId(e,this.network);if(!s?.success){if(n<i){this.logger.info(`Profile not found for account ${e}, retrying in ${o}ms... (${s?.error})`),n++,await new Promise(e=>setTimeout(e,o));continue}return this.logger.error(`Failed to retrieve profile for account ID: ${e}`,s?.error),{profile:null,success:!1,error:s?.error||`Failed to retrieve profile for account ID: ${e}`}}const a=s?.profile;let c=null;s?.topicInfo?.inboundTopic&&s?.topicInfo?.outboundTopic&&s?.topicInfo?.profileTopicId&&(c={inboundTopic:s.topicInfo.inboundTopic,outboundTopic:s.topicInfo.outboundTopic,profileTopicId:s.topicInfo.profileTopicId});const l={profile:a,topicInfo:c,success:!0};return Yd.getInstance().set(r,l),l}catch(eg){if(n<i){this.logger.info(`Error retrieving profile for account ${e}, retrying in ${o}ms... (${eg.message})`),n++,await new Promise(e=>setTimeout(e,o));continue}const r=`Failed to retrieve profile: ${eg.message}`;return this.logger.error(r),{profile:null,success:!1,error:r}}}return{profile:null,success:!1,error:"Unexpected error in profile retrieval"}}async retrieveOutboundConnectTopic(e){return await this.retrieveCommunicationTopics(e,!0)}async retrieveCommunicationTopics(e,t,r){try{const i=await this.retrieveProfile(e,t,r);if(!i?.success)throw new Error(i.error||"Failed to retrieve profile");const o=i.profile;if(!o)throw new Error(`Profile is null or undefined for account ${e}`);if(!o.inboundTopicId||!o.outboundTopicId)throw new Error("Invalid HCS-11 profile for HCS-10 agent: missing inboundTopicId or outboundTopicId");if(!i.topicInfo)throw new Error(`TopicInfo is missing in the profile for account ${e}`);return i.topicInfo}catch(eg){const t=eg,r=`Failed to retrieve topic info: ${t.message}`;throw this.logger.error(r),t}}async retrieveOutboundMessages(e,t){try{const r=await this.retrieveCommunicationTopics(e);if(!r)return this.logger.warn(`No outbound connect topic found for agentAccountId: ${e}`),[];return(await this.getMessages(r.outboundTopic,t)).messages.filter(e=>"hcs-10"===e.p&&("connection_request"===e.op||"connection_created"===e.op||"message"===e.op))}catch(eg){const t=`Failed to retrieve outbound messages: ${eg.message}`;return this.logger.error(t),[]}}async hasConnectionCreated(e,t){try{const r=await this.retrieveCommunicationTopics(e);return(await this.retrieveOutboundMessages(r.outboundTopic)).some(e=>"connection_created"===e.op&&e.connection_id===t)}catch(eg){const t=`Failed to check connection created: ${eg.message}`;return this.logger.error(t),!1}}async getMessageContent(e,t=!1){if(!e.match(/^hcs:\/\/(\d+)\/([0-9]+\.[0-9]+\.[0-9]+)$/))return e;try{const r=new Ql(this.logger.getLevel());if(!r.isValidHRL(e))return e;return(await r.resolveHRL(e,{network:this.network,returnRaw:t})).content}catch(eg){const t=`Error resolving HRL reference: ${eg.message}`;throw this.logger.error(t),new Error(t)}}async getMessageContentWithType(e,t=!1){if(!e.match(/^hcs:\/\/(\d+)\/([0-9]+\.[0-9]+\.[0-9]+)$/))return{content:e,contentType:"text/plain",isBinary:!1};try{const r=new Ql(this.logger.getLevel());return await r.getContentWithType(e,{network:this.network,returnRaw:t})}catch(eg){const t=`Error resolving HRL reference with type: ${eg.message}`;throw this.logger.error(t),new Error(t)}}async submitConnectionRequest(e,t){const r=this.getAccountAndSigner();if(!r?.accountId)throw new Error("Operator account ID is not set");const i=await this.getOperatorId(),o=r.accountId,n=await this.canSubmitToTopic(e,o);if(!n?.canSubmit)throw new Error(`Cannot submit to topic: ${n.reason}`);const s=await this.retrieveInboundAccountId(e);if(!s)throw new Error("Failed to retrieve topic info account ID");const a=n.requiresFee,c=$d({inboundTopicId:e,operatorId:i,memo:t}),l=await this.submitPayload(c,void 0,void 0,a);this.logger.info(`Submitted connection request to topic ID: ${e}`);const d=await this.retrieveCommunicationTopics(o);if(!d)throw new Error("Failed to retrieve outbound topic");const u=l.topicSequenceNumber?.toNumber();if(!u)throw new Error("Failed to get response sequence number");const p=`${e}@${s}`,h=qd({outboundTopicId:d.outboundTopic,operatorId:p,connectionRequestId:u,memo:t});return await this.submitPayload(h),l}async recordOutboundConnectionConfirmation({outboundTopicId:e,requestorOutboundTopicId:t,connectionRequestId:r,confirmedRequestId:i,connectionTopicId:o,operatorId:n,memo:s}){const a=jd({outboundTopicId:e,requestorOutboundTopicId:t,connectionTopicId:o,confirmedRequestId:i,connectionRequestId:r,operatorId:n,memo:s});return await this.submitPayload(a)}async waitForConnectionConfirmation(e,t,r=60,i=2e3,o=!0){this.logger.info(`Waiting for connection confirmation on inbound topic ${e} for request ID ${t}`);for(let n=0;n<r;n++){this.logger.info(`Attempt ${n+1}/${r} to find connection confirmation`);const s=(await this.mirrorNode.getTopicMessages(e,{order:"desc",limit:100})).filter(e=>"connection_created"===e.op);if(this.logger.info(`Found ${s.length} connection_created messages`),s.length>0)for(const e of s)if(Number(e.connection_id)===Number(t)){const r={connectionTopicId:e.connection_topic_id,sequence_number:Number(e.sequence_number),confirmedBy:e.operator_id,memo:e.m},i=this.extractAccountFromOperatorId(r.confirmedBy),n=this.getAccountAndSigner(),s=await this.retrieveCommunicationTopics(i),a=await this.retrieveCommunicationTopics(n.accountId);return this.logger.info("Connection confirmation found",r),o&&await this.recordOutboundConnectionConfirmation({requestorOutboundTopicId:s.outboundTopic,outboundTopicId:a.outboundTopic,connectionRequestId:t,confirmedRequestId:r.sequence_number,connectionTopicId:r.connectionTopicId,operatorId:r.confirmedBy,memo:r.memo||"Connection confirmed"}),r}n<r-1&&(this.logger.info(`No matching confirmation found, waiting ${i}ms before retrying...`),await new Promise(e=>setTimeout(e,i)))}throw new Error(`Connection confirmation not found after ${r} attempts for request ID ${t}`)}async getOperatorId(e){if(this.operatorId&&!e)return this.operatorId;const t=this.getAccountAndSigner();if(!t?.accountId)throw new Error("Operator ID not found");const r=await this.retrieveProfile(t.accountId);if(!r?.success)throw new Error("Failed to retrieve profile");if(!r?.topicInfo?.inboundTopic)throw new Error("Failed to retrieve inbound topic");const i=`${r.topicInfo?.inboundTopic}@${t.accountId}`;return this.operatorId=i,i}async retrieveInboundAccountId(e){const t=await this.mirrorNode.getTopicInfo(e);if(!t?.memo)throw new Error("Failed to retrieve topic info");const r=t.memo.toString().split(":"),i=r?.[4];if(!i)throw new Error("Failed to retrieve topic info account ID");return i}clearCache(){Yd.getInstance().clear()}_generateHcs10Memo(e,t){const r=t.ttl??60;switch(e){case"inbound":if(!t.accountId)throw new Error("accountId is required for inbound memo");return`hcs-10:0:${r}:0:${t.accountId}`;case"outbound":return`hcs-10:0:${r}:1`;case"connection":if(!t.inboundTopicId||void 0===t.connectionId)throw new Error("inboundTopicId and connectionId are required for connection memo");return`hcs-10:1:${r}:2:${t.inboundTopicId}:${t.connectionId}`;default:throw new Error(`Invalid HCS-10 memo type: ${e}`)}}async getTopicMemoType(e){try{const t=await this.mirrorNode.getTopicInfo(e);if(!t?.memo)return this.logger.debug(`No memo found for topic ${e}`),null;const r=t.memo.toString();if(!r.startsWith("hcs-10:"))return this.logger.debug(`Topic ${e} is not an HCS-10 topic`),null;const i=r.split(":");if(i.length<4)return this.logger.warn(`Invalid HCS-10 memo format for topic ${e}: ${r}`),null;const o=i[3];switch(o){case"0":return"inbound";case"1":return"outbound";case"2":return"connection";case"3":return"registry";default:return this.logger.warn(`Unknown HCS-10 type enum: ${o} for topic ${e}`),null}}catch(t){return this.logger.error(`Error getting topic memo type for ${e}:`,t),null}}async checkRegistrationStatus(e,t,r){try{const i=await fetch(`${r}/api/request-confirm`,{method:"POST",headers:{"Content-Type":"application/json","X-Network":t},body:JSON.stringify({transaction_id:e})});if(!i.ok)throw new Error(`Failed to confirm registration: ${i.statusText}`);return await i.json()}catch(eg){const t=eg,r=`Error checking registration status: ${t.message}`;throw this.logger.error(r),t}}isValidOperatorId(e){if(!e)return!1;const t=e.split("@");if(2!==t.length)return!1;const r=t[0],i=t[1];if(!r)return!1;if(!i)return!1;const o=/^[0-9]+\.[0-9]+\.[0-9]+$/;return!!o.test(i)&&!!o.test(r)}async getTransactionRequests(e,t){this.logger.debug(`Retrieving transaction requests from topic ${e}`);const{messages:r}=await this.getMessageStream(e,{limit:t?.limit,sequenceNumber:t?.sequenceNumber,order:t?.order||"desc"}),i=r.filter(e=>"transaction"===e.op&&e.schedule_id).map(e=>({operator_id:e.operator_id||"",schedule_id:e.schedule_id||"",data:e.data||"",memo:e.m,sequence_number:Number(e.sequence_number)})).sort((e,t)=>e.sequence_number&&t.sequence_number?t.sequence_number-e.sequence_number:0);return t?.limit?i.slice(0,t.limit):i}getHcs10TransactionMemo(e){if("object"!=typeof e||!("op"in e))return null;const t=e;let r,i;switch(t.op){case"register":r="0",i="0";break;case"delete":r="1",i="0";break;case"migrate":r="2",i="0";break;case"connection_request":r="3",i=t.outbound_topic_id?"2":"1";break;case"connection_created":r="4",i=t.outbound_topic_id?"2":"1";break;case"connection_closed":r="5",i=t.outbound_topic_id?"2":"3";break;case"message":case"transaction":default:r="6",i="3";break;case"close_connection":r="5",i="3"}return`hcs-10:op:${r}:${i}`}}class Yd{constructor(){this.CACHE_TTL=36e5,this.cache=new Map,this.cacheExpiry=new Map}static getInstance(){return Yd.instance||(Yd.instance=new Yd),Yd.instance}set(e,t){this.cache.set(e,t),this.cacheExpiry.set(e,Date.now()+this.CACHE_TTL)}get(e){const t=this.cacheExpiry.get(e);if(t&&t>Date.now())return this.cache.get(e);t&&(this.cache.delete(e),this.cacheExpiry.delete(e))}clear(){this.cache.clear(),this.cacheExpiry.clear()}}class Xd extends Error{constructor(e,t){super(e),this.payloadSize=t,this.name="PayloadSizeError"}}class Zd extends Error{constructor(e){super(e),this.name="AccountCreationError"}}class Qd extends Error{constructor(e){super(e),this.name="TopicCreationError"}}class eu extends Error{constructor(e){super(e),this.name="ConnectionConfirmationError"}}class tu{constructor(){this.config={},this.logger=z.getInstance({module:"AgentBuilder"})}setName(e){return this.config.name=e,this}setAlias(e){return this.config.alias=e,this}setBio(e){return this.config.bio=e,this}setDescription(e){return this.config.bio=e,this}setCapabilities(e){return this.config.capabilities=e,this}setAgentType(e){return this.config.metadata?this.config.metadata.type=e:this.config.metadata={type:e},this}setType(e){return this.config.metadata?this.config.metadata.type=e:this.config.metadata={type:e},this}setModel(e){return this.config.metadata||(this.config.metadata={type:"manual"}),this.config.metadata.model=e,this}setCreator(e){return this.config.metadata||(this.config.metadata={type:"manual"}),this.config.metadata.creator=e,this}addSocial(e,t){return this.config.metadata||(this.config.metadata={type:"manual"}),this.config.metadata.socials||(this.config.metadata.socials={}),this.config.metadata.socials[e]=t,this}addProperty(e,t){return this.config.metadata||(this.config.metadata={type:"manual"}),this.config.metadata.properties||(this.config.metadata.properties={}),this.config.metadata.properties[e]=t,this}setMetadata(e){return this.config.metadata=e,this}setProfilePicture(e,t){return this.config.pfpBuffer=e,this.config.pfpFileName=t,this}setExistingProfilePicture(e){return this.config.existingPfpTopicId=e,this}setNetwork(e){return this.config.network=e,this}setInboundTopicType(e){return this.config.inboundTopicType=e,this}setFeeConfig(e){return this.config.feeConfig=e,this}setConnectionFeeConfig(e){return this.config.connectionFeeConfig=e,this}setExistingAccount(e,t){return this.config.existingAccount={accountId:e,privateKey:t},this}setInboundTopicId(e){return this.config.inboundTopicId=e,this}setOutboundTopicId(e){return this.config.outboundTopicId=e,this}setBaseAccount(e){return this.baseAccount=e,this}build(){if(!this.config.name)throw new Error("Agent display name is required");if(this.config.bio||this.logger?.warn("Agent description is not set"),this.config.pfpBuffer||this.config.existingPfpTopicId||this.logger.warn("No profile picture provided or referenced."),!this.config.network)throw new Error("Network is required");if(this.config.inboundTopicType||(this.config.inboundTopicType=yc.PUBLIC),this.config.capabilities||(this.config.capabilities=[]),this.config.metadata?this.config.metadata.type||(this.config.metadata.type="manual"):this.config.metadata={type:"manual"},this.config.inboundTopicType===yc.FEE_BASED&&!this.config.feeConfig)throw new Error("Fee configuration is required for fee-based topics");const e=this.config;return this.baseAccount&&(e.baseAccount=this.baseAccount),e}}class ru extends Jd{constructor(e){super({network:e.network,logLevel:e.logLevel,prettyPrint:e.prettyPrint,feeAmount:e.feeAmount,mirrorNode:e.mirrorNode,silent:e.silent,keyType:e.keyType}),this.logger=z.getInstance({level:e.logLevel||"info",module:"HCS-SDK",silent:e.silent}),this.operatorAccountId=e.operatorId,this.operatorCtx=oe({network:this.network,operatorId:this.operatorAccountId,operatorKey:e.operatorPrivateKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:"mainnet"===e.network?i.Client.forMainnet():i.Client.forTestnet()}),this.client=this.operatorCtx.client,this.network=e.network,this.guardedRegistryBaseUrl=e.guardedRegistryBaseUrl||"https://moonscape.tech",this.hcs11Client=new Dd({network:e.network,auth:{operatorId:e.operatorId,privateKey:this.operatorCtx.operatorKey.toString()},logLevel:e.logLevel,silent:e.silent,keyType:e.keyType})}async ensureInitialized(){await this.operatorCtx.ensureInitialized()}getClient(){return this.client}async createAccount(e=50){await this.ensureInitialized(),this.logger.info(`Creating new account with ${e} HBAR initial balance`);const t=i.PrivateKey.generateED25519(),r=(new i.AccountCreateTransaction).setKeyWithoutAlias(t.publicKey).setInitialBalance(new i.Hbar(e)),o=await r.execute(this.client),n=(await o.getReceipt(this.client)).accountId;if(!n)throw this.logger.error("Account creation failed: accountId is null"),new Zd("Failed to create account: accountId is null");return this.logger.info(`Account created successfully: ${n.toString()}`),{accountId:n.toString(),privateKey:t.toString()}}async createInboundTopic(e,t,r=60,i){let o,n;switch(await this.ensureInitialized(),this._generateHcs10Memo(Gd.INBOUND,{accountId:e,ttl:r}),t){case yc.PUBLIC:o=!1;break;case yc.CONTROLLED:o=!0;break;case yc.FEE_BASED:if(o=!1,!i)throw new Error("Fee configuration builder is required for fee-based topics");i.customFees.forEach(t=>{t.feeCollectorAccountId||(t.feeCollectorAccountId=e)}),n=i.build(),n.customFees=n.customFees.map(t=>({...t,feeCollectorAccountId:t.feeCollectorAccountId||e}));break;default:throw new Error(`Unsupported inbound topic type: ${t}`)}const s=this.client.operatorPublicKey||this.operatorCtx.operatorKey.publicKey,a=Md({accountId:e,ttl:r,adminKey:!0,submitKey:o,operatorPublicKey:s});this.logger.info("Creating inbound topic");const{topicId:c}=await this.executeTopicCreateTransaction({transaction:a,feeConfig:n});return c}async createAgent(e,t=60,r,i){await this.ensureInitialized();const o=e.build(),n=this.client.operatorAccountId?.toString();if(!n)throw new Error("Failed to retrieve operator account ID");const s=await this._createEntityTopics(t,{outboundTopicId:r?.outboundTopicId||"",inboundTopicId:r?.inboundTopicId||"",pfpTopicId:r?.pfpTopicId||o.existingPfpTopicId||"",profileTopicId:r?.profileTopicId||""},n,o.inboundTopicType,o.feeConfig,o.pfpBuffer,o.pfpFileName,i);if(s.profileTopicId)this.logger.info(`Using existing profile topic ID: ${s.profileTopicId}`);else{i&&i({stage:"preparing",message:"Creating agent profile",progressPercent:60,details:{outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,state:{currentStage:"profile",completedPercentage:60}}});const e=await this.storeHCS11Profile(o.name,o.bio,s.inboundTopicId,s.outboundTopicId,o.capabilities,o.metadata,o.pfpBuffer&&o.pfpBuffer.length>0&&!s.pfpTopicId?o.pfpBuffer:void 0,o.pfpFileName,s.pfpTopicId);s.profileTopicId=e.profileTopicId,this.logger.info(`Profile stored with topic ID: ${s.profileTopicId}`),i&&i({stage:"preparing",message:"Agent profile created",progressPercent:70,details:{outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,profileTopicId:s.profileTopicId,state:{currentStage:"profile",completedPercentage:70}}})}return s}async create(e,t){const r=t?.progressCallback,i=new ps({module:"ProfileCreate",logger:this.logger,callback:r?e=>r({stage:e.stage,message:e.message,progressPercent:e.progressPercent,details:e.details}):void 0});try{const r=e instanceof tu;let o;if(o=t?.existingState?t.existingState:{currentStage:"init",completedPercentage:0,createdResources:[]},r){this.logger.info("Creating Agent Profile and HCS-10 Topics");const t=e.build();o.agentMetadata=t.metadata}else this.logger.info("Creating Person HCS-11 Profile");i.preparing(`Starting ${r?"agent":"person"} resource creation`,0,{state:o});const n=this.client.operatorAccountId?.toString();if(!n)throw new Error("Failed to retrieve operator account ID");const{inboundTopicId:s,outboundTopicId:a,state:c}=await this.createCommunicationTopics(n,t,i);let l,d,u;if(o=c,e.setInboundTopicId(s),e.setOutboundTopicId(a),r){const t=e.build();l=t.existingPfpTopicId||o.pfpTopicId,d=t.pfpBuffer,u=t.pfpFileName||"pfp.png"}else{const t=e.build();l=o.pfpTopicId,d=t.pfpBuffer,u=t.pfpFileName}!l&&d&&u?l=await this.handleProfilePictureCreation(d,u,o,i):l&&(i.preparing(`Using existing profile picture: ${l}`,50,{state:o}),o.pfpTopicId=l),await this.createAndInscribeProfile(r,e,l,o,s,a,t,i),o.currentStage="complete",o.completedPercentage=100,i.completed((r?"Agent":"Person")+" profile created successfully",{profileTopicId:o.profileTopicId,inboundTopicId:s,outboundTopicId:a,pfpTopicId:l,state:o});let p="";o.outboundTopicId&&(p=o.outboundTopicId);let h="";o.inboundTopicId&&(h=o.inboundTopicId);let g="";o.pfpTopicId&&(g=o.pfpTopicId);let m="";return o.profileTopicId&&(m=o.profileTopicId),{outboundTopicId:p,inboundTopicId:h,pfpTopicId:g,profileTopicId:m,success:!0,state:o}}catch(o){return i.failed("Error during profile creation",{error:o.message}),{outboundTopicId:"",inboundTopicId:"",pfpTopicId:"",profileTopicId:"",success:!1,error:o.message,state:{currentStage:"init",completedPercentage:0,error:o.message}}}}async inscribePfp(e,t){try{this.logger.info("Inscribing profile picture using HCS-11 client");const r=await this.hcs11Client.inscribeImage(e,t);if(!r.success)throw this.logger.error(`Failed to inscribe profile picture: ${r.error}`),new Error(r?.error||"Failed to inscribe profile picture");return this.logger.info(`Successfully inscribed profile picture with topic ID: ${r.imageTopicId}`),{pfpTopicId:r.imageTopicId,transactionId:r.transactionId,success:!0}}catch(eg){const t=eg,r=`Error inscribing profile picture: ${t.message}`;return this.logger.error(r),{pfpTopicId:"",transactionId:"",success:!1,error:t.message}}}async storeHCS11Profile(e,t,r,i,o=[],n,s,a,c){try{let l=c||"";if(!l&&s&&a){this.logger.info("Inscribing profile picture for HCS-11 profile");const e=await this.inscribePfp(s,a);e.success?l=e.pfpTopicId:this.logger.warn(`Failed to inscribe profile picture: ${e.error}, proceeding without pfp`)}else c&&(this.logger.info(`Using existing profile picture with topic ID: ${c} for HCS-11 profile`),l=c);const d=this.hcs11Client.getAgentTypeFromMetadata({type:n.type||"autonomous"}),u=n.socials?Object.entries(n.socials).filter(([e,t])=>t).map(([e,t])=>({platform:e,handle:t})):void 0,p=this.hcs11Client.createAIAgentProfile(e,d,o,n.model||"unknown",{alias:e.toLowerCase().replace(/\s+/g,"_"),bio:t,profileImage:l?`hcs://1/${l}`:void 0,socials:u,properties:n.properties,inboundTopicId:r,outboundTopicId:i,creator:n.creator}),h=await this.hcs11Client.createAndInscribeProfile(p,!0);if(!h.success)throw this.logger.error(`Failed to inscribe profile: ${h.error}`),new Error(h.error||"Failed to inscribe profile");return this.logger.info(`Profile inscribed with topic ID: ${h.profileTopicId}, transaction ID: ${h.transactionId}`),{profileTopicId:h.profileTopicId,pfpTopicId:l,transactionId:h.transactionId,success:!0}}catch(eg){const t=eg,r=`Error storing HCS-11 profile: ${t.message}`;return this.logger.error(r),{profileTopicId:"",pfpTopicId:"",transactionId:"",success:!1,error:t.message}}}async setupFees(e,t,r=[]){let o=e;if(!this.client.operatorPublicKey)return o;if(!t.customFees||0===t.customFees.length)return this.logger.warn("No custom fees provided in fee config for setupFees"),o;t.customFees.length>10&&(this.logger.warn("More than 10 custom fees provided, only the first 10 will be used"),t.customFees=t.customFees.slice(0,10));const n=t.customFees.map(e=>{if(!e.feeCollectorAccountId)return this.logger.error("Internal Error: Fee collector ID missing in setupFees"),null;if("FIXED_FEE"===e.type){const t=(new i.CustomFixedFee).setAmount(Number(e.feeAmount.amount)).setFeeCollectorAccountId(i.AccountId.fromString(e.feeCollectorAccountId));return e.feeTokenId&&t.setDenominatingTokenId(i.TokenId.fromString(e.feeTokenId)),t}return null}).filter(Boolean);if(0===n.length)return this.logger.warn("No valid custom fees to apply in setupFees"),o;const s=[...t.exemptAccounts||[],...r];return s.length>0&&(o=await this.setupExemptKeys(e,s)),o.setFeeScheduleKey(this.client.operatorPublicKey).setCustomFees(n)}async setupExemptKeys(e,t){let r=e;const i=Array.from(new Set(t)).filter(e=>e!==this.client.operatorAccountId?.toString());let o=[];if(i.length>0)try{o=await oc(i,this.network,this.logger)}catch(eg){const t=`Error getting exempt keys: ${eg.message}, continuing without exempt keys`;this.logger.warn(t)}return o.length>0&&(r=r.setFeeExemptKeys(o)),r}async handleConnectionRequest(e,t,r,o,n=60){this.logger.info(`Handling connection request ${r} from ${t}`);const s=this.getClient().operatorAccountId?.toString();if(!s)throw new Error("Failed to retrieve operator account ID");let a=await this.mirrorNode.getPublicKey(t);const c=await this.mirrorNode.getPublicKey(s);if(!c)throw new Error("Failed to retrieve public key");const l=new i.KeyList([c,a],1);let d;try{const t=Ud({ttl:n,inboundTopicId:e,connectionId:r,adminKey:l,submitKey:l});if(o){const e=o.build(),r={...e,exemptAccounts:[...e.exemptAccounts||[]]},{topicId:i}=await this.executeTopicCreateTransaction({transaction:t,feeConfig:r});d=i}else{const{topicId:e}=await this.executeTopicCreateTransaction({transaction:t});d=e}this.logger.info(`Created new connection topic ID: ${d}`)}catch(f){const e=`Failed to create connection topic: ${f}`;throw this.logger.error(e),new Qd(e)}const u=`${e}@${s}`,p=await this.confirmConnection(e,d,t,r,"Connection accepted. Looking forward to collaborating!"),h=await this.retrieveCommunicationTopics(s),g=await this.retrieveCommunicationTopics(t),m=`${g.inboundTopic}@${t}`;return await this.recordOutboundConnectionConfirmation({outboundTopicId:h.outboundTopic,requestorOutboundTopicId:g.outboundTopic,connectionRequestId:r,confirmedRequestId:p,connectionTopicId:d,operatorId:m,memo:`Connection established with ${t}`}),{connectionTopicId:d,confirmedConnectionSequenceNumber:p,operatorId:u}}async confirmConnection(e,t,r,i,o,n){const s=await this.getOperatorId();this.logger.info(`Confirming connection with ID ${i}`);const a=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),c=Hd({inboundTopicId:e,connectionTopicId:t,connectedAccountId:r,operatorId:s,connectionId:i,memo:o}),l=await this.submitPayload(c,void 0,n,a.requiresFee),d=l.topicSequenceNumber?.toNumber();if(!d)throw new eu("Failed to confirm connection: sequence number is null");return d}async sendMessage(e,t,r,i,o){const n=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),s=await this.getOperatorId(),a={p:"hcs-10",op:"message",operator_id:s,data:t,m:r},c=JSON.stringify(a);if(globalThis.Buffer.from(c).length>1e3){this.logger.info("Message payload exceeds 1000 bytes, storing via inscription");try{const e=globalThis.Buffer.from(t),r=`message-${Date.now()}.json`,i=await this.inscribeFile(e,r,{progressCallback:o?.progressCallback,waitMaxAttempts:o?.waitMaxAttempts,waitIntervalMs:o?.waitIntervalMs});if(!Ka(i))throw new Error("Failed to inscribe large message content");a.data=`hcs://1/${Ka(i)}`,this.logger.info(`Large message inscribed with topic ID: ${Ka(i)}`)}catch(d){const e=`Error inscribing large message: ${d.message}`;throw this.logger.error(e),new Error(e)}}this.logger.info("Submitting message to connection topic",a);const l=Wd({connectionTopicId:e,operatorId:s,data:a.data,memo:r});return await this.submitPayload(l,void 0,i,n.requiresFee)}async executeTopicCreateTransaction(e){let t=e.transaction;e.feeConfig&&(t=await this.setupFees(t,e.feeConfig,e.additionalExemptAccounts||[]));try{const e=await t.execute(this.client),r=await e.getReceipt(this.client);if(!r.topicId)throw this.logger.error("Failed to create topic: topicId is null"),new Error("Failed to create topic: topicId is null");return{topicId:r.topicId.toString(),receipt:r,response:e}}catch(r){throw this.logger.error("Topic creation failed",{error:r.message,transactionId:r.transactionId?.toString(),operatorId:this.client.operatorAccountId?.toString()}),r}}async createTopic(e,t,r,i){this.logger.info("Creating topic");const o=Y({memo:e,adminKey:t,submitKey:r,operatorPublicKey:this.client.operatorPublicKey||this.operatorCtx.operatorKey?.publicKey}),{topicId:n}=await this.executeTopicCreateTransaction({transaction:o,feeConfig:i});return n}async submitPayload(e,t,r,o=!1){if(e instanceof i.TopicMessageSubmitTransaction||"string"!=typeof e&&"function"==typeof e.getMessage){const t=(i.TopicMessageSubmitTransaction,e),n=t.getMessage();if(!n)throw new Error("Message payload is missing");const s=globalThis.Buffer.from(n).length;if(s>1e3)throw new Xd("Payload size exceeds 1000 bytes limit",s);let a;if(o&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),t.setMaxTransactionFee(new i.Hbar(this.feeAmount))),r){const e=t.freezeWith(this.client),i=await e.sign(r);a=await i.execute(this.client)}else a=await t.execute(this.client);const c=await a.getReceipt(this.client);if(!c)throw this.logger.error("Failed to submit message: receipt is null"),new Error("Failed to submit message: receipt is null");return this.logger.info("Message submitted successfully"),c}const n="string"==typeof t?t:JSON.stringify(t),s=globalThis.Buffer.byteLength(n,"utf8");if(s>1e3)throw new Xd("Payload size exceeds 1000 bytes limit",s);const a=X({topicId:e,message:n,transactionMemo:this.getHcs10TransactionMemo(t)||void 0});let c;if(o&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),a.setMaxTransactionFee(new i.Hbar(this.feeAmount))),r){const e=a.freezeWith(this.client),t=await e.sign(r);c=await t.execute(this.client)}else c=await a.execute(this.client);const l=await c.getReceipt(this.client);if(!l)throw this.logger.error("Failed to submit message: receipt is null"),new Error("Failed to submit message: receipt is null");return this.logger.info("Message submitted successfully"),l}async inscribeFile(e,t,r){if(this.logger.info("Inscribing file"),!this.client.operatorAccountId)throw this.logger.error("Operator account ID is not set"),new Error("Operator account ID is not set");if(!this.operatorCtx.operatorKey)throw this.logger.error("Operator private key is not set"),new Error("Operator private key is not set");const i=k.lookup(t)||"application/octet-stream",o=this.operatorCtx.operatorKey,n=await us.createWithAuth({type:"server",accountId:this.client.operatorAccountId.toString(),privateKey:o,network:this.network}),s={mode:"file",waitForConfirmation:!0,waitMaxAttempts:r?.waitMaxAttempts||30,waitIntervalMs:r?.waitIntervalMs||4e3,progressCallback:r?.progressCallback,logging:{level:this.logger.getLevel?this.logger.getLevel():"info"}},a=await Fa({type:"buffer",buffer:e,fileName:t,mimeType:i},{accountId:this.client.operatorAccountId.toString(),privateKey:o,network:this.network},s,n);if(!a.confirmed||!a.inscription)throw new Error("Inscription was not confirmed");return a.inscription}async waitForConnectionConfirmation(e,t,r=60,i=2e3,o=!0){this.logger.info(`Waiting for connection confirmation on inbound topic ${e} for request ID ${t}`);for(let n=0;n<r;n++){this.logger.info(`Attempt ${n+1}/${r} to find connection confirmation`);const s=(await this.mirrorNode.getTopicMessages(e)).filter(e=>"connection_created"===e.op);if(this.logger.info(`Found ${s.length} connection_created messages`),s.length>0)for(const e of s)if(Number(e.connection_id)===Number(t)){const r={connectionTopicId:e.connection_topic_id,sequence_number:Number(e.sequence_number),confirmedBy:e.operator_id,memo:e.m},i=this.extractAccountFromOperatorId(r.confirmedBy),n=this.getAccountAndSigner(),s=await this.retrieveCommunicationTopics(i),a=await this.retrieveCommunicationTopics(n.accountId);return this.logger.info("Connection confirmation found",r),o&&await this.recordOutboundConnectionConfirmation({requestorOutboundTopicId:s.outboundTopic,outboundTopicId:a.outboundTopic,connectionRequestId:t,confirmedRequestId:r.sequence_number,connectionTopicId:r.connectionTopicId,operatorId:r.confirmedBy,memo:r.memo||"Connection confirmed"}),r}n<r-1&&(this.logger.info(`No matching confirmation found, waiting ${i}ms before retrying...`),await new Promise(e=>setTimeout(e,i)))}throw new Error(`Connection confirmation not found after ${r} attempts for request ID ${t}`)}getAccountAndSigner(){const e=this.operatorCtx.operatorKey;return{accountId:this.client.operatorAccountId.toString(),signer:e}}async createAndRegisterAgent(e,t){try{const r=e.build(),o=t?.progressCallback,n=t?.baseUrl||this.guardedRegistryBaseUrl;let s=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};s.agentMetadata=r.metadata,o&&o({stage:"preparing",message:"Starting agent creation process",progressPercent:0,details:{state:s}});let a,c=r.existingAccount;if(s.inboundTopicId&&s.outboundTopicId&&s.profileTopicId){if(c=c||r.existingAccount,!c)throw new Error("Cannot resume registration without account information");const e="ecdsa"===this.operatorCtx.keyType?i.PrivateKey.fromStringECDSA(c.privateKey).publicKey.toString():i.PrivateKey.fromStringED25519(c.privateKey).publicKey.toString();a=new ru({network:r.network,operatorId:c.accountId,operatorPrivateKey:c.privateKey,operatorPublicKey:e,logLevel:"info",guardedRegistryBaseUrl:n}),this.logger.info("Resuming registration with existing state",{inboundTopicId:s.inboundTopicId,outboundTopicId:s.outboundTopicId,profileTopicId:s.profileTopicId,pfpTopicId:s.pfpTopicId})}else{if(!c)if(s.createdResources&&s.createdResources.some(e=>e.startsWith("account:"))){const e=s.createdResources.find(e=>e.startsWith("account:")),i=e?.split(":")[1];i&&r.existingAccount?(c=r.existingAccount,this.logger.info(`Resuming with existing account: ${i}`)):(c=await this.createAccount(t?.initialBalance),s.createdResources=s.createdResources||[],s.createdResources.push(`account:${c.accountId}`))}else c=await this.createAccount(t?.initialBalance),s.createdResources=s.createdResources||[],s.createdResources.push(`account:${c.accountId}`);o&&o({stage:"preparing",message:"Created account or using existing account",progressPercent:20,details:{state:s,account:c}});const i=new ie({mirrorNode:this.mirrorNode,logger:this.logger}),l=await i.resolveOperatorKey(c.accountId,c.privateKey),d=l.privateKey.publicKey.toString();a=new ru({network:r.network,operatorId:c.accountId,operatorPrivateKey:l.privateKey.toString(),operatorPublicKey:d,keyType:l.keyType,logLevel:"info",guardedRegistryBaseUrl:n}),o&&o({stage:"preparing",message:"Initialized agent client",progressPercent:25,details:{state:s}});let u=s.outboundTopicId,p=s.inboundTopicId,h=s.pfpTopicId,g=s.profileTopicId;if(!u||!p||!g){h&&e.setExistingProfilePicture(h);const t=await a.createAgent(e,60,s,e=>{o&&o({stage:e.stage,message:e.message,progressPercent:e.progressPercent||0,details:{...e.details,state:{...s,...e.details?.state}}})});u=t.outboundTopicId,p=t.inboundTopicId,h=t.pfpTopicId,g=t.profileTopicId,s.outboundTopicId=u,s.inboundTopicId=p,s.pfpTopicId=h,s.profileTopicId=g,s.createdResources||(s.createdResources=[]),h&&!s.createdResources.includes(`pfp:${h}`)&&s.createdResources.push(`pfp:${h}`),s.createdResources.includes(`inbound:${p}`)||s.createdResources.push(`inbound:${p}`),s.createdResources.includes(`outbound:${u}`)||s.createdResources.push(`outbound:${u}`),s.createdResources.includes(`profile:${g}`)||s.createdResources.push(`profile:${g}`)}s.currentStage="profile",s.completedPercentage=60,o&&o({stage:"submitting",message:"Created agent with topics and profile",progressPercent:60,details:{state:s,outboundTopicId:u,inboundTopicId:p,pfpTopicId:h,profileTopicId:g}})}const l=`${s.inboundTopicId}@${c.accountId}`;if("complete"!==s.currentStage||!s.createdResources?.includes(`registration:${s.inboundTopicId}`)){const e=await a.registerAgentWithGuardedRegistry(c.accountId,r.network,{progressCallback:e=>{const t=60+.4*(e.progressPercent||0);o&&o({stage:e.stage,message:e.message,progressPercent:t,details:{...e.details,outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,profileTopicId:s.profileTopicId,operatorId:l,state:e.details?.state||s}})},existingState:s});if(!e.success)return{...e,state:s};s=e.state||s}return o&&o({stage:"completed",message:"Agent creation and registration complete",progressPercent:100,details:{outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,profileTopicId:s.profileTopicId,operatorId:l,state:s}}),{success:!0,state:s,metadata:{accountId:c.accountId,privateKey:c.privateKey,operatorId:l,inboundTopicId:s.inboundTopicId,outboundTopicId:s.outboundTopicId,profileTopicId:s.profileTopicId,pfpTopicId:s.pfpTopicId}}}catch(eg){const r=eg,i=`Failed to create and register agent: ${r.message}`;return this.logger.error(i),{error:r.message,success:!1,state:t?.existingState||{currentStage:"init",completedPercentage:0,error:r.message}}}}async registerAgentWithGuardedRegistry(e,t=this.network,r){try{this.logger.info("Registering agent with guarded registry");const o=r?.maxAttempts??60,n=r?.delayMs??2e3,s=r?.progressCallback;let a=r?.existingState||{currentStage:"registration",completedPercentage:0,createdResources:[]};s&&s({stage:"preparing",message:"Preparing agent registration",progressPercent:10,details:{state:a}});const c=await this.executeRegistration(e,t,this.guardedRegistryBaseUrl,this.logger);if(!c.success)return{...c,state:a};if(s&&s({stage:"submitting",message:"Submitting registration to registry",progressPercent:30,details:{transactionId:c.transactionId,state:a}}),c.transaction){const e=i.Transaction.fromBytes(globalThis.Buffer.from(c.transaction,"base64"));this.logger.info("Processing registration transaction"),await e.execute(this.client),this.logger.info("Successfully processed registration transaction")}s&&s({stage:"confirming",message:"Confirming registration transaction",progressPercent:60,details:{accountId:e,transactionId:c.transactionId,state:a}});const l=await this.waitForRegistrationConfirmation(c.transactionId,t,this.guardedRegistryBaseUrl,o,n,this.logger);return a.currentStage="complete",a.completedPercentage=100,a.createdResources||(a.createdResources=[]),c.transactionId&&a.createdResources.push(`registration:${c.transactionId}`),s&&s({stage:"completed",message:"Agent registration complete",progressPercent:100,details:{confirmed:l,transactionId:c.transactionId,state:a}}),{...c,confirmed:l,state:a}}catch(eg){const t=eg,r=`Failed to register agent: ${t.message}`;return this.logger.error(r),{error:t.message,success:!1}}}async registerAgent(e,t,r,i,o){this.logger.info("Registering agent");const n=Vd({registryTopicId:e,accountId:t,inboundTopicId:r,memo:i});await this.submitPayload(n,void 0,o)}async getInboundTopicType(e){try{const t=await this.mirrorNode.getTopicInfo(e);if(!t)throw new Error("Topic does not exist");if(!(t.submit_key&&t.submit_key.key))return yc.PUBLIC;if(t.fee_schedule_key&&t.fee_schedule_key.key&&t.custom_fees){const r=t.custom_fees;if(r&&r.fixed_fees&&r.fixed_fees.length>0)return this.logger.info(`Topic ${e} is fee-based with ${r.fixed_fees.length} custom fees`),yc.FEE_BASED}return yc.CONTROLLED}catch(eg){const t=`Error determining topic type: ${eg.message}`;throw this.logger.error(t),new Error(t)}}getNetwork(){return this.network}getLogger(){return this.logger}getOperatorAccountId(){return this.client.operatorAccountId?.toString()??null}async createScheduledTransaction(e,t,r,o){this.logger.info("Creating scheduled transaction");const n=(new i.ScheduleCreateTransaction).setScheduledTransaction(e).setPayerAccountId(o?i.AccountId.fromString(o):this.client.operatorAccountId);if(t&&n.setScheduleMemo(t),r){const e=b.addSeconds(new Date,r),t=i.Timestamp.fromDate(e);n.setExpirationTime(t)}const s=await n.execute(this.client),a=await s.getReceipt(this.client);if(!a.scheduleId)throw this.logger.error("Failed to create scheduled transaction: scheduleId is null"),new Error("Failed to create scheduled transaction: scheduleId is null");const c=a.scheduleId.toString(),l=s.transactionId.toString();return this.logger.info(`Scheduled transaction created successfully: ${c}`),{scheduleId:c,transactionId:l}}async sendTransactionOperation(e,t,r,i,o){const n=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),s={p:"hcs-10",op:"transaction",operator_id:await this.getOperatorId(),schedule_id:t,data:r,m:o?.memo};return this.logger.info("Submitting transaction operation to connection topic",s),await this.submitPayload(e,s,i,n.requiresFee)}async sendTransaction(e,t,r,i){this.logger.info("Creating scheduled transaction and sending transaction operation");const{scheduleId:o,transactionId:n}=await this.createScheduledTransaction(t,i?.scheduleMemo,i?.expirationTime,i?.schedulePayerAccountId);return{scheduleId:o,transactionId:n,receipt:await this.sendTransactionOperation(e,o,r,i?.submitKey,{memo:i?.operationMemo})}}async createCommunicationTopics(e,t,r){let i=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};if(r&&r.preparing("Starting communication topic creation",0,{state:i}),!i.outboundTopicId){i.currentStage="topics",r&&r.preparing("Creating outbound topic",5,{state:i});const e=this.client.operatorPublicKey||this.operatorCtx.operatorKey.publicKey,o=Kd({ttl:t?.ttl??60,adminKey:!0,submitKey:!0,operatorPublicKey:e}),{topicId:n}=await this.executeTopicCreateTransaction({transaction:o});i.outboundTopicId=n,i.createdResources&&i.createdResources.push(`outbound:${i.outboundTopicId}`)}if(!i.inboundTopicId){i.currentStage="topics",r&&r.preparing("Creating inbound topic",10,{state:i});const o=this.client.operatorPublicKey||this.operatorCtx.operatorKey.publicKey,n=Md({accountId:e,ttl:t?.ttl??60,adminKey:!0,submitKey:!1,operatorPublicKey:o}),{topicId:s}=await this.executeTopicCreateTransaction({transaction:n});i.inboundTopicId=s,i.createdResources&&i.createdResources.push(`inbound:${i.inboundTopicId}`)}return{inboundTopicId:i.inboundTopicId,outboundTopicId:i.outboundTopicId,state:i}}async handleProfilePictureCreation(e,t,r,i){r.currentStage="pfp",i.preparing("Creating profile picture",30,{state:r}),i.createSubProgress({minPercent:30,maxPercent:50,logPrefix:"PFP"});const o=await this.inscribePfp(e,t);if(!o.success){let e="Failed to inscribe profile picture";throw o.error&&(e=o.error),new Error(e)}const n=o.pfpTopicId;return r.pfpTopicId=n,r.createdResources&&r.createdResources.push(`pfp:${r.pfpTopicId}`),i.preparing("Profile picture created",50,{state:r}),n}async createAndInscribeProfile(e,t,r,i,o,n,s,a){if(this.logger.info("Creating and inscribing profile"),i.profileTopicId)a&&a.preparing(`Using existing ${e?"agent":"person"} profile`,95,{state:i});else{let c;if(a&&a.preparing(`Storing HCS-11 ${e?"agent":"person"} profile`,80),a?.createSubProgress({minPercent:80,maxPercent:95,logPrefix:"StoreProfile"}),e){const e=t.build(),i=e.metadata?.socials?Object.entries(e.metadata.socials).map(([e,t])=>({platform:e,handle:t})):[];c=this.hcs11Client.createAIAgentProfile(e.name,"manual"===e.metadata?.type?0:1,e.capabilities||[],e.metadata?.model||"unknown",{alias:e.name.toLowerCase().replace(/\s+/g,"_"),bio:e.bio,profileImage:r?`hcs://1/${r}`:void 0,socials:i,properties:e.metadata?.properties||{},inboundTopicId:o,outboundTopicId:n,creator:e.metadata?.creator})}else{const e=t.build(),{pfpBuffer:i,pfpFileName:s,...a}=e;c=this.hcs11Client.createPersonalProfile(e.display_name,{alias:e.alias,bio:e.bio,socials:e.socials,profileImage:r?`hcs://1/${r}`:e.profileImage,properties:e.properties,inboundTopicId:o,outboundTopicId:n})}const l=await this.hcs11Client.createAndInscribeProfile(c,s?.updateAccountMemo??!0);if(!l.success){a&&a.failed(`Failed to inscribe ${e?"agent":"person"} profile`,{error:l.error});let t=`Failed to inscribe ${e?"agent":"person"} profile`;throw l.error&&(t=l.error),new Error(t)}i.profileTopicId=l.profileTopicId,i.createdResources&&i.createdResources.push(`profile:${l.profileTopicId}`),a&&a.preparing("HCS-11 Profile stored",95,{state:i})}}async createMCPServer(e,t=60,r,i){await this.ensureInitialized();const o=e.build(),n=this.client.operatorAccountId?.toString();if(!n)throw new Error("Failed to retrieve operator account ID");const s=await this._createEntityTopics(t,{outboundTopicId:r?.outboundTopicId||"",inboundTopicId:r?.inboundTopicId||"",pfpTopicId:r?.pfpTopicId||o.existingPfpTopicId||"",profileTopicId:r?.profileTopicId||""},n,yc.PUBLIC,void 0,o.pfpBuffer,o.pfpFileName,i);if(s.profileTopicId)this.logger.info(`Using existing profile topic ID: ${s.profileTopicId}`);else{this.logger.info("Creating and storing HCS-11 MCP server profile"),i&&i({stage:"preparing",message:"Creating MCP server profile",progressPercent:60,details:{outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,state:{currentStage:"profile",completedPercentage:60}}}),await this.hcs11Client.initializeOperator();const e=this.hcs11Client.createMCPServerProfile(o.name,o.mcpServer,{alias:o.alias,bio:o.bio,socials:o.socials||[],inboundTopicId:s.inboundTopicId,outboundTopicId:s.outboundTopicId,profileImage:s.pfpTopicId?`hcs://1/${s.pfpTopicId}`:void 0}),t=await this.hcs11Client.inscribeProfile(e);if(!t.success)throw this.logger.error(`Failed to inscribe MCP server profile: ${t.error}`),new Error(t.error||"Failed to inscribe MCP server profile");s.profileTopicId=t.profileTopicId,this.logger.info(`MCP server profile stored with topic ID: ${s.profileTopicId}`);const r=await this.hcs11Client.updateAccountMemoWithProfile(n,s.profileTopicId);r.success?this.logger.info("Updated account memo with profile reference"):this.logger.warn(`Failed to update account memo: ${r.error}, but continuing with MCP server creation`),i&&i({stage:"preparing",message:"MCP server profile created",progressPercent:70,details:{outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,profileTopicId:s.profileTopicId,state:{currentStage:"profile",completedPercentage:70}}})}return s}async _createEntityTopics(e,t,r,i,o,n,s,a){let{outboundTopicId:c,inboundTopicId:l,pfpTopicId:d,profileTopicId:u}=t;if(c)this.logger.info(`Using existing outbound topic ID: ${c}`);else{const t=Kd({ttl:e,adminKey:!0,submitKey:!0,operatorPublicKey:this.client.operatorPublicKey||this.operatorCtx.operatorKey.publicKey}),{topicId:r}=await this.executeTopicCreateTransaction({transaction:t});c=r,this.logger.info(`Created new outbound topic ID: ${c}`),a&&a({stage:"preparing",message:"Created outbound topic",progressPercent:30,details:{outboundTopicId:c,state:{currentStage:"topics",completedPercentage:30}}})}if(l?this.logger.info(`Using existing inbound topic ID: ${l}`):(l=await this.createInboundTopic(r,i,e,i===yc.FEE_BASED?o:void 0),this.logger.info(`Created new inbound topic ID: ${l}`),a&&a({stage:"preparing",message:"Created inbound topic",progressPercent:40,details:{outboundTopicId:c,inboundTopicId:l,state:{currentStage:"topics",completedPercentage:40}}})),!d&&n&&n.length>0&&s){this.logger.info("Inscribing new profile picture"),a&&a({stage:"preparing",message:"Inscribing profile picture",progressPercent:50,details:{outboundTopicId:c,inboundTopicId:l,state:{currentStage:"pfp",completedPercentage:50}}});d=(await this.inscribePfp(n,s)).pfpTopicId,this.logger.info(`Profile picture inscribed with topic ID: ${d}`),a&&a({stage:"preparing",message:"Profile picture inscribed",progressPercent:55,details:{outboundTopicId:c,inboundTopicId:l,pfpTopicId:d,state:{currentStage:"pfp",completedPercentage:55}}})}else d&&this.logger.info(`Using existing profile picture with topic ID: ${d}`);return{inboundTopicId:l,outboundTopicId:c,pfpTopicId:d,profileTopicId:u}}async createAndRegisterMCPServer(e,t){try{const r=e.build(),o=t?.progressCallback,n=t?.baseUrl||this.guardedRegistryBaseUrl;let s=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};s.serverMetadata={name:r.name,description:r.mcpServer.description,services:r.mcpServer.services},o&&o({stage:"preparing",message:"Starting MCP server creation process",progressPercent:0,details:{state:s}});let a,c=r.existingAccount;if(s.inboundTopicId&&s.outboundTopicId&&s.profileTopicId){if(c=c||r.existingAccount,!c)throw new Error("Cannot resume registration without account information");const e=re(c.privateKey),t=("ed25519"===e.detectedType?i.PrivateKey.fromStringED25519(c.privateKey):i.PrivateKey.fromStringECDSA(c.privateKey)).publicKey.toString();a=new ru({network:r.network,operatorId:c.accountId,operatorPrivateKey:c.privateKey,operatorPublicKey:t,keyType:e.detectedType,logLevel:"info",guardedRegistryBaseUrl:n}),this.logger.info("Resuming registration with existing state",{inboundTopicId:s.inboundTopicId,outboundTopicId:s.outboundTopicId,profileTopicId:s.profileTopicId,pfpTopicId:s.pfpTopicId})}else{if(!c)if(s.createdResources&&s.createdResources.some(e=>e.startsWith("account:"))){const e=s.createdResources.find(e=>e.startsWith("account:")),i=e?.split(":")[1];i&&r.existingAccount?(c=r.existingAccount,this.logger.info(`Resuming with existing account: ${i}`)):(c=await this.createAccount(t?.initialBalance),s.createdResources=s.createdResources||[],s.createdResources.push(`account:${c.accountId}`))}else c=await this.createAccount(t?.initialBalance),s.createdResources=s.createdResources||[],s.createdResources.push(`account:${c.accountId}`);o&&o({stage:"preparing",message:"Created account or using existing account",progressPercent:20,details:{state:s,account:c}});const l=new ie({mirrorNode:this.mirrorNode,logger:this.logger}),d=await l.resolveOperatorKey(c.accountId,c.privateKey);e.setExistingAccount(c.accountId,c.privateKey);const u=("ed25519"===d.keyType?i.PrivateKey.fromStringED25519(c.privateKey):i.PrivateKey.fromStringECDSA(c.privateKey)).publicKey.toString();a=new ru({network:r.network,operatorId:c.accountId,operatorPrivateKey:c.privateKey,operatorPublicKey:u,logLevel:"info",guardedRegistryBaseUrl:n}),o&&o({stage:"preparing",message:"Initialized MCP server client",progressPercent:25,details:{state:s}});let p=s.outboundTopicId,h=s.inboundTopicId,g=s.pfpTopicId,m=s.profileTopicId;if(!p||!h||!m){g&&e.setExistingProfilePicture(g);const t=await a.createMCPServer(e,60,s,e=>{o&&o({stage:e.stage,message:e.message,progressPercent:e.progressPercent||0,details:{...e.details,state:{...s,...e.details?.state}}})});p=t.outboundTopicId,h=t.inboundTopicId,g=t.pfpTopicId,m=t.profileTopicId,s.outboundTopicId=p,s.inboundTopicId=h,s.pfpTopicId=g,s.profileTopicId=m,s.createdResources||(s.createdResources=[]),g&&!s.createdResources.includes(`pfp:${g}`)&&s.createdResources.push(`pfp:${g}`),s.createdResources.includes(`inbound:${h}`)||s.createdResources.push(`inbound:${h}`),s.createdResources.includes(`outbound:${p}`)||s.createdResources.push(`outbound:${p}`),s.createdResources.includes(`profile:${m}`)||s.createdResources.push(`profile:${m}`)}s.currentStage="profile",s.completedPercentage=60,o&&o({stage:"submitting",message:"Created MCP server with topics and profile",progressPercent:60,details:{state:s,outboundTopicId:p,inboundTopicId:h,pfpTopicId:g,profileTopicId:m}})}const l=`${s.inboundTopicId}@${c.accountId}`;if("complete"!==s.currentStage||!s.createdResources?.includes(`registration:${s.inboundTopicId}`)){const e=await a.registerAgentWithGuardedRegistry(c.accountId,r.network,{progressCallback:e=>{const t=60+.4*(e.progressPercent||0);o&&o({stage:e.stage,message:e.message,progressPercent:t,details:{...e.details,outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,profileTopicId:s.profileTopicId,operatorId:l,state:e.details?.state||s}})},existingState:s});if(!e.success)return{...e,state:s};s=e.state||s}return o&&o({stage:"completed",message:"MCP server creation and registration complete",progressPercent:100,details:{outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,profileTopicId:s.profileTopicId,operatorId:l,state:s}}),{success:!0,state:s,metadata:{accountId:c.accountId,privateKey:c.privateKey,operatorId:l,inboundTopicId:s.inboundTopicId,outboundTopicId:s.outboundTopicId,profileTopicId:s.profileTopicId,pfpTopicId:s.pfpTopicId}}}catch(eg){const r=eg,i=`Failed to create and register MCP server: ${r.message}`;return this.logger.error(i),{error:r.message,success:!1,state:t?.existingState||{currentStage:"init",completedPercentage:0,error:r.message}}}}async createRegistryTopic(e={}){const{ttl:t=86400,metadata:r,adminKey:i=!1,submitKey:o=!1,waitForConfirmation:n=!0,waitMaxAttempts:s=30,waitIntervalMs:a=4e3,progressCallback:c}=e;try{let e;if(await this.ensureInitialized(),c&&c({stage:"preparing",message:"Preparing registry topic creation",progressPercent:10,details:{metadata:!!r}}),r){this.logger.info("Creating metadata inscription for registry"),c&&c({stage:"submitting",message:"Creating registry metadata inscription",progressPercent:30,details:{metadataName:r.name}});const t=globalThis.Buffer.from(JSON.stringify(r,null,2)),i={mode:"file",waitForConfirmation:n,waitMaxAttempts:s,waitIntervalMs:a,logging:{level:this.logger.getLevel?this.logger.getLevel():"info"}},o=await Fa({type:"buffer",buffer:t,fileName:`registry-metadata-${Date.now()}.json`,mimeType:"application/json"},{accountId:this.client.operatorAccountId.toString(),privateKey:this.operatorCtx.operatorKey,network:this.network},i);if(!o.confirmed||!o.inscription)throw new Error("Metadata inscription was not confirmed");e=Ka(o.inscription),this.logger.info(`Metadata inscribed to topic: ${e}`)}c&&c({stage:"submitting",message:"Creating registry topic",progressPercent:60,details:{metadataTopicId:e}});const l=this.operatorCtx.operatorKey,d=Ld({ttl:t,metadataTopicId:e,adminKey:i,submitKey:o,operatorPublicKey:this.client.operatorPublicKey||l.publicKey}),{topicId:u,response:p}=await this.executeTopicCreateTransaction({transaction:d});return c&&c({stage:"completed",message:"Registry topic created successfully",progressPercent:100,details:{topicId:u,metadataTopicId:e,transactionId:p.transactionId.toString()}}),this.logger.info(`Registry topic created successfully: ${u}`),{success:!0,topicId:u,transactionId:p.transactionId.toString(),metadataTopicId:e}}catch(l){const e=l instanceof Error?l.message:"Unknown error";return c&&c({stage:"failed",message:`Registry creation failed: ${e}`,progressPercent:0,details:{error:e}}),this.logger.error("Failed to create registry topic",{error:e}),{success:!1,error:e}}}}const iu="undefined"!=typeof window;var ou=(e=>(e[e.ACTION=0]="ACTION",e[e.ASSEMBLY=2]="ASSEMBLY",e[e.HASHLINKS=3]="HASHLINKS",e))(ou||{});class nu{constructor(e,t,r,i,o){this.entries=new Map,this.networkType=e,this.logger=t,this.registryType=r,this.topicId=i,this.client=o}async getEntry(e){const t=this.entries.get(e);return t||(this.topicId&&this.client?(await this.sync(),this.entries.get(e)||null):null)}async getLatestEntry(e){if(!this.client)return null;try{const t=await this.client.mirrorNode.getTopicMessagesByFilter(e,{order:"desc",limit:1});if(!t||0===t.length)return null;const r=t[0];let i;if(r.raw_content)i=JSON.parse(r.raw_content);else{const e=r;if("hcs-12"!==e.p||!e.op)return null;i={p:e.p,op:e.op,name:e.name,version:e.version,description:e.description,permissions:e.permissions,metadata:e.metadata,data:e.data,category:e.category,source:e.source,inputs:e.inputs,outputs:e.outputs,tags:e.tags,fields:e.fields,styles:e.styles,actions:e.actions,blocks:e.blocks,refs:e.refs},Object.keys(i).forEach(e=>{void 0===i[e]&&delete i[e]})}return{id:r.sequence_number.toString(),sequenceNumber:r.sequence_number,timestamp:r.consensus_timestamp||(new Date).toISOString(),submitter:r.payer||"unknown",data:i}}catch(t){return this.logger.error("Failed to get latest entry",{topicId:e,error:t}),null}}async listEntries(e){this.topicId&&this.client&&await this.sync();const t=Array.from(this.entries.values());return e?t.filter(t=>(!e.submitter||t.submitter===e.submitter)&&(!(e.afterTimestamp&&t.timestamp<e.afterTimestamp)&&!(e.beforeTimestamp&&t.timestamp>e.beforeTimestamp))):t}async sync(){if(this.topicId&&this.client){this.logger.info("Syncing registry entries",{topicId:this.topicId,registryType:ou[this.registryType],lastSync:this.lastSyncTimestamp});try{const t=await this.client.mirrorNode.getTopicMessagesByFilter(this.topicId,{startTime:this.lastSyncTimestamp,order:"asc",limit:100});for(const r of t)try{let e;if(r.raw_content)e=JSON.parse(r.raw_content);else{const t=r;if("hcs-12"!==t.p||!t.op)continue;e={p:t.p,op:t.op,name:t.name,version:t.version,description:t.description,permissions:t.permissions,metadata:t.metadata,data:t.data,category:t.category,source:t.source,inputs:t.inputs,outputs:t.outputs,tags:t.tags,fields:t.fields,styles:t.styles,actions:t.actions,blocks:t.blocks,refs:t.refs,t_id:t.t_id,hash:t.hash,wasm_hash:t.wasm_hash,info_t_id:t.info_t_id,validation_rules:t.validation_rules,js_t_id:t.js_t_id,js_hash:t.js_hash,interface_version:t.interface_version,title:t.title,template:t.template,author:t.author,m:t.m},Object.keys(e).forEach(t=>{void 0===e[t]&&delete e[t]})}if("hcs-12"!==e.p)continue;const t={id:r.sequence_number.toString(),sequenceNumber:r.sequence_number,timestamp:r.consensus_timestamp||(new Date).toISOString(),submitter:r.payer||"unknown",data:e};this.entries.set(t.id,t)}catch(e){this.logger.warn("Failed to parse registry message",{sequenceNumber:r.sequence_number,error:e})}t.length>0?this.lastSyncTimestamp=t[t.length-1].consensus_timestamp||(new Date).toISOString():this.lastSyncTimestamp=(new Date).toISOString(),this.logger.info("Registry sync completed",{topicId:this.topicId,messageCount:t.length,lastSync:this.lastSyncTimestamp})}catch(e){throw this.logger.error("Failed to sync registry",{error:e}),e}}else this.logger.warn("Cannot sync without topic ID and client")}getTopicMemo(){return`hcs-12:1:60:${this.registryType}`}async createRegistryTopic(){if(!this.client)throw new Error("Client required to create topic");const e=await this.client.createRegistryTopic(this.registryType);return this.topicId=e,e}getConfig(){return{type:this.registryType,indexed:!1,ttl:60,topicId:this.topicId,memo:this.getTopicMemo()}}async inscribeContent(e,t,r){if(!this.client)throw new Error("Client required for inscription");const i="string"==typeof e?globalThis.Buffer.from(e):e;let o;if(this.logger.info("Inscribing content via HCS-1",{size:i.length,mimeType:t,registryType:ou[this.registryType]}),"getOperatorAccountId"in this.client)o=await Fa({type:"buffer",buffer:i,fileName:"application/octet-stream"===t&&"wasm"===r?.fileType?`${r?.name||"content"}.wasm`:r?.name||"content",mimeType:t},{accountId:this.client.getOperatorAccountId(),privateKey:this.client.getOperatorPrivateKey(),network:this.networkType},{mode:"file",metadata:r,waitForConfirmation:!0});else{const{accountId:e,signer:n}=await this.client.getAccountAndSigner();o=await Oa({type:"buffer",buffer:i,fileName:"application/octet-stream"===t&&"wasm"===r?.fileType?`${r?.name||"content"}.wasm`:r?.name||"content",mimeType:t},n,{mode:"file",metadata:r,waitForConfirmation:!0})}if(!o.confirmed)throw new Error("Failed to inscribe content");const n=o.inscription.topic_id;if(!n)throw new Error("No topic ID in inscription response");return this.logger.info("Content inscribed successfully",{topicId:n}),n}validateBaseRegistration(e){if(!e.p||"hcs-12"!==e.p)throw new Error("Invalid protocol identifier");if(!e.op||"register"!==e.op)throw new Error("Invalid operation")}clearCache(){this.entries.clear(),this.lastSyncTimestamp=void 0,this.logger.info("Registry cache cleared",{registryType:ou[this.registryType]})}getStats(){return{entryCount:this.entries.size,lastSync:this.lastSyncTimestamp,topicId:this.topicId,registryType:ou[this.registryType]}}}const su=r.z.object({p:r.z.literal("hcs-12")}),au=r.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid Hedera address format"),cu=r.z.string().regex(/^[a-f0-9]{64}$/,"Invalid SHA-256 hash format"),lu=r.z.object({format:r.z.enum(["tar.gz","zip","car"]),root_manifest:r.z.string(),includes_lockfile:r.z.boolean(),workspace_members:r.z.array(r.z.string()).optional()}),du=r.z.object({source_t_id:au,source_hash:cu,compiler_version:r.z.string(),cargo_version:r.z.string(),target:r.z.literal("wasm32-unknown-unknown"),profile:r.z.string(),build_flags:r.z.array(r.z.string()),lockfile_hash:cu,source_structure:lu}),uu=r.z.lazy(()=>r.z.object({type:r.z.string().optional(),required:r.z.array(r.z.string()).optional(),properties:r.z.record(uu).optional(),pattern:r.z.string().optional(),minimum:r.z.number().optional(),maximum:r.z.number().optional(),regex:r.z.string().optional(),min:r.z.number().optional(),max:r.z.number().optional(),length:r.z.number().optional(),email:r.z.boolean().optional(),url:r.z.boolean().optional(),uuid:r.z.boolean().optional(),cuid:r.z.boolean().optional(),cuid2:r.z.boolean().optional(),ulid:r.z.boolean().optional(),datetime:r.z.boolean().optional(),ip:r.z.boolean().optional(),startsWith:r.z.string().optional(),endsWith:r.z.string().optional(),includes:r.z.string().optional(),gt:r.z.number().optional(),gte:r.z.number().optional(),lt:r.z.number().optional(),lte:r.z.number().optional(),int:r.z.boolean().optional(),positive:r.z.boolean().optional(),nonnegative:r.z.boolean().optional(),negative:r.z.boolean().optional(),nonpositive:r.z.boolean().optional(),multipleOf:r.z.number().optional(),finite:r.z.boolean().optional(),safe:r.z.boolean().optional(),nonempty:r.z.boolean().optional(),literal:r.z.union([r.z.string(),r.z.number(),r.z.boolean()]).optional(),enum:r.z.array(r.z.string()).optional(),nullable:r.z.boolean().optional(),nullish:r.z.boolean().optional(),optional:r.z.boolean().optional(),element:r.z.any().optional(),shape:r.z.record(r.z.any()).optional(),strict:r.z.boolean().optional(),passthrough:r.z.boolean().optional(),catchall:r.z.any().optional()})),pu=r.z.object({p:r.z.literal("hcs-12"),op:r.z.literal("register"),t_id:au,hash:cu,wasm_hash:cu,js_t_id:au.optional(),js_hash:cu.optional(),interface_version:r.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid version format").optional(),info_t_id:au.optional(),source_verification:du.optional(),previous_version:r.z.string().optional(),migration_notes:r.z.string().optional(),validation_rules:r.z.record(uu).optional(),m:r.z.string().optional()}),hu=r.z.object({p:r.z.literal("hcs-12"),op:r.z.enum(["register","template"]),name:r.z.string(),version:r.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid semver format"),data:r.z.union([r.z.any(),r.z.string()]).optional(),t_id:au.optional()});r.z.enum(["register","add-action","add-block","update"]);const gu=su.extend({op:r.z.literal("register"),name:r.z.string(),version:r.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid semver format"),description:r.z.string().optional(),tags:r.z.array(r.z.string()).optional(),author:r.z.string().optional()}),mu=su.extend({op:r.z.literal("add-action"),t_id:au,alias:r.z.string(),config:r.z.any().optional(),data:au.optional()}),fu=su.extend({op:r.z.literal("add-block"),block_t_id:au,actions:r.z.record(r.z.string(),au).optional(),attributes:r.z.record(r.z.any()).optional(),children:r.z.array(r.z.string()).optional(),data:au.optional()}),yu=su.extend({op:r.z.literal("update"),description:r.z.string().optional(),tags:r.z.array(r.z.string()).optional()});r.z.object({type:r.z.enum(["vertical","horizontal","grid"]),responsive:r.z.boolean().optional(),containerClass:r.z.string().optional()}),r.z.object({source_t_id:au,source_hash:cu,description:r.z.string().optional()});const bu=r.z.discriminatedUnion("op",[gu,mu,fu,yu]),wu=gu,Iu=su.extend({op:r.z.literal("register"),t_id:au,name:r.z.string().max(100,"Name must be 100 characters or less"),description:r.z.string().max(500,"Description must be 500 characters or less").optional(),tags:r.z.array(r.z.string()).max(10,"Maximum 10 tags allowed").optional(),category:r.z.string().optional(),featured:r.z.boolean().optional(),icon:r.z.string().optional(),author:r.z.string().optional(),website:r.z.string().url().optional()});function Tu(e){return pu.parse(e)}function Su(e){return bu.parse(e)}function ku(e,t){const r=t.safeParse(e);return r.success?{isValid:!0,errors:[],data:r.data}:{isValid:!1,errors:r.error.errors.map(e=>`${e.path.join(".")}: ${e.message}`)}}class Eu extends nu{constructor(e,t,r,i){super(e,t,ou.ACTION,r,i),this.actionsByHash=new Map,this.cryptoAdapter=ud()}async registerWithWasm(e,t,r){let i,o;if(od()){i=this.createSSRSafeHash(e,"wasm");const r=JSON.stringify(t);o=this.createSSRSafeHash(globalThis.Buffer.from(r),"info")}else{const r=this.cryptoAdapter.createHash("sha256").update(e).digest("hex"),n=r instanceof Promise?await r:r;i="string"==typeof n?n:n.toString("hex");const s=JSON.stringify(t),a=this.cryptoAdapter.createHash("sha256").update(globalThis.Buffer.from(s)).digest("hex"),c=a instanceof Promise?await a:a;o="string"==typeof c?c:c.toString("hex")}const n=await this.inscribeContent(e,"application/octet-stream",{name:t.name,version:t.version,hash:i,fileType:"wasm"});let s;const a=JSON.stringify(t);globalThis.Buffer.byteLength(a,"utf8")>1024&&(s=await this.inscribeContent(a,"application/json",{name:`${t.name}-info`,version:t.version}));const c={p:"hcs-12",op:"register",t_id:n,hash:o,wasm_hash:i,info_t_id:s,source_verification:r,m:`${t.name} v${t.version}`};return await this.register(c),c}async register(e){if(this.validateRegistration(e),this.topicId&&this.client){this.logger.info("Submitting action registration to HCS",{topicId:this.topicId,hash:e.hash,wasmHash:e.wasm_hash});const t=(await this.client.submitMessage(this.topicId,JSON.stringify(e))).sequenceNumber;if(!t)throw new Error("No sequence number returned from submission");const r={id:t.toString(),sequenceNumber:t,timestamp:(new Date).toISOString(),submitter:"getHashConnect"in this.client?(await this.client.getAccountAndSigner()).accountId:this.client.getOperatorAccountId(),data:e};return this.entries.set(r.id,r),this.actionsByHash.set(e.hash,e),this.logger.info("Action registered",{hash:e.hash,sequenceNumber:t,hasSourceVerification:!!e.source_verification}),t.toString()}{const t=this.entries.size+1,r={id:t.toString(),sequenceNumber:t,timestamp:(new Date).toISOString(),submitter:"local",data:e};return this.entries.set(r.id,r),this.actionsByHash.set(e.hash,e),t.toString()}}async getAction(e){const t=this.actionsByHash.get(e);return t||(this.topicId&&this.client?(await this.sync(),this.actionsByHash.get(e)||null):null)}async getActionByTopicId(e){this.logger.debug("getActionByTopicId called",{topicId:e}),console.log("DEBUG: getActionByTopicId called",{topicId:e,cacheSize:this.actionsByHash.size,cachedTopicIds:Array.from(this.actionsByHash.values()).map(e=>e.t_id)});for(const t of this.actionsByHash.values())if(t.t_id===e)return this.logger.debug("Action found in cache",{topicId:e,action:t}),console.log("DEBUG: Action found in cache",{topicId:e,action:t}),t;if(this.topicId&&this.client){this.logger.debug("Action not in cache, syncing...",{topicId:e}),console.log("DEBUG: Action not in cache, syncing..."),await this.sync(),console.log("DEBUG: After sync",{cacheSize:this.actionsByHash.size,cachedTopicIds:Array.from(this.actionsByHash.values()).map(e=>e.t_id)});for(const t of this.actionsByHash.values())if(t.t_id===e)return this.logger.debug("Action found after sync",{topicId:e,action:t}),console.log("DEBUG: Action found after sync",{topicId:e,action:t}),t}return this.logger.warn("Action not found",{topicId:e}),console.log("DEBUG: Action not found",{topicId:e}),null}async getActionInfo(e){const t=await this.getAction(e);if(!t)return null;try{let e;if(!t.info_t_id)return this.logger.warn("Inline INFO storage not yet implemented"),null;{if(!this.client)return this.logger.error("Client not initialized - cannot fetch INFO"),null;let r;if("getOperatorAccountId"in this.client)r=await Da(t.info_t_id,{accountId:this.client.getOperatorAccountId(),privateKey:this.client.getOperatorPrivateKey(),network:this.networkType});else{const{accountId:e}=await this.client.getAccountAndSigner();r=await Da(t.info_t_id,{accountId:e,network:this.networkType})}if(!r.content)return this.logger.error("No content in inscription response"),null;e="string"==typeof r.content?r.content:globalThis.Buffer.from(r.content).toString("utf8")}const r=JSON.parse(e);let i;if(od())i=this.createSSRSafeHash(globalThis.Buffer.from(e),"info");else{const t=this.cryptoAdapter.createHash("sha256").update(globalThis.Buffer.from(e)).digest("hex"),r=t instanceof Promise?await t:t;i="string"==typeof r?r:r.toString("hex")}if(i!==t.hash)throw this.logger.error("INFO hash mismatch",{expected:t.hash,computed:i}),new Error("Module info verification failed");return r}catch(r){return this.logger.error("Failed to fetch action INFO",{hash:e,error:r}),null}}async getActionWasm(e){const t=await this.getAction(e);if(!t)return null;if(!this.client)return this.logger.error("Client not initialized - cannot fetch WASM"),null;try{let e;if("getOperatorAccountId"in this.client)e=await Da(t.t_id,{accountId:this.client.getOperatorAccountId(),privateKey:this.client.getOperatorPrivateKey(),network:this.networkType});else{const{accountId:r}=await this.client.getAccountAndSigner();e=await Da(t.t_id,{accountId:r,network:this.networkType})}if(!e.content)return this.logger.error("No content in inscription response"),null;const r="string"==typeof e.content?globalThis.Buffer.from(e.content,"base64"):globalThis.Buffer.from(e.content);let i;if(od())i=this.createSSRSafeHash(r,"wasm");else{const e=this.cryptoAdapter.createHash("sha256").update(r).digest("hex"),t=e instanceof Promise?await e:e;i="string"==typeof t?t:t.toString("hex")}if(i!==t.wasm_hash)throw this.logger.error("WASM hash mismatch",{expected:t.wasm_hash,computed:i}),new Error("WASM binary verification failed");return new Uint8Array(r)}catch(r){return this.logger.error("Failed to fetch WASM from HCS-1",{topicId:t.t_id,error:r}),null}}async searchActions(e){return(await this.listEntries({submitter:e.creator,afterTimestamp:e.afterTimestamp,beforeTimestamp:e.beforeTimestamp})).map(e=>e.data).filter(t=>{if(void 0!==e.hasSourceVerification){if(!!t.source_verification!==e.hasSourceVerification)return!1}return!0})}async getVersionChain(e){const t=[];let r=e;for(;r;){const e=await this.getAction(r);if(!e)break;t.push(e),r=void 0}return t}validateRegistration(e){try{Tu(e)}catch(t){if(t instanceof r.ZodError){const e=t.errors[0];throw new Error(`Validation failed: ${e.path.join(".")} - ${e.message}`)}throw t}}async sync(){await super.sync(),this.actionsByHash.clear();for(const e of this.entries.values()){const t=e.data;this.actionsByHash.set(t.hash,t)}}clearCache(){super.clearCache(),this.actionsByHash.clear()}createSSRSafeHash(e,t){let r=0;for(let i=0;i<Math.min(e.length,256);i++)r=(r<<5)-r+e[i]&4294967295;return`ssr-${t}-${e.length}-${Math.abs(r).toString(16).padStart(8,"0")}`}}class vu{constructor(e,t,r){this.blockCache=new Map,this.templateCache=new Map,this.networkType=e,this.logger=t,this.client=r}async loadBlockDefinition(e){const t=this.blockCache.get(e);if(t)return t;try{const t=new Ql,r=await t.resolve(e,{network:this.networkType});if(!r.content)throw new Error(`Block definition not found: ${e}`);let i;return i="object"!=typeof r.content||null===r.content||r.content instanceof ArrayBuffer?JSON.parse("string"==typeof r.content?r.content:r.content.toString()):r.content,this.blockCache.set(e,i),i}catch(r){throw this.logger.error("Failed to load block definition",{blockTopicId:e,error:r.message}),new Error(`Failed to load block definition: ${r.message}`)}}async loadBlockTemplate(e){const t=this.templateCache.get(e);if(t)return t;try{const t=new Ql,r=await t.resolve(e,{network:this.networkType});if(!r.content)throw new Error(`Block template not found: ${e}`);let i;return i="string"==typeof r.content?r.content:"object"==typeof r.content&&null!==r.content?r.content.text||JSON.stringify(r.content):r.content.toString(),this.templateCache.set(e,i),i}catch(r){throw this.logger.error("Failed to load block template",{templateTopicId:e,error:r.message}),new Error(`Failed to load block template: ${r.message}`)}}async loadBlock(e){const t=await this.loadBlockDefinition(e);return{definition:t,template:await this.loadBlockTemplate(t.template_t_id)}}async storeBlock(e,t){if(!this.client||!("inscribeFile"in this.client))throw new Error("Client does not support inscription");try{const r=globalThis.Buffer.from(e),i=await this.client.inscribeFile(r,`block-${t.name}-template.html`);if(!i?.topic_id)throw new Error("Failed to inscribe block template");const o={...t,template_t_id:i.topic_id},n=globalThis.Buffer.from(JSON.stringify(o)),s=await this.client.inscribeFile(n,`block-${t.name}-definition.json`);if(!s?.topic_id)throw new Error("Failed to inscribe block definition");return this.blockCache.set(s.topic_id,o),this.templateCache.set(i.topic_id,e),{definitionTopicId:s.topic_id,templateTopicId:i.topic_id}}catch(r){throw this.logger.error("Failed to store block",{error:r.message}),new Error(`Failed to store block: ${r.message}`)}}clearCache(){this.blockCache.clear(),this.templateCache.clear()}}class Au extends nu{constructor(e,t,r,i){super(e,t,ou.ASSEMBLY,r,i),this.assemblyStates=new Map}getTopicMemo(){return`hcs-12:0:60:${this.registryType}`}async register(e){return this.submitMessage(e)}async createAssemblyTopic(){const e=await this.createRegistryTopic();return this.topicId=e,e}async addAction(e){return this.submitMessage(e)}async addBlock(e){return this.submitMessage(e)}async update(e){return this.submitMessage(e)}async submitMessage(e){if(this.validateMessage(e),!this.topicId)throw new Error("Assembly topic ID not found");if(!this.client)throw new Error("Client not found");this.logger.info("Submitting assembly message to HCS",{topicId:this.topicId,op:e.op});const t=(await this.client.submitMessage(this.topicId,JSON.stringify(e))).sequenceNumber;if(!t)throw new Error("No sequence number returned from submission");const r={id:t.toString(),sequenceNumber:t,timestamp:(new Date).toISOString(),submitter:"getHashConnect"in this.client?(await this.client.getAccountAndSigner()).accountId:this.client.getOperatorAccountId(),data:e};return this.entries.set(r.id,r),await this.processMessage(r),this.logger.info("Assembly message processed",{op:e.op,sequenceNumber:t}),t.toString()}async processMessage(e){const t=e.data;if(!this.topicId)return;let r=this.assemblyStates.get(this.topicId);switch(t.op){case"register":const i=t;r={topicId:this.topicId,name:i.name,version:i.version,description:i.description,tags:i.tags,author:i.author,actions:[],blocks:[],created:e.timestamp,updated:e.timestamp},this.assemblyStates.set(this.topicId,r);break;case"add-action":if(!r)return void this.logger.warn("Cannot add action without assembly registration");const o=t,n={t_id:o.t_id,alias:o.alias,config:o.config,data:o.data};r.actions.push(n),r.updated=e.timestamp;break;case"add-block":if(!r)return void this.logger.warn("Cannot add block without assembly registration");const s=t,a={block_t_id:s.block_t_id,actions:s.actions,attributes:s.attributes,children:s.children,data:s.data};r.blocks.push(a),r.updated=e.timestamp;break;case"update":if(!r)return void this.logger.warn("Cannot update without assembly registration");const c=t;void 0!==c.description&&(r.description=c.description),void 0!==c.tags&&(r.tags=c.tags),r.updated=e.timestamp}}async getAssemblyState(e){const t=e||this.topicId;if(!t||!this.client)return null;let r=this.assemblyStates.get(t);if(r)return r;if(t===this.topicId&&this.entries.size>0){this.logger.debug("Building state from existing entries",{topicId:t,entriesCount:this.entries.size}),this.assemblyStates.clear();for(const r of this.entries.values())this.processAssemblyMessage(t,r);const e=this.assemblyStates.get(t)||null;return this.logger.debug("Built state from entries",{topicId:t,hasState:!!e,name:e?.name}),e}this.logger.info("Syncing assembly state from topic",{topicId:t});try{const e=await this.client.mirrorNode.getTopicMessagesByFilter(t,{order:"asc",limit:1e3}),r=Array.isArray(e)?e:[];this.logger.info("Processing assembly messages",{topicId:t,messageCount:r.length});for(const n of r)try{let e;if(!n.message)continue;try{let t;t="undefined"==typeof window?globalThis.Buffer.from(n.message,"base64").toString("utf-8"):(new TextDecoder).decode(Uint8Array.from(atob(n.message),e=>e.charCodeAt(0))),e=JSON.parse(t),this.logger.debug("Successfully parsed message",{sequenceNumber:n.sequence_number,op:e.op,p:e.p})}catch(i){this.logger.debug("Failed to decode/parse message",{sequenceNumber:n.sequence_number,error:i});continue}if("hcs-12"!==e.p){this.logger.debug("Skipping non-HCS-12 message",{sequenceNumber:n.sequence_number,protocol:e.p});continue}const r={id:n.sequence_number.toString(),sequenceNumber:n.sequence_number,timestamp:n.consensus_timestamp||(new Date).toISOString(),submitter:n.payer_account_id||"unknown",data:e};this.processAssemblyMessage(t,r),this.logger.debug("Processed message for assembly",{topicId:t,sequenceNumber:r.sequenceNumber,op:r.data.op})}catch(i){this.logger.warn("Failed to parse assembly message",{sequenceNumber:n.sequence_number,error:i})}const o=this.assemblyStates.get(t)||null;return this.logger.info("Assembly state after sync",{topicId:t,hasState:!!o,name:o?.name,version:o?.version,actionsCount:o?.actions?.length||0,blocksCount:o?.blocks?.length||0}),o}catch(i){return this.logger.error("Failed to sync assembly state",{topicId:t,error:i}),null}}processAssemblyMessage(e,t){const r=t.data;let i=this.assemblyStates.get(e);switch(this.logger.debug("Processing assembly message",{topicId:e,op:r.op,hasState:!!i}),r.op){case"register":const o=r;i={topicId:e,name:o.name,version:o.version,description:o.description,tags:o.tags,author:o.author,actions:[],blocks:[],created:t.timestamp,updated:t.timestamp},this.assemblyStates.set(e,i),this.logger.debug("Assembly registered",{topicId:e,name:o.name,version:o.version});break;case"add-action":if(!i)return void this.logger.warn("Cannot add action without assembly registration");const n=r,s={t_id:n.t_id,alias:n.alias,config:n.config,data:n.data};i.actions.push(s),i.updated=t.timestamp;break;case"add-block":if(!i)return void this.logger.warn("Cannot add block without assembly registration");const a=r,c={block_t_id:a.block_t_id,actions:a.actions,attributes:a.attributes,children:a.children,data:a.data};i.blocks.push(c),i.updated=t.timestamp;break;case"update":if(!i)return void this.logger.warn("Cannot update without assembly registration");const l=r;void 0!==l.description&&(i.description=l.description),void 0!==l.tags&&(i.tags=l.tags),i.updated=t.timestamp}}async sync(){if(this.topicId&&this.client){this.entries.clear(),this.assemblyStates.delete(this.topicId),this.logger.info("Syncing assembly messages",{topicId:this.topicId});try{const t=await this.client.mirrorNode.getTopicMessagesByFilter(this.topicId,{order:"asc",limit:1e3}),r=Array.isArray(t)?t:[];this.logger.info("Processing assembly messages",{topicId:this.topicId,messageCount:r.length});for(const i of r)try{let t;if(i.message)try{let e;e="undefined"==typeof window?globalThis.Buffer.from(i.message,"base64").toString("utf-8"):(new TextDecoder).decode(Uint8Array.from(atob(i.message),e=>e.charCodeAt(0))),t=JSON.parse(e)}catch(e){this.logger.debug("Failed to decode/parse message in sync",{sequenceNumber:i.sequence_number,error:e});continue}else if(i.raw_content)try{t=JSON.parse(i.raw_content)}catch{continue}else{const e=i;if(!e.p||!e.op)continue;t={...e},delete t.consensus_timestamp,delete t.sequence_number,delete t.payer_account_id,delete t.topic_id,delete t.running_hash,delete t.running_hash_version,delete t.chunk_info,delete t.created,delete t.payer}if("hcs-12"!==t.p)continue;const r={id:i.sequence_number.toString(),sequenceNumber:i.sequence_number,timestamp:i.consensus_timestamp||(new Date).toISOString(),submitter:i.payer_account_id||"unknown",data:t};this.entries.set(r.id,r),await this.processMessage(r),this.logger.debug("Processed sync message",{sequenceNumber:r.sequenceNumber,op:r.data.op})}catch(e){this.logger.warn("Failed to parse assembly message",{sequenceNumber:i.sequence_number,error:e})}this.logger.info("Assembly sync completed",{topicId:this.topicId,messageCount:r.length})}catch(e){throw this.logger.error("Failed to sync assembly",{error:e}),e}}else this.logger.warn("Cannot sync without topic ID and client")}validateMessage(e){try{Su(e)}catch(t){if(t instanceof r.ZodError){const e=t.errors.map(e=>`${e.path.join(".")}: ${e.message}`);throw new Error(`Assembly validation failed: ${e.join("; ")}`)}throw t}}}class Cu extends nu{constructor(e,t,r,i){super(e,t,ou.HASHLINKS,r,i)}async register(e){this.validateRegistration(e);const t=`${this.topicId||"local"}_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,r={id:t,sequenceNumber:0,timestamp:(new Date).toISOString(),submitter:this.client&&"getHashConnect"in this.client?"browser":this.client?.getOperatorAccountId()||"local",data:e};if(this.entries.set(t,r),this.client&&this.topicId)try{const i=JSON.stringify(e),o=await this.client.submitMessage(this.topicId,i);return o.sequenceNumber&&(r.sequenceNumber=o.sequenceNumber,r.id=o.sequenceNumber.toString(),this.entries.delete(t),this.entries.set(r.id,r)),this.logger.info("HashLink submitted to HCS",{transactionId:o.transactionId,sequenceNumber:o.sequenceNumber,topicId:this.topicId}),r.id}catch(i){throw this.logger.error("Failed to submit HashLink to HCS",{error:i}),this.entries.delete(t),i}return this.logger.info("HashLink registered in directory",{id:t,name:e.name,assemblyTopicId:e.t_id,tags:e.tags}),t}async searchByTags(e){return(await this.listEntries()).map(e=>e.data).filter(t=>!(!t.tags||0===t.tags.length)&&e.some(e=>t.tags?.includes(e)))}async searchByName(e){const t=await this.listEntries(),r=e.toLowerCase();return t.map(e=>e.data).filter(e=>e.name.toLowerCase().includes(r)||(e.description?.toLowerCase().includes(r)??!1))}async getFeatured(){return(await this.listEntries()).map(e=>e.data).filter(e=>!0===e.featured)}async getByCategory(e){return(await this.listEntries()).map(e=>e.data).filter(t=>t.category===e)}async getCategories(){const e=await this.listEntries(),t=new Set;return e.forEach(e=>{const r=e.data;r.category&&t.add(r.category)}),Array.from(t).sort()}async getAllTags(){const e=await this.listEntries(),t=new Set;return e.forEach(e=>{const r=e.data;r.tags&&r.tags.forEach(e=>t.add(e))}),Array.from(t).sort()}validateRegistration(e){this.validateBaseRegistration(e);const t=ku(e,Iu);if(!t.isValid)throw new Error(`HashLinks validation failed: ${t.errors.join(", ")}`);if(!e.t_id||!e.t_id.match(/^\d+\.\d+\.\d+$/))throw new Error("Valid assembly topic ID (t_id) is required");if(e.tags&&e.tags.length>10)throw new Error("Maximum 10 tags allowed");if(e.name.length>100)throw new Error("Name must be 100 characters or less");if(e.description&&e.description.length>500)throw new Error("Description must be 500 characters or less")}getStats(){const e=super.getStats(),t=Array.from(this.entries.values()),r=new Set,i=new Set;let o=0;return t.forEach(e=>{const t=e.data;t.category&&r.add(t.category),t.tags&&t.tags.forEach(e=>i.add(e)),t.featured&&o++}),{...e,categories:r.size,totalTags:i.size,featuredCount:o}}}class xu{constructor(e,t,r,i){this.cache=new Map,this.logger=e,this.assemblyRegistry=t,this.actionRegistry=r,this.blockLoader=i}async loadAssembly(e){this.logger.debug("Loading assembly",{topicId:e});const t=this.cache.get(e);if(t)return this.logger.debug("Assembly loaded from cache",{topicId:e}),t;try{const t=await this.assemblyRegistry.getAssemblyState(e);if(!t)throw new Error(`Assembly not found: ${e}`);const r={topicId:e,state:t,actions:[],blocks:[]};return this.cache.set(e,r),this.logger.debug("Assembly loaded successfully",{topicId:e,name:t.name,version:t.version,actionsCount:t.actions?.length||0,blocksCount:t.blocks?.length||0}),r}catch(r){throw this.logger.error("Failed to load assembly",{topicId:e,error:r}),new Error(`Failed to load assembly: ${r instanceof Error?r.message:"Unknown error"}`)}}async resolveReferences(e){this.logger.debug("Resolving assembly references",{name:e.name});const t={topicId:e.topicId,state:e,actions:[],blocks:[]};if(e.actions)for(const i of e.actions)try{const e=await this.resolveActionReference(i);t.actions.push({alias:i.alias,t_id:i.t_id,definition:e,config:i.config})}catch(r){this.logger.warn("Failed to resolve action reference",{t_id:i.t_id,alias:i.alias,error:r}),t.actions.push({alias:i.alias,t_id:i.t_id,definition:null,config:i.config,error:r instanceof Error?r.message:"Unknown error"})}if(e.blocks)for(const i of e.blocks)try{const{definition:e,template:r}=await this.resolveBlockReference(i);t.blocks.push({block_t_id:i.block_t_id,definition:e,template:r,attributes:i.attributes,actions:i.actions,children:i.children})}catch(r){this.logger.warn("Failed to resolve block reference",{block_t_id:i.block_t_id,error:r}),t.blocks.push({block_t_id:i.block_t_id,definition:null,attributes:i.attributes,actions:i.actions,children:i.children,error:r instanceof Error?r.message:"Unknown error"})}return t}validateComposition(e){const t=[];if(this.logger.debug("Validating assembly composition",{topicId:e.topicId}),e.state.name||t.push("Assembly must have a name"),e.state.version||t.push("Assembly must have a version"),e.state.blocks)for(const r of e.state.blocks){if(r.actions)for(const[i,o]of Object.entries(r.actions)){const n=e.state.actions?.some(e=>e.t_id===o);n||t.push(`Block ${r.block_t_id} references non-existent action: ${o} for key ${i}`)}if(r.children)for(const i of r.children){const o=e.state.blocks?.some(e=>e.block_t_id===i);o||t.push(`Block ${r.block_t_id} references non-existent child block: ${i}`)}}for(const r of e.actions)r.error&&t.push(`Action ${r.alias} has resolution error: ${r.error}`);for(const r of e.blocks)r.error&&t.push(`Block ${r.block_t_id} has resolution error: ${r.error}`);return{valid:0===t.length,errors:t}}async loadAndResolveAssembly(e){this.logger.debug("Loading and resolving assembly",{topicId:e});try{const t=await this.loadAssembly(e),r=await this.resolveReferences(t.state),i=this.validateComposition(r);return i.valid||this.logger.warn("Assembly validation failed",{topicId:e,errors:i.errors}),r}catch(t){throw this.logger.error("Failed to load and resolve assembly",{topicId:e,error:t}),new Error(`Failed to load and resolve assembly: ${t instanceof Error?t.message:"Unknown error"}`)}}async resolveActionReference(e){const t=await this.actionRegistry.getActionByTopicId(e.t_id);if(!t)throw new Error(`Action not found at topic: ${e.t_id}`);return t}async resolveBlockReference(e){return await this.blockLoader.loadBlock(e.block_t_id)}clearCache(){this.cache.clear(),this.logger.debug("Assembly cache cleared")}getCachedAssembly(e){return this.cache.get(e)}isAssemblyCached(e){return this.cache.has(e)}}class Ru{constructor(e){this.network=e.network,this.logger=e.logger||z.getInstance({level:e.logLevel||"info",module:"HCS12-BaseClient",prettyPrint:e.prettyPrint,silent:e.silent}),this.mirrorNode=new G(e.network,this.logger,e.mirrorNode)}initializeRegistries(e){this.actionRegistryTopicId=e?.action,this._assemblyRegistryTopicId=e?.assembly,this._hashLinksRegistryTopicId=e?.hashlinks}async registerAssembly(e){if(!this._assemblyRegistry)throw new Error("Assembly registry not initialized");return{id:await this._assemblyRegistry.register(e)}}async getAction(e){if(!this._actionRegistry)throw new Error("Action registry not initialized");return this._actionRegistry.getAction(e)}async loadBlock(e){return this._blockLoader||(this._blockLoader=new vu(this.network,this.logger,this)),this._blockLoader.loadBlock(e)}async getAssembly(e,t){if(!this._assemblyRegistry)throw new Error("Assembly registry not initialized");const r=await this._assemblyRegistry.listEntries();for(const i of r){const r=await this._assemblyRegistry.getAssemblyState(i.id);if(r&&r.name===e&&r.version===t)return r}return null}async loadAssembly(e){this._actionRegistry&&(this.logger.info("Syncing action registry before loading assembly"),await this._actionRegistry.sync());const t=new Au(this.network,this.logger,e,this);await t.sync();return new xu(this.logger,t,this._actionRegistry,this._blockLoader).loadAndResolveAssembly(e)}async getAssemblyState(e){if(!this._assemblyRegistry)throw new Error("Assembly registry not initialized");return this._assemblyRegistry.getAssemblyState(e)}ensureAssemblyEngine(){if(!this._assemblyEngine){if(!this._actionRegistry||!this._blockLoader||!this._assemblyRegistry)throw new Error("Registries must be initialized before assembly engine");this._assemblyEngine=new xu(this.logger,this._assemblyRegistry,this._actionRegistry,this._blockLoader)}}async registerHashLink(e){if(!this._hashLinksRegistry)throw new Error("HashLinks registry not initialized");return{id:await this._hashLinksRegistry.register(e)}}async searchHashLinksByTags(e){if(!this._hashLinksRegistry)throw new Error("HashLinks registry not initialized");return this._hashLinksRegistry.searchByTags(e)}async searchHashLinksByName(e){if(!this._hashLinksRegistry)throw new Error("HashLinks registry not initialized");return this._hashLinksRegistry.searchByName(e)}async getFeaturedHashLinks(){if(!this._hashLinksRegistry)throw new Error("HashLinks registry not initialized");return this._hashLinksRegistry.getFeatured()}async getHashLinksByCategory(e){if(!this._hashLinksRegistry)throw new Error("HashLinks registry not initialized");return this._hashLinksRegistry.getByCategory(e)}async syncRegistries(){const e=[];this._actionRegistry&&e.push(this._actionRegistry.sync()),this._assemblyRegistry&&e.push(this._assemblyRegistry.sync()),this._hashLinksRegistry&&e.push(this._hashLinksRegistry.sync()),await Promise.all(e)}getRegistryTopicIds(){return{action:this.actionRegistryTopicId,assembly:this._assemblyRegistryTopicId,hashlinks:this._hashLinksRegistryTopicId}}clearCaches(){this._actionRegistry?.clearCache(),this._blockLoader?.clearCache(),this._assemblyRegistry?.clearCache(),this._hashLinksRegistry?.clearCache()}get actionRegistry(){return this._actionRegistry}get blockLoader(){return this._blockLoader}get assemblyRegistry(){return this._assemblyRegistry}get hashLinksRegistry(){return this._hashLinksRegistry}}class Nu{constructor(){this.block={apiVersion:3},this.attributes={},this.supports={},this.actions={},this.logger=new z({module:"BlockBuilder"})}setName(e){return this.block.name=e,this}setTitle(e){return this.block.title=e,this}setDescription(e){return this.block.description=e,this}setCategory(e){return this.block.category=e,this}setIcon(e){return this.block.icon=e,this}setKeywords(e){return this.block.keywords=e,this}setApiVersion(e){return this.block.apiVersion=e,this}addAttribute(e,t,r,i){const o={type:t,default:r};return i?.enum&&(o.enum=i.enum),i?.source&&(o.source=i.source),i?.selector&&(o.selector=i.selector),i?.attribute&&(o.attribute=i.attribute),this.attributes[e]=o,this}setTemplateTopicId(e){return this.block.template_t_id=e,this}setTemplate(e){return this.templateBuffer=e,this}setActions(e){return this.actions=e,this}addAction(e,t){return this.actions[e]=t,this}addSupport(e,t=!0){return this.supports[e]=t,this}enableCommonSupports(){return this.supports={...this.supports,align:!0,anchor:!0,className:!0,spacing:{margin:!0,padding:!0}},this}build(){if(!this.block.name)throw new Error("Block name is required");if(!this.block.title)throw new Error("Block title is required");if(!this.block.category)throw new Error("Block category is required");if(!this.block.template_t_id)throw new Error("Block template_t_id is required");return{apiVersion:this.block.apiVersion||3,name:this.block.name,title:this.block.title,category:this.block.category,template_t_id:this.block.template_t_id,icon:this.block.icon,description:this.block.description,keywords:this.block.keywords,attributes:this.attributes,supports:this.supports}}static createDisplayBlock(e,t){return(new Nu).setName(e).setTitle(t).setCategory("formatting").enableCommonSupports()}static createInteractiveBlock(e,t){return(new Nu).setName(e).setTitle(t).setCategory("widgets").enableCommonSupports()}static createWidgetBlock(e,t){return this.createInteractiveBlock(e,t)}static createContainerBlock(e,t){return(new Nu).setName(e).setTitle(t).setCategory("design").enableCommonSupports().addSupport("html",!1)}getTemplate(){return this.templateBuffer}getActions(){return this.actions}setTopicId(e){return this.blockTopicId=e,this}getTopicId(){if(!this.blockTopicId)throw new Error("Block topic ID not set");return this.blockTopicId}getName(){return this.block.name}}class _u{constructor(e,t){this.wasmCache=new Map,this.logger=e,this.network=t,this.hrlResolver=new Ql}async execute(e,t){try{if(this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Executing WASM action",{actionId:e.t_id,method:t.method,hasJavaScript:!!e.js_t_id}),e.js_t_id)return await this.executeJavaScript(e,t);throw new Error("Raw WASM execution is not supported for wasm-bindgen modules. JavaScript wrapper is required.")}catch(r){return this.logger&&"function"==typeof this.logger.error?this.logger.error("WASM execution failed",{actionId:e.t_id,error:r.message}):console.error("WASM execution failed",{actionId:e.t_id,error:r.message}),{success:!1,error:r.message}}}readWasmString(e,t){const r=new Uint8Array(e.buffer);let i=0;for(;0!==r[t+i];)i++;return(new TextDecoder).decode(r.slice(t,t+i))}async executeJavaScript(e,t){try{if(this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Loading JavaScript wrapper",{jsTopicId:e.js_t_id}),"undefined"==typeof window){this.logger&&"function"==typeof this.logger.info&&this.logger.info("Executing JavaScript wrapper in Node.js environment");const t=await this.hrlResolver.resolve(e.js_t_id,{network:this.network,returnRaw:!1});if(!t.content||"string"!=typeof t.content)throw new Error("Failed to load JavaScript module: invalid content");await this.hrlResolver.resolve(e.t_id,{network:this.network,returnRaw:!0}),global,globalThis,WebAssembly,console,queueMicrotask,TextDecoder,TextEncoder,void 0!==globalThis.FinalizationRegistry&&globalThis.FinalizationRegistry,URL;throw new Error("WASM execution in Node.js/SSR environment is not supported. This functionality is browser-only.")}{const r=await this.hrlResolver.resolve(e.js_t_id,{network:this.network,returnRaw:!1});if(!r.content||"string"!=typeof r.content)throw new Error("Failed to load JavaScript module: invalid content");const i=new Blob([r.content],{type:"application/javascript"}),o=URL.createObjectURL(i);try{this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Importing JavaScript module from blob URL");const r=new Function("url","return import(url)"),i=await r(o);if(this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Module imported, exports:",Object.keys(i)),!i.default&&!i.init)throw new Error("No init function found in JavaScript module");{const t=i.default||i.init;this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Loading WASM bytes from topic:",e.t_id);const r=await this.hrlResolver.resolve(e.t_id,{network:this.network,returnRaw:!0});if(this.logger&&"function"==typeof this.logger.debug){const e=r.content instanceof ArrayBuffer?r.content.byteLength:r.content.length;this.logger.debug("WASM bytes loaded, size:",e)}await t({module_or_path:r.content}),this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("WASM module initialized successfully")}const n=i.WasmInterface;if(!n)throw new Error("WasmInterface not found in module exports. Available exports: "+Object.keys(i).join(", "));this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Creating WasmInterface instance");const s=new n;let a,c;if("POST"===t.method&&s.POST){const e=t.params.operation||"default",r={...t.params,...t.state},i=JSON.stringify(r);this.logger&&"function"==typeof this.logger.debug?this.logger.debug("Calling POST method",{actionName:e,paramsJson:i,allParams:r}):console.log("WASM POST params:",{actionName:e,paramsJson:i,allParams:r}),a=await s.POST(e,i,this.network.toString(),"")}else if("GET"===t.method&&s.GET){const e=t.params.operation||"default",r=JSON.stringify(t.params);this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Calling GET method",{actionName:e,paramsJson:r}),a=await s.GET(e,r,this.network.toString())}else{if("INFO"!==t.method||!s.INFO)throw new Error(`Method ${t.method} not supported by WASM module`);this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Calling INFO method"),a=s.INFO()}try{c=JSON.parse(a)}catch{c={value:a}}return s.free&&s.free(),URL.revokeObjectURL(o),{success:!0,data:c}}catch(eg){throw URL.revokeObjectURL(o),eg}}}catch(r){const t=r instanceof Error?r.message:String(r),i=r instanceof Error?r.stack:void 0;return this.logger&&"function"==typeof this.logger.error?this.logger.error("JavaScript execution failed",{jsTopicId:e.js_t_id,error:t,stack:i,fullError:r}):console.error("JavaScript execution failed",{jsTopicId:e.js_t_id,error:t,stack:i,fullError:r}),{success:!1,error:t||"Unknown error"}}}clearCache(){this.wasmCache.clear()}}class Pu{constructor(e){this.logger=e}async scanTemplate(e){const t=[],r=/<([^>]+)\s+data-hashlink=["']([^"']+)["']([^>]*)>/gs;let i;for(;null!==(i=r.exec(e));){const e=i[0],r=i[1].split(/\s+/)[0],n=i[2],s=i[3];try{const i=this.parseHashLinkURI(n),o=s.match(/data-attributes=(['"])((?:(?!\1).)*)\1/s);let a;if(o)try{const e=o[2];a=JSON.parse(e)}catch(eg){this.logger.warn("Failed to parse data-attributes",{uri:n,attributes:o[2],error:eg.message})}const c=s.match(/data-actions=(['"])((?:(?!\1).)*)\1/s);let l;if(c)try{const e=c[2];l=JSON.parse(e)}catch(eg){this.logger.warn("Failed to parse data-actions",{uri:n,actions:c[2],error:eg.message})}const d=s.match(/data-loading=['"]([^'"]+)['"]/),u=d?.[1]||"eager";t.push({element:r,uri:n,...i,attributes:a,actions:l,loading:u,placeholder:e}),this.logger.debug("Found HashLink reference",{uri:n,parsed:i})}catch(o){this.logger.error("Failed to parse HashLink URI",{uri:n,error:o.message})}}return t}parseHashLinkURI(e){const t=e.match(/^hcs:\/\/(\d+)\/(.+)$/);if(!t)throw new Error(`Invalid HashLink URI format: ${e}`);const r=t[1],i=t[2];if("2"===r){const e=i.split("/");if(2!==e.length)throw new Error(`Invalid HCS-2 reference format: ${i}`);return{protocol:r,reference:i,registryId:e[0],entryName:e[1]}}return{protocol:r,reference:i}}createPlaceholder(e,t){return`\x3c!-- HASHLINK_PLACEHOLDER_${t}_${e.uri.replace(/[^a-zA-Z0-9]/g,"_")} --\x3e`}}class Fu{constructor(e,t,r,i){this.logger=e,this.blockLoader=t,this.hrlResolver=r,this.network=i,this.cache=new Map,this.renderStack=new Set}async resolveReference(e,t){this.logger.debug("Resolving HashLink reference",{uri:e.uri,protocol:e.protocol});try{switch(e.protocol){case"12":return await this.resolveHCS12Block(e,t);case"1":return await this.resolveHCS1Block(e,t);case"2":return await this.resolveHCS2Block(e,t);default:throw new Error(`Unsupported HashLink protocol: ${e.protocol}`)}}catch(r){return this.logger.error("Failed to resolve HashLink",{uri:e.uri,error:r.message}),{blockId:e.reference,definition:null,template:null,attributes:{},actions:{},error:r.message}}}async resolveHCS12Block(e,t){const r=e.reference;if(this.renderStack.has(r))return{blockId:r,definition:null,template:null,attributes:{},actions:{},error:"Circular reference detected"};const i=this.getCacheKey(r,e.attributes,e.actions);if(this.cache.has(i))return this.cache.get(i);try{const o=await this.blockLoader.loadBlock(r);if(!o||!o.definition)throw new Error(`Block not found: ${r}`);const n={...this.extractDefaults(o.definition),...t.attributes,...e.attributes},s={...t.actions,...e.actions},a={blockId:r,definition:o.definition,template:o.template,attributes:n,actions:s};return this.cache.set(i,a),a}catch(o){throw this.renderStack.delete(r),new Error(`Failed to load HCS-12 block ${r}: ${o.message}`)}}async resolveHCS1Block(e,t){const r=e.reference;try{const t=await this.blockLoader.loadBlock(r);if(t&&t.definition)return{blockId:r,definition:t.definition,template:t.template,attributes:{...this.extractDefaults(t.definition),...e.attributes},actions:e.actions||{}};return{blockId:r,definition:null,template:(await this.hrlResolver.resolve(r,{network:this.network})).content,attributes:e.attributes||{},actions:e.actions||{}}}catch(i){throw new Error(`Failed to load HCS-1 content ${r}: ${i.message}`)}}async resolveHCS2Block(e,t){if(!e.registryId||!e.entryName)throw new Error("Invalid HCS-2 reference: missing registry ID or entry name");try{const t=`hcs://2/${e.registryId}`;await this.hrlResolver.resolve(t,{network:this.network});return this.logger.warn("HCS-2 registry lookup not fully implemented",{registryId:e.registryId,entryName:e.entryName}),{blockId:`${e.registryId}/${e.entryName}`,definition:null,template:`\x3c!-- HCS-2 lookup not implemented: ${e.uri} --\x3e`,attributes:e.attributes||{},actions:e.actions||{}}}catch(r){throw new Error(`Failed to resolve HCS-2 entry: ${r.message}`)}}extractDefaults(e){const t={};return e.attributes&&Object.entries(e.attributes).forEach(([e,r])=>{r&&"object"==typeof r&&"default"in r&&(t[e]=r.default)}),t}getCacheKey(e,t,r){return`${e}:${t?JSON.stringify(t):""}:${r?JSON.stringify(r):""}`}pushRenderStack(e){this.renderStack.add(e)}popRenderStack(e){this.renderStack.delete(e)}clearCache(){this.cache.clear()}}const Ou={ACTIONS:{CALCULATOR:"0.0.TBD1",NFT_MINT:"0.0.TBD2",TOKEN_TRANSFER:"0.0.TBD3"},BLOCKS:{BUTTON:"0.0.TBD4",NFT_GALLERY:"0.0.TBD5",FORM:"0.0.TBD6"},ASSEMBLIES:{NFT_MARKETPLACE:"0.0.TBD7",TOKEN_DASHBOARD:"0.0.TBD8"}},Du={ACTIONS:{},BLOCKS:{},ASSEMBLIES:{}};const zu=/^[a-z0-9][a-z0-9-]*$/,Bu=r.z.object({registry:r.z.string().min(1),name:r.z.string().min(1),version:r.z.string().min(1),protocol:r.z.string().min(1),nativeId:r.z.string().min(1),skills:r.z.array(r.z.number().int().nonnegative())});function Mu(e){return e.trim()}function Ku(e){return e.trim().toLowerCase()}function Uu(e){const t=Bu.parse(e);if("hcs-10"===t.protocol.trim().toLowerCase()&&!md(t.nativeId.trim()))throw new Error("HCS-14: For protocol hcs-10, nativeId must be CAIP-10 (hedera:<network>:<account>)");if("acp-virtuals"===t.protocol.trim().toLowerCase()&&!wd(t.nativeId.trim()))throw new Error("HCS-14: For protocol acp-virtuals, nativeId must be EIP-155 CAIP-10 (eip155:<chainId>:<address>)");const r={registry:Ku(t.registry),name:Mu(t.name),version:Mu(t.version),protocol:Ku(t.protocol),nativeId:Mu(t.nativeId),skills:[...t.skills].sort((e,t)=>e-t)},i=["skills","name","nativeId","protocol","registry","version"],o={};for(const n of i)o[n]=r[n];return{normalized:r,canonicalJson:JSON.stringify(o)}}const Lu="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function $u(e){if(0===e.length)return"";let t=0;for(;t<e.length&&0===e[t];)t++;if(t===e.length)return"1".repeat(t);const r=[0];for(let o=t;o<e.length;o++){let t=e[o];for(let e=0;e<r.length;e++){const i=(r[e]<<8)+t;r[e]=i%58,t=i/58|0}for(;t>0;)r.push(t%58),t=t/58|0}let i="";for(let o=0;o<t;o++)i+="1";for(let o=r.length-1;o>=0;o--)i+=Lu[r[o]];return i}function Hu(e){if(!e.startsWith("z"))throw new Error("Invalid multibase base58btc");return function(e){if(0===e.length)return new Uint8Array(0);let t=0;for(;t<e.length&&"1"===e[t];)t++;const r=[];for(let i=t;i<e.length;i++){const t=e[i],o=Lu.indexOf(t);if(-1===o)throw new Error("Invalid Base58 character");let n=o;for(let e=0;e<r.length;e++){const t=58*r[e]+n;r[e]=255&t,n=t>>8}for(;n>0;)r.push(255&n),n>>=8}for(let i=0;i<t;i++)r.push(0);return r.reverse(),Uint8Array.from(r)}(e.slice(1))}function qu(e){const t=[];return e.uid&&t.push(["uid",e.uid]),e.registry&&t.push(["registry",e.registry]),e.proto&&t.push(["proto",e.proto]),e.nativeId&&t.push(["nativeId",e.nativeId]),e.domain&&t.push(["domain",e.domain]),e.src&&t.push(["src",e.src]),0===t.length?"":t.map(([e,t])=>`${e}=${t}`).join(";")}function ju(e,t){let r,i;if(e.startsWith("uaid:aid:"))r="aid",i=e.slice(9);else{if(!e.startsWith("did:"))throw new Error("Invalid DID format");{const t=e.indexOf(":"),o=e.indexOf(":",t+1);if(o<0)throw new Error("Invalid DID format");r=e.slice(t+1,o),i=e.slice(o+1)}}const{sanitized:o,hadSuffix:n}=function(e){const t=e.search(/[;?#]/);return-1===t?{sanitized:e,hadSuffix:!1}:{sanitized:e.slice(0,t),hadSuffix:!0}}(i);let s=o;if("hedera"===r){const e=o.match(/^(mainnet|testnet|previewnet|devnet):(.+)$/);e&&(s=e[2])}const a={...t||{}};var c;n&&!a.src&&(a.src=(c=e,"z"+$u(globalThis.Buffer.from(c,"utf8"))));const l=qu(a);return l?`uaid:did:${s};${l}`:`uaid:did:${s}`}function Wu(e,t,r){return"string"==typeof e?ju(e,t):async function(e,t,r){const{normalized:i,canonicalJson:o}=Uu(e),n=ud().createHash("sha384").update(globalThis.Buffer.from(o,"utf8")).digest(),s=await Promise.resolve(n),a=$u(globalThis.Buffer.isBuffer(s)?s:globalThis.Buffer.from(s)),c=!1!==r?.includeParams,l=c?function(e,t){const r={...t};return r.registry||(r.registry=e.registry),r.nativeId||(r.nativeId=e.nativeId),r.uid||(r.uid="0"),r}(i,t||{}):{},d=c?qu(l):"";return d?`uaid:aid:${a};${d}`:`uaid:aid:${a}`}(e,t,r)}function Vu(e){if(e.startsWith("uaid:")){const t=e.slice(5);let r,i;if(t.startsWith("did:"))r="did",i=t.slice(4);else{if(!t.startsWith("aid:"))throw new Error("Invalid UAID");r="aid",i=t.slice(4)}const o=i.indexOf(";"),n=o>=0?i.slice(0,o):i,s=(e=>{const t={};if(!e)return t;const r=e.split(";");for(const i of r){const e=i.indexOf("=");if(e>0){const r=i.slice(0,e),o=i.slice(e+1);t[r]=o}}return t})(o>=0?i.slice(o+1):"");return{method:"did"===r?"uaid":"aid",id:n,params:s}}throw new Error("Invalid DID")}let Gu;function Ju(e,t){if(!t||"object"!=typeof t)return!1;const r=Reflect.get(t,"code"),i=Reflect.get(t,"message"),o="string"==typeof i?i:"";if("string"==typeof r&&r.includes("MODULE_NOT_FOUND"))return o.includes(e);if(o){const t=o.toLowerCase();if(t.includes("cannot find module")||t.includes("module not found")||t.includes("cannot find package"))return t.includes(e.toLowerCase())}return!1}async function Yu(e){try{return await import(e)}catch(t){if(Ju(e,t))return null;throw t}}async function Xu(e){if(Aa)return Yu(e);const t=await async function(){if(void 0!==Gu)return Gu;if(Aa)return Gu=null,Gu;try{const e="undefined"!=typeof global?global:globalThis,t=e.process?.mainModule?.require??e.require;Gu="function"==typeof t&&"function"==typeof t.resolve?t:null}catch{Gu=null}return Gu}();if(t)try{return t(e)}catch(r){if(!Ju(e,r))throw r}return Yu(e)}const Zu=["@hiero-did-sdk","resolver"].join("/");let Qu=null;class ep{constructor(){this.meta={id:"hedera/hiero-resolver",didMethods:["hedera"],caip2Networks:["hedera:mainnet","hedera:testnet","hedera:previewnet","hedera:devnet"],caip10Namespaces:["hedera"],displayName:"Hedera (Hiero Resolver)",description:"Resolves did:hedera identifiers via Hiero DID resolver.",homepage:"https://github.com/hiero-ledger/hiero-did-sdk-js"}}supports(e){return e.startsWith("did:hedera:")}async resolve(e){const t=await async function(){return Qu||(Qu=Xu(Zu).then(e=>e?.resolveDID??null)),Qu}();if(!t)throw new Error("Hiero resolver unavailable. Ensure @hiero-did-sdk/resolver is installed.");const r=await t(e);return r&&"string"==typeof r.id?{id:r.id}:null}}class tp{constructor(){this.resolvers=[]}register(e){this.resolvers.push(e)}list(){return[...this.resolvers]}filterByDidMethod(e){return this.resolvers.filter(t=>t.meta?.didMethods?.includes(e))}async resolveDid(e){for(const t of this.resolvers)if(t.supports(e))return t.resolve(e);return null}async resolveUaid(e){const t=Vu(e);if("uaid"!==t.method)return null;const r=t.params.src;if(r){const e=globalThis.Buffer.from(Hu(r)).toString("utf8");return this.resolveDid(e)}const i=t.id;if(i.startsWith("testnet:")||i.startsWith("mainnet:")||i.startsWith("previewnet:")||i.startsWith("devnet:")){const e=`did:hedera:${i}`;return this.resolveDid(e)}const o=t.params.proto,n=t.params.nativeId;if("hcs-10"===o&&n){const e=n.match(/^hedera:(mainnet|testnet|previewnet|devnet):/);if(e){const t=`did:hedera:${e[1]}:${i}`;return this.resolveDid(t)}}return null}}const rp=new tp;function ip(){rp.register(new ep)}class op{constructor(){this.issuers=[]}register(e){this.issuers.push(e)}list(){return[...this.issuers]}filterByDidMethod(e){return this.issuers.filter(t=>t.meta.didMethods.includes(e))}filterByCaip2(e){return this.issuers.filter(t=>t.meta.caip2Networks?.includes(e))}filter(e){return this.issuers.filter(e)}async issue(e){for(const t of this.issuers)if(t.supports(e.method))return t.issue(e);throw new Error(`No issuer registered for method: ${e.method}`)}}const np=new op,sp=["@hiero-did-sdk","registrar"].join("/");let ap=null;class cp{constructor(){this.meta={id:"hedera/hiero",didMethods:["hedera"],caip2Networks:["hedera:mainnet","hedera:testnet","hedera:previewnet","hedera:devnet"],caip10Namespaces:["hedera"],displayName:"Hedera (Hiero Registrar)",description:"Issues did:hedera identifiers using the Hiero DID registrar.",homepage:"https://github.com/hiero-ledger/hiero-did-sdk-js"}}supports(e){return"hedera"===e}async issue(e){if("hedera"!==e.method)throw new Error('HederaHieroIssuer only handles method "hedera"');if(!("client"in e))throw new Error("Hedera client is required to issue did:hedera");const t=await async function(){return ap||(ap=Xu(sp).then(e=>e?.createDID??null)),ap}();if(!t)throw new Error("Hiero registrar unavailable. Ensure @hiero-did-sdk/registrar is installed.");return(await t({},{client:e.client})).did}}class lp{constructor(e){this.registry=e?.registry??rp,this.issuers=new op,this.registerHederaIssuer(),this.registerHederaResolver(),this.logger=z.getInstance({module:"HCS-14"}),this.client=e?.client,this.network=e?.network,this.operatorId=e?.operatorId,!this.client&&e?.network&&e?.operatorId&&e?.privateKey&&this.configureHederaClient(e.network,e.operatorId,e.privateKey),e?.privateKey&&(this.operatorPrivateKey=e.privateKey),e?.hcs10Client&&(this.hcs10Client=e.hcs10Client)}configureHederaClient(e,t,r){const o=oe({network:e,operatorId:t,operatorKey:r,mirrorNode:new G(e),logger:this.logger,client:i.Client.forName(e)});this.operatorCtx=o,this.client=o.client,this.network=e,this.operatorId=t,this.operatorPrivateKey=r}async ensureInitializedHedera(){this.operatorCtx&&(await this.operatorCtx.ensureInitialized(),this.operatorId||(this.operatorId=this.operatorCtx.operatorId.toString()),this.operatorPrivateKey||(this.operatorPrivateKey=this.operatorCtx.operatorKey.toString()),this.client||(this.client=this.operatorCtx.client))}getIssuerRegistry(){return this.issuers}listIssuers(){return this.issuers.list()}listResolvers(){return this.registry.list()}filterIssuersByMethod(e){return this.issuers.filterByDidMethod(e)}filterResolversByMethod(e){return this.registry.filterByDidMethod(e)}registerHederaIssuer(){this.issuers.register(new cp)}async createDid(e){return this.issuers.issue(e)}canonicalizeAgentData(e){return Uu(e)}createUaid(e,t,r){return"string"==typeof e?Wu(e,t):Wu(e,t,r)}parseHcs14Did(e){return Vu(e)}isHederaNetwork(e){return hd(e)}isHederaCaip10(e){return md(e)}toHederaCaip10(e,t){return fd(e,t)}parseHederaCaip10(e){return yd(e)}isEip155Caip10(e){return wd(e)}toEip155Caip10(e,t){return Id(e,t)}getResolverRegistry(){return this.registry}registerHederaResolver(){this.registry.register(new ep)}async createDidWithUaid(e){const t=await this.createDid(e.issue);let r=e.uid;const i=e.proto;let o=e.nativeId;if("hedera"===e.issue.method){if(await this.ensureInitializedHedera(),!o){if(!this.network||!this.operatorId)throw new Error("nativeId not provided and network/operatorId are not configured");o=fd(this.network,this.operatorId)}if(!r&&"hcs-10"===i&&this.network&&this.operatorId)try{if(!this.hcs10Client&&this.operatorPrivateKey&&(this.hcs10Client=new ru({network:this.network,operatorId:this.operatorId,operatorPrivateKey:this.operatorPrivateKey,silent:!0})),this.hcs10Client)r=await this.hcs10Client.getOperatorId();else{const e=new Dd({network:this.network,auth:{operatorId:this.operatorId},silent:!0}),t=await e.fetchProfileByAccountId(this.operatorId,this.network),i=t?.topicInfo?.inboundTopic;r=i?`${i}@${this.operatorId}`:this.operatorId}}catch{r=this.operatorId}}r=r??"0";const n=this.createUaid(t,{uid:r,proto:i,nativeId:o});return{did:t,uaid:n,parsed:Vu(n)}}}const dp=Object.freeze(Object.defineProperty({__proto__:null,CanonicalAgentDataSchema:Bu,HCS14Client:lp,HCS14_PROTOCOL_REGEX:zu,HederaHieroIssuer:cp,HieroDidResolver:ep,IssuerRegistry:op,ResolverRegistry:tp,canonicalizeAgentData:Uu,createUaid:Wu,defaultIssuerRegistry:np,defaultResolverRegistry:rp,isEip155Caip10:wd,isHederaCaip10:md,isHederaNetwork:hd,parseHcs14Did:Vu,parseHederaCaip10:yd,registerDefaultResolvers:ip,toEip155Caip10:Id,toHederaCaip10:fd},Symbol.toStringTag,{value:"Module"}));function up(e){return`hcs://1/${e}`}class pp{constructor(e){this.network=e.network,this.logger=e.logger||z.getInstance({level:e.logLevel||"info",module:"HCS5Client",silent:e.silent}),this.mirrorNode=new G(this.network,this.logger)}}function hp(e){const t=(new i.TokenMintTransaction).setTokenId(i.TokenId.fromString(e.tokenId)).setMetadata([globalThis.Buffer.from(e.metadata)]);return e.transactionMemo&&t.setTransactionMemo(e.transactionMemo),t}var gp=(e=>(e.REGISTER="register",e.UPDATE="update",e.DELETE="delete",e.MIGRATE="migrate",e))(gp||{}),mp=(e=>(e[e.INDEXED=0]="INDEXED",e[e.NON_INDEXED=1]="NON_INDEXED",e))(mp||{});const fp=r.z.string().regex(/^\d+\.\d+\.\d+$/,{message:"Topic ID must be in Hedera format (e.g., '0.0.123456')"}),yp=r.z.object({p:r.z.string().regex(/^hcs-\d+$/,{message:"Protocol must be in format 'hcs-N' where N is a number"}),op:r.z.enum(["register","update","delete","migrate"]),m:r.z.string().max(500,"Memo must not exceed 500 characters").optional(),ttl:r.z.number().int().positive().optional()}),bp=yp.extend({op:r.z.literal("register"),t_id:fp,metadata:r.z.string().optional()}),wp=yp.extend({op:r.z.literal("update"),uid:r.z.string(),t_id:fp,metadata:r.z.string().optional()}),Ip=yp.extend({op:r.z.literal("delete"),uid:r.z.string()}),Tp=yp.extend({op:r.z.literal("migrate"),t_id:fp,metadata:r.z.string().optional()}),Sp=r.z.discriminatedUnion("op",[bp,wp,Ip,Tp]);class kp{constructor(e){this.network=e.network,this.logger=e.logger||z.getInstance({level:e.logLevel||"info",module:"HCS2Client",silent:e.silent}),this.mirrorNode=new G(this.network,this.logger,e.mirrorNodeUrl?{customUrl:e.mirrorNodeUrl}:void 0)}parseRegistryTypeFromMemo(e){try{const t=/hcs-2:(\d):(\d+)/,r=e.match(t);if(r&&3===r.length){const e=parseInt(r[1]),t=parseInt(r[2]);if(void 0!==e&&!isNaN(t))return{registryType:e,ttl:t}}return}catch(t){return void this.logger.error(`Error parsing registry type from memo: ${t}`)}}generateRegistryMemo(e,t){return`hcs-2:${e}:${t}`}validateMessage(e){try{return Sp.parse(e),{valid:!0,errors:[]}}catch(t){const e=[];return t instanceof r.ZodError?t.errors.forEach(t=>{const r=t.path.join(".");e.push(`${r?r+": ":""}${t.message}`)}):e.push(`Unexpected error: ${t}`),this.logger.debug(`Message validation failed: ${e.join(", ")}`),{valid:!1,errors:e}}}createRegisterMessage(e,t,r,i="hcs-2"){return{p:i,op:gp.REGISTER,t_id:e,metadata:t,m:r}}createUpdateMessage(e,t,r,i,o="hcs-2"){return{p:o,op:gp.UPDATE,t_id:e,uid:t,metadata:r,m:i}}createDeleteMessage(e,t,r="hcs-2"){return{p:r,op:gp.DELETE,uid:e,m:t}}createMigrateMessage(e,t,r,i="hcs-2"){return{p:i,op:gp.MIGRATE,t_id:e,metadata:t,m:r}}parseRegistryEntries(e,t,r,i){const o=[];let n;this.logger.debug(`Parsing ${t.length} messages for topic ${e}`);for(const a of t)try{if(!a.message){this.logger.debug(`Message is missing 'message' property: ${JSON.stringify(a)}`);continue}const t=globalThis.Buffer.from(a.message,"base64").toString("utf-8"),i=JSON.parse(t);this.logger.debug(`Successfully parsed message: ${JSON.stringify(i)}`);const{valid:s,errors:c}=this.validateMessage(i);if(!s){this.logger.warn(`Invalid HCS-2 message: ${c.join(", ")}`);continue}const l={topicId:e,sequence:a.sequence_number,timestamp:a.consensus_timestamp,payer:a.payer_account_id,message:i,consensus_timestamp:a.consensus_timestamp,registry_type:r};o.push(l),(r===mp.NON_INDEXED||!n||l.timestamp>n.timestamp)&&(n=l)}catch(s){this.logger.warn(`Error parsing message: ${s}`)}return this.logger.debug(`Parsed ${o.length} valid entries for topic ${e}`),{topicId:e,registryType:r,ttl:i,entries:r===mp.INDEXED?o:n?[n]:[],latestEntry:n}}}function Ep(e){var t,r;return Y({memo:e.memoOverride??(t=e.registryType,r=e.ttl,`hcs-2:${t}:${r}`),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}const vp=class e extends kp{constructor(e){super({network:e.network,logLevel:e.logLevel,silent:e.silent,mirrorNodeUrl:e.mirrorNodeUrl,logger:e.logger}),this.registryTypeCache=new Map,this.operatorId="string"==typeof e.operatorId?i.AccountId.fromString(e.operatorId):e.operatorId,this.operatorCtx=oe({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:this.createClient(e.network)}),this.client=this.operatorCtx.client}async ensureInitialized(){await this.operatorCtx.ensureInitialized()}createClient(e){return"mainnet"===e?i.Client.forMainnet():i.Client.forTestnet()}async createRegistry(e={}){try{await this.ensureInitialized();const t=e.registryType??mp.INDEXED,r=e.ttl??86400;this.generateRegistryMemo(t,r);let o,n,s,a;if(e.adminKey)if("string"==typeof e.adminKey)try{n=i.PublicKey.fromString(e.adminKey)}catch{const t=globalThis.Buffer.from(e.adminKey.replace(/^0x/i,""),"hex");n="ed25519"===this.operatorCtx.keyType?i.PublicKey.fromBytesED25519(t):i.PublicKey.fromBytesECDSA(t)}else"boolean"==typeof e.adminKey?n=this.operatorCtx.operatorKey.publicKey:(n=e.adminKey.publicKey,o=e.adminKey);if(e.submitKey)if("string"==typeof e.submitKey)try{a=i.PublicKey.fromString(e.submitKey)}catch{const t=globalThis.Buffer.from(e.submitKey.replace(/^0x/i,""),"hex");a="ed25519"===this.operatorCtx.keyType?i.PublicKey.fromBytesED25519(t):i.PublicKey.fromBytesECDSA(t)}else"boolean"==typeof e.submitKey?a=this.operatorCtx.operatorKey.publicKey:(a=e.submitKey.publicKey,s=e.submitKey);const c=Ep({registryType:t,ttl:r,adminKey:n,submitKey:a,operatorPublicKey:this.operatorCtx.operatorKey.publicKey}),l=await c.freezeWith(this.client);o&&await l.sign(o),s&&await l.sign(s);const d=await l.execute(this.client),u=(await d.getReceipt(this.client)).topicId;if(!u)throw new Error("Failed to create registry: No topic ID in receipt");const p=u.toString();return this.registryTypeCache.set(p,t),this.logger.info(`Created registry topic: ${p} (${t===mp.INDEXED?"Indexed":"Non-indexed"}, TTL: ${r}s)`),{success:!0,topicId:p,transactionId:d.transactionId.toString()}}catch(t){return this.logger.error(`Failed to create registry: ${t}`),{success:!1,error:`Failed to create registry: ${t}`}}}async registerEntry(e,t,r="hcs-2"){try{await this.ensureInitialized();const i=this.createRegisterMessage(t.targetTopicId,t.metadata,t.memo,r),o=t.registryType??await this.resolveRegistryType(e);this.registryTypeCache.set(e,o);const n=t.analyticsMemo??this.buildAnalyticsMemo(gp.REGISTER,o),s=await this.submitMessage(e,i,n);return this.logger.info(`Registered entry in registry ${e} pointing to topic ${t.targetTopicId} using protocol ${r}`),{success:!0,receipt:s,sequenceNumber:s.topicSequenceNumber?.low??void 0}}catch(i){return this.logger.error(`Failed to register entry: ${i}`),{success:!1,error:`Failed to register entry: ${i}`}}}async updateEntry(e,t){try{await this.ensureInitialized();const r=await this.mirrorNode.getTopicInfo(e),i=this.parseRegistryTypeFromMemo(r.memo);if(!i||i.registryType!==mp.INDEXED)throw new Error("Update operation is only valid for indexed registries");const o=this.createUpdateMessage(t.targetTopicId,t.uid,t.metadata,t.memo),n=t.registryType??await this.resolveRegistryType(e);this.registryTypeCache.set(e,n);const s=t.analyticsMemo??this.buildAnalyticsMemo(gp.UPDATE,n),a=await this.submitMessage(e,o,s);return this.logger.info(`Updated entry with UID ${t.uid} in registry ${e}`),{success:!0,receipt:a,sequenceNumber:a.topicSequenceNumber?.low??void 0}}catch(r){throw this.logger.error(`Failed to update entry: ${r}`),r}}async deleteEntry(e,t){try{await this.ensureInitialized();const r=await this.mirrorNode.getTopicInfo(e),i=this.parseRegistryTypeFromMemo(r.memo);if(!i||i.registryType!==mp.INDEXED)throw new Error("Delete operation is only valid for indexed registries");const o=this.createDeleteMessage(t.uid,t.memo),n=t.registryType??await this.resolveRegistryType(e);this.registryTypeCache.set(e,n);const s=t.analyticsMemo??this.buildAnalyticsMemo(gp.DELETE,n),a=await this.submitMessage(e,o,s);return this.logger.info(`Deleted entry with UID ${t.uid} from registry ${e}`),{success:!0,receipt:a,sequenceNumber:a.topicSequenceNumber?.low??void 0}}catch(r){throw this.logger.error(`Failed to delete entry: ${r}`),r}}async migrateRegistry(e,t){try{await this.ensureInitialized();const r=this.createMigrateMessage(t.targetTopicId,t.metadata,t.memo),i=t.registryType??await this.resolveRegistryType(e);this.registryTypeCache.set(e,i);const o=t.analyticsMemo??this.buildAnalyticsMemo(gp.MIGRATE,i),n=await this.submitMessage(e,r,o);return this.logger.info(`Migrated registry ${e} to ${t.targetTopicId}`),{success:!0,receipt:n,sequenceNumber:n.topicSequenceNumber?.low??void 0}}catch(r){throw this.logger.error(`Failed to migrate registry: ${r}`),r}}async getRegistry(e,t={}){try{await this.ensureInitialized();const i=await this.mirrorNode.getTopicInfo(e);this.logger.debug(`Retrieved topic info for ${e}: ${JSON.stringify(i)}`);const o=this.parseRegistryTypeFromMemo(i.memo);if(!o)throw new Error(`Topic ${e} is not an HCS-2 registry (invalid memo format)`);this.logger.debug(`Retrieving messages for topic ${e} with limit ${t.limit??100}`);const n=await this.mirrorNode.getTopicMessages(e,{sequenceNumber:t.skip&&t.skip>0?`gt:${t.skip}`:void 0,limit:t.limit??100,order:t.order??"asc"}),s=t.limit?n.slice(0,t.limit):n;this.logger.debug(`Retrieved ${n.length} messages, using ${s.length} after applying limit.`);const a=[];let c;for(const t of s)try{const r={p:"hcs-2",op:t.op,t_id:t.t_id,uid:t.uid,metadata:t.metadata,m:t.m},{valid:i,errors:n}=this.validateMessage(r);if(!i){this.logger.warn(`Invalid HCS-2 message: ${n.join(", ")}`);continue}const s={topicId:e,sequence:t.sequence_number,timestamp:t.consensus_timestamp,payer:t.payer_account_id||t.payer||"",message:r,consensus_timestamp:t.consensus_timestamp,registry_type:o.registryType};a.push(s),(o.registryType===mp.NON_INDEXED||!c||s.timestamp>c.timestamp)&&(c=s)}catch(r){this.logger.warn(`Error processing message: ${r}`)}this.logger.debug(`Processed ${a.length} valid entries for registry ${e}`);return{topicId:e,registryType:o.registryType,ttl:o.ttl,entries:o.registryType===mp.INDEXED?a:c?[c]:[],latestEntry:c}}catch(r){throw this.logger.error(`Failed to get registry: ${r}`),r}}buildAnalyticsMemo(t,r){return`hcs-2:op:${e.operationAnalyticsCode[t]}:${r}`}async resolveRegistryType(e){const t=this.registryTypeCache.get(e);if(void 0!==t)return t;const r=await this.mirrorNode.getTopicInfo(e),i=this.parseRegistryTypeFromMemo(r.memo);if(!i)throw new Error(`Topic ${e} is not an HCS-2 registry (invalid memo format)`);return this.registryTypeCache.set(e,i.registryType),i.registryType}async submitMessage(e,t,r){try{await this.ensureInitialized();const{valid:i,errors:o}=this.validateMessage(t);if(!i)throw new Error(`Invalid HCS-2 message: ${o.join(", ")}`);const n=X({topicId:e,message:JSON.stringify(t),transactionMemo:r}),s=await n.execute(this.client);return await s.getReceipt(this.client)}catch(i){throw this.logger.error(`Failed to submit message: ${i}`),i}}async getTopicInfo(e){return this.mirrorNode.getTopicInfo(e)}close(){this.logger.info("HCS-2 client closed.")}getKeyType(){return this.operatorCtx.keyType}getOperatorKey(){return this.operatorCtx.operatorKey}};vp.operationAnalyticsCode={[gp.REGISTER]:0,[gp.UPDATE]:1,[gp.DELETE]:2,[gp.MIGRATE]:3};let Ap=vp;class Cp extends kp{constructor(e){super({network:e.network,logLevel:e.logLevel,silent:e.silent,mirrorNodeUrl:e.mirrorNodeUrl,logger:e.logger}),this.hwc=e.hwc,Aa?this.logger.info("HCS-2 browser client initialized successfully"):this.logger.error("BrowserHCS2Client initialized in server environment - browser-specific features will not be available. Use HCS2Client instead.")}getOperatorId(){const e=this.hwc.getAccountInfo();if(!e||!e.accountId)throw new Error("No connected account found");return e.accountId}async createRegistry(e={}){try{const t=e.registryType??mp.INDEXED,r=e.ttl??86400,o=this.generateRegistryMemo(t,r);let n=(new i.TopicCreateTransaction).setTopicMemo(o);if(e.adminKey){let t;if("string"==typeof e.adminKey)try{t=i.PublicKey.fromString(e.adminKey)}catch{const r=te.detect(e.adminKey);if(!r.rawBytes)throw new Error("Failed to parse admin public key");t="ed25519"===r.type?i.PublicKey.fromBytesED25519(r.rawBytes):i.PublicKey.fromBytesECDSA(r.rawBytes)}else t="boolean"==typeof e.adminKey?await this.mirrorNode.getPublicKey(this.getOperatorId()):e.adminKey.publicKey;n=n.setAdminKey(t)}if(e.submitKey){let t;if("string"==typeof e.submitKey)try{t=i.PublicKey.fromString(e.submitKey)}catch{const r=te.detect(e.submitKey);if(!r.rawBytes)throw new Error("Failed to parse submit public key");t="ed25519"===r.type?i.PublicKey.fromBytesED25519(r.rawBytes):i.PublicKey.fromBytesECDSA(r.rawBytes)}else t="boolean"==typeof e.submitKey?await this.mirrorNode.getPublicKey(this.getOperatorId()):e.submitKey.publicKey;n=n.setSubmitKey(t)}const s=await this.executeWithWallet(n);if(s?.error)throw new Error(s.error);const a=s?.result;if(!a?.topicId)throw new Error("Failed to create registry: No topic ID in receipt");const c=a.topicId.toString();return this.logger.info(`Created registry topic: ${c} (${t===mp.INDEXED?"Indexed":"Non-indexed"}, TTL: ${r}s)`),{success:!0,topicId:c,transactionId:s.transactionId||"unknown"}}catch(t){return this.logger.error(`Failed to create registry: ${t}`),{success:!1,error:`Failed to create registry: ${t}`}}}async registerEntry(e,t){try{const r=this.createRegisterMessage(t.targetTopicId,t.metadata,t.memo);if(r.op!==gp.REGISTER)throw new Error(`Invalid operation type: ${r.op}, expected ${gp.REGISTER}`);const i=await this.submitMessage(e,r);return this.logger.info(`Registered entry in registry ${e} pointing to topic ${t.targetTopicId}`),{success:!0,receipt:i,sequenceNumber:i.topicSequenceNumber?.low??void 0}}catch(r){return this.logger.error(`Failed to register entry: ${r}`),{success:!1,error:`Failed to register entry: ${r}`}}}async updateEntry(e,t){try{const r=await this.mirrorNode.getTopicInfo(e),i=this.parseRegistryTypeFromMemo(r.memo);if(!i||i.registryType!==mp.INDEXED)throw new Error("Update operation is only valid for indexed registries");const o=this.createUpdateMessage(t.targetTopicId,t.uid,t.metadata,t.memo),n=await this.submitMessage(e,o);return this.logger.info(`Updated entry with UID ${t.uid} in registry ${e}`),{success:!0,receipt:n,sequenceNumber:n.topicSequenceNumber?.low??void 0}}catch(r){return this.logger.error(`Failed to update entry: ${r}`),{success:!1,error:`Failed to update entry: ${r}`}}}async deleteEntry(e,t){try{const r=await this.mirrorNode.getTopicInfo(e),i=this.parseRegistryTypeFromMemo(r.memo);if(!i||i.registryType!==mp.INDEXED)throw new Error("Delete operation is only valid for indexed registries");const o=this.createDeleteMessage(t.uid,t.memo),n=await this.submitMessage(e,o);return this.logger.info(`Deleted entry with UID ${t.uid} from registry ${e}`),{success:!0,receipt:n,sequenceNumber:n.topicSequenceNumber?.low??void 0}}catch(r){return this.logger.error(`Failed to delete entry: ${r}`),{success:!1,error:`Failed to delete entry: ${r}`}}}async migrateRegistry(e,t){try{const r=this.createMigrateMessage(t.targetTopicId,t.metadata,t.memo),i=await this.submitMessage(e,r);return this.logger.info(`Migrated registry ${e} to ${t.targetTopicId}`),{success:!0,receipt:i,sequenceNumber:i.topicSequenceNumber?.low??void 0}}catch(r){return this.logger.error(`Failed to migrate registry: ${r}`),{success:!1,error:`Failed to migrate registry: ${r}`}}}async getRegistry(e,t={}){try{const r=await this.mirrorNode.getTopicInfo(e),i=this.parseRegistryTypeFromMemo(r.memo);if(!i)throw new Error(`Topic ${e} is not an HCS-2 registry (invalid memo format)`);const o=await this.mirrorNode.getTopicMessages(e,{sequenceNumber:t.skip&&t.skip>0?`gt:${t.skip}`:void 0,limit:t.limit??100,order:t.order??"asc"}),n=t.limit?o.slice(0,t.limit):o;return this.parseRegistryEntries(e,n,i.registryType,i.ttl)}catch(r){throw this.logger.error(`Failed to get registry: ${r}`),r}}async submitMessage(e,t){try{const{valid:r,errors:i}=this.validateMessage(t);if(!r)throw new Error(`Invalid HCS-2 message: ${i.join(", ")}`);const o=X({topicId:e,message:JSON.stringify(t)}),n=await this.executeWithWallet(o);if(n?.error)throw new Error(n.error);return n.result}catch(r){throw this.logger.error(`Failed to submit message: ${r}`),r}}async executeWithWallet(e){const t=this.hwc.executeTransactionWithErrorHandling;if(!t)throw new Error("Wallet SDK does not support executeTransactionWithErrorHandling");return await t.call(this.hwc,e,!1)}}const xp={PROTOCOL:"hcs-20",PUBLIC_TOPIC_ID:"0.0.4350190",REGISTRY_TOPIC_ID:"0.0.4362300",MAX_NUMBER_LENGTH:18,MAX_NAME_LENGTH:100,MAX_METADATA_LENGTH:100,HEDERA_ACCOUNT_REGEX:/^(0|(?:[1-9]\d*))\.(0|(?:[1-9]\d*))\.(0|(?:[1-9]\d*))$/},Rp=r.z.string().regex(xp.HEDERA_ACCOUNT_REGEX,"Invalid Hedera account ID format"),Np=r.z.string().regex(/^\d+$/,"Must be a valid number").max(xp.MAX_NUMBER_LENGTH,`Max ${xp.MAX_NUMBER_LENGTH} digits`),_p=r.z.string().min(1,"Tick cannot be empty").transform(e=>e.toLowerCase().trim()),Pp=r.z.object({p:r.z.literal("hcs-20"),m:r.z.string().optional()}),Fp=Pp.extend({op:r.z.literal("deploy"),name:r.z.string().min(1).max(xp.MAX_NAME_LENGTH),tick:_p,max:Np,lim:Np.optional(),metadata:r.z.string().max(xp.MAX_METADATA_LENGTH).optional()}),Op=Pp.extend({op:r.z.literal("mint"),tick:_p,amt:Np,to:Rp}),Dp=Pp.extend({op:r.z.literal("burn"),tick:_p,amt:Np,from:Rp}),zp=Pp.extend({op:r.z.literal("transfer"),tick:_p,amt:Np,from:Rp,to:Rp}),Bp=Pp.extend({op:r.z.literal("register"),name:r.z.string().min(1).max(xp.MAX_NAME_LENGTH),metadata:r.z.string().max(xp.MAX_METADATA_LENGTH).optional(),private:r.z.boolean(),t_id:Rp}),Mp=r.z.discriminatedUnion("op",[Fp,Op,Dp,zp,Bp]);class Kp extends Error{constructor(e){super(e),this.name="HCS20Error"}}class Up extends Kp{constructor(e,t){super(e),this.tick=t,this.name="PointsDeploymentError"}}class Lp extends Kp{constructor(e,t,r,i,o,n){super(e),this.tick=t,this.from=r,this.to=i,this.amount=o,this.availableBalance=n,this.name="PointsTransferError"}}class $p extends Kp{constructor(e,t,r,i,o){super(e),this.tick=t,this.from=r,this.amount=i,this.availableBalance=o,this.name="PointsBurnError"}}class Hp extends Kp{constructor(e,t){super(e),this.validationErrors=t,this.name="PointsValidationError"}}class qp extends Kp{constructor(e,t){super(e),this.topicId=t,this.name="TopicRegistrationError"}}class jp extends Kp{constructor(e){super(`Invalid Hedera account format: ${e}`),this.account=e,this.name="InvalidAccountFormatError"}}class Wp{constructor(e){this.logger=e.logger||new z({module:"HCS20Client"}),this.network="mainnet"===e.network?"mainnet":"testnet",this.mirrorNode=new G(this.network,this.logger,e.mirrorNodeUrl?{customUrl:e.mirrorNodeUrl}:void 0),this.registryTopicId=e.registryTopicId||xp.REGISTRY_TOPIC_ID,this.publicTopicId=e.publicTopicId||xp.PUBLIC_TOPIC_ID}validateMessage(e){try{return Mp.parse(e),{valid:!0}}catch(t){if(t.errors){return{valid:!1,errors:t.errors.map(e=>`${e.path.join(".")}: ${e.message}`)}}return{valid:!1,errors:[t.message]}}}normalizeTick(e){return e.toLowerCase().trim()}accountToString(e){if("string"==typeof e){if(!xp.HEDERA_ACCOUNT_REGEX.test(e))throw new jp(e);return e}return e.toString()}topicToString(e){if("string"==typeof e){if(!xp.HEDERA_ACCOUNT_REGEX.test(e))throw new jp(e);return e}return e.toString()}}function Vp(e){const t={p:"hcs-20",op:"deploy",name:e.name,tick:e.tick.toLowerCase().trim(),max:e.max,lim:e.lim,metadata:e.metadata,m:e.memo};return X({topicId:e.topicId,message:JSON.stringify(t)})}function Gp(e){const t={p:"hcs-20",op:"mint",tick:e.tick.toLowerCase().trim(),amt:e.amt,to:e.to,m:e.memo};return X({topicId:e.topicId,message:JSON.stringify(t)})}function Jp(e){const t={p:"hcs-20",op:"transfer",tick:e.tick.toLowerCase().trim(),amt:e.amt,from:e.from,to:e.to,m:e.memo};return X({topicId:e.topicId,message:JSON.stringify(t)})}function Yp(e){const t={p:"hcs-20",op:"burn",tick:e.tick.toLowerCase().trim(),amt:e.amt,from:e.from,m:e.memo};return X({topicId:e.topicId,message:JSON.stringify(t)})}function Xp(e){const t={p:"hcs-20",op:"register",name:e.name,metadata:e.metadata,private:e.isPrivate,t_id:e.topicId,m:e.memo};return X({topicId:e.registryTopicId,message:JSON.stringify(t)})}const Zp="hcs-21",Qp=["npm","pypi","oci","composer","packagist","cargo","nuget","maven","rubygems","helm","go"],eh=/^hcs:\/\/1\/0\.0\.\d+\/\d+$/;var th=(e=>(e[e.REGISTRY=0]="REGISTRY",e))(th||{});const rh=r.z.object({p:r.z.literal(Zp),op:r.z.enum(["register","update"]),registry:r.z.enum(Qp),t_id:r.z.string().min(1),n:r.z.string().min(1),d:r.z.string().min(1),a:r.z.string().min(1),tags:r.z.array(r.z.string().min(1)).max(16).optional(),metadata:r.z.string().regex(eh,"metadata must be an HCS-1 HRL (hcs://1/<topicId>/<sequence>)").optional()});class ih extends Error{constructor(e,t){super(e),this.code=t,this.name="HCS21ValidationError"}}function oh(e){return`hcs-21:${e.indexed??0}:${e.ttl}:${th.REGISTRY}`}function nh(e){return Y({memo:oh({ttl:e.ttl,indexed:e.indexed}),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function sh(e){return X({topicId:e.topicId,message:JSON.stringify(e.declaration),transactionMemo:e.transactionMemo})}class ah{constructor(e){this.network=e.network,this.logger=e.logger||new z({level:"info",module:"HCS-21"}),this.mirrorNode=new G(this.network,this.logger,{customUrl:e.mirrorNodeUrl})}buildDeclaration(e){const t={p:Zp,op:e.op,registry:e.registry,t_id:e.t_id,n:e.name,d:e.description,a:e.author,tags:e.tags,metadata:e.metadata};return this.validateDeclaration(t)}validateDeclaration(e){try{const t="string"==typeof e?JSON.parse(e):e,r=rh.parse(t);return this.assertSizeLimit(r),r}catch(t){const e=t instanceof Error?t.message:"Invalid package declaration";throw new ih(e,"invalid_payload")}}async fetchDeclarations(e,t){const r=await this.mirrorNode.getTopicMessages(e,{limit:t?.limit,order:t?.order}),i=[];for(const n of r)if(n.p===Zp)try{const e=this.validateDeclaration(n);i.push({declaration:e,consensusTimestamp:n.consensus_timestamp,sequenceNumber:n.sequence_number,payer:n.payer})}catch(o){const e=o instanceof Error?o.message:"unknown error";this.logger.warn(`Skipping invalid HCS-21 message: ${e}`)}return i}assertSizeLimit(e){const t=JSON.stringify(e),r=globalThis.Buffer.byteLength(t,"utf8");if(r>1024)throw new ih(`HCS-21 payload exceeds 1024 bytes (${r})`,"size_exceeded")}}function ch(e){const t=(new i.AccountCreateTransaction).setECDSAKeyWithAlias(e.publicKey).setInitialBalance(e.initialBalance instanceof i.Hbar?e.initialBalance:new i.Hbar(e.initialBalance??1));return"number"==typeof e.maxAutomaticTokenAssociations&&t.setMaxAutomaticTokenAssociations(e.maxAutomaticTokenAssociations),e.accountMemo&&t.setAccountMemo(e.accountMemo),t}function lh(e){const t=(new i.AccountCreateTransaction).setKeyWithoutAlias(e.publicKey).setInitialBalance(e.initialBalance instanceof i.Hbar?e.initialBalance:new i.Hbar(e.initialBalance??1));return"number"==typeof e.maxAutomaticTokenAssociations&&t.setMaxAutomaticTokenAssociations(e.maxAutomaticTokenAssociations),e.accountMemo&&t.setAccountMemo(e.accountMemo),t}class dh{constructor(e){this.network=e.network,this.logger=e.logger||new z({module:"HCS-15",level:e.logLevel||"info"}),this.mirrorNode=new G(this.network,this.logger,{customUrl:e.mirrorNodeUrl})}async verifyPetalAccount(e,t){try{const r=await this.mirrorNode.requestAccount(e),i=await this.mirrorNode.requestAccount(t),o=r?.key?.key||"";return""!==o&&o===(i?.key?.key||"")}catch(eg){return this.logger.warn("verifyPetalAccount failed",{error:String(eg)}),!1}}}var uh=(e=>(e[e.COMMUNICATION=0]="COMMUNICATION",e[e.TRANSACTION=1]="TRANSACTION",e[e.STATE=2]="STATE",e))(uh||{}),ph=(e=>(e.FLORA_CREATED="flora_created",e.TRANSACTION="transaction",e.STATE_UPDATE="state_update",e.FLORA_JOIN_REQUEST="flora_join_request",e.FLORA_JOIN_VOTE="flora_join_vote",e.FLORA_JOIN_ACCEPTED="flora_join_accepted",e))(ph||{});class hh extends Error{constructor(e,t){super(e),this.code=t,this.name="FloraError"}}function gh(e){const t=function(e){return`hcs-16:${e.floraAccountId}:${e.topicType}`}({floraAccountId:e.floraAccountId,topicType:e.topicType}),r=Y({memo:t,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey});return e.autoRenewAccountId&&r.setAutoRenewAccountId(i.AccountId.fromString(e.autoRenewAccountId)),r}function mh(e){const t=(new i.AccountCreateTransaction).setKey(e.keyList),r="number"==typeof e.initialBalanceHbar?e.initialBalanceHbar:1;t.setInitialBalance(new i.Hbar(r));const o="number"==typeof e.maxAutomaticTokenAssociations?e.maxAutomaticTokenAssociations:-1;return t.setMaxAutomaticTokenAssociations(o),t}function fh(e){const t={p:"hcs-16",op:e.op,operator_id:e.operatorId,...e.body||{}};return X({topicId:e.topicId,message:JSON.stringify(t)})}function yh(e){return fh({topicId:e.topicId,operatorId:e.operatorId,op:ph.FLORA_CREATED,body:{flora_account_id:e.floraAccountId,topics:e.topics}})}function bh(e){return fh({topicId:e.topicId,operatorId:e.operatorId,op:ph.TRANSACTION,body:{schedule_id:e.scheduleId,data:e.data,m:e.data}})}function wh(e){return fh({topicId:e.topicId,operatorId:e.operatorId,op:ph.STATE_UPDATE,body:{hash:e.hash,epoch:e.epoch,timestamp:(new Date).toISOString()}})}function Ih(e){return fh({topicId:e.topicId,operatorId:e.operatorId,op:ph.FLORA_JOIN_REQUEST,body:{candidate_account_id:e.candidateAccountId}})}function Th(e){return fh({topicId:e.topicId,operatorId:e.operatorId,op:ph.FLORA_JOIN_VOTE,body:{candidate_account_id:e.candidateAccountId,approve:e.approve}})}function Sh(e){return fh({topicId:e.topicId,operatorId:e.operatorId,op:ph.FLORA_JOIN_ACCEPTED,body:{members:e.members,epoch:e.epoch}})}class kh{constructor(e){this.network=e.network,this.logger=e.logger||new z({level:"info",module:"HCS-16"}),this.mirrorNode=new G(this.network,this.logger,{customUrl:e.mirrorNodeUrl})}async assembleKeyList(e){const t=[];for(const r of e.members){const e=await this.mirrorNode.getPublicKey(r);t.push(e)}return new i.KeyList(t,e.threshold)}async assembleSubmitKeyList(e){const t=[];for(const r of e){const e=await this.mirrorNode.getPublicKey(r);t.push(e)}return new i.KeyList(t,1)}buildFloraTopicCreateTxs(e){return{communication:gh({floraAccountId:e.floraAccountId,topicType:uh.COMMUNICATION,adminKey:e.keyList,submitKey:e.submitList,autoRenewAccountId:e.autoRenewAccountId}),transaction:gh({floraAccountId:e.floraAccountId,topicType:uh.TRANSACTION,adminKey:e.keyList,submitKey:e.submitList,autoRenewAccountId:e.autoRenewAccountId}),state:gh({floraAccountId:e.floraAccountId,topicType:uh.STATE,adminKey:e.keyList,submitKey:e.submitList,autoRenewAccountId:e.autoRenewAccountId})}}parseTopicMemo(e){const t=e.match(/^hcs-16:([0-9.]+):(\d)$/);return t?{protocol:"hcs-16",floraAccountId:t[1],topicType:Number(t[2])}:null}createFloraMessage(e,t,r){return{p:"hcs-16",op:e,operator_id:t,...r||{}}}async getRecentMessages(e,t){const r=t?.limit??25,i=t?.order??"desc",o=await this.mirrorNode.getTopicMessages(e,{limit:r,order:i}),n=[];for(const s of o){if("hcs-16"!==s.p)continue;const{consensus_timestamp:e,sequence_number:r,running_hash:i,running_hash_version:o,topic_id:a,payer:c,created:l,chunk_info:d,...u}=s,p=u.op,h=u.operator_id;if(t?.opFilter&&p!==t.opFilter)continue;if("string"!=typeof h)continue;const g=u;n.push({message:g,consensus_timestamp:e,sequence_number:Number(r),payer:c})}return n}async getLatestMessage(e,t){const r=await this.getRecentMessages(e,{limit:1,order:"desc",opFilter:t});if(0===r.length)return null;const i=r[0];return Object.assign({},i.message,{consensus_timestamp:i.consensus_timestamp,sequence_number:i.sequence_number})}}const Eh=r.z.object({p:r.z.literal("hcs-17"),op:r.z.literal("state_hash"),state_hash:r.z.string().min(1),topics:r.z.array(r.z.string()),account_id:r.z.string().min(1),timestamp:r.z.string().optional(),m:r.z.string().optional()});class vh extends Error{constructor(e,t){super(e),this.code=t,this.name="StateHashError"}}var Ah=(e=>(e[e.STATE=0]="STATE",e))(Ah||{});function Ch(e){return`hcs-17:0:${e}`}function xh(e){try{const t=e.match(/^hcs-17:(\d+):(\d+)$/);if(!t)return;const r=Number(t[1]),i=Number(t[2]);if(Number.isNaN(r)||Number.isNaN(i)||i<=0)return;return{type:r,ttl:i}}catch{return}}class Rh{constructor(e){this.network=e.network,this.logger=e.logger||new z({level:e.logLevel||"info",module:"HCS-17"}),this.mirrorNode=new G(this.network,this.logger,{customUrl:e.mirrorNodeUrl})}createMessage(e){return{p:"hcs-17",op:"state_hash",state_hash:e.stateHash,topics:e.topics,account_id:e.accountId,timestamp:(new Date).toISOString(),m:e.memo}}validateMessage(e){const t=Eh.safeParse(e);if(t.success)return{valid:!0,errors:[]};const r=t.error.errors.map(e=>`${e.path.join(".")}: ${e.message}`);return this.logger.debug(`HCS-17 message validation failed: ${r.join(", ")}`),{valid:!1,errors:r}}generateTopicMemo(e){return Ch(e)}async validateHCS17Topic(e){try{const t=xh((await this.mirrorNode.getTopicInfo(e)).memo);return t?t.type!==Ah.STATE?{valid:!1,error:"Unsupported HCS-17 topic type"}:{valid:!0,type:t.type,ttl:t.ttl}:{valid:!1,error:"Invalid HCS-17 memo format"}}catch(eg){return{valid:!1,error:String(eg)}}}async getRecentMessages(e,t){const r=t?.limit??25,i=t?.order??"desc",o=await this.mirrorNode.getTopicMessages(e,{limit:r,order:i}),n=[];for(const s of o)try{if("hcs-17"!==s.p||"state_hash"!==s.op)continue;const e=s,{valid:t}=this.validateMessage(e);if(!t)continue;n.push({message:{p:"hcs-17",op:"state_hash",state_hash:e.state_hash,topics:e.topics,account_id:e.account_id,timestamp:e.timestamp,m:e.m},consensus_timestamp:e.consensus_timestamp,sequence_number:Number(e.sequence_number),payer:e.payer})}catch(tg){this.logger.debug(`Failed to parse HCS-17 message: ${tg}`)}return n}async getLatestMessage(e){const t=await this.getRecentMessages(e,{limit:1,order:"desc"});if(!t.length)return null;const{message:r,consensus_timestamp:i,sequence_number:o}=t[0];return Object.assign({},r,{consensus_timestamp:i,sequence_number:o})}calculateAccountStateHash(e){try{this.logger.debug("Calculating account state hash",{accountId:e.accountId,topicCount:e.topics.length});const t=[...e.topics].sort((e,t)=>e.topicId.localeCompare(t.topicId));let r="";for(const e of t)r+=e.topicId+e.latestRunningHash;let i="";i="string"==typeof e.publicKey?e.publicKey:e.publicKey.toString(),r+=i;const o=w.createHash("sha384");o.update(r);const n=o.digest("hex");return this.logger.debug("Account state hash calculated",{accountId:e.accountId,stateHash:n}),{stateHash:n,accountId:e.accountId,timestamp:new Date,topicCount:e.topics.length}}catch(t){throw this.logger.error("Failed to calculate account state hash",t),new Error("HCS-17 CALCULATION_FAILED")}}calculateCompositeStateHash(e){try{this.logger.debug("Calculating composite state hash",{compositeAccountId:e.compositeAccountId,memberCount:e.memberStates.length,topicCount:e.compositeTopics.length});const t=[...e.memberStates].sort((e,t)=>e.accountId.localeCompare(t.accountId)),r=[...e.compositeTopics].sort((e,t)=>e.topicId.localeCompare(t.topicId));let i="";for(const e of t)i+=e.accountId+e.stateHash;for(const e of r)i+=e.topicId+e.latestRunningHash;i+=e.compositePublicKeyFingerprint;const o=w.createHash("sha384");o.update(i);const n=o.digest("hex");return this.logger.debug("Composite state hash calculated",{compositeAccountId:e.compositeAccountId,stateHash:n}),{stateHash:n,accountId:e.compositeAccountId,timestamp:new Date,topicCount:e.compositeTopics.length,memberCount:e.memberStates.length,compositeTopicCount:e.compositeTopics.length}}catch(t){throw this.logger.error("Failed to calculate composite state hash",t),new Error("HCS-17 COMPOSITE_CALCULATION_FAILED")}}calculateKeyFingerprint(e,t){try{const r={threshold:t,keys:[...e].sort((e,t)=>e.toString().localeCompare(t.toString())).map(e=>e.toString())},i=w.createHash("sha384");return i.update(JSON.stringify(r)),i.digest("hex")}catch(r){throw this.logger.error("Failed to calculate key fingerprint",r),new Error("HCS-17 FINGERPRINT_FAILED")}}createStateHashMessage(e,t,r,i){return{p:"hcs-17",op:"state_hash",state_hash:e,topics:r,account_id:t,timestamp:(new Date).toISOString(),m:i}}async verifyStateHash(e,t){try{let r;r="publicKey"in e?this.calculateAccountStateHash(e).stateHash:this.calculateCompositeStateHash(e).stateHash;const i=r===t,o="accountId"in e?e.accountId:e.compositeAccountId;return this.logger.debug("State hash verification",{accountId:o,isValid:i,expected:t,calculated:r}),i}catch(r){return this.logger.error("Failed to verify state hash",r),!1}}}function Nh(e){return Y({memo:Ch(e.ttl),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function _h(e){const t={p:"hcs-17",op:"state_hash",state_hash:e.stateHash,topics:e.topics,account_id:e.accountId,timestamp:(new Date).toISOString(),m:e.memo};return X({topicId:e.topicId,message:JSON.stringify(t),transactionMemo:e.transactionMemo})}var Ph=(e=>(e.ANNOUNCE="announce",e.PROPOSE="propose",e.RESPOND="respond",e.COMPLETE="complete",e.WITHDRAW="withdraw",e))(Ph||{});function Fh(e){return"object"==typeof e&&null!==e}function Oh(e){return"string"==typeof e}function Dh(e){return"number"==typeof e&&Number.isFinite(e)}function zh(e){if(!Fh(e))return!1;if("hcs-18"!==e.p)return!1;if(!Oh(e.op))return!1;const t=e.op;return!!["announce","propose","respond","complete","withdraw"].includes(t)&&"data"in e}var Bh=(e=>(e.IDLE="idle",e.ANNOUNCED="announced",e.PROPOSING="proposing",e.FORMING="forming",e.ACTIVE="active",e.WITHDRAWN="withdrawn",e))(Bh||{});class Mh extends Error{constructor(e,t){super(e),this.code=t,this.name="DiscoveryError"}}function Kh(e,t){return t&&t.trim().length>0?t:e&&e>0?`hcs-18:0:${e}`:"hcs-18:0"}function Uh(e){return Y({memo:Kh(e.ttlSeconds,e.memoOverride),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function Lh(e){const t="string"==typeof e.transactionMemo&&e.transactionMemo.length>0?e.transactionMemo:`hcs-18:op:${function(e){switch(e){case Ph.ANNOUNCE:return 0;case Ph.PROPOSE:return 1;case Ph.RESPOND:return 2;case Ph.COMPLETE:return 3;case Ph.WITHDRAW:return 4;default:return 0}}(e.message.op)}`;return(new i.TopicMessageSubmitTransaction).setTopicId(e.topicId).setMessage(JSON.stringify(e.message)).setTransactionMemo(t)}function $h(e){return{p:"hcs-18",op:Ph.ANNOUNCE,data:e}}function Hh(e){return{p:"hcs-18",op:Ph.PROPOSE,data:e}}function qh(e){return{p:"hcs-18",op:Ph.RESPOND,data:e}}function jh(e){return{p:"hcs-18",op:Ph.COMPLETE,data:e}}function Wh(e){return{p:"hcs-18",op:Ph.WITHDRAW,data:e}}class Vh{constructor(e){this.network=e.network,this.logger=e.logger||z.getInstance({module:"HCS-18"}),this.mirrorNode=new G(this.network,this.logger)}async getDiscoveryMessages(e,t){const r=["announce","propose","respond","complete","withdraw"],i=await this.mirrorNode.getTopicMessages(e,t);return i?i.filter(e=>"hcs-18"===e.p&&r.includes(e.op)):[]}isProposalReady(e){const t=Array.from(e.responses.values()).filter(e=>"accept"===e.decision),r=e.data.members.length-1;return t.length>=r}}var Gh=(e=>(e.FIXED_FEE="FIXED_FEE",e.FRACTIONAL_FEE="FRACTIONAL_FEE",e.ROYALTY_FEE="ROYALTY_FEE",e))(Gh||{});class Jh{constructor(e){this.customFees=[],this.logger=e.logger,this.mirrorNode=new G(e.network,e.logger),this.defaultCollectorAccountId=e.defaultCollectorAccountId||""}static forHbar(e,t,r,i,o=[]){return new Jh({network:r,logger:i,defaultCollectorAccountId:t}).addHbarFee(e,t,o)}static async forToken(e,t,r,i,o,n=[],s){const a=new Jh({network:i,logger:o,defaultCollectorAccountId:r});return await a.addTokenFee(e,t,r,s,n),a}addHbarFee(e,t,r=[]){if(e<=0)throw new Error("HBAR amount must be greater than zero");return this.customFees.push({feeAmount:{amount:1e8*e,decimals:0},feeCollectorAccountId:t||this.defaultCollectorAccountId,feeTokenId:void 0,exemptAccounts:[...r],type:Gh.FIXED_FEE}),this}async addTokenFee(e,t,r,i,o=[]){if(e<=0)throw new Error("Token amount must be greater than zero");if(!t)throw new Error("Fee token ID is required when adding a token fee");let n=i;if(void 0===n)try{const e=await this.mirrorNode.getTokenInfo(t);e?.decimals?(n=parseInt(e.decimals,10),this.logger.info(`Fetched decimals for ${t}: ${n}`)):(this.logger.warn(`Could not fetch decimals for ${t}, defaulting to 0.`),n=0)}catch(s){this.logger.error(`Error fetching decimals for ${t}, defaulting to 0: ${s}`),n=0}return this.customFees.push({feeAmount:{amount:e*10**n,decimals:n},feeCollectorAccountId:r||this.defaultCollectorAccountId,feeTokenId:t,exemptAccounts:[...o],type:Gh.FIXED_FEE}),this}build(){if(0===this.customFees.length)throw new Error("At least one fee must be added using addHbarFee/addTokenFee or created using forHbar/forToken");if(this.customFees.length>10)throw new Error("Maximum of 10 custom fees per topic allowed");const e=new Set;this.customFees.forEach(t=>{t.exemptAccounts.forEach(t=>e.add(t))});return{customFees:this.customFees.map(e=>({...e,feeCollectorAccountId:e.feeCollectorAccountId||this.defaultCollectorAccountId})),exemptAccounts:Array.from(e)}}}class Yh{constructor(){this.resolver=null,this.onUnavailableCallbacks=[],this.logger=z.getInstance({module:"ContentResolverRegistry"})}static getInstance(){return Yh._instance||(Yh._instance=new Yh),Yh._instance}register(e){this.resolver&&this.logger.warn("Resolver already registered, replacing existing"),this.resolver=e,this.logger.info("Content resolver registered")}getResolver(){return this.resolver}isAvailable(){return null!==this.resolver}unregister(){this.resolver&&(this.resolver=null,this.logger.info("Content resolver unregistered"),this.onUnavailableCallbacks.forEach(e=>{try{e()}catch(t){this.logger.error("Error in unavailable callback:",t)}}))}onUnavailable(e){this.onUnavailableCallbacks.push(e)}offUnavailable(e){const t=this.onUnavailableCallbacks.indexOf(e);-1!==t&&this.onUnavailableCallbacks.splice(t,1)}async withResolver(e,t){if(!this.resolver)return this.logger.warn("No resolver available, using fallback"),await t();try{return await e(this.resolver)}catch(r){return this.logger.warn("Resolver operation failed, using fallback:",r),await t()}}}const Xh=Yh.getInstance();class Zh{constructor(){this.contentStore=null,this.logger=z.getInstance({module:"ContentStoreService"})}static getInstance(){return Zh._instance||(Zh._instance=new Zh),Zh._instance}async setInstance(e){this.contentStore&&this.logger.warn("Content store already set, replacing"),this.contentStore=e,this.logger.info("Content store instance set")}getInstance(){return this.contentStore}dispose(){this.contentStore=null,this.logger.info("Content store disposed")}isAvailable(){return null!==this.contentStore}}const Qh=Zh.getInstance();exports.AIAgentCapability=gc,exports.AIAgentDetailsSchema=Sd,exports.AIAgentProfileSchema=_d,exports.AIAgentType=pc,exports.AccountCreationError=Zd,exports.ActionBuilder=class{constructor(e){this.cryptoAdapter=ud(),this.logger=e,this.registration={p:"hcs-12",op:"register"}}setTopicId(e){if(!this.isValidTopicId(e))throw new Error("Invalid topic ID format");return this.registration.t_id=e,this}setAlias(e){return this.alias=e,this}setHash(e){if(!this.isValidHash(e))throw new Error("Invalid hash format");return this.registration.hash=e,this}setWasmHash(e){if(!this.isValidHash(e))throw new Error("Invalid hash format");return this.registration.wasm_hash=e,this}setInfoTopicId(e){if(!this.isValidTopicId(e))throw new Error("Invalid topic ID format");return this.registration.info_t_id=e,this}setJsTopicId(e){if(!this.isValidTopicId(e))throw new Error("Invalid topic ID format");return this.registration.js_t_id=e,this}setJsHash(e){if(!this.isValidHash(e))throw new Error("Invalid hash format");return this.registration.js_hash=e,this}setInterfaceVersion(e){if(!this.isValidVersion(e))throw new Error("Invalid version format");return this.registration.interface_version=e,this}addValidationRule(e,t){return this.registration.validation_rules||(this.registration.validation_rules={}),this.registration.validation_rules[e]=t,this}setSourceVerification(e){if(!this.isValidTopicId(e.source_t_id))throw new Error("Invalid source topic ID");if(!this.isValidHash(e.source_hash))throw new Error("Invalid source hash");if("wasm32-unknown-unknown"!==e.target)throw new Error("Invalid compilation target");return this.registration.source_verification=e,this}build(e={validate:!0}){return!1!==e.validate&&this.validate(),{...this.registration}}reset(){return this.registration={p:"hcs-12",op:"register"},this.alias=void 0,this}getAlias(){if(!this.alias)throw new Error("Action alias not set");return this.alias}getTopicId(){if(!this.registration.t_id)throw new Error("Action topic ID not set");return this.registration.t_id}async generateWasmHash(e){if(od())return this.createSSRSafeHash(e,"wasm");const t=this.cryptoAdapter.createHash("sha256").update(globalThis.Buffer.from(e)).digest("hex"),r=t instanceof Promise?await t:t;return"string"==typeof r?r:r.toString("hex")}async generateInfoHash(e){const t=JSON.stringify(e,Object.keys(e).sort());if(od())return this.createSSRSafeHash(globalThis.Buffer.from(t),"info");const r=this.cryptoAdapter.createHash("sha256").update(globalThis.Buffer.from(t)).digest("hex"),i=r instanceof Promise?await r:r;return"string"==typeof i?i:i.toString("hex")}async calculateHash(e){const t="string"==typeof e||e instanceof Uint8Array?globalThis.Buffer.from(e):e;if(od())return this.createSSRSafeHash(t,"data");const r=this.cryptoAdapter.createHash("sha256").update(t).digest("hex"),i=r instanceof Promise?await r:r;return"string"==typeof i?i:i.toString("hex")}createSSRSafeHash(e,t){const r=e instanceof Uint8Array?globalThis.Buffer.from(e):e;let i=0;for(let o=0;o<Math.min(r.length,256);o++)i=(i<<5)-i+r[o]&4294967295;return`ssr-${t}-${r.length}-${Math.abs(i).toString(16).padStart(8,"0")}`}async createFromWasmAndInfo(e,t,r){const i=await this.generateWasmHash(t),o=await this.generateInfoHash(r),n=this.registration.js_t_id,s=this.registration.js_hash,a=this.registration.interface_version;return this.reset().setTopicId(e).setHash(o).setWasmHash(i),n&&this.setJsTopicId(n),s&&this.setJsHash(s),a&&this.setInterfaceVersion(a),this.build()}isComplete(e){return!!("hcs-12"===e.p&&"register"===e.op&&e.t_id&&e.hash&&e.wasm_hash)}validate(){if(!this.registration.t_id)throw new Error("Topic ID is required");if(!this.registration.hash)throw new Error("INFO hash is required");if(!this.registration.wasm_hash)throw new Error("WASM hash is required")}isValidTopicId(e){return/^\d+\.\d+\.\d+$/.test(e)}isValidHash(e){return/^[a-f0-9]{64}$/.test(e)}isValidVersion(e){return/^\d+\.\d+\.\d+$/.test(e)}},exports.ActionRegistry=Eu,exports.AgentBuilder=tu,exports.AssemblyBuilder=class{constructor(e){this.registration={p:"hcs-12",op:"register"},this.operations=[],this.updateFields={p:"hcs-12",op:"update"},this.logger=e||new z({module:"AssemblyBuilder"})}setName(e){if(!this.isValidName(e))throw new Error("Invalid assembly name format");return this.registration.name=e,this}setVersion(e){if(!this.isValidSemver(e))throw new Error("Invalid semantic version");return this.registration.version=e,this}setDescription(e){return this.registration.description=e,this.updateFields&&(this.updateFields.description=e),this}setTags(e){return this.registration.tags=e,this.updateFields&&(this.updateFields.tags=e),this}addTag(e){return this.registration.tags||(this.registration.tags=[]),this.updateFields.tags||(this.updateFields.tags=[]),this.registration.tags.push(e),this.updateFields.tags.push(e),this}setAuthor(e){return this.registration.author=e,this}addAction(e){const t=e.getTopicId(),r=e.getAlias();if(!this.isValidAlias(r))throw new Error("Invalid alias format");const i={p:"hcs-12",op:"add-action",t_id:t,alias:r};return this.operations.push(i),this}addBlock(e){const t=e.getTopicId();if(!this.isValidTopicId(t))throw new Error(`Invalid block topic ID: ${t}`);const r=e.build(),i=e.getActions(),o=this.extractDefaultAttributes(r.attributes);if(i&&Object.keys(i).length>0)for(const[s,a]of Object.entries(i))if(!this.isValidTopicId(a))throw new Error(`Invalid action topic ID for "${s}": ${a}`);const n={p:"hcs-12",op:"add-block",block_t_id:t,...Object.keys(i).length>0&&{actions:i},attributes:o};return this.operations.push(n),this}updateMetadata(e,t){const r={p:"hcs-12",op:"update",description:e,tags:t};return this.operations.push(r),this}build(){if(!this.registration.name)throw new Error("Assembly name is required");if(!this.registration.version)throw new Error("Assembly version is required");return{...this.registration}}buildUpdate(){const e={p:"hcs-12",op:"update"};return void 0!==this.updateFields.description&&(e.description=this.updateFields.description),void 0!==this.updateFields.tags&&(e.tags=this.updateFields.tags),e}buildOperations(){return[...this.operations]}reset(){return this.registration={p:"hcs-12",op:"register"},this.operations=[],this.updateFields={p:"hcs-12",op:"update"},this}getRegistration(){return this.build()}getOperations(){return this.buildOperations()}buildPreview(){const e=[],t=[];for(const r of this.operations)switch(r.op){case"add-action":e.push({t_id:r.t_id,alias:r.alias,config:r.config,data:r.data});break;case"add-block":t.push({block_t_id:r.block_t_id,actions:r.actions,attributes:r.attributes,children:r.children,data:r.data});break;case"update":r.description&&(this.registration.description=r.description),r.tags&&(this.registration.tags=r.tags)}return{topicId:"",name:this.registration.name,version:this.registration.version,description:this.registration.description,tags:this.registration.tags,author:this.registration.author,actions:e,blocks:t,created:(new Date).toISOString(),updated:(new Date).toISOString()}}validate(){const e=[];this.registration.name||e.push("Assembly name is required"),this.registration.version||e.push("Assembly version is required"),this.registration.version&&!this.isValidSemver(this.registration.version)&&e.push("Invalid semantic version format");const t=new Set;for(const i of this.operations)"add-action"===i.op?(t.has(i.alias)?e.push(`Duplicate alias: ${i.alias}`):t.add(i.alias),this.isValidTopicId(i.t_id)||e.push(`Invalid topic ID for ${i.alias}: ${i.t_id}`),this.isValidAlias(i.alias)||e.push(`Invalid alias format: ${i.alias}`)):"add-block"===i.op&&(this.isValidTopicId(i.block_t_id)||e.push(`Invalid block topic ID: ${i.block_t_id}`));const r=new Set;this.operations.filter(e=>"add-action"===e.op).forEach(e=>r.add(e.alias));for(const i of this.operations)if("add-block"===i.op&&i.actions)for(const[t,r]of Object.entries(i.actions))this.isValidTopicId(r)||e.push(`Block ${i.block_t_id} has invalid action topic ID for key ${t}: ${r}`);return{valid:0===e.length,errors:e}}isValidSemver(e){return/^\d+\.\d+\.\d+(-[\w\.\+]+)?$/.test(e)}isValidTopicId(e){return/^\d+\.\d+\.\d+$/.test(e)}isValidAlias(e){return/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(e)&&e.length>=2&&e.length<=50}isValidName(e){return/^[a-z0-9-]+$/.test(e)&&e.length>=2&&e.length<=100}extractDefaultAttributes(e){if(!e)return{};const t={};for(const[r,i]of Object.entries(e))i&&"object"==typeof i&&"default"in i&&(t[r]=i.default);return t}},exports.AssemblyEngine=xu,exports.AssemblyRegistry=Au,exports.BaseProfileSchema=Rd,exports.BaseRegistry=nu,exports.BlockBuilder=Nu,exports.BlockLoader=vu,exports.BlockRenderer=class{constructor(e,t,r,i){this.MAX_DEPTH=10,this.logger=e,this.gutenbergBridge=t,this.templateEngine=r,this.stateManager=i,this.hashLinkScanner=new Pu(e)}async render(e,t={}){try{this.currentBlock=e,this.currentOptions=t,t.assembly&&(this.assembly=t.assembly),t.actionRegistry&&(this.actionRegistry=t.actionRegistry),t.network&&!this.wasmExecutor&&(this.wasmExecutor=new _u(this.logger,t.network)),t.initialState&&this.stateManager.setBlockState(e.id,t.initialState);let r=this.stateManager.getBlockState(e.id)||{attributes:{},actionResults:{}};r.attributes&&"object"==typeof r.attributes||(this.logger.warn("Invalid state structure, fixing...",{state:r}),r={attributes:r||{},actionResults:{}});let i={},o=e.attributes||{};if(this.assembly){const t=this.assembly.state?.blocks?.find(t=>t.block_t_id===e.id||t.block_t_id===e.t_id);t&&(i=t.actions||{},o={...t.attributes,...o})}const n={};e.attributes&&Object.entries(e.attributes).forEach(([e,t])=>{t&&"object"==typeof t&&"default"in t&&(n[e]=t.default)});const s={...n};o&&"object"==typeof o&&Object.entries(o).forEach(([e,t])=>{"object"==typeof t&&null!==t||(s[e]=t)}),r.attributes&&"object"==typeof r.attributes&&Object.entries(r.attributes).forEach(([e,t])=>{"object"==typeof t&&null!==t||(s[e]=t)}),r.attributes={...s},this.stateManager.setBlockState(e.id,r);const a={attributes:s,actions:i,blockId:e.id,actionResults:r.actionResults||{}};this.logger.debug("Template context",{blockId:e.id,attributes:a.attributes,hasActions:!!i,actionKeys:Object.keys(i),rawState:r,mergedAttributes:s});let c=await this.templateEngine.render(e.template||"",a);if(this.shouldProcessHashLinks(t)&&(c=await this.processHashLinks(c,e,t)),t.container&&"undefined"!=typeof window){const r="string"==typeof t.container?document.querySelector(t.container):t.container;if(r instanceof HTMLElement)return r.innerHTML=c,e.styles&&this.applyStyles(e.id,e.styles),this.setupEventHandlers(r,e.id),{element:r,html:c,cleanup:()=>this.cleanup(e.id)}}return{html:c}}catch(r){throw this.logger.error("Block render failed",{blockId:e.id,error:r}),r}}applyStyles(e,t){if("undefined"==typeof document)return;const r=`hashlink-styles-${e}`;let i=document.getElementById(r);i||(i=document.createElement("style"),i.id=r,document.head.appendChild(i)),i.textContent=t}setupEventHandlers(e,t){this.stateManager.onStateChange(t,t=>{this.updateBlockUI(e,t)}),e.querySelectorAll("[data-action]").forEach(e=>{e.addEventListener("click",async r=>{r.preventDefault();const i=e.dataset.action,o=e.dataset.params;this.logger.debug("Action button clicked",{actionTopicId:i,paramsStr:o,hasAction:!!i}),i&&await this.executeAction(t,i,o)})})}async updateBlockDisplay(e,t){try{this.logger.debug("updateBlockDisplay called",{blockId:e,newState:t});const r=document.querySelector(`[data-block-id="${e}"]`);if(!r||!r.parentElement)return void this.logger.warn("Block element not found for re-render",{blockId:e});const i=r.parentElement;if(this.currentBlock&&this.currentBlock.id===e&&this.currentOptions){const r={...this.currentOptions,container:i,initialState:t};await this.render(this.currentBlock,r);this.logger.debug("Block re-rendered with updated state",{blockId:e,newState:t})}}catch(r){this.logger.error("Failed to re-render block",{blockId:e,error:r.message})}}async executeAction(e,t,r){try{this.logger.debug("Executing action",{blockId:e,actionTopicId:t});let i={};if(r)try{i=JSON.parse(r)}catch(eg){this.logger.warn("Failed to parse action params",{paramsStr:r})}const o=this.stateManager.getBlockState(e)||{attributes:{},actionResults:{}};if(this.wasmExecutor&&this.actionRegistry){this.logger.debug("Looking up action in registry",{actionTopicId:t});const r=await this.actionRegistry.getActionByTopicId(t);if(this.logger.debug("Action lookup result",{found:!!r,actionTopicId:t,actionData:r}),!r)throw new Error(`Action not found: ${t}`);this.logger.debug("Executing WASM",{actionData:r,params:i,state:o.attributes});const n=await this.wasmExecutor.execute(r,{method:"POST",params:i,state:o.attributes});if(this.logger.debug("WASM execution result",{result:n}),n.success&&n.data){const t=i.operation||"default";let r=n.data;r.success&&r.data&&(r=r.data);const s={...o,attributes:{...o.attributes,...r},actionResults:{...o.actionResults,[t]:r}};this.stateManager.updateBlockState(e,s),await this.updateBlockDisplay(e,s)}else this.logger.error("Action execution failed",{result:n})}else this.stateManager.sendMessage(e,"action",{action:t,params:i})}catch(i){this.logger.error("Failed to execute action",{blockId:e,actionTopicId:t,error:i.message}),this.stateManager.sendMessage(e,"action-error",{action:t,error:i.message})}}updateBlockUI(e,t){Object.entries(t).forEach(([t,r])=>{e.querySelectorAll(`[data-bind="${t}"]`).forEach(e=>{e instanceof HTMLElement&&(e.textContent=String(r))})})}cleanup(e){const t=document.getElementById(`hashlink-styles-${e}`);t&&t.remove(),this.stateManager.removeBlockState(e)}shouldProcessHashLinks(e){const t=e.depth||0,r=e.maxDepth||this.MAX_DEPTH;return t>=r?(this.logger.warn("Max render depth reached, skipping HashLink processing",{depth:t,maxDepth:r}),!1):!(!e.network||!e.blockLoader&&!this.blockLoader)}ensureHashLinkResolver(e){!this.hashLinkResolver&&e.network&&(this.blockLoader=e.blockLoader||this.blockLoader,this.hrlResolver=e.hrlResolver||this.hrlResolver,this.blockLoader&&this.hrlResolver&&(this.hashLinkResolver=new Fu(this.logger,this.blockLoader,this.hrlResolver,e.network)))}async processHashLinks(e,t,r){if(this.ensureHashLinkResolver(r),!this.hashLinkResolver)return this.logger.warn("HashLink resolver not available, skipping processing"),e;this.hashLinkResolver.pushRenderStack(t.id);try{const o=await this.hashLinkScanner.scanTemplate(e);if(0===o.length)return e;this.logger.debug("Processing HashLinks",{parentBlockId:t.id,referenceCount:o.length});const n={blockId:t.id,depth:(r.depth||0)+1,parentContext:r.parentContext,attributes:r.initialState?.attributes||{},actions:{},assembly:this.assembly,maxDepth:r.maxDepth||this.MAX_DEPTH};if(this.assembly){const e=this.assembly.state?.blocks?.find(e=>e.block_t_id===t.id||e.block_t_id===t.t_id);e?.actions&&(n.actions=e.actions)}let s=e;for(let e=0;e<o.length;e++){const t=o[e];try{const e=await this.hashLinkResolver.resolveReference(t,n);if(e.error){this.logger.error("Failed to resolve HashLink",{uri:t.uri,error:e.error});const r=`\x3c!-- HashLink Error: ${e.error} --\x3e`;s=s.replace(t.placeholder,r);continue}let i;if(e.definition){const t={id:e.blockId,template:e.template||"",attributes:e.definition.attributes,p:"hcs-12",op:"register",name:e.definition.name,version:"1.0.0",title:e.definition.title,description:e.definition.description},o={attributes:e.attributes,actionResults:{}},s={attributes:e.attributes,actions:e.actions,blockId:e.blockId,actionResults:{}};if(e.template){i=await this.templateEngine.render(e.template,s);const a={...r,depth:n.depth,parentContext:n,initialState:o};this.shouldProcessHashLinks(a)&&(i=await this.processHashLinks(i,t,a))}else i="\x3c!-- Block has no template --\x3e"}else i=e.template?e.template:"\x3c!-- Empty block --\x3e";"lazy"===t.loading&&(i=this.wrapLazyLoad(i,t)),s=s.replace(t.placeholder,i)}catch(i){this.logger.error("Error processing HashLink",{uri:t.uri,error:i.message});const e=`\x3c!-- HashLink Error: ${i.message} --\x3e`;s=s.replace(t.placeholder,e)}}return s}finally{this.hashLinkResolver.popRenderStack(t.id)}}wrapLazyLoad(e,t){return`\n <div id="${`lazy-${t.uri.replace(/[^a-zA-Z0-9]/g,"-")}`}" class="hashlink-lazy-container" data-hashlink-lazy="${t.uri}">\n <div class="hashlink-lazy-placeholder">Loading...</div>\n <template class="hashlink-lazy-content">${e}</template>\n </div>\n `}},exports.BlockStateManager=class{constructor(e){this.blockStates=new Map,this.stateListeners=new Map,this.messageHandlers=new Map,this.schemas=new Map,this.persistentBlocks=new Set,this.unusedBlocks=new Set,this.maxBlockStates=1e3,this.logger=e}createBlockState(e,t){for(this.logger.debug("Creating block state",{blockId:e}),this.schemas.has(e)&&this.validateState(e,t);this.blockStates.size>=this.maxBlockStates;)this.unusedBlocks.size>0?this.cleanupUnusedStates():this.evictOldestBlock();this.blockStates.set(e,{...t}),this.logger.debug("Block state created",{blockId:e,stateKeys:Object.keys(t)})}getBlockState(e){return this.blockStates.has(e)?{...this.blockStates.get(e)}:null}hasBlockState(e){return this.blockStates.has(e)}updateBlockState(e,t){if(!this.blockStates.has(e))throw new Error(`Block state not found: ${e}`);const r={...this.blockStates.get(e)},i={...r,...t};this.schemas.has(e)&&this.validateState(e,i),this.blockStates.set(e,i);const o=this.stateListeners.get(e)||[];for(const s of o)try{s(i,r,e)}catch(n){this.logger.error("State change listener error",{blockId:e,error:n})}this.logger.debug("Block state updated",{blockId:e,updates:t})}destroyBlockState(e){this.logger.debug("Destroying block state",{blockId:e}),this.blockStates.delete(e),this.stateListeners.delete(e),this.messageHandlers.delete(e),this.schemas.delete(e),this.persistentBlocks.delete(e),this.unusedBlocks.delete(e),this.logger.debug("Block state destroyed",{blockId:e})}onStateChange(e,t){this.stateListeners.has(e)||this.stateListeners.set(e,[]),this.stateListeners.get(e).push(t)}removeStateChangeListener(e,t){const r=this.stateListeners.get(e);if(r){const e=r.indexOf(t);e>-1&&r.splice(e,1)}}onBlockMessage(e,t){this.messageHandlers.has(e)||this.messageHandlers.set(e,[]),this.messageHandlers.get(e).push(t)}sendBlockMessage(e,t,r,i){const o={type:r,payload:i,fromBlock:e,toBlock:t},n=this.messageHandlers.get(t)||[];for(const a of n)try{a(o)}catch(s){this.logger.error("Block message handler error",{fromBlock:e,toBlock:t,type:r,error:s})}this.logger.debug("Block message sent",{fromBlock:e,toBlock:t,type:r})}broadcastMessage(e,t){for(const i of this.blockStates.keys()){const o=this.messageHandlers.get(i)||[],n={type:e,payload:t,fromBlock:"system",toBlock:i};for(const t of o)try{t(n)}catch(r){this.logger.error("Broadcast message handler error",{blockId:i,type:e,error:r})}}this.logger.debug("Message broadcasted",{type:e,blockCount:this.blockStates.size})}async bindActionResult(e,t,r,i){if(!this.blockStates.has(e))throw new Error(`Block state not found: ${e}`);const o=this.getBlockState(e);let n;try{if(r.success&&i.onSuccess)n=i.onSuccess(o,r);else{if(r.success||!i.onError)return;n=i.onError(o,r)}n&&this.updateBlockState(e,n),this.logger.debug("Action result bound to state",{blockId:e,actionName:t,success:r.success})}catch(s){throw this.logger.error("Action result binding failed",{blockId:e,actionName:t,error:s}),s}}async persistBlockState(e){if(!this.storageBackend)return this.logger.warn("No storage backend configured"),void this.persistentBlocks.add(e);if(!this.blockStates.has(e))throw new Error(`Block state not found: ${e}`);try{const t=this.blockStates.get(e);await this.storageBackend.setItem(e,JSON.stringify(t)),this.persistentBlocks.add(e),this.logger.debug("Block state persisted",{blockId:e})}catch(t){this.logger.error("Failed to persist block state",{blockId:e,error:t})}}async restoreBlockState(e){if(this.storageBackend)try{const t=await this.storageBackend.getItem(e);if(t){const r=JSON.parse(t);this.blockStates.set(e,r),this.persistentBlocks.add(e),this.logger.debug("Block state restored",{blockId:e})}}catch(t){this.logger.error("Failed to restore block state",{blockId:e,error:t})}else this.logger.warn("No storage backend configured")}isPersistent(e){return this.persistentBlocks.has(e)}setStorageBackend(e){this.storageBackend=e}setBlockStateSchema(e,t){this.schemas.set(e,t),this.logger.debug("Block state schema set",{blockId:e})}setMaxBlockStates(e){this.maxBlockStates=e}getActiveBlockCount(){return this.blockStates.size}markBlockUnused(e){this.unusedBlocks.add(e)}cleanupUnusedStates(){for(const e of this.unusedBlocks)this.destroyBlockState(e);this.unusedBlocks.clear(),this.logger.debug("Unused states cleaned up")}evictOldestBlock(){for(const e of this.blockStates.keys())if(!this.persistentBlocks.has(e))return this.destroyBlockState(e),void this.logger.debug("Evicted block to make room",{blockId:e});this.logger.warn("Cannot evict blocks - all are persistent")}getListenerCount(e){return(this.stateListeners.get(e)?.length||0)+(this.messageHandlers.get(e)?.length||0)}validateState(e,t){const r=this.schemas.get(e);if(r&&"object"===r.type){if("object"!=typeof t||null===t)throw new Error("State validation failed: expected object");if(r.required)for(const e of r.required)if(!(e in t))throw new Error(`State validation failed: missing required property '${e}'`);if(r.properties)for(const[e,i]of Object.entries(r.properties))if(e in t){const r=t[e],o=i.type;if("string"===o&&"string"!=typeof r)throw new Error(`State validation failed: property '${e}' must be string`);if("number"===o&&"number"!=typeof r)throw new Error(`State validation failed: property '${e}' must be number`);if("number"===o&&void 0!==i.minimum&&r<i.minimum)throw new Error(`State validation failed: property '${e}' below minimum`)}}}setBlockState(e,t){this.blockStates.has(e)?this.updateBlockState(e,t):this.createBlockState(e,t)}removeBlockState(e){this.blockStates.delete(e),this.stateListeners.delete(e),this.messageHandlers.delete(e),this.persistentBlocks.delete(e),this.schemas.delete(e),this.storageBackend&&this.storageBackend.removeItem(e).catch(t=>{this.logger.error("Failed to remove persisted state",{blockId:e,error:t})}),this.logger.debug("Block state removed",{blockId:e})}sendMessage(e,t,r,i="system"){const o=this.messageHandlers.get(e)||[],n={type:t,payload:r,fromBlock:i,toBlock:e};for(const a of o)try{a(n)}catch(s){this.logger.error("Message handler error",{blockId:e,type:t,error:s})}}},exports.BrowserHCS20Client=class extends Wp{constructor(e){super({network:e.network,logger:e.logger,mirrorNodeUrl:e.mirrorNodeUrl,registryTopicId:e.registryTopicId,publicTopicId:e.publicTopicId}),this.hwc=e.hwc,this.feeAmount=e.feeAmount||20}getOperatorId(){const e=this.hwc.getAccountInfo();if(!e?.accountId)throw new Error("Wallet not connected");return e.accountId}async createRegistryTopic(){const e=new Cp({hwc:this.hwc,network:this.network}),t=await e.createRegistry();if(!t.success)throw new Error("Failed to create topic");return t.topicId}async deployPoints(e){const t=this.getOperatorId(),{progressCallback:r}=e;try{let i;if(r?.({stage:"creating-topic",percentage:20}),e.usePrivateTopic){const e=await this.mirrorNode.getPublicKey(t),r=new Cp({hwc:this.hwc,network:this.network}),o=await r.createRegistry({submitKey:e.toString(),adminKey:e.toString()});if(!o.success)throw new Error("Failed to create topic");i=o.topicId,this.logger.info(`Created private topic: ${i}`)}else i=this.publicTopicId;r?.({stage:"submitting-deploy",percentage:50,topicId:i});const o={p:"hcs-20",op:"deploy",name:e.name,tick:this.normalizeTick(e.tick),max:e.maxSupply,lim:e.limitPerMint,metadata:e.metadata,m:e.topicMemo},n=this.validateMessage(o);if(!n.valid)throw new Hp("Invalid deploy message",n.errors);const s=await this.submitPayload(i,o,e.usePrivateTopic),a=s.transactionHash?.toString()||"";return r?.({stage:"confirming",percentage:80,topicId:i,deployTxId:a}),await new Promise(e=>setTimeout(e,2e3)),r?.({stage:"complete",percentage:100,topicId:i,deployTxId:a}),{name:e.name,tick:this.normalizeTick(e.tick),maxSupply:e.maxSupply,limitPerMint:e.limitPerMint,metadata:e.metadata,topicId:i,deployerAccountId:t,currentSupply:"0",deploymentTimestamp:(new Date).toISOString(),isPrivate:e.usePrivateTopic||!1}}catch(i){throw r?.({stage:"complete",percentage:100,error:i instanceof Error?i.message:"Unknown error"}),i}}async mintPoints(e){const{progressCallback:t}=e;try{t?.({stage:"validating",percentage:20}),t?.({stage:"submitting",percentage:50});const r={p:"hcs-20",op:"mint",tick:this.normalizeTick(e.tick),amt:e.amount,to:this.accountToString(e.to),m:e.memo},i=e.topicId||this.publicTopicId,o=await this.submitPayload(i,r,!1),n=o.transactionHash?.toString()||"";return t?.({stage:"confirming",percentage:80,mintTxId:n}),await new Promise(e=>setTimeout(e,2e3)),t?.({stage:"complete",percentage:100,mintTxId:n}),{id:n,operation:"mint",tick:this.normalizeTick(e.tick),amount:e.amount,to:this.accountToString(e.to),timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:i,transactionId:n,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async transferPoints(e){const{progressCallback:t}=e;try{t?.({stage:"validating-balance",percentage:20}),t?.({stage:"submitting",percentage:50});const r={p:"hcs-20",op:"transfer",tick:this.normalizeTick(e.tick),amt:e.amount,from:this.accountToString(e.from),to:this.accountToString(e.to),m:e.memo},i=e.topicId||this.publicTopicId,o=await this.submitPayload(i,r,!1),n=o.transactionHash?.toString()||"";return t?.({stage:"confirming",percentage:80,transferTxId:n}),await new Promise(e=>setTimeout(e,2e3)),t?.({stage:"complete",percentage:100,transferTxId:n}),{id:n,operation:"transfer",tick:this.normalizeTick(e.tick),amount:e.amount,from:this.accountToString(e.from),to:this.accountToString(e.to),timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:i,transactionId:n,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async burnPoints(e){const{progressCallback:t}=e;try{t?.({stage:"validating-balance",percentage:20}),t?.({stage:"submitting",percentage:50});const r={p:"hcs-20",op:"burn",tick:this.normalizeTick(e.tick),amt:e.amount,from:this.accountToString(e.from),m:e.memo},i=e.topicId||this.publicTopicId,o=await this.submitPayload(i,r,!1),n=o.transactionHash?.toString()||"";return t?.({stage:"confirming",percentage:80,burnTxId:n}),await new Promise(e=>setTimeout(e,2e3)),t?.({stage:"complete",percentage:100,burnTxId:n}),{id:n,operation:"burn",tick:this.normalizeTick(e.tick),amount:e.amount,from:this.accountToString(e.from),timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:i,transactionId:n,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async registerTopic(e){const{progressCallback:t}=e;try{t?.({stage:"validating",percentage:20});const r={p:"hcs-20",op:"register",name:e.name,metadata:e.metadata,private:e.isPrivate,t_id:this.topicToString(e.topicId),m:e.memo},i=this.validateMessage(r);if(!i.valid)throw new Hp("Invalid register message",i.errors);t?.({stage:"submitting",percentage:50});const o=await this.submitPayload(this.registryTopicId,r,!1),n=o.transactionHash?.toString()||"";t?.({stage:"confirming",percentage:80,registerTxId:n}),await new Promise(e=>setTimeout(e,2e3)),t?.({stage:"complete",percentage:100,registerTxId:n})}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),new qp(r instanceof Error?r.message:"Unknown error",this.topicToString(e.topicId))}}async submitPayload(e,t,r){let o;this.logger.debug(`Submitting payload to topic ${e}`),o="string"==typeof t?t:JSON.stringify(t);const n=(new i.TopicMessageSubmitTransaction).setTopicId(i.TopicId.fromString(e)).setMessage(o);r&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),n.setMaxTransactionFee(new i.Hbar(this.feeAmount)));const s=await this.hwc.executeTransactionWithErrorHandling(n,!1);if(s?.error)throw this.logger.error(`Failed to submit payload: ${s.error}`),new Error(`Failed to submit payload: ${s.error}`);if(!s?.result)throw this.logger.error("Failed to submit message: receipt is null or undefined"),new Error("Failed to submit message: receipt is null or undefined");return this.logger.debug("Payload submitted successfully via HWC"),s.result}},exports.BrowserHCS2Client=Cp,exports.BrowserHCSClient=class extends Jd{constructor(e){let t;if(super({network:e.network,logLevel:e.logLevel,prettyPrint:e.prettyPrint,feeAmount:e.feeAmount,mirrorNode:e.mirrorNode,silent:e.silent}),this.hcs11Client=null,this.hwc=e.hwc,e.guardedRegistryBaseUrl?this.guardedRegistryBaseUrl=e.guardedRegistryBaseUrl:this.guardedRegistryBaseUrl="https://moonscape.tech",t=e.logLevel?e.logLevel:"info",this.logger=z.getInstance({level:t,module:"HCS-Browser",prettyPrint:e.prettyPrint,silent:e.silent}),iu)try{const{accountId:t,signer:r}=this.getAccountAndSigner();this.hcs11Client=new Dd({network:e.network,auth:{operatorId:t,signer:r},logLevel:e.logLevel,silent:e.silent})}catch(tg){this.logger.warn(`Failed to initialize HCS11Client: ${tg}`)}else this.logger.error("BrowserHCSClient initialized in server environment - browser-specific features will not be available. Use HCS10Client instead.")}async sendMessage(e,t,r,i,o){this.logger.info("Sending message");const n={p:"hcs-10",op:"message",operator_id:await this.getOperatorId(),data:t,m:r},s=await this.canSubmitToTopic(e,this.hwc.getAccountInfo().accountId),a=JSON.stringify(n);if(globalThis.Buffer.from(a).length>1e3){this.logger.info("Message payload exceeds 1000 bytes, storing via inscription");try{const e=globalThis.Buffer.from(t),r=`message-${Date.now()}.json`,i=await this.inscribeFile(e,r,{progressCallback:o?.progressCallback,waitMaxAttempts:o?.waitMaxAttempts,waitIntervalMs:o?.waitIntervalMs});if(!Ka(i))throw new Error("Failed to inscribe large message content");n.data=`hcs://1/${Ka(i)}`,this.logger.info(`Large message inscribed with topic ID: ${Ka(i)}`)}catch(c){throw this.logger.error("Error inscribing large message:",c),new Error(`Failed to handle large message: ${c instanceof Error?c.message:"Unknown error"}`)}}return await this.submitPayload(e,n,i,s.requiresFee)}async getPublicKey(e){return await this.mirrorNode.getPublicKey(e)}async handleConnectionRequest(e,t,r,o="Connection accepted. Looking forward to collaborating!",n=60){this.logger.info("Handling connection request");const s=this.hwc.getAccountInfo().accountId;if(!s)throw new Error("Failed to retrieve user account ID");const a=await this.mirrorNode.getPublicKey(t),c=await this.mirrorNode.getPublicKey(s);if(!c)throw new Error("Failed to retrieve public key");const l=new i.KeyList([c,a],1),d=this._generateHcs10Memo(Gd.CONNECTION,{ttl:n,inboundTopicId:e,connectionId:r}),u=(new i.TopicCreateTransaction).setTopicMemo(d).setAutoRenewAccountId(i.AccountId.fromString(s)).setAdminKey(l).setSubmitKey(l);this.logger.debug("Executing topic creation transaction");const p=await this.hwc.executeTransactionWithErrorHandling(u,!1);if(p?.error)throw this.logger.error(p.error),new Error(p.error);const h=p?.result;if(!h?.topicId)throw this.logger.error("Failed to create topic: topicId is null"),new Error("Failed to create topic: topicId is null");const g=h.topicId.toString(),m=`${e}@${s}`,f=await this.confirmConnection(e,g,t,r,m,o),y=await this.retrieveCommunicationTopics(s),b=await this.retrieveCommunicationTopics(t),w=`${b.inboundTopic}@${t}`;return await this.recordOutboundConnectionConfirmation({outboundTopicId:y.outboundTopic,requestorOutboundTopicId:b.outboundTopic,connectionRequestId:r,confirmedRequestId:f,connectionTopicId:g,operatorId:w,memo:`Connection established with ${t}`}),{connectionTopicId:g,confirmedConnectionSequenceNumber:f,operatorId:m}}async confirmConnection(e,t,r,i,o,n){this.logger.info("Confirming connection");const s={p:"hcs-10",op:"connection_created",connection_topic_id:t,connected_account_id:r,operator_id:o,connection_id:i,m:n},a=await this.submitPayload(e,s);if(!a?.topicSequenceNumber)throw this.logger.error("Failed to confirm connection: sequence number is null"),new Error("Failed to confirm connection: sequence number is null");return a.topicSequenceNumber.toNumber()}async create(e,t){const r=t?.progressCallback,i=new ps({module:"ProfileCreate",logger:this.logger,callback:r});try{const r=e instanceof tu;let o;if(o=t?.existingState?t.existingState:{currentStage:"init",completedPercentage:0,createdResources:[]},r){this.logger.info("Creating Agent Profile and HCS-10 Topics");const t=e.build();o.agentMetadata=t.metadata}else this.logger.info("Creating Person HCS-11 Profile");i.preparing(`Starting ${r?"agent":"person"} resource creation`,0,{state:o});const{inboundTopicId:n,outboundTopicId:s,state:a}=await this.createCommunicationTopics(t,i);let c,l,d;if(o=a,e.setInboundTopicId(n),e.setOutboundTopicId(s),r){const t=e.build();c=t.existingPfpTopicId||o.pfpTopicId,l=t.pfpBuffer,d=t.pfpFileName||"pfp.png"}else{const t=e.build();c=o.pfpTopicId,l=t.pfpBuffer,d=t.pfpFileName}!c&&l&&d?c=await this.handleProfilePictureCreation(l,d,o,i):c&&(i.preparing(`Using existing profile picture: ${c}`,50,{state:o}),o.pfpTopicId=c),await this.createAndInscribeProfile(r,e,c,o,n,s,t,i),o.currentStage="complete",o.completedPercentage=100,i.completed((r?"Agent":"Person")+" profile created successfully",{profileTopicId:o.profileTopicId,inboundTopicId:n,outboundTopicId:s,pfpTopicId:c,state:o});let u="";o.outboundTopicId&&(u=o.outboundTopicId);let p="";o.inboundTopicId&&(p=o.inboundTopicId);let h="";o.pfpTopicId&&(h=o.pfpTopicId);let g="";return o.profileTopicId&&(g=o.profileTopicId),{outboundTopicId:u,inboundTopicId:p,pfpTopicId:h,profileTopicId:g,success:!0,state:o}}catch(o){return i.failed("Error during profile creation",{error:o.message}),{outboundTopicId:"",inboundTopicId:"",pfpTopicId:"",profileTopicId:"",success:!1,error:o.message,state:{currentStage:"init",completedPercentage:0,error:o.message}}}}async handleProfilePictureCreation(e,t,r,i){r.currentStage="pfp",i.preparing("Creating profile picture",30,{state:r});const o=i.createSubProgress({minPercent:30,maxPercent:50,logPrefix:"PFP"}),n=await this.inscribePfp(e,t,{progressCallback:e=>o.report({...e,progressPercent:e.progressPercent??0,details:{...e.details,state:r}})});if(!n.success){let e="Failed to inscribe profile picture";throw n.error&&(e=n.error),new Error(e)}const s=n.pfpTopicId;return r.pfpTopicId=s,r.createdResources&&r.createdResources.push(`pfp:${r.pfpTopicId}`),i.preparing("Profile picture created",50,{state:r}),s}async createAndInscribeProfile(e,t,r,i,o,n,s,a){if(!this.hcs11Client)throw a&&a.failed("HCS11Client is not available"),new Error("HCS11Client is not available");if(this.logger.info("Creating and inscribing profile"),i.profileTopicId)a&&a.preparing(`Using existing ${e?"agent":"person"} profile`,95,{state:i});else{a&&a.preparing(`Storing HCS-11 ${e?"agent":"person"} profile`,80);const c=a?.createSubProgress({minPercent:80,maxPercent:95,logPrefix:"StoreProfile"});let l;if(e){const e=t.build(),i=e.metadata?.socials?Object.entries(e.metadata.socials).map(([e,t])=>({platform:e,handle:t})):[];l=this.hcs11Client.createAIAgentProfile(e.name,"manual"===e.metadata?.type?0:1,e.capabilities||[],e.metadata?.model||"unknown",{alias:e.name.toLowerCase().replace(/\s+/g,"_"),bio:e.bio,profileImage:r?`hcs://1/${r}`:void 0,socials:i,properties:e.metadata?.properties||{},inboundTopicId:o,outboundTopicId:n,creator:e.metadata?.creator})}else{const e=t.build(),{pfpBuffer:i,pfpFileName:s,...a}=e;l=this.hcs11Client.createPersonalProfile(e.display_name,{alias:e.alias,bio:e.bio,socials:e.socials,profileImage:r?`hcs://1/${r}`:e.profileImage,properties:e.properties,inboundTopicId:o,outboundTopicId:n})}const d=await this.hcs11Client.createAndInscribeProfile(l,s?.updateAccountMemo??!0,{progressCallback:e=>c?.report({...e,progressPercent:e.progressPercent??0})});if(!d.success){a&&a.failed(`Failed to inscribe ${e?"agent":"person"} profile`,{error:d.error});let t=`Failed to inscribe ${e?"agent":"person"} profile`;throw d.error&&(t=d.error),new Error(t)}i.profileTopicId=d.profileTopicId,i.createdResources&&i.createdResources.push(`profile:${d.profileTopicId}`),a&&a.preparing("HCS-11 Profile stored",95,{state:i})}}initializeRegistrationState(e,t){const r=t||{inboundTopicId:e,currentStage:"registration",completedPercentage:0,createdResources:[]};return"registration"!==r.currentStage&&"complete"!==r.currentStage&&(r.currentStage="registration"),r}updateStateForCompletedRegistration(e,t){e.currentStage="complete",e.completedPercentage=100,e.createdResources&&e.createdResources.push(`registration:${t}`)}async registerAgentWithGuardedRegistry(e,t=this.network,r){try{let o;if(this.logger.info("Registering agent with guarded registry"),r?.existingState?.inboundTopicId)this.logger.info("Using inboundTopicId from existing state"),o=r.existingState.inboundTopicId;else{const t=await this.retrieveProfile(e,!1,{maxRetries:5,retryDelay:3e3});if(!t.success||!t.profile||!t.topicInfo){const r=t.error||`Failed to retrieve profile for account ${e}. Make sure the agent profile is created and memo is updated before registration.`;return this.logger.error(r),{error:r,success:!1,state:{currentStage:"registration",completedPercentage:0,error:r}}}o=t.topicInfo.inboundTopic}const n=this.initializeRegistrationState(o,r?.existingState),s=new ps({module:"AgentRegistration",logger:this.logger,callback:r?.progressCallback});s.preparing("Preparing agent registration",10,{inboundTopicId:o,accountId:e});const a=await this.executeRegistration(e,t,this.guardedRegistryBaseUrl,this.logger);if(!a.success)return{...a,state:n};if(s.submitting("Submitting registration to registry",30,{transactionId:a.transactionId}),a.transaction){const e=i.Transaction.fromBytes(globalThis.Buffer.from(a.transaction,"base64"));this.logger.info("Processing registration transaction");const t=await this.hwc.executeTransactionWithErrorHandling(e,!0);if(t.error)return{...a,error:t.error,success:!1,state:n};this.logger.info("Successfully processed registration transaction")}s.confirming("Confirming registration transaction",60,{accountId:e,inboundTopicId:o,transactionId:a.transactionId});const c=r?.maxAttempts??60,l=r?.delayMs??2e3,d=await this.waitForRegistrationConfirmation(a.transactionId,t,this.guardedRegistryBaseUrl,c,l,this.logger);return this.updateStateForCompletedRegistration(n,o),s.completed("Agent registration complete",{transactionId:a.transactionId,inboundTopicId:o,state:n,confirmed:d}),{...a,confirmed:d,state:n}}catch(o){return this.logger.error(`Registration error: ${o.message}`),{error:`Error during registration: ${o.message}`,success:!1,state:{currentStage:"registration",completedPercentage:0,error:o.message}}}}async createAndRegisterAgent(e,t){try{const r=e.build(),i=t?.progressCallback,o=new ps({module:"AgentCreateRegister",logger:this.logger,callback:i});let n=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};if(n.agentMetadata=r.metadata,o.preparing("Starting agent creation process",0,{state:n}),"complete"!==n.currentStage||!n.inboundTopicId||!n.outboundTopicId||!n.profileTopicId){const t=await this.create(e,{progressCallback:e=>{const t=.3*(e.progressPercent||0);o.report({...e,progressPercent:t,details:{...e.details,state:e.details?.state||n}})},existingState:n,updateAccountMemo:!0});if(!("state"in t))throw new Error("Create method did not return expected agent state.");if(!t.success)throw new Error(t.error||"Failed to create agent resources");n=t.state,n.agentMetadata=r.metadata,this.logger.info("Waiting for account memo update to propagate..."),await new Promise(e=>setTimeout(e,5e3))}o.preparing(`Agent creation status: ${n.currentStage}, ${n.completedPercentage}%`,30,{state:n});const{accountId:s}=this.getAccountAndSigner();if("complete"!==n.currentStage||!n.createdResources?.includes(`registration:${n.inboundTopicId}`)){t?.baseUrl&&(this.guardedRegistryBaseUrl=t.baseUrl);const e=await this.registerAgentWithGuardedRegistry(s,r.network,{progressCallback:e=>{const t=30+.7*(e.progressPercent||0);o.report({...e,progressPercent:t,details:{...e.details,state:e.details?.state||n}})},maxAttempts:t?.maxAttempts,delayMs:t?.delayMs,existingState:n});if(!e.success)throw new Error(e.error||"Failed to register agent with registry");n=e.state}return o.completed("Agent creation and registration complete",{state:n}),{success:!0,state:n,metadata:{accountId:s,operatorId:`${n.inboundTopicId}@${s}`,inboundTopicId:n.inboundTopicId,outboundTopicId:n.outboundTopicId,profileTopicId:n.profileTopicId,pfpTopicId:n.pfpTopicId,privateKey:null,...n.agentMetadata}}}catch(r){return this.logger.error(`Failed to create and register agent: ${r.message}`),{success:!1,error:`Failed to create and register agent: ${r.message}`,state:t?.existingState||{currentStage:"init",completedPercentage:0,error:r.message}}}}async storeHCS11Profile(e,t,r,i,o=[],n={},s,a,c,l){try{const d=l?.progressCallback,u=new ps({module:"StoreHCS11Profile",logger:this.logger,callback:d});u.preparing("Preparing agent profile data",0);let p=c;if(!p&&s&&a){const e=u.createSubProgress({minPercent:0,maxPercent:60,logPrefix:"PFP"}),t=await this.inscribePfp(s,a,{progressCallback:t=>{e.report({stage:t.stage,message:t.message,progressPercent:t.progressPercent||0,details:t.details})}});t.success?p=t.pfpTopicId:u.failed("Failed to inscribe profile picture, continuing without PFP")}else c?u.preparing(`Using existing profile picture: ${c}`,30):u.preparing("No profile picture provided",30);if(!this.hcs11Client)return u.failed("HCS11Client is not available in this environment"),{profileTopicId:"",success:!1,error:"HCS11Client is not available in this environment",transactionId:""};const h=this.hcs11Client.getAgentTypeFromMetadata({type:n.type||"autonomous"});u.preparing("Building agent profile",65);const g=n.socials?Object.entries(n.socials).filter(([e,t])=>t).map(([e,t])=>({platform:e,handle:t})):void 0,m=this.hcs11Client.createAIAgentProfile(e,h,o,n.model||"unknown",{alias:e.toLowerCase().replace(/\s+/g,"_"),bio:t,profileImage:p?`hcs://1/${p}`:void 0,socials:g,properties:{version:n.version||"1.0.0",creator:n.creator||"Unknown",supported_languages:n.supported_languages||["en"],permissions:n.permissions||[],model_details:n.model_details,training:n.training,capabilities_description:n.capabilities_description,...n},inboundTopicId:r,outboundTopicId:i,creator:n.creator}),f=u.createSubProgress({minPercent:65,maxPercent:100,logPrefix:"Profile"}),y=await this.hcs11Client.createAndInscribeProfile(m,l?.updateAccountMemo??!0,{progressCallback:e=>{f.report({stage:e.stage,message:e.message,progressPercent:e.progressPercent||0,details:e.details})}});return y.success?(u.completed("Profile stored successfully",{profileTopicId:y.profileTopicId}),{profileTopicId:y.profileTopicId,pfpTopicId:p,success:!0,transactionId:y.transactionId||""}):(u.failed("Failed to inscribe profile"),{profileTopicId:"",success:!1,error:y.error||"Failed to inscribe profile",transactionId:y.transactionId||""})}catch(d){return this.logger.error(`Error storing HCS11 profile: ${d.message}`),{profileTopicId:"",success:!1,error:d.message,transactionId:""}}}async createTopic(e,t,r){this.logger.info("Creating topic");const{accountId:o,signer:n}=this.getAccountAndSigner(),s=(new i.TopicCreateTransaction).setTopicMemo(e),a=await this.mirrorNode.getPublicKey(o);t&&a&&(s.setAdminKey(a),s.setAutoRenewAccountId(o)),r&&a&&s.setSubmitKey(a);const c=await this.hwc.executeTransactionWithErrorHandling(s,!1),l=c.error;if(l)return this.logger.error(l),{success:!1,error:l};const d=c.result;return d?.topicId?{success:!0,topicId:d.topicId.toString()}:(this.logger.error("Failed to create topic: topicId is null"),{success:!1,error:"Failed to create topic: topicId is null"})}async submitPayload(e,t,r,o){let n;this.logger.debug(`Submitting payload to topic ${e}`),n="string"==typeof t?t:JSON.stringify(t);const s=(new i.TopicMessageSubmitTransaction).setTopicId(e).setMessage(n),a=this.getHcs10TransactionMemo(t);let c;if(a&&s.setTransactionMemo(a),o&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),s.setMaxTransactionFee(new i.Hbar(this.feeAmount))),r){const{signer:e}=this.getAccountAndSigner();s.freezeWithSigner(e);const t=await s.sign(r);c=await this.hwc.executeTransactionWithErrorHandling(t,!0)}else c=await this.hwc.executeTransactionWithErrorHandling(s,!1);if(c?.error)throw this.logger.error(`Failed to submit payload: ${c.error}`),new Error(`Failed to submit payload: ${c.error}`);if(!c?.result)throw this.logger.error("Failed to submit message: receipt is null or undefined"),new Error("Failed to submit message: receipt is null or undefined");return this.logger.debug("Payload submitted successfully via HWC"),c.result}async inscribeFile(e,t,r){const{accountId:i,signer:o}=this.getAccountAndSigner(),n=k.lookup(t)||"application/octet-stream",s=await us.createWithAuth({type:"client",accountId:i,signer:o,network:this.network}),a={mode:"file",waitForConfirmation:!0,waitMaxAttempts:r?.waitMaxAttempts||30,waitIntervalMs:r?.waitIntervalMs||4e3,progressCallback:r?.progressCallback,logging:{level:this.logger.getLevel?this.logger.getLevel():"info"}},c=await Oa({type:"buffer",buffer:e,fileName:t,mimeType:n},o,{...a,network:this.network},s);if(!c.confirmed||!c.inscription)throw new Error("Inscription was not confirmed");return c.inscription}getAccountAndSigner(){const e=this?.hwc?.getAccountInfo(),t=e?.accountId?.toString(),r=this?.hwc?.dAppConnector?.signers?.find(e=>e.getAccountId().toString()===t);if(!r)throw this.logger.error("Failed to find signer",{accountId:t,signers:this?.hwc?.dAppConnector?.signers,accountInfo:e}),new Error("Failed to find signer");return{accountId:t,signer:r}}async inscribePfp(e,t,r){try{const i=r?.progressCallback,o=new ps({module:"PFP-Inscription",logger:this.logger,callback:i});if(!this.hcs11Client)return o.failed("HCS11Client is not available in this environment"),{pfpTopicId:"",success:!1,error:"HCS11Client is not available in this environment",transactionId:""};o.preparing("Preparing to inscribe profile picture",10),this.logger.info("Inscribing profile picture using HCS-11 client");const n=e=>{o.report({stage:e.stage||"confirming",message:e.message||"Processing PFP inscription",progressPercent:e.progressPercent||50,details:e.details})},s=await this.hcs11Client.inscribeImage(e,t,{progressCallback:n});if(!s.success){let e="Failed to inscribe profile picture";s.error&&(e=s.error);let t="";return s.transactionId&&(t=s.transactionId),{pfpTopicId:"",success:!1,error:e,transactionId:t}}return o.completed("Successfully inscribed profile picture",{pfpTopicId:s.imageTopicId}),this.logger.info(`Successfully inscribed profile picture with topic ID: ${s.imageTopicId}`),{pfpTopicId:s.imageTopicId,success:!0,transactionId:s.transactionId||""}}catch(i){return this.logger.error(`Error inscribing profile picture: ${i.message}`),{pfpTopicId:"",success:!1,error:i.message,transactionId:""}}}async createCommunicationTopics(e,t){let r=e?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};t&&t.preparing("Starting communication topic creation",0,{state:r});const{accountId:i}=this.getAccountAndSigner();if(!r.outboundTopicId){r.currentStage="topics",t&&t.preparing("Creating outbound topic",5,{state:r});const o=this._generateHcs10Memo(Gd.OUTBOUND,{ttl:e?.ttl,accountId:i}),n=await this.createTopic(o,!0,!0);if(!n.success||!n.topicId)throw new Error(n.error||"Failed to create outbound topic");r.outboundTopicId=n.topicId,r.createdResources&&r.createdResources.push(`outbound:${r.outboundTopicId}`)}if(!r.inboundTopicId){r.currentStage="topics",t&&t.preparing("Creating inbound topic",10,{state:r});const o=this._generateHcs10Memo(Gd.INBOUND,{ttl:e?.ttl,accountId:i}),n=await this.createTopic(o,!0,!1);if(!n.success||!n.topicId)throw new Error(n.error||"Failed to create inbound topic");r.inboundTopicId=n.topicId,r.createdResources&&r.createdResources.push(`inbound:${r.inboundTopicId}`)}return{inboundTopicId:r.inboundTopicId,outboundTopicId:r.outboundTopicId,state:r}}},exports.CanonicalAgentDataSchema=Bu,exports.ConnectionConfirmationError=eu,exports.ConnectionsManager=class{constructor(e){this.connections=new Map,this.pendingRequests=new Map,this.profileCache=new Map,this.filterPendingAccountIds=new Set;const t={module:"ConnectionsManager",level:e?.logLevel||"info",prettyPrint:!0,silent:e?.silent};if(this.logger=z.getInstance(t),e?.filterPendingAccountIds&&(this.filterPendingAccountIds=new Set(e.filterPendingAccountIds)),!e.baseClient)throw new Error("ConnectionsManager requires a baseClient to operate");this.baseClient=e.baseClient}async fetchConnectionData(e){try{const t=await this.baseClient.retrieveCommunicationTopics(e),r=e=>Boolean(e)&&!e.includes(":");if(!r(t?.inboundTopic)||!r(t?.outboundTopic))return this.logger.warn("Invalid topic IDs detected in retrieved communication topics"),this.getAllConnections();const[i,o]=await Promise.all([this.baseClient.getMessages(t?.outboundTopic),this.baseClient.getMessages(t?.inboundTopic)]);this.processOutboundMessages(i.messages||[],e),this.processInboundMessages(o.messages||[]);const n=Array.from(this.connections.values()).filter(e=>"pending"===e.status||e.isPending).length;return this.logger.debug(`Processed ${i.messages?.length||0} outbound and ${o.messages?.length||0} inbound messages. Found ${n} pending connections.`),await this.checkTargetInboundTopicsForConfirmations(),await this.checkOutboundRequestsForConfirmations(),await this.fetchProfilesForConnections(),await this.fetchConnectionActivity(),this.getAllConnections()}catch(t){return this.logger.error("Error fetching connection data:",t),this.getAllConnections()}}async checkTargetInboundTopicsForConfirmations(){const e=Array.from(this.connections.values()).filter(e=>(e.isPending||"pending"===e.status)&&e.targetInboundTopicId);if(0===e.length)return;const t=new Map;e.forEach(e=>{if(e.targetInboundTopicId){const r=t.get(e.targetInboundTopicId)||[];r.push(e),t.set(e.targetInboundTopicId,r)}});for(const[i,o]of t.entries())for(let e=1;e<=2;e++)try{const t=(await this.baseClient.getMessages(i)).messages||[];let r=!1;for(const e of o){const i=e.connectionRequestId;if(!i)continue;const o=t.find(t=>{if("connection_created"!==t.op||!t.connection_topic_id)return!1;if(t.connection_id!==i)return!1;if(e.uniqueRequestKey){const r=e.uniqueRequestKey.split(":");if(r.length>1){const i=r[1];if(t.operator_id&&t.operator_id===i)return!0;if(t.connected_account_id===e.targetAccountId)return!0}}return!0});if(o?.connection_topic_id){r=!0;const t=o.connection_topic_id;let n=e.uniqueRequestKey;const s={connectionTopicId:t,targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName,targetInboundTopicId:e.targetInboundTopicId,status:"established",isPending:!1,needsConfirmation:!1,created:new Date(o.created||e.created),profileInfo:e.profileInfo,connectionRequestId:i,uniqueRequestKey:e.uniqueRequestKey,originTopicId:e.originTopicId,processed:e.processed,memo:e.memo};this.connections.set(t,s),n&&this.connections.delete(n),this.logger.debug(`Confirmed connection in target inbound topic: ${t}`)}}if(r||2===e)break;await new Promise(e=>setTimeout(e,500))}catch(r){if(this.logger.debug(`Error fetching target inbound topic ${i}:`,r),2===e)break;await new Promise(e=>setTimeout(e,500))}}async checkOutboundRequestsForConfirmations(){const e=Array.from(this.connections.values());this.logger.info(`Total connections in map: ${e.length}`);const t=e.filter(e=>"pending"===e.status);this.logger.info(`Connections with status='pending': ${t.length}`);const r=e.filter(e=>"pending"===e.status);if(Boolean(r?.length))for(const o of r){if(this.logger.debug(`Processing pending connection: ${o.connectionTopicId}`),!o.targetAccountId){this.logger.debug(`Skipping connection ${o.connectionTopicId} - no targetAccountId`);continue}let e=o.targetInboundTopicId;if(!e)try{const t=await this.baseClient.retrieveProfile(o.targetAccountId);if(!t?.profile?.inboundTopicId){this.logger.debug(`Couldn't get inbound topic ID for account ${o.targetAccountId}`);continue}e=t.profile.inboundTopicId,this.connections.set(o.connectionTopicId,{...o,targetInboundTopicId:e}),this.logger.debug(`Updated connection ${o.connectionTopicId} with inbound topic ID: ${e}`)}catch(i){this.logger.debug(`Error fetching profile for ${o.targetAccountId}: ${i}`);continue}if(!e||e.includes(":")){this.logger.debug(`Skipping invalid inbound topic format: ${e}`);continue}const t=o.connectionRequestId||o.inboundRequestId;if(t)try{this.logger.debug(`Checking for confirmations on topic ${e} for request ID ${t}`);const r=await this.baseClient.getMessages(e),i=(r.messages||[]).find(e=>"connection_created"===e.op&&e.connection_id===t&&e.connection_topic_id);if(i?.connection_topic_id){const e=i.connection_topic_id;this.logger.info(`Found confirmation for request #${t} to ${o.targetAccountId} on their inbound topic`);const r={connectionTopicId:e,targetAccountId:o.targetAccountId,targetAgentName:o.targetAgentName,targetInboundTopicId:o.targetInboundTopicId,targetOutboundTopicId:o.targetOutboundTopicId,status:"established",isPending:!1,needsConfirmation:!1,created:new Date(i.created||o.created),lastActivity:new Date(i.created||o.created),profileInfo:o.profileInfo,connectionRequestId:o.connectionRequestId,confirmedRequestId:o.confirmedRequestId,requesterOutboundTopicId:o.requesterOutboundTopicId,inboundRequestId:o.inboundRequestId,closedReason:o.closedReason,closeMethod:o.closeMethod,uniqueRequestKey:o.uniqueRequestKey,originTopicId:o.originTopicId,processed:o.processed,memo:o.memo};this.connections.set(e,r),o.connectionTopicId&&this.connections.delete(o.connectionTopicId)}else this.logger.debug(`No confirmation found for request ID ${t} on topic ${e}`)}catch(i){this.logger.warn(`Error checking for confirmations on target inbound topic for ${o.targetAccountId}: ${i}`)}else this.logger.debug(`Skipping connection ${o.connectionTopicId} - no request ID`)}else this.logger.info("No pending connections found")}async fetchProfilesForConnections(){const e=new Set;for(const r of this.connections.values())r.targetAccountId&&!this.profileCache.has(r.targetAccountId)&&e.add(r.targetAccountId);const t=Array.from(e).map(async e=>{try{const t=await this.baseClient.retrieveProfile(e);t.success&&t.profile&&(this.addProfileInfo(e,t.profile),this.updatePendingConnectionsWithProfileInfo(e,t.profile))}catch(t){this.logger.debug(`Failed to fetch profile for ${e}:`,t)}});await Promise.allSettled(t)}updatePendingConnectionsWithProfileInfo(e,t){const r=Array.from(this.connections.values()).filter(t=>t.targetAccountId===e&&(t.isPending||t.needsConfirmation)&&!t.targetInboundTopicId);if(r.length>0&&t.inboundTopicId)for(const i of r){const e={...i,targetInboundTopicId:t.inboundTopicId};this.connections.set(i.connectionTopicId,e)}}async fetchConnectionActivity(){const e=this.getActiveConnections().filter(e=>{const t=e.connectionTopicId;return!(!t||t.includes(":")||!t.match(/^0\.0\.\d+$/))||(this.logger.debug(`Skipping activity fetch for invalid topic ID format: ${t}`),!1)}).map(async e=>{try{const t=e.connectionTopicId,r=await this.baseClient.getMessages(t);r?.messages?.length>0&&this.processConnectionMessages(t,r.messages)}catch(t){this.logger.debug(`Failed to fetch activity for ${e.connectionTopicId}:`,t)}});await Promise.allSettled(e)}shouldFilterAccount(e){return!!this.filterPendingAccountIds.has(e)&&!this.hasEstablishedConnectionWithAccount(e)}processOutboundMessages(e,t){if(!Boolean(e?.length))return Array.from(this.connections.values());const r=e.filter(e=>"connection_request"===e.op&&e.connection_request_id);for(const n of r){const e=n.connection_request_id,r=n.operator_id||"",i=this.baseClient.extractAccountFromOperatorId(r),o=this.baseClient.extractTopicFromOperatorId(r);if(this.shouldFilterAccount(i)){this.logger.debug(`Filtering out outbound request to account: ${i}`);continue}const s=Array.from(this.connections.values()).some(t=>t.connectionRequestId===e&&!t.isPending&&t.targetAccountId===i),a=`req-${e}:${r}`;if(!s&&!this.pendingRequests.has(a)){const s={id:e,requesterId:t,requesterTopicId:n.outbound_topic_id||"",targetAccountId:i,targetTopicId:o,operatorId:r,sequenceNumber:n.sequence_number,created:n.created||new Date,memo:n.m,status:"pending"};if(this.pendingRequests.set(a,s),!this.connections.has(a)){const t={connectionTopicId:a,targetAccountId:i,targetInboundTopicId:o,status:"pending",isPending:!0,needsConfirmation:!1,created:n.created||new Date,connectionRequestId:e,uniqueRequestKey:a,originTopicId:n.outbound_topic_id||"",processed:!1,memo:n.m};this.connections.set(a,t)}}}const i=e.filter(e=>"connection_created"===e.op&&e.connection_topic_id&&e.connection_request_id);for(const n of i){const e=n.connection_request_id,t=n.connection_topic_id,r=this.baseClient.extractAccountFromOperatorId(n.operator_id||"");if(this.shouldFilterAccount(r)){this.logger.debug(`Filtering out outbound confirmation to account: ${r}`);continue}const i=`req-${e}:${n.operator_id}`,o=this.pendingRequests.get(i);if(o&&(o.status="confirmed"),this.connections.has(i)&&this.connections.delete(i),this.connections.has(t)){const r=this.connections.get(t);this.connections.set(t,{...r,status:"established",isPending:!1,needsConfirmation:!1,connectionRequestId:e,confirmedRequestId:n.confirmed_request_id,requesterOutboundTopicId:n.outbound_topic_id,uniqueRequestKey:i,originTopicId:n.outbound_topic_id||"",processed:!1,memo:n.m})}else this.connections.set(t,{connectionTopicId:t,targetAccountId:r,status:"established",isPending:!1,needsConfirmation:!1,created:n.created||new Date,connectionRequestId:e,confirmedRequestId:n.confirmed_request_id,requesterOutboundTopicId:n.outbound_topic_id,uniqueRequestKey:i,originTopicId:n.outbound_topic_id||"",processed:!1,memo:n.m})}const o=e.filter(e=>"connection_closed"===e.op||"close_connection"===e.op&&e.connection_topic_id);for(const n of o){const e=n.connection_topic_id;if(this.connections.has(e)){const t=this.connections.get(e);if(this.shouldFilterAccount(t.targetAccountId)&&"established"!==t.status)continue;const r=n.connection_request_id&&n.operator_id?`req-${n.connection_request_id}:${n.operator_id}`:void 0;this.connections.set(e,{...t,status:"closed",isPending:!1,needsConfirmation:!1,lastActivity:n.created||new Date,closedReason:n.reason,closeMethod:n.close_method,uniqueRequestKey:r,originTopicId:t.originTopicId,processed:!1,memo:n.m})}}return Array.from(this.connections.values()).filter(e=>"established"===e.status||"closed"===e.status||!this.filterPendingAccountIds.has(e.targetAccountId))}processInboundMessages(e){if(!Boolean(e?.length))return Array.from(this.connections.values());const t=e.filter(e=>"connection_request"===e.op&&e.sequence_number),r=e.filter(e=>"connection_created"===e.op&&e.connection_topic_id&&e.connection_id);for(const i of t){const e=i.sequence_number,t=i.operator_id||"",o=this.baseClient.extractAccountFromOperatorId(t),n=this.baseClient.extractTopicFromOperatorId(t);if(this.shouldFilterAccount(o)){this.logger.debug(`Filtering out request from account: ${o}`);continue}const s=`inb-${e}:${t}`;r.some(t=>t.connection_id===e)?this.logger.debug(`Skipping request from ${o} as it has already been confirmed`):this.connections.has(s)||this.connections.set(s,{connectionTopicId:s,targetAccountId:o,targetInboundTopicId:n,status:"needs_confirmation",isPending:!1,needsConfirmation:!0,created:i.created||new Date,inboundRequestId:e,uniqueRequestKey:s,originTopicId:n,processed:!1,memo:i.m})}for(const i of r){const e=i.connection_id,t=i.connection_topic_id,r=i.connected_account_id||"",o=i.operator_id||"";if(this.shouldFilterAccount(r)){this.logger.debug(`Filtering out confirmation for account: ${r}`);continue}const n=`inb-${e}:${o}`;if(this.connections.has(n)&&this.connections.delete(n),this.connections.has(t)){const r=this.connections.get(t);this.connections.set(t,{...r,status:"established",isPending:!1,needsConfirmation:!1,inboundRequestId:e,uniqueRequestKey:n,originTopicId:i.connection_topic_id,processed:!1,memo:i.m})}else this.connections.set(t,{connectionTopicId:t,targetAccountId:r,status:"established",isPending:!1,needsConfirmation:!1,created:i.created||new Date,inboundRequestId:e,uniqueRequestKey:n,originTopicId:i.connection_topic_id,processed:!1,memo:i.m})}return Array.from(this.connections.values()).filter(e=>"established"===e.status||"closed"===e.status||!this.filterPendingAccountIds.has(e.targetAccountId))}processConnectionMessages(e,t){if(!t||0===t.length||!this.connections.has(e))return this.connections.get(e);const r=t.filter(e=>e.created).sort((e,t)=>{const r=e.created?new Date(e.created).getTime():0;return(t.created?new Date(t.created).getTime():0)-r})[0];if(r?.created){const t=this.connections.get(e);this.connections.set(e,{...t,lastActivity:r.created})}const i=t.find(e=>"close_connection"===e.op);if(i){const t=this.connections.get(e);this.connections.set(e,{...t,status:"closed",lastActivity:i.created||new Date,closedReason:i.reason,closeMethod:"explicit"})}return this.connections.get(e)}addProfileInfo(e,t){this.profileCache.set(e,t);const r=Array.from(this.connections.values()).filter(t=>t.targetAccountId===e);for(const i of r)this.connections.set(i.connectionTopicId,{...i,profileInfo:t,targetAgentName:t.display_name,targetInboundTopicId:t.inboundTopicId,targetOutboundTopicId:t.outboundTopicId})}getAllConnections(){return Array.from(this.connections.values()).filter(e=>"established"===e.status||"closed"===e.status||!this.filterPendingAccountIds.has(e.targetAccountId))}getPendingRequests(){return Array.from(this.connections.values()).filter(e=>e.isPending&&!this.filterPendingAccountIds.has(e.targetAccountId))}hasEstablishedConnectionWithAccount(e){return Array.from(this.connections.values()).some(t=>t.targetAccountId===e&&"established"===t.status)}getActiveConnections(){return Array.from(this.connections.values()).filter(e=>"established"===e.status)}getConnectionsNeedingConfirmation(){return Array.from(this.connections.values()).filter(e=>e.needsConfirmation&&!this.filterPendingAccountIds.has(e.targetAccountId))}getConnectionByTopicId(e){return this.connections.get(e)}getConnectionByAccountId(e){return Array.from(this.connections.values()).find(t=>t.targetAccountId===e&&"established"===t.status)}getConnectionsByAccountId(e){return Array.from(this.connections.values()).filter(t=>t.targetAccountId===e)}updateOrAddConnection(e){this.connections.set(e.connectionTopicId,e)}clearAll(){this.connections.clear(),this.pendingRequests.clear()}isConnectionRequestProcessed(e,t){for(const r of this.connections.values()){if(r.originTopicId===e&&r.inboundRequestId===t&&r.processed)return!0;if(r.originTopicId===e&&r.connectionRequestId===t&&r.processed)return!0}return!1}markConnectionRequestProcessed(e,t){let r=!1;for(const[i,o]of this.connections.entries())o.originTopicId===e&&o.inboundRequestId===t&&(this.connections.set(i,{...o,processed:!0}),r=!0,this.logger.debug(`Marked inbound connection request #${t} on topic ${e} as processed`)),o.originTopicId===e&&o.connectionRequestId===t&&(this.connections.set(i,{...o,processed:!0}),r=!0,this.logger.debug(`Marked outbound connection request #${t} on topic ${e} as processed`));return r}async getPendingTransactions(e,t){try{const i=await this.baseClient.getTransactionRequests(e,t?{...t}:void 0),o=[];for(const e of i)try{const t=await this.baseClient.mirrorNode.getScheduledTransactionStatus(e.schedule_id);t.executed||t.deleted||o.push(e)}catch(r){this.logger.error(`Error checking transaction status: ${r}`),o.push(e)}return o}catch(r){return this.logger.error(`Error getting pending transactions: ${r}`),[]}}getScheduledTransactionStatus(e){return this.baseClient.mirrorNode.getScheduledTransactionStatus(e)}async getLastOperatorActivity(e,t){try{const r=(await this.baseClient.getMessageStream(e)).messages.filter(e=>e.operator_id&&e.operator_id.includes(t)&&e.created);if(0===r.length)return;return r.sort((e,t)=>t.created.getTime()-e.created.getTime()),r[0].created}catch(r){return void this.logger.error(`Error getting last operator activity: ${r}`)}}},exports.ContentResolverRegistry=Xh,exports.ContentResolverRegistryImpl=Yh,exports.ContentStoreService=Qh,exports.CustomFeeType=Gh,exports.DiscoveryError=Mh,exports.DiscoveryErrorCodes={INVALID_MESSAGE:"INVALID_MESSAGE",TIMEOUT:"TIMEOUT",INSUFFICIENT_PETALS:"INSUFFICIENT_PETALS",FLORA_CREATION_FAILED:"FLORA_CREATION_FAILED",ALREADY_IN_DISCOVERY:"ALREADY_IN_DISCOVERY",INVALID_STATE:"INVALID_STATE"},exports.DiscoveryOperation=Ph,exports.DiscoveryState=Bh,exports.EVMBridge=class{constructor(e="mainnet-public",t="mirrornode.hedera.com/api/v1/contracts/call",r){this.network=e,this.mirrorNodeUrl=t,this.cache=r||new ec,this.logger=z.getInstance({module:"EVMBridge"})}async executeCommands(e,t={}){let r={...t};const o={};for(const s of e){const e=`${s.c.contractAddress}-${s.c.abi.name}`,t=await this.cache.get(e);if(t)o[s.c.abi.name]=JSON.parse(t),Object.assign(r,o[s.c.abi.name]);else try{const t=new c.ethers.Interface([{...s.c.abi}]),n=t.encodeFunctionData(s.c.abi.name),a=i.ContractId.fromSolidityAddress(s.c.contractAddress),l=await this.readFromMirrorNode(n,i.AccountId.fromString("0.0.800"),a);if(this.logger.info(`Result for ${s.c.contractAddress}:`,l?.result),!l?.result){this.logger.warn(`Failed to get result from mirror node for ${s.c.contractAddress}`),o[s.c.abi.name]="0",Object.assign(r,o[s.c.abi.name]);continue}const d=t?.decodeFunctionResult(s.c.abi.name,l.result);let u={values:[]};d&&s.c.abi.outputs?.forEach((e,t)=>{const r=tc(d[t],e.type);u.values.push(r),e.name&&(u[e.name]=r)}),await this.cache.set(e,JSON.stringify(u)),o[s.c.abi.name]=u,r[s.c.abi.name]=u}catch(n){this.logger.error(`Error executing command for ${s.c.contractAddress}:`,n),o[s.c.abi.name]="0",Object.assign(r,o[s.c.abi.name])}}return{results:o,stateData:r}}async executeCommand(e,t={}){const{results:r,stateData:i}=await this.executeCommands([e],t);return{result:r[e.c.abi.name],stateData:i}}async readFromMirrorNode(e,t,r){try{const i=r.toSolidityAddress(),o=t.toSolidityAddress(),n=await fetch(`https://${this.network}.${this.mirrorNodeUrl}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({block:"latest",data:e,estimate:!1,gas:3e5,gasPrice:1e8,from:o.startsWith("0x")?o:`0x${o}`,to:i?.startsWith("0x")?i:`0x${i}`,value:0})});if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);return await n.json()}catch(i){return this.logger.error("Error reading from mirror node:",i),null}}async clearCache(){await this.cache.clear()}async clearCacheForContract(e,t){await this.cache.delete(`${e}-${t}`)}setLogLevel(e){this.logger.setLogLevel(e)}},exports.EndpointType=hc,exports.FallbackCryptoAdapter=dd,exports.FallbackHashAdapter=rd,exports.FallbackHmacAdapter=ad,exports.FeeConfigBuilder=Jh,exports.FloraBuilder=class{constructor(){this.config={version:"1.0",type:3},this.logger=z.getInstance({module:"FloraBuilder"})}setDisplayName(e){return this.config.display_name=e,this}setBio(e){return this.config.bio=e,this}setMembers(e){return this.config.members=e,this}setThreshold(e){return this.config.threshold=e,this}setTopics(e){return this.config.topics=e,this.config.inboundTopicId=e.communication,this.config.outboundTopicId=e.transaction,this}setPolicies(e){return this.config.policies=e,this}setMetadata(e){return this.config.metadata=e,this}addMetadata(e,t){return this.config.metadata||(this.config.metadata={}),this.config.metadata[e]=t,this}build(){if(!this.config.display_name)throw new Error("Flora display name is required");if(!this.config.members||0===this.config.members.length)throw new Error("Flora must have at least one member");if(!this.config.threshold||this.config.threshold<1)throw new Error("Flora threshold must be at least 1");if(this.config.threshold>this.config.members.length)throw new Error("Flora threshold cannot exceed number of members");if(!this.config.topics)throw new Error("Flora topics are required");if(!this.config.inboundTopicId||!this.config.outboundTopicId)throw new Error("Flora inbound and outbound topic IDs are required");return this.config}},exports.FloraError=hh,exports.FloraOperation=ph,exports.FloraTopicType=uh,exports.GutenbergBridge=class{constructor(e){this.logger=e}convertToGutenberg(e){if(this.logger.debug("Converting BlockDefinition to Gutenberg format",{name:e.name}),!e||!e.name)throw new Error("Invalid block definition: missing name");const t={apiVersion:e.apiVersion,name:e.name,title:e.title,category:e.category,icon:e.icon,description:e.description,keywords:e.keywords,attributes:e.attributes,supports:e.supports};return t.attributes||(t.attributes={}),t.supports||(t.supports={}),this.logger.debug("Converted to Gutenberg format",{name:t.name,attributeCount:Object.keys(t.attributes).length}),t}parseFromGutenberg(e){if(this.logger.debug("Parsing Gutenberg block to BlockDefinition",{name:e.name}),!e||!e.name)throw new Error("Invalid Gutenberg block: missing name");if(!e.title)throw new Error("Invalid Gutenberg block: missing title");const t={apiVersion:e.apiVersion||3,name:e.name,title:e.title,category:e.category||"common",template_t_id:"",icon:e.icon,description:e.description,keywords:e.keywords,attributes:e.attributes||{},supports:e.supports||{}};return this.logger.debug("Parsed from Gutenberg format",{name:t.name}),t}validateBlockStructure(e){this.logger.debug("Validating block structure",{name:e.name});const t={isValid:!0,errors:[],warnings:[]};return this.validateBasicStructure(e,t),this.validateBlockName(e,t),this.validateAttributes(e,t),this.validateSupports(e,t),this.validateParentChild(e,t),t.isValid=0===t.errors.filter(e=>"critical"===e.severity||"high"===e.severity).length,this.logger.debug("Block structure validation completed",{name:e.name,isValid:t.isValid,errorCount:t.errors.length,warningCount:t.warnings.length}),t}validateBasicStructure(e,t){e.name&&""!==e.name.trim()||t.errors.push({code:"MISSING_NAME",message:"Block name cannot be empty",field:"name",severity:"critical"}),e&&(e.title||t.errors.push({code:"MISSING_TITLE",message:"Block title is required",field:"data.title",severity:"high"}),e.description||t.warnings.push({code:"MISSING_DESCRIPTION",message:"Block description improves usability",field:"data.description",impact:"usability"})),e||t.errors.push({code:"MISSING_BLOCK_JSON",message:"data is required for Gutenberg compatibility",field:"data",severity:"critical"})}validateBlockName(e,t){if(!e.name)return;/^[a-z0-9-]+\/[a-z0-9-]+$/.test(e.name)||t.errors.push({code:"INVALID_BLOCK_NAME",message:"Block name must follow namespace/block-name format (lowercase, hyphens only)",field:"name",severity:"high"}),e&&e.name&&t.warnings.push({code:"NAME_MISMATCH",message:"Block name should match data.name",field:"name",impact:"functionality"})}validateAttributes(e,t){if(!e||!e.attributes)return;const r=e.attributes,i=["string","number","boolean","array","object"];for(const[o,n]of Object.entries(r))n.type?(i.includes(n.type)||t.errors.push({code:"INVALID_ATTRIBUTE_TYPE",message:`Attribute '${o}' has invalid type '${n.type}'`,field:`attributes.${o}.type`,severity:"high"}),n.enum&&n.default&&!n.enum.includes(n.default)&&t.warnings.push({code:"DEFAULT_NOT_IN_ENUM",message:`Attribute '${o}' default value not in enum`,field:`attributes.${o}.default`,impact:"functionality"})):t.errors.push({code:"MISSING_ATTRIBUTE_TYPE",message:`Attribute '${o}' must specify a type`,field:`attributes.${o}.type`,severity:"medium"})}validateSupports(e,t){if(!e||!e.supports)return;const r=e.supports;if(void 0!==r.align)if("boolean"==typeof r.align);else if(Array.isArray(r.align)){const e=["left","center","right","wide","full"],i=r.align.filter(t=>!e.includes(t));i.length>0&&t.warnings.push({code:"INVALID_ALIGNMENT",message:`Invalid alignment values: ${i.join(", ")}`,field:"supports.align",impact:"functionality"})}}validateParentChild(e,t){e&&(e.parent&&t.warnings.push({code:"REQUIRES_PARENT",message:"Block requires a specific parent block",field:"parent",impact:"usability"}),e.provides&&Object.keys(e.provides).length>0&&t.warnings.push({code:"PROVIDES_CONTEXT",message:"Block provides context to child blocks",field:"provides",impact:"functionality"}),e.usesContext&&e.usesContext.length>0&&t.warnings.push({code:"USES_CONTEXT",message:"Block depends on context from parent blocks",field:"usesContext",impact:"functionality"}))}},exports.HCS=M,exports.HCS10BaseClient=Jd,exports.HCS10Cache=Yd,exports.HCS10Client=ru,exports.HCS11Client=Dd,exports.HCS11ProfileSchema=Od,exports.HCS12BaseClient=Ru,exports.HCS12BrowserClient=class extends Ru{constructor(e){super(e),this.hwc=e.hwc,this.updateAccountFromWallet(),this.logger.info("HCS-12 Browser Client initialized",{network:e.network,accountId:this.accountId})}async updateAccountFromWallet(){try{const{accountId:e}=await this.getAccountAndSigner();this.accountId=e}catch(e){this.logger.warn("No active wallet connection")}}async getAccountAndSigner(){const e=this?.hwc?.getAccountInfo(),t=e?.accountId?.toString(),r=this?.hwc?.dAppConnector?.signers?.find(e=>e.getAccountId().toString()===t);if(!r||!t)throw this.logger.error("Failed to find signer",{accountId:t,signers:this?.hwc?.dAppConnector?.signers,accountInfo:e}),new Error("Failed to find signer or account");return{accountId:t,signer:r}}getOperatorAccountId(){throw new Error("Browser client does not have operator account")}getOperatorPrivateKey(){throw new Error("Browser client does not have operator private key")}initializeRegistries(e){super.initializeRegistries(e),this._actionRegistry=new Eu(this.network,this.logger,this.actionRegistryTopicId,this),this._blockLoader=new vu(this.network,this.logger,this),this._assemblyRegistry=new Au(this.network,this.logger,this._assemblyRegistryTopicId,this),this._hashLinksRegistry=new Cu(this.network,this.logger,this._hashLinksRegistryTopicId,this),this.logger.info("Registries initialized with signer",{actionTopicId:this.actionRegistryTopicId,assemblyTopicId:this._assemblyRegistryTopicId,hashLinksTopicId:this._hashLinksRegistryTopicId})}async createRegistryTopic(e,t,r){const{accountId:o,signer:n}=await this.getAccountAndSigner(),s={[ou.ACTION]:"hcs-12:1:60:0",[ou.ASSEMBLY]:"hcs-12:1:60:2",[ou.HASHLINKS]:"hcs-12:1:60:3"}[e];this.logger.info("Creating registry topic via wallet",{registryType:ou[e],memo:s,accountId:o});const a=(new i.TopicCreateTransaction).setTopicMemo(s).setTransactionId(i.TransactionId.generate(o));if(t)if("boolean"==typeof t&&t){const e=await n.getAccountKey();a.setAdminKey(e),a.setAutoRenewAccountId(i.AccountId.fromString(o))}else(t instanceof i.PublicKey||t instanceof i.KeyList)&&(a.setAdminKey(t),a.setAutoRenewAccountId(i.AccountId.fromString(o)));if(r)if("boolean"==typeof r&&r){const e=await n.getAccountKey();a.setSubmitKey(e)}else(r instanceof i.PublicKey||r instanceof i.KeyList)&&a.setSubmitKey(r);const c=await a.freezeWithSigner(n),l=await c.executeWithSigner(n),d=await l.getReceiptWithSigner(n);if(!d.topicId)throw new Error("Failed to create topic: topicId is null");const u=d.topicId.toString();switch(this.logger.info("Registry topic created via wallet",{topicId:u,registryType:ou[e]}),e){case ou.ACTION:this.actionRegistryTopicId=u;break;case ou.ASSEMBLY:this._assemblyRegistryTopicId=u;case ou.HASHLINKS:}return u}async createAssemblyTopic(){this.logger.info("Creating new assembly topic");return await this.createRegistryTopic(ou.ASSEMBLY)}async registerAssemblyDirect(e,t){return this.logger.info("Registering assembly",{topicId:e,name:t.name,version:t.version}),this._submitMessage(e,JSON.stringify(t))}async addBlockToAssembly(e,t){return this.logger.info("Adding block to assembly",{assemblyTopicId:e,blockTopicId:t.block_t_id}),this._submitMessage(e,JSON.stringify(t))}async addActionToAssembly(e,t){return this.logger.info("Adding action to assembly",{assemblyTopicId:e,actionTopicId:t.t_id,alias:t.alias}),this._submitMessage(e,JSON.stringify(t))}async updateAssembly(e,t){return this.logger.info("Updating assembly",{assemblyTopicId:e,update:t}),this._submitMessage(e,JSON.stringify(t))}async storeBlock(e,t){if(!this.blockLoader)throw new Error("Block loader not initialized");return this.blockLoader.storeBlock(e,t)}async submitMessage(e,t,r){return this.logger.warn("submitMessage is deprecated. Use operation-specific methods instead."),this._submitMessage(e,t,r)}async _submitMessage(e,t,r){const{accountId:o,signer:n}=await this.getAccountAndSigner();this.logger.debug("Submitting message to topic via wallet",{topicId:e,messageLength:t.length,accountId:o});const s=(new i.TopicMessageSubmitTransaction).setTopicId(i.TopicId.fromString(e)).setMessage(t).setTransactionId(i.TransactionId.generate(o));r&&this.logger.warn("Submit key parameter ignored in browser client - using wallet signer");const a=await s.freezeWithSigner(n),c=await a.executeWithSigner(n),l=await c.getReceiptWithSigner(n);return this.logger.info("Message submitted successfully via wallet",{topicId:e,transactionId:c.transactionId.toString(),sequenceNumber:l.topicSequenceNumber?.toString()}),{transactionId:c.transactionId.toString(),sequenceNumber:l.topicSequenceNumber?Number(l.topicSequenceNumber):void 0}}getHashConnect(){return this.hwc}getAccountId(){return this.accountId}async isConnected(){try{return await this.getAccountAndSigner(),!0}catch{return!1}}async inscribeFile(e,t,r){const{accountId:i,signer:o}=await this.getAccountAndSigner();this.logger.info("Inscribing file via HCS-1 (browser)",{fileName:t});const n=k.lookup(t)||"application/octet-stream",s=await us.createWithAuth({type:"client",accountId:i,signer:o,network:this.network}),a={mode:"file",waitForConfirmation:!0,waitMaxAttempts:r?.waitMaxAttempts||30,waitIntervalMs:r?.waitIntervalMs||4e3,progressCallback:r?.progressCallback,logging:{level:this.logger.getLevel?this.logger.getLevel():"info"},network:this.network},c=await Oa({type:"buffer",buffer:e,fileName:t,mimeType:n},o,a,s);if(!c.confirmed||!c.inscription)throw new Error("Inscription failed to confirm");return c.inscription}async registerAction(e){const t=e.build();if(!this._actionRegistry)throw new Error("Action registry not initialized");const r=await this._submitMessage(this.actionRegistryTopicId,JSON.stringify(t));return this.logger.info("Action registered (browser)",{topicId:t.t_id,transactionId:r.transactionId}),e}async registerBlock(e){const t=e.getTemplate();if(t){const r=await this.inscribeFile(t,`${e.getName()||"block"}-template.html`);e.setTemplateTopicId(r.topic_id)}const r=e.build();if(!r.template_t_id)throw new Error("Block must have either a template buffer (via setTemplate) or template_t_id");const i=await this.inscribeFile(globalThis.Buffer.from(JSON.stringify(r,null,2)),`${r.name}-definition.json`);return this.logger.info("Block registered (browser)",{name:r.name,definitionTopicId:i.topic_id,templateTopicId:r.template_t_id}),e.setTopicId(i.topic_id),e}async createAssembly(e){if(!e)return this.createAssemblyTopic();const t=e.build(),r=await this.createAssemblyTopic();await this.registerAssemblyDirect(r,t);const i=e.getOperations();for(const o of i)switch(o.op){case"add-block":await this.addBlockToAssembly(r,o);break;case"add-action":await this.addActionToAssembly(r,o);break;case"update":await this.updateAssembly(r,o)}return this.logger.info("Assembly created (browser)",{topicId:r,name:t.name,version:t.version,operations:i.length}),r}},exports.HCS12Client=class extends Ru{constructor(e){super(e),this.operatorAccountId=e.operatorId,this.operatorCtx=oe({network:this.network,operatorId:this.operatorAccountId,operatorKey:e.operatorPrivateKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:"mainnet"===e.network?i.Client.forMainnet():i.Client.forTestnet()}),this.client=this.operatorCtx.client,this.logger.info("HCS-12 SDK Client initialized",{network:e.network,operatorId:this.operatorAccountId,keyType:this.operatorCtx.keyType})}initializeRegistries(e){super.initializeRegistries(e),this._actionRegistry=new Eu(this.network,this.logger,this.actionRegistryTopicId,this),this._blockLoader=new vu(this.network,this.logger,this),this._assemblyRegistry=new Au(this.network,this.logger,this._assemblyRegistryTopicId,this),this._hashLinksRegistry=new Cu(this.network,this.logger,this._hashLinksRegistryTopicId,this),this.logger.info("Registries initialized",{actionTopicId:this.actionRegistryTopicId,assemblyTopicId:this._assemblyRegistryTopicId,hashLinksTopicId:this._hashLinksRegistryTopicId})}async createRegistryTopic(e,t,r){const i={[ou.ACTION]:"hcs-12:1:60:0",[ou.ASSEMBLY]:"hcs-12:1:60:2",[ou.HASHLINKS]:"hcs-12:1:60:3"}[e];this.logger.info("Creating registry topic",{registryType:ou[e],memo:i});const o=Y({memo:i,adminKey:t,submitKey:r,operatorPublicKey:this.client.operatorPublicKey||void 0}),n=await o.execute(this.client),s=await n.getReceipt(this.client);if(!s.topicId)throw new Error("Failed to create topic: topicId is null");const a=s.topicId.toString();switch(this.logger.info("Registry topic created",{topicId:a,registryType:ou[e]}),e){case ou.ACTION:this.actionRegistryTopicId=a;break;case ou.ASSEMBLY:this._assemblyRegistryTopicId=a;case ou.HASHLINKS:}return a}async registerAssemblyDirect(e,t){return this.logger.info("Registering assembly",{topicId:e,name:t.name,version:t.version}),this._submitMessage(e,JSON.stringify(t))}async addBlockToAssembly(e,t){return this.logger.info("Adding block to assembly",{assemblyTopicId:e,blockTopicId:t.block_t_id}),this._submitMessage(e,JSON.stringify(t))}async addActionToAssembly(e,t){return this.logger.info("Adding action to assembly",{assemblyTopicId:e,actionTopicId:t.t_id,alias:t.alias}),this._submitMessage(e,JSON.stringify(t))}async updateAssembly(e,t){return this.logger.info("Updating assembly",{assemblyTopicId:e,update:t}),this._submitMessage(e,JSON.stringify(t))}async submitMessage(e,t,r){return this.logger.warn("submitMessage is deprecated. Use operation-specific methods instead."),this._submitMessage(e,t,r)}async _submitMessage(e,t,r){this.logger.debug("Submitting message to topic",{topicId:e,messageLength:t.length});const i=X({topicId:e,message:t});let o;if(r){const e=i.freezeWith(this.client),t=await e.sign(r);o=await t.execute(this.client)}else o=await i.execute(this.client);const n=await o.getReceipt(this.client);return this.logger.info("Message submitted successfully",{topicId:e,transactionId:o.transactionId.toString(),sequenceNumber:n.topicSequenceNumber?.toString()}),{transactionId:o.transactionId.toString(),sequenceNumber:n.topicSequenceNumber?Number(n.topicSequenceNumber):void 0}}getClient(){return this.client}getOperatorAccountId(){return this.operatorAccountId}getOperatorPrivateKey(){return this.operatorCtx.operatorKey.toString()}async inscribeFile(e,t,r){this.logger.info("Inscribing file via HCS-1",{fileName:t});const i=k.lookup(t)||"application/octet-stream",o=await us.createWithAuth({type:"server",accountId:this.operatorAccountId,privateKey:this.operatorCtx.operatorKey.toString(),network:this.network}),n={mode:"file",waitForConfirmation:!0,waitMaxAttempts:r?.waitMaxAttempts||30,waitIntervalMs:r?.waitIntervalMs||4e3,progressCallback:r?.progressCallback,logging:{level:this.logger.getLevel?this.logger.getLevel():"info"}},s=await Fa({type:"buffer",buffer:e,fileName:t,mimeType:i},{accountId:this.operatorAccountId,privateKey:this.operatorCtx.operatorKey,network:this.network},n,o);if(!s.confirmed||!s.inscription)throw new Error("Inscription failed to confirm");return s.inscription}async createAssemblyTopic(){if(!this._assemblyRegistry)throw new Error("Assembly registry not initialized");return this._assemblyRegistry.createAssemblyTopic()}async registerAction(e){const t=e.build();if(!this._actionRegistry)throw new Error("Action registry not initialized");const r=await this._submitMessage(this.actionRegistryTopicId,JSON.stringify(t));return this.logger.info("Action registered",{topicId:t.t_id,transactionId:r.transactionId}),e}async registerBlock(e){const t=e.getTemplate();if(t){const r=await this.inscribeFile(t,`${e.getName()||"block"}-template.html`);e.setTemplateTopicId(r.topic_id)}const r=e.build();if(!r.template_t_id)throw new Error("Block must have either a template buffer (via setTemplate) or template_t_id");const i=await this.inscribeFile(globalThis.Buffer.from(JSON.stringify(r,null,2)),`${r.name}-definition.json`);return this.logger.info("Block registered",{name:r.name,definitionTopicId:i.topic_id,templateTopicId:r.template_t_id}),e.setTopicId(i.topic_id),e}async createAssembly(e){const t=e.build(),r=await this.createAssemblyTopic();await this.registerAssemblyDirect(r,t);const i=e.getOperations();for(const o of i)switch(o.op){case"add-block":await this.addBlockToAssembly(r,o);break;case"add-action":await this.addActionToAssembly(r,o);break;case"update":await this.updateAssembly(r,o)}return this.logger.info("Assembly created",{topicId:r,name:t.name,version:t.version,operations:i.length}),r}},exports.HCS14Client=lp,exports.HCS14_PROTOCOL_REGEX=zu,exports.HCS15BaseClient=dh,exports.HCS15BrowserClient=class extends dh{constructor(e){super(e),this.signer=e.signer||e.hwc?.dAppConnector?.signers?.[0]}requireSigner(){if(!this.signer)throw new Error("HCS-15 Browser client requires an active DAppSigner");return this.signer}async createBaseAccount(e){const t=this.requireSigner(),r=i.PrivateKey.generateECDSA(),o=r.publicKey,n=ch({publicKey:o,initialBalance:new i.Hbar(e?.initialBalance??10),maxAutomaticTokenAssociations:e?.maxAutomaticTokenAssociations,accountMemo:e?.accountMemo}),s=await n.freezeWithSigner(t),a=await s.executeWithSigner(t),c=await a.getReceiptWithSigner(t),l=c?.accountId?.toString?.(),d=`0x${o.toEvmAddress()}`;return this.logger.info("Created HCS-15 base account (browser)",{accountId:l,evmAddress:d}),{accountId:l,privateKey:r,privateKeyHex:r.toStringRaw(),publicKey:o,evmAddress:d}}async createPetalAccount(e){const t=this.requireSigner(),r=lh({publicKey:("string"==typeof e.basePrivateKey?i.PrivateKey.fromStringECDSA(e.basePrivateKey):e.basePrivateKey).publicKey,initialBalance:new i.Hbar(e.initialBalance??1),maxAutomaticTokenAssociations:e.maxAutomaticTokenAssociations,accountMemo:e.accountMemo}),o=await r.freezeWithSigner(t),n=await o.executeWithSigner(t),s=await n.getReceiptWithSigner(t),a=s?.accountId?.toString?.();return this.logger.info("Created HCS-15 petal account (browser)",{accountId:a}),{accountId:a}}},exports.HCS15Client=class extends dh{constructor(e){super(e),this.operatorId=i.AccountId.fromString(e.operatorId),this.operatorCtx=oe({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:"mainnet"===this.network?i.Client.forMainnet():i.Client.forTestnet()}),this.client=this.operatorCtx.client}getKeyType(){return this.operatorCtx.keyType}async close(){try{this.client.close()}catch{}}async createBaseAccount(e){const t=i.PrivateKey.generateECDSA(),r=t.publicKey,o=ch({publicKey:r,initialBalance:new i.Hbar(e?.initialBalance??10),maxAutomaticTokenAssociations:e?.maxAutomaticTokenAssociations,accountMemo:e?.accountMemo}),n=await o.execute(this.client),s=await n.getReceipt(this.client);if(!s.accountId)throw new Error("HCS-15 BASE_ACCOUNT_CREATE_FAILED");const a=s.accountId.toString(),c=`0x${r.toEvmAddress()}`;return this.logger.info("Created HCS-15 base account",{accountId:a,evmAddress:c}),{accountId:a,privateKey:t,privateKeyHex:t.toStringRaw(),publicKey:r,evmAddress:c,receipt:s}}async createPetalAccount(e){const t=lh({publicKey:("string"==typeof e.basePrivateKey?i.PrivateKey.fromStringECDSA(e.basePrivateKey):e.basePrivateKey).publicKey,initialBalance:new i.Hbar(e.initialBalance??1),maxAutomaticTokenAssociations:e.maxAutomaticTokenAssociations,accountMemo:e.accountMemo}),r=await t.execute(this.client),o=await r.getReceipt(this.client);if(!o.accountId)throw new Error("HCS-15 PETAL_ACCOUNT_CREATE_FAILED");const n=o.accountId.toString();return this.logger.info("Created HCS-15 petal account",{accountId:n}),{accountId:n,receipt:o}}},exports.HCS16BaseClient=kh,exports.HCS16BrowserClient=class extends kh{constructor(e){super({network:e.network}),this.hwc=e.hwc,this.signer=e.signer}ensureConnected(){if(this.signer&&"function"==typeof this.signer.getAccountId)return this.signer.getAccountId().toString();const e=this.hwc?.getAccountInfo?.(),t=e?.accountId;if(!t)throw new Error("No active wallet connection");return t}getSigner(){if(this.signer)return this.signer;this.ensureConnected();const e=this.hwc?.dAppConnector?.signers?.[0];if(!e)throw new Error("No active wallet signer");return e}async createFloraTopic(e){this.ensureConnected();const t=this.getSigner(),r=gh({floraAccountId:e.floraAccountId,topicType:e.topicType,adminKey:e.adminKey,submitKey:e.submitKey,autoRenewAccountId:e.autoRenewAccountId}),i=await r.freezeWithSigner(t),o=await i.executeWithSigner(t),n=await o.getReceiptWithSigner(t);return n?.topicId?.toString?.()||""}async sendFloraCreated(e){const t=this.getSigner(),r=yh(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async sendTransaction(e){const t=this.getSigner(),r=bh(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async signSchedule(e){const t=this.getSigner(),r=await(new i.ScheduleSignTransaction).setScheduleId(e.scheduleId).freezeWithSigner(t);await r.executeWithSigner(t)}async sendStateUpdate(e){const t=this.getSigner(),r=wh(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async createFloraAccountWithTopics(e){const t=this.getSigner(),r=await this.assembleKeyList({members:e.members,threshold:e.threshold}),i=await this.assembleSubmitKeyList(e.members),o=mh({keyList:r,initialBalanceHbar:"number"==typeof e.initialBalanceHbar?e.initialBalanceHbar:5,maxAutomaticTokenAssociations:-1}),n=await o.freezeWithSigner(t),s=await n.executeWithSigner(t),a=await s.getReceiptWithSigner(t),c=a?.accountId?.toString?.();if(!c)throw new Error("Failed to create Flora account");const{communication:l,transaction:d,state:u}=this.buildFloraTopicCreateTxs({floraAccountId:c,keyList:r,submitList:i,autoRenewAccountId:e.autoRenewAccountId}),p=await(await(await l.freezeWithSigner(t)).executeWithSigner(t)).getReceiptWithSigner(t),h=await(await(await d.freezeWithSigner(t)).executeWithSigner(t)).getReceiptWithSigner(t),g=await(await(await u.freezeWithSigner(t)).executeWithSigner(t)).getReceiptWithSigner(t);return{floraAccountId:c,topics:{communication:p?.topicId?.toString?.()||"",transaction:h?.topicId?.toString?.()||"",state:g?.topicId?.toString?.()||""}}}async publishFloraCreated(e){const t=this.getSigner(),r=yh({topicId:e.communicationTopicId,operatorId:e.operatorId,floraAccountId:e.floraAccountId,topics:e.topics}),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async sendFloraJoinRequest(e){const t=this.getSigner(),r=Ih(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async sendFloraJoinVote(e){const t=this.getSigner(),r=Th(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async sendFloraJoinAccepted(e){const t=this.getSigner(),r=Sh(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}},exports.HCS16Client=class extends kh{constructor(e){super({network:e.network,logger:e.logger}),this.operatorId=i.AccountId.fromString(e.operatorId);const t=new G(e.network,this.logger);this.operatorCtx=oe({network:e.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:t,logger:this.logger,client:"mainnet"===e.network?i.Client.forMainnet():i.Client.forTestnet()}),this.client=this.operatorCtx.client}async createFloraTopic(e){const t=gh({floraAccountId:e.floraAccountId,topicType:e.topicType,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:this.client.operatorPublicKey||void 0,autoRenewAccountId:e.autoRenewAccountId}),r=await t.execute(this.client),i=await r.getReceipt(this.client);if(!i.topicId)throw new Error("Failed to create Flora topic");return i.topicId.toString()}async sendFloraCreated(e){const t=yh(e);return(await t.execute(this.client)).getReceipt(this.client)}async sendTransaction(e){const t=bh(e);return(await t.execute(this.client)).getReceipt(this.client)}async signSchedule(e){const t=await(new i.ScheduleSignTransaction).setScheduleId(e.scheduleId).freezeWith(this.client),r=await t.sign(e.signerKey);return(await r.execute(this.client)).getReceipt(this.client)}async sendStateUpdate(e){const t=wh(e);return(await t.execute(this.client)).getReceipt(this.client)}async assembleKeyList(e){return super.assembleKeyList(e)}async createFloraAccountWithTopics(e){const t=await this.assembleKeyList({members:e.members,threshold:e.threshold}),r=await this.assembleSubmitKeyList(e.members),i=mh({keyList:t,initialBalanceHbar:"number"==typeof e.initialBalanceHbar?e.initialBalanceHbar:5,maxAutomaticTokenAssociations:-1}),o=await i.execute(this.client),n=await o.getReceipt(this.client);if(!n.accountId)throw new Error("Failed to create Flora account");const s=n.accountId.toString(),{communication:a,transaction:c,state:l}=this.buildFloraTopicCreateTxs({floraAccountId:s,keyList:t,submitList:r,autoRenewAccountId:e.autoRenewAccountId}),d=await a.execute(this.client).then(e=>e.getReceipt(this.client)),u=await c.execute(this.client).then(e=>e.getReceipt(this.client)),p=await l.execute(this.client).then(e=>e.getReceipt(this.client));return{floraAccountId:s,topics:{communication:d.topicId.toString(),transaction:u.topicId.toString(),state:p.topicId.toString()}}}async publishFloraCreated(e){const t=yh({topicId:e.communicationTopicId,operatorId:e.operatorId,floraAccountId:e.floraAccountId,topics:e.topics});return(await t.execute(this.client)).getReceipt(this.client)}},exports.HCS17BaseClient=Rh,exports.HCS17BrowserClient=class extends Rh{constructor(e){super(e),this.hwc=e.hwc,this.signer=e.signer}ensureConnected(){if(this.signer&&"function"==typeof this.signer.getAccountId)return this.signer.getAccountId().toString();const e=this.hwc?.getAccountInfo?.(),t=e?.accountId;if(!t)throw new Error("No active wallet connection");return t}getSigner(){if(this.signer)return this.signer;this.ensureConnected();const e=this.hwc?.dAppConnector?.signers?.[0];if(!e)throw new Error("No active wallet signer");return e}async createStateTopic(e){this.ensureConnected();const t=this.getSigner(),r=Nh({ttl:e?.ttl??86400}),i=await r.freezeWithSigner(t),o=await i.executeWithSigner(t),n=await o.getReceiptWithSigner(t),s=n?.topicId?.toString?.()||"";return this.logger.info(`Created HCS-17 state topic via wallet: ${s}`),s}async submitMessage(e,t){const{valid:r,errors:i}=this.validateMessage(t);if(!r)throw new Error(`Invalid HCS-17 message: ${i.join(", ")}`);const o=this.getSigner(),n=_h({topicId:e,stateHash:t.state_hash,accountId:t.account_id,topics:t.topics,memo:t.m}),s=await n.freezeWithSigner(o),a=await s.executeWithSigner(o);return await a.getReceiptWithSigner(o),{}}async computeAndPublish(e){this.ensureConnected();const t=this.getSigner(),r=[];for(const a of e.topics){const e=(await this.mirrorNode.getTopicMessages(a,{limit:1,order:"desc"}))[0],t=e&&e.running_hash||"";r.push({topicId:a,latestRunningHash:t})}const i={accountId:e.accountId,publicKey:e.accountPublicKey,topics:r},o=this.calculateAccountStateHash(i),n=_h({topicId:e.publishTopicId,stateHash:o.stateHash,accountId:e.accountId,topics:e.topics,memo:e.memo}),s=await n.freezeWithSigner(t);return await s.executeWithSigner(t),{stateHash:o.stateHash}}},exports.HCS17Client=class extends Rh{constructor(e){super(e),this.operatorId=i.AccountId.fromString(e.operatorId),this.operatorCtx=oe({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:"mainnet"===e.network?i.Client.forMainnet():i.Client.forTestnet()}),this.client=this.operatorCtx.client}getKeyType(){return this.operatorCtx.keyType}async createStateTopic(e){const t=Nh({ttl:e?.ttl??86400,adminKey:e?.adminKey,submitKey:e?.submitKey,operatorPublicKey:this.client.operatorPublicKey||void 0}),r=await t.execute(this.client),i=await r.getReceipt(this.client);if(!i.topicId)throw new Error("Failed to create topic: topicId empty");const o=i.topicId.toString();return this.logger.info(`Created HCS-17 state topic ${o}`),o}async submitMessage(e,t){const{valid:r,errors:i}=this.validateMessage(t);if(!r)throw new Error(`Invalid HCS-17 message: ${i.join(", ")}`);const o=_h({topicId:e,stateHash:t.state_hash,accountId:t.account_id,topics:t.topics,memo:t.m}),n=await o.execute(this.client);return await n.getReceipt(this.client)}async computeAndPublish(e){const t=[];for(const a of e.topics){const e=(await this.mirrorNode.getTopicMessages(a,{limit:1,order:"desc"}))[0],r=e?.running_hash||"";t.push({topicId:a,latestRunningHash:r})}const r={accountId:e.accountId,publicKey:e.accountPublicKey,topics:t},i=this.calculateAccountStateHash(r);this.createStateHashMessage(i.stateHash,e.accountId,e.topics,e.memo);const o=_h({topicId:e.publishTopicId,stateHash:i.stateHash,accountId:e.accountId,topics:e.topics,memo:e.memo}),n=await o.execute(this.client),s=await n.getReceipt(this.client);return{stateHash:i.stateHash,receipt:s}}},exports.HCS17TopicType=Ah,exports.HCS18BaseClient=Vh,exports.HCS18BrowserClient=class{constructor(e){this.hwc=e.hwc}async submit(e,t){return await this.hwc.submitMessageToTopic(e,JSON.stringify(t))}async announce(e){const t=$h(e.data);return this.submit(e.discoveryTopicId,t)}async propose(e){const t=Hh(e.data);return this.submit(e.discoveryTopicId,t)}async respond(e){const t=qh(e.data);return this.submit(e.discoveryTopicId,t)}async complete(e){const t=jh(e.data);return this.submit(e.discoveryTopicId,t)}async withdraw(e){const t=Wh(e.data);return this.submit(e.discoveryTopicId,t)}},exports.HCS18Client=class extends Vh{constructor(e){super({network:e.network,logger:z.getInstance({level:e.logLevel||"info",module:"HCS-18",silent:e.silent})}),this.operatorCtx=oe({network:this.network,operatorId:e.operatorId,operatorKey:e.operatorKey,mirrorNode:this.mirrorNode,logger:this.logger,client:i.Client.forName(this.network)}),this.client=this.operatorCtx.client}async ensureInitialized(){await this.operatorCtx.ensureInitialized()}async createDiscoveryTopic(e){await this.ensureInitialized();const t=e?.ttlSeconds;let r;try{r=this.operatorCtx.operatorKey.publicKey}catch{r=void 0}const i=Uh({ttlSeconds:t,adminKey:e?.adminKey,submitKey:e?.submitKey,operatorPublicKey:r,memoOverride:e?.memoOverride}),o=await i.execute(this.client),n=await o.getReceipt(this.client),s=n.topicId?.toString();if(!s)throw new Error("Failed to create discovery topic");return{topicId:s,receipt:n}}async announce(e){await this.ensureInitialized();const t=$h(e.data),r=Lh({topicId:e.discoveryTopicId,message:t,transactionMemo:e.memo}),i=await r.execute(this.client),o=await i.getReceipt(this.client),n=o.topicSequenceNumber.toNumber();return{receipt:o,sequenceNumber:n}}async propose(e){await this.ensureInitialized();const t=Hh(e.data),r=Lh({topicId:e.discoveryTopicId,message:t,transactionMemo:e.memo}),i=await r.execute(this.client),o=await i.getReceipt(this.client),n=o.topicSequenceNumber.toNumber();return{receipt:o,sequenceNumber:n}}async respond(e){await this.ensureInitialized();const t=qh(e.data),r=Lh({topicId:e.discoveryTopicId,message:t,transactionMemo:e.memo}),i=await r.execute(this.client);return await i.getReceipt(this.client)}async complete(e){await this.ensureInitialized();const t=jh(e.data),r=Lh({topicId:e.discoveryTopicId,message:t,transactionMemo:e.memo}),i=await r.execute(this.client);return await i.getReceipt(this.client)}async withdraw(e){await this.ensureInitialized();const t=Wh(e.data),r=Lh({topicId:e.discoveryTopicId,message:t,transactionMemo:e.memo}),i=await r.execute(this.client);return await i.getReceipt(this.client)}},exports.HCS20BaseClient=Wp,exports.HCS20BurnMessageSchema=Dp,exports.HCS20Client=class extends Wp{constructor(e){super(e),this.operatorAccountId="string"==typeof e.operatorId?i.AccountId.fromString(e.operatorId):e.operatorId,this.operatorId=this.operatorAccountId.toString();const t="mainnet"===this.network?i.Client.forMainnet():i.Client.forTestnet();this.operatorCtx=oe({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:t}),this.client=this.operatorCtx.client,this.operatorCtx.ensureInitialized()}async ensureInitialized(){await this.operatorCtx.ensureInitialized()}async submitPayload(e,t){let r;if(t){const i=e.freezeWith(this.client),o=await i.sign(t);r=await o.execute(this.client)}else r=await e.execute(this.client);const o=await r.getReceipt(this.client);if(!o||o.status!==i.Status.Success)throw new Error("Failed to submit message to topic");return{receipt:o,transactionId:r.transactionId.toString()}}async createPublicTopic(e){await this.ensureInitialized(),this.logger.info("Creating public HCS-20 topic...");const t=await(new i.TopicCreateTransaction).setTopicMemo(e||"HCS-20 Public Topic").execute(this.client),r=await t.getReceipt(this.client);if(r.status!==i.Status.Success||!r.topicId)throw new Error("Failed to create public topic");const o=r.topicId.toString();return this.logger.info(`Created public topic: ${o}`),this.publicTopicId=o,o}async createRegistryTopic(){await this.ensureInitialized(),this.logger.info("Creating HCS-20 registry topic...");const e=new Ap({operatorId:this.operatorId,operatorKey:this.operatorCtx.operatorKey,network:this.network}),t=await e.createRegistry({submitKey:this.operatorCtx.operatorKey,adminKey:this.operatorCtx.operatorKey});if(!t.success)throw new Error("Failed to create registry topic");const r=t.topicId;return this.logger.info(`Created registry topic: ${r}`),this.registryTopicId=r,r}async deployPoints(e){await this.ensureInitialized();const{progressCallback:t}=e;try{let r;t?.({stage:"creating-topic",percentage:20});const i=new Ap({operatorId:this.operatorId,operatorKey:this.operatorCtx.operatorKey,network:this.network});if(e.usePrivateTopic){const t=await i.createRegistry({submitKey:this.operatorCtx.operatorKey,adminKey:this.operatorCtx.operatorKey});if(!t.success)throw new Up("Failed to create topic",e.tick);r=t.topicId,this.logger.info(`Created private topic: ${r}`)}else r=this.publicTopicId;t?.({stage:"submitting-deploy",percentage:50,topicId:r});const o={p:"hcs-20",op:"deploy",name:e.name,tick:this.normalizeTick(e.tick),max:e.maxSupply,lim:e.limitPerMint,metadata:e.metadata,m:e.topicMemo},n=this.validateMessage(o);if(!n.valid)throw new Hp("Invalid deploy message",n.errors);const s=Vp({topicId:r,name:e.name,tick:e.tick,max:e.maxSupply,lim:e.limitPerMint,metadata:e.metadata,memo:e.topicMemo}),{transactionId:a}=await this.submitPayload(s);t?.({stage:"confirming",percentage:80,topicId:r,deployTxId:a}),await this.waitForMirrorNodeConfirmation(r,a),t?.({stage:"complete",percentage:100,topicId:r,deployTxId:a});return{name:e.name,tick:this.normalizeTick(e.tick),maxSupply:e.maxSupply,limitPerMint:e.limitPerMint,metadata:e.metadata,topicId:r,deployerAccountId:this.operatorId,currentSupply:"0",deploymentTimestamp:(new Date).toISOString(),isPrivate:e.usePrivateTopic||!1}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async mintPoints(e){await this.ensureInitialized();const{progressCallback:t}=e;try{t?.({stage:"validating",percentage:20});const r=this.normalizeTick(e.tick);t?.({stage:"submitting",percentage:50});const i=e.topicId?this.topicToString(e.topicId):this.publicTopicId,o=Gp({topicId:i,tick:e.tick,amt:e.amount,to:this.accountToString(e.to),memo:e.memo}),{transactionId:n}=await this.submitPayload(o);t?.({stage:"confirming",percentage:80,mintTxId:n}),await this.waitForMirrorNodeConfirmation(i,n),t?.({stage:"complete",percentage:100,mintTxId:n});return{id:n,operation:"mint",tick:r,amount:e.amount,to:this.accountToString(e.to),timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:i,transactionId:n,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async transferPoints(e){await this.ensureInitialized();const{progressCallback:t}=e;try{t?.({stage:"validating-balance",percentage:20});const r=this.normalizeTick(e.tick),i=this.accountToString(e.from),o=this.accountToString(e.to);if(i!==this.operatorId)throw new Lp("For public topics, transaction payer must match sender",e.tick,i,o,e.amount);t?.({stage:"submitting",percentage:50});const n=e.topicId?this.topicToString(e.topicId):this.publicTopicId,s=Jp({topicId:n,tick:e.tick,amt:e.amount,from:i,to:o,memo:e.memo}),{transactionId:a}=await this.submitPayload(s);t?.({stage:"confirming",percentage:80,transferTxId:a}),await this.waitForMirrorNodeConfirmation(n,a),t?.({stage:"complete",percentage:100,transferTxId:a});return{id:a,operation:"transfer",tick:r,amount:e.amount,from:i,to:o,timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:n,transactionId:a,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async burnPoints(e){await this.ensureInitialized();const{progressCallback:t}=e;try{t?.({stage:"validating-balance",percentage:20});const r=this.normalizeTick(e.tick),i=this.accountToString(e.from);if(i!==this.operatorId)throw new $p("For public topics, transaction payer must match burner",e.tick,i,e.amount);t?.({stage:"submitting",percentage:50});const o=e.topicId?this.topicToString(e.topicId):this.publicTopicId,n=Yp({topicId:o,tick:e.tick,amt:e.amount,from:i,memo:e.memo}),{transactionId:s}=await this.submitPayload(n);t?.({stage:"confirming",percentage:80,burnTxId:s}),await this.waitForMirrorNodeConfirmation(o,s),t?.({stage:"complete",percentage:100,burnTxId:s});return{id:s,operation:"burn",tick:r,amount:e.amount,from:i,timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:o,transactionId:s,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async registerTopic(e){await this.ensureInitialized();const{progressCallback:t}=e;try{t?.({stage:"validating",percentage:20});const r={p:"hcs-20",op:"register",name:e.name,metadata:e.metadata,private:e.isPrivate,t_id:this.topicToString(e.topicId),m:e.memo},i=this.validateMessage(r);if(!i.valid)throw new Hp("Invalid register message",i.errors);if(!this.registryTopicId)throw new Up("Registry topic not available",e.name);t?.({stage:"submitting",percentage:50});const o=Xp({registryTopicId:this.registryTopicId,name:e.name,topicId:this.topicToString(e.topicId),isPrivate:e.isPrivate,metadata:e.metadata,memo:e.memo}),{transactionId:n}=await this.submitPayload(o,this.operatorCtx.operatorKey);t?.({stage:"confirming",percentage:80,registerTxId:n}),await this.waitForMirrorNodeConfirmation(this.registryTopicId,n),t?.({stage:"complete",percentage:100,registerTxId:n}),this.logger.info(`Registered topic ${e.topicId} in registry`)}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async waitForMirrorNodeConfirmation(e,t,r=10){for(let o=0;o<r;o++){try{const r=await this.mirrorNode.getTopicMessages(e,{limit:10,order:"desc"});if(r.some(e=>{if("object"!=typeof e||null===e)return!1;return"string"==typeof e.consensus_timestamp}))return void this.logger.debug(`Transaction ${t} confirmed on mirror node`)}catch(i){this.logger.debug(`Mirror node check attempt ${o+1} failed:`,i)}await B(2e3)}this.logger.warn(`Transaction ${t} not found on mirror node after ${r} attempts`)}},exports.HCS20DeployMessageSchema=Fp,exports.HCS20Error=Kp,exports.HCS20MessageSchema=Mp,exports.HCS20MintMessageSchema=Op,exports.HCS20PointsIndexer=class{constructor(e,t,r){this.isProcessing=!1,this.lastIndexedSequence=new Map,this.logger=t||new z({level:"info",module:"HCS20PointsIndexer"}),this.mirrorNode=new G(e,this.logger,{customUrl:r}),this.state=this.initializeState()}initializeState(){return{deployedPoints:new Map,balances:new Map,transactions:[],lastProcessedSequence:0,lastProcessedTimestamp:(new Date).toISOString()}}getState(){return{...this.state,deployedPoints:new Map(this.state.deployedPoints),balances:new Map(this.state.balances),transactions:[...this.state.transactions]}}getPointsInfo(e){return this.state.deployedPoints.get(this.normalizeTick(e))}getBalance(e,t){const r=this.normalizeTick(e),i=this.state.balances.get(r);if(!i)return"0";const o=i.get(t);return o?.balance||"0"}async startIndexing(e){if(this.isProcessing)return void this.logger.warn("Indexing already in progress");this.isProcessing=!0;const t=!1!==e?.includePublicTopic,r=!1!==e?.includeRegistryTopic,i=t?e?.publicTopicId||xp.PUBLIC_TOPIC_ID:null,o=r?e?.registryTopicId||xp.REGISTRY_TOPIC_ID:null,n=e?.pollInterval||3e4;await this.indexTopics(i,o,e?.privateTopics);const s=async()=>{if(this.isProcessing){try{await this.indexTopics(i,o,e?.privateTopics)}catch(t){this.logger.error("Polling error:",t)}this.isProcessing&&setTimeout(s,n)}};setTimeout(s,n)}async indexOnce(e){const t=!1!==e?.includePublicTopic,r=!1!==e?.includeRegistryTopic,i=t?e?.publicTopicId||xp.PUBLIC_TOPIC_ID:null,o=r?e?.registryTopicId||xp.REGISTRY_TOPIC_ID:null;await this.indexTopics(i,o,e?.privateTopics)}stopIndexing(){this.isProcessing=!1,this.logger.info("Indexing stopped")}async indexTopics(e,t,r){this.logger.debug("Starting indexing cycle"),e&&await this.indexTopic(e,!1);const i=[...t?await this.getRegisteredTopics(t):[],...r||[]];for(const o of i)await this.indexTopic(o,!0);this.logger.debug("Indexing cycle complete")}async getRegisteredTopics(e){const t=[];try{(await this.mirrorNode.getTopicMessages(e,{limit:100,order:"asc"})).filter(e=>"hcs-20"===e.p&&"register"===e.op&&"string"==typeof e.t_id).forEach(e=>{t.push(e.t_id)})}catch(r){this.logger.error("Failed to fetch registry messages:",r)}return t}async indexTopic(e,t){try{const r=this.lastIndexedSequence.get(e);this.logger.debug(`Indexing topic ${e}, starting from sequence ${r||0}`);const i=await this.mirrorNode.getTopicMessages(e,{sequenceNumber:r?r+1:void 0,limit:1e3,order:"asc"});this.logger.debug(`Fetched ${i.length} messages from topic ${e}`);let o=r||0;for(const n of i){if("hcs-20"!==n.p)continue;const r=Mp.safeParse(n);if(!r.success){this.logger.debug("Skipping message due to schema mismatch");continue}const i=r.data,s=n.sequence_number??0;this.logger.debug(`Found HCS-20 message: op=${i.op}, sequence=${s}`),s>o&&(o=s);const a={consensus_timestamp:n.consensus_timestamp??"",sequence_number:s,payer_account_id:n.payer_account_id??n.payer??"",transaction_id:n.transaction_id??""};this.processMessage(i,a,e,t),this.state.lastProcessedSequence++,this.state.lastProcessedTimestamp=n.consensus_timestamp||""}o>(r||0)&&this.lastIndexedSequence.set(e,o)}catch(r){this.logger.error(`Failed to index topic ${e}:`,r)}}processMessage(e,t,r,i){switch(e.op){case"deploy":this.processDeployMessage(e,t,r,i);break;case"mint":this.processMintMessage(e,t,r,i);break;case"transfer":this.processTransferMessage(e,t,r,i);break;case"burn":this.processBurnMessage(e,t,r,i)}}processDeployMessage(e,t,r,i){const o=this.normalizeTick(e.tick);if(this.state.deployedPoints.has(o))return;const n={name:e.name,tick:o,maxSupply:e.max,limitPerMint:e.lim,metadata:e.metadata,topicId:r,deployerAccountId:t.payer_account_id,currentSupply:"0",deploymentTimestamp:t.consensus_timestamp,isPrivate:i};this.state.deployedPoints.set(o,n),this.logger.info(`Deployed points: ${o}`)}processMintMessage(e,t,r,i){const o=this.normalizeTick(e.tick),n=this.state.deployedPoints.get(o);if(!n)return;const s=BigInt(e.amt),a=BigInt(n.currentSupply);if(a+s>BigInt(n.maxSupply))return;if(n.limitPerMint&&s>BigInt(n.limitPerMint))return;n.currentSupply=(a+s).toString();let c=this.state.balances.get(o);c||(c=new Map,this.state.balances.set(o,c));const l=c.get(e.to),d=l?(BigInt(l.balance)+s).toString():e.amt;c.set(e.to,{tick:o,accountId:e.to,balance:d,lastUpdated:t.consensus_timestamp}),this.state.transactions.push({id:t.transaction_id||`${r}-${t.sequence_number}`,operation:"mint",tick:o,amount:e.amt,to:e.to,timestamp:t.consensus_timestamp,sequenceNumber:t.sequence_number,topicId:r,transactionId:t.transaction_id||"",memo:e.m})}processTransferMessage(e,t,r,i){const o=this.normalizeTick(e.tick),n=this.state.balances.get(o);if(!n)return;if(!i&&t.payer_account_id!==e.from)return;const s=n.get(e.from);if(!s||BigInt(s.balance)<BigInt(e.amt))return;const a=BigInt(e.amt);s.balance=(BigInt(s.balance)-a).toString(),s.lastUpdated=t.consensus_timestamp;const c=n.get(e.to);c?(c.balance=(BigInt(c.balance)+a).toString(),c.lastUpdated=t.consensus_timestamp):n.set(e.to,{tick:o,accountId:e.to,balance:e.amt,lastUpdated:t.consensus_timestamp}),this.state.transactions.push({id:t.transaction_id||`${r}-${t.sequence_number}`,operation:"transfer",tick:o,amount:e.amt,from:e.from,to:e.to,timestamp:t.consensus_timestamp,sequenceNumber:t.sequence_number,topicId:r,transactionId:t.transaction_id||"",memo:e.m})}processBurnMessage(e,t,r,i){const o=this.normalizeTick(e.tick),n=this.state.deployedPoints.get(o),s=this.state.balances.get(o);if(!n||!s)return;if(!i&&t.payer_account_id!==e.from)return;const a=s.get(e.from);if(!a||BigInt(a.balance)<BigInt(e.amt))return;const c=BigInt(e.amt);a.balance=(BigInt(a.balance)-c).toString(),a.lastUpdated=t.consensus_timestamp,n.currentSupply=(BigInt(n.currentSupply)-c).toString(),this.state.transactions.push({id:t.transaction_id||`${r}-${t.sequence_number}`,operation:"burn",tick:o,amount:e.amt,from:e.from,timestamp:t.consensus_timestamp,sequenceNumber:t.sequence_number,topicId:r,transactionId:t.transaction_id||"",memo:e.m})}normalizeTick(e){return e.toLowerCase().trim()}},exports.HCS20RegisterMessageSchema=Bp,exports.HCS20TransferMessageSchema=zp,exports.HCS20_CONSTANTS=xp,exports.HCS21BaseClient=ah,exports.HCS21BrowserClient=class extends ah{constructor(e){super({network:e.network,logger:e.logger}),this.hwc=e.hwc}async publishDeclaration(e){const t="p"in e.declaration?this.validateDeclaration(e.declaration):this.buildDeclaration(e.declaration);await this.hwc.submitMessageToTopic(e.topicId,JSON.stringify(t))}async fetchDeclarations(e){const{messages:t=[]}=await this.hwc.getMessages(e),r=[];for(const o of t)try{const e=this.validateDeclaration(o.message);r.push({declaration:e,consensusTimestamp:o.consensus_timestamp,sequenceNumber:Number(o.sequence_number||0),payer:o.payer_account_id})}catch(i){const e=i instanceof Error?i.message:"unknown error";this.logger.warn(`Skipping invalid HCS-21 browser message: ${e}`)}return r}},exports.HCS21Client=class extends ah{constructor(e){const t=e.logger||new z({level:e.logLevel||"info",module:"HCS-21"});super({network:e.network,logger:t,mirrorNodeUrl:e.mirrorNodeUrl});const r="mainnet"===e.network?i.Client.forMainnet():i.Client.forTestnet();this.operatorCtx=oe({network:e.network,operatorId:e.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:r}),this.operatorCtx.ensureInitialized(),this.client=this.operatorCtx.client}async inscribeMetadata(e){await this.operatorCtx.ensureInitialized();const t=JSON.stringify(e.metadata,null,2),r=globalThis.Buffer.from(t,"utf8"),i={waitForConfirmation:!0,...e.inscriptionOptions||{},metadata:{...e.inscriptionOptions?.metadata||{},...e.metadata}},o=await Fa({type:"buffer",buffer:r,fileName:e.fileName||`hcs21-package-metadata-${Date.now()}.json`,mimeType:"application/json"},{accountId:this.operatorCtx.operatorId.toString(),privateKey:this.operatorCtx.operatorKey,network:this.network},i);if(!o.confirmed||!o.inscription)throw new ih("Failed to inscribe package metadata","invalid_payload");const n=o.inscription.jsonTopicId||o.inscription.topic_id||Ka(o.inscription);if(!n)throw new ih("Metadata inscription did not return a topic ID","invalid_payload");const s=o.inscription.sequence_number??o.inscription.sequenceNumber,a=await this.resolveMetadataPointer(n,s),c=o.result&&"jobId"in o.result?{jobId:o.result.jobId,transactionId:o.result.transactionId}:{};return{pointer:a.pointer,topicId:n,sequenceNumber:a.sequenceNumber,...c}}async createRegistryTopic(e){await this.operatorCtx.ensureInitialized();const t=nh({ttl:e.ttl,indexed:e.indexed,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:this.operatorCtx.operatorKey.publicKey});e.transactionMemo&&t.setTransactionMemo(e.transactionMemo);const r=await t.execute(this.client),o=await r.getReceipt(this.client);if(o.status!==i.Status.Success||!o.topicId)throw new ih("Failed to create HCS-21 registry topic","invalid_payload");return o.topicId.toString()}async publishDeclaration(e){await this.operatorCtx.ensureInitialized();const t=this.normalizeDeclarationInput(e.declaration),r=sh({topicId:e.topicId,declaration:t,transactionMemo:e.transactionMemo}),o=await r.execute(this.client),n=await o.getReceipt(this.client);if(n.status!==i.Status.Success)throw new ih("Failed to submit HCS-21 declaration","invalid_payload");return{sequenceNumber:n.topicSequenceNumber?.toNumber(),transactionId:o.transactionId.toString()}}normalizeDeclarationInput(e){return"p"in e?this.validateDeclaration(e):this.buildDeclaration(e)}async resolveMetadataPointer(e,t){const r="string"==typeof t?Number(t):t;let i="number"==typeof r&&Number.isFinite(r)?r:void 0;if(!i){const[t]=await this.mirrorNode.getTopicMessages(e,{limit:1,order:"desc"});if(!t||!t.sequence_number)throw new ih("Unable to resolve metadata sequence number","invalid_payload");i=Number(t.sequence_number)}if(!Number.isFinite(i))throw new ih("Invalid metadata sequence number","invalid_payload");const o=`hcs://1/${e}/${i}`;if(!eh.test(o))throw new ih("Metadata pointer format is invalid","invalid_payload");return{pointer:o,sequenceNumber:i}}},exports.HCS21MetadataPointerPattern=eh,exports.HCS21TopicType=th,exports.HCS21ValidationError=ih,exports.HCS21_MAX_MESSAGE_BYTES=1024,exports.HCS21_PROTOCOL=Zp,exports.HCS21_REGISTRY_NAMESPACES=Qp,exports.HCS2BaseClient=kp,exports.HCS2Client=Ap,exports.HCS2Operation=gp,exports.HCS2RegistryType=mp,exports.HCS5BrowserClient=class extends pp{constructor(e){super({network:e.network,logLevel:e.logLevel,silent:e.silent,logger:void 0,operatorId:"0.0.0",operatorKey:""}),this.hwc=e.hwc,this.signer=e.signer}getSigner(){if(this.signer)return this.signer;const e=this.hwc.getAccountInfo()?.accountId,t=this.hwc.dAppConnector?.signers?.find(t=>t.getAccountId().toString()===e);if(!t)throw new Error("No active wallet signer");return t}async mint(e){try{if(!e.metadataTopicId)return{success:!1,error:"metadataTopicId is required for mint()"};const t=up(e.metadataTopicId),r=hp({tokenId:e.tokenId,metadata:t});let o;if(e.supplyKey&&e.supplyKey instanceof i.PrivateKey){const t=this.getSigner();r.freezeWithSigner(t);const i=await r.sign(e.supplyKey);o=await this.hwc.executeTransactionWithErrorHandling(i,!0)}else o=await this.hwc.executeTransactionWithErrorHandling(r,!1);if(o.error)return{success:!1,error:o.error};const n=o.result;return{success:!0,serialNumber:n.serials?.[0]?Number(n.serials[0].toString()):void 0,transactionId:n?.transactionId?.toString?.(),metadata:t}}catch(eg){return{success:!1,error:String(eg)}}}async createHashinal(e){try{const t=this.getSigner(),r={...e.inscriptionOptions,mode:"hashinal",waitForConfirmation:!0,network:this.network},i=await Oa(e.inscriptionInput,t,r),o=i.inscription?.jsonTopicId||i.inscription?.topic_id;return i.confirmed&&o?await this.mint({tokenId:e.tokenId,metadataTopicId:o,supplyKey:e.supplyKey,memo:e.memo}):{success:!1,error:"Failed to inscribe content"}}catch(eg){return{success:!1,error:String(eg)}}}},exports.HCS5Client=class extends pp{constructor(e){super(e),this.operatorId=i.AccountId.fromString(e.operatorId),this.operatorCtx=oe({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,mirrorNode:this.mirrorNode,logger:this.logger}),this.client=this.operatorCtx.client}async ensureInitialized(){await this.operatorCtx.ensureInitialized()}async mint(e){try{if(await this.ensureInitialized(),!e.metadataTopicId)return{success:!1,error:"metadataTopicId is required for mint()"};const t=up(e.metadataTopicId),r=hp({tokenId:e.tokenId,metadata:t}),i=await r.freezeWith(this.client);if(e.supplyKey){const t=new ie({mirrorNode:this.mirrorNode,logger:this.logger}),r="string"==typeof e.supplyKey?await t.resolveSupplyKey(e.tokenId,e.supplyKey,this.operatorCtx.keyType):e.supplyKey;await i.sign(r)}const o=await i.execute(this.client),n=await o.getReceipt(this.client);return{success:!0,serialNumber:n.serials&&n.serials[0]?Number(n.serials[0].toString()):void 0,transactionId:o.transactionId?.toString?.(),metadata:t}}catch(eg){const t=eg;return this.logger.error(`Failed to mint HCS-5 Hashinal: ${t.message}`),{success:!1,error:t.message}}}async createHashinal(e){try{await this.ensureInitialized();const t=await Fa(e.inscriptionInput,{accountId:this.operatorId.toString(),privateKey:this.operatorCtx.operatorKey,network:this.network},{...e.inscriptionOptions||{},mode:"hashinal",waitForConfirmation:!0});if(!t.confirmed||!t.inscription)return{success:!1,error:"Failed to inscribe content"};const r=t.inscription.jsonTopicId||t.inscription.topic_id;return r?await this.mint({tokenId:e.tokenId,metadataTopicId:r,supplyKey:e.supplyKey,memo:e.memo}):{success:!1,error:"No topic ID from inscription"}}catch(eg){const t=eg;return this.logger.error(`Failed to inscribe and mint HCS-5 Hashinal: ${t.message}`),{success:!1,error:t.message}}}},exports.HCS6BaseClient=J,exports.HCS6BrowserClient=class extends J{constructor(e){super(e),this.hwc=e.hwc,this.signer=e.signer}ensureConnected(){const e=this.hwc.getAccountInfo(),t=e?.accountId;if(!t)throw new Error("No active wallet connection: wallet integration required to perform write operations");return t}getSigner(){const e=this.signer;if(e)return e;this.ensureConnected();const t=this.hwc.dAppConnector,r=t?.signers?.[0];if(!r)throw new Error("No active wallet signer");return r}async createRegistry(e){try{this.ensureConnected();const t=e?.ttl??86400,r=this.generateRegistryMemo(t),i=await this.hwc.createTopic(r);return this.logger.info(`Created HCS-6 registry topic via wallet: ${i} (TTL ${t})`),{success:!0,topicId:i}}catch(t){return this.logger.error(`Failed to create HCS-6 registry: ${t}`),{success:!1,error:String(t)}}}async registerEntry(e,t){try{if(!(await this.validateHCS6Topic(e)))throw new Error(`Topic ${e} is not a valid HCS-6 registry`);const r=this.createRegisterMessage(t.targetTopicId,t.memo),i=await this.submitMessage(e,r),o=i.topicSequenceNumber;return{success:!0,receipt:i,sequenceNumber:"number"==typeof o?o:o?.low}}catch(r){return this.logger.error(`Failed to register HCS-6 entry: ${r}`),{success:!1,error:String(r)}}}async getRegistry(e,t={}){try{const r=await this.mirrorNode.getTopicInfo(e);this.logger.debug(`Retrieved topic info for HCS-6 ${e}: ${JSON.stringify(r)}`);const i=this.parseRegistryTypeFromMemo(r.memo);if(!i)throw new Error(`Topic ${e} is not an HCS-6 registry (invalid memo format)`);this.logger.debug(`Retrieving messages for HCS-6 topic ${e} with limit ${t.limit??100}`);const o=await this.mirrorNode.getTopicMessages(e,{sequenceNumber:t.skip&&t.skip>0?`gt:${t.skip}`:void 0,limit:t.limit??100,order:t.order??"asc"}),n=t.limit?o.slice(0,t.limit):o;return this.logger.debug(`Retrieved ${o.length} messages, using ${n.length} after applying limit.`),this.parseRegistryEntries(e,n,i.registryType,i.ttl)}catch(r){throw this.logger.error(`Failed to get HCS-6 registry: ${r}`),r}}async submitMessage(e,t){this.ensureConnected();const{valid:r,errors:i}=this.validateMessage(t);if(!r)throw new Error(`Invalid HCS-6 message: ${i.join(", ")}`);return await this.hwc.submitMessageToTopic(e,JSON.stringify(t))}async createHashinal(e){try{if(!this.signer)return{success:!1,error:"No signer configured for browser createHashinal"};const t={...e.inscriptionOptions,mode:"hashinal",metadata:e.metadata,waitForConfirmation:!0,network:this.network},r={type:"buffer",buffer:globalThis.Buffer.from(JSON.stringify(e.metadata)),fileName:"metadata.json",mimeType:"application/json"},i=await Oa(r,this.signer,t),o=i.inscription?.jsonTopicId||Ka(i.inscription);if(!o)return{success:!1,error:"Failed to inscribe metadata"};let n=e.registryTopicId;if(!n){const t=await this.createRegistry({ttl:e.ttl});if(!t.success||!t.topicId)return{success:!1,error:t.error};n=t.topicId}const s=await this.registerEntry(n,{targetTopicId:o,memo:e.memo||"Initial dynamic hashinal registration"});return s.success?{success:!0,registryTopicId:n,inscriptionTopicId:o}:{success:!1,error:s.error}}catch(t){return this.logger.error(`Failed to create dynamic hashinal: ${t}`),{success:!1,error:String(t)}}}async register(e){try{if(!this.signer)return{success:!1,error:"No signer configured for browser register"};let t;t=e.data?.base64?{type:"buffer",buffer:globalThis.Buffer.from(e.data.base64,"base64"),fileName:"data."+(e.data.mimeType?.split("/")[1]||"bin"),mimeType:e.data.mimeType||"application/octet-stream"}:e.data?.url?{type:"url",url:e.data.url}:{type:"buffer",buffer:globalThis.Buffer.from(JSON.stringify(e.metadata)),fileName:"metadata.json",mimeType:"application/json"};const r={...e.inscriptionOptions,mode:"hashinal",metadata:e.metadata,waitForConfirmation:!0,network:this.network},i=await Oa(t,this.signer,r),o=i.inscription?.jsonTopicId||Ka(i.inscription);if(!o)return{success:!1,error:"Failed to inscribe data"};let n=e.registryTopicId;if(!n){const t=await this.createRegistry({ttl:e.ttl});if(!t.success||!t.topicId)return{success:!1,error:t.error};n=t.topicId}const s=await this.registerEntry(n,{targetTopicId:o,memo:e.memo||"Dynamic hashinal registration"});return s.success?{success:!0,registryTopicId:n,inscriptionTopicId:o}:{success:!1,error:s.error}}catch(t){return this.logger.error(`Failed to register dynamic hashinal: ${t}`),{success:!1,error:String(t)}}}async validateHCS6Topic(e){try{const t=await this.mirrorNode.getTopicInfo(e),r=this.parseRegistryTypeFromMemo(t.memo);return r?r.registryType===U.NON_INDEXED||(this.logger.warn(`Topic ${e} is not a valid HCS-6 registry (must be non-indexed)`),!1):(this.logger.warn(`Topic ${e} is not a valid HCS-6 registry (invalid memo format)`),!1)}catch(t){return this.logger.error(`Error validating HCS-6 topic ${e}: ${t}`),!1}}},exports.HCS6Client=class extends J{constructor(e){super({network:e.network,logLevel:e.logLevel,silent:e.silent,mirrorNodeUrl:e.mirrorNodeUrl,logger:e.logger}),this.operatorId="string"==typeof e.operatorId?i.AccountId.fromString(e.operatorId):e.operatorId,this.operatorCtx=oe({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:this.createClient(e.network)}),this.client=this.operatorCtx.client}async ensureInitialized(){await this.operatorCtx.ensureInitialized()}createClient(e){return"mainnet"===e?i.Client.forMainnet():i.Client.forTestnet()}close(){this.logger.info("HCS-6 client closed.")}getKeyType(){return this.operatorCtx.keyType}getOperatorKey(){return this.operatorCtx.operatorKey}async submitMessage(e,t){return this.submitMessageWithKey(e,t,void 0)}async submitMessageWithKey(e,t,r){const{valid:o,errors:n}=this.validateMessage(t);if(!o)throw new Error(`Invalid HCS-6 message: ${n.join(", ")}`);let s=(new i.TopicMessageSubmitTransaction).setTopicId(i.TopicId.fromString(e)).setMessage(JSON.stringify(t));if(!r){const e=await s.execute(this.client);return await e.getReceipt(this.client)}const a="string"==typeof r?i.PrivateKey.fromString(r):r,c=await s.freezeWith(this.client);await c.sign(a);const l=await c.execute(this.client);return await l.getReceipt(this.client)}async registerEntryWithKey(e,t,r){try{const i=this.createRegisterMessage(t.targetTopicId,t.memo),o=await this.submitMessageWithKey(e,i,r),n=o.topicSequenceNumber?.toNumber();return{success:!0,receipt:o,sequenceNumber:n}}catch(i){return this.logger.error(`Failed to register HCS-6 entry: ${i}`),{success:!1,error:String(i)}}}async createRegistry(e={}){try{await this.ensureInitialized();const t=e.ttl??86400;if(!(t>=3600))throw new Error("TTL must be at least 3600 seconds (1 hour)");let r,o;if(e.submitKey)if("string"==typeof e.submitKey)try{r=i.PublicKey.fromString(e.submitKey)}catch{const t=globalThis.Buffer.from(e.submitKey.replace(/^0x/i,""),"hex");r="ed25519"===this.operatorCtx.keyType?i.PublicKey.fromBytesED25519(t):i.PublicKey.fromBytesECDSA(t)}else"boolean"==typeof e.submitKey?r=this.operatorCtx.operatorKey.publicKey:(r=e.submitKey.publicKey,o=e.submitKey);let n=Z({ttl:t,submitKey:r,adminKey:this.operatorCtx.operatorKey.publicKey,operatorPublicKey:this.operatorCtx.operatorKey.publicKey});const s=await n.freezeWith(this.client);o&&await s.sign(o);const a=await s.execute(this.client),c=(await a.getReceipt(this.client)).topicId;if(!c)throw new Error("Failed to create HCS-6 registry: No topic ID in receipt");return{success:!0,topicId:c.toString(),transactionId:a.transactionId.toString()}}catch(t){return this.logger.error(`Failed to create HCS-6 registry: ${t}`),{success:!1,error:`Failed to create HCS-6 registry: ${t}`}}}async registerEntry(e,t){return await this.ensureInitialized(),this.registerEntryWithKey(e,t,void 0)}async getRegistry(e,t={}){await this.ensureInitialized();const r=((await this.mirrorNode.getTopicInfo(e)).memo||"").match(/^hcs-6:(\d):(\d+)$/);if(!r)throw new Error(`Topic ${e} is not an HCS-6 registry (invalid memo format)`);const i=parseInt(r[2]),o=parseInt(r[1]),n=(await this.mirrorNode.getTopicMessages(e,{sequenceNumber:t.skip&&t.skip>0?`gt:${t.skip}`:void 0,limit:t.limit??100,order:t.order??"asc"})).map(t=>{try{const r=t,{valid:i}=this.validateMessage(r);return i?{topicId:e,sequence:r.sequence_number,timestamp:r.consensus_timestamp||"",payer:r.payer||"",message:r,consensus_timestamp:r.consensus_timestamp||"",registry_type:o}:null}catch{return null}}).filter(e=>Boolean(e)),s=n.length>0?n[n.length-1]:void 0;return{topicId:e,registryType:o,ttl:i,entries:n,latestEntry:s}}async mint(e){try{if(await this.ensureInitialized(),!e.metadataTopicId)return{success:!1,error:"metadataTopicId is required for mint()"};const t=L(e.metadataTopicId);let r=(new i.TokenMintTransaction).setTokenId(i.TokenId.fromString(e.tokenId)).setMetadata([globalThis.Buffer.from(t)]);const o=await r.freezeWith(this.client);if(e.supplyKey){const t=new ie({mirrorNode:this.mirrorNode,logger:this.logger}),r="string"==typeof e.supplyKey?await t.resolveSupplyKey(e.tokenId,e.supplyKey,this.operatorCtx.keyType):e.supplyKey;await o.sign(r)}const n=await o.execute(this.client),s=await n.getReceipt(this.client);return{success:!0,serialNumber:s.serials&&s.serials[0]?Number(s.serials[0].toString()):void 0,transactionId:n.transactionId?.toString?.(),metadata:t}}catch(eg){return{success:!1,error:String(eg)}}}async inscribeAndMint(e){try{await this.ensureInitialized();const t={...e.inscriptionOptions,mode:"hashinal",waitForConfirmation:!0},r=await Fa(e.inscriptionInput,{accountId:this.operatorId.toString(),privateKey:this.operatorCtx.operatorKey,network:this.network},t);if(!r.confirmed||!r.inscription)return{success:!1,error:"Failed to inscribe content"};const i=r.inscription.jsonTopicId||r.inscription.topic_id;return i?await this.mint({tokenId:e.tokenId,metadataTopicId:i,supplyKey:e.supplyKey,memo:e.memo}):{success:!1,error:"No topic ID from inscription"}}catch(eg){return{success:!1,error:String(eg)}}}async createHashinal(e){try{let t,r;if(await this.ensureInitialized(),e.registryTopicId){t=e.registryTopicId;const r=(await this.mirrorNode.getTopicInfo(t)).memo||"";if(!/^hcs-6:\d:\d+$/.test(r))throw new Error(`Topic ${t} is not a valid HCS-6 registry`)}else{const i=await this.createRegistry({ttl:e.ttl,submitKey:!0});if(!i.success||!i.topicId)throw new Error(i.error||"Failed to create HCS-6 registry");t=i.topicId,r=i.transactionId}const i=globalThis.Buffer.from(JSON.stringify(e.metadata)),o={...e.inscriptionOptions,mode:"hashinal",metadata:e.metadata,waitForConfirmation:!0},n=await Fa({type:"buffer",buffer:i,fileName:"metadata.json",mimeType:"application/json"},{accountId:this.operatorId.toString(),privateKey:this.operatorCtx.operatorKey,network:this.network},o);if(!n.confirmed||!n.inscription)throw new Error("Failed to inscribe metadata");const s=n.inscription.jsonTopicId||n.inscription.topic_id;if(!s)throw new Error("No inscription topic ID available");const a=await this.registerEntryWithKey(t,{targetTopicId:s,memo:e.memo||"Dynamic hashinal registration"},e.submitKey);if(!a.success)throw new Error(a.error||"Failed to register entry");return{success:!0,registryTopicId:t,inscriptionTopicId:s,transactionId:r}}catch(eg){return{success:!1,error:String(eg)}}}async register(e){try{let t,r,i;if(await this.ensureInitialized(),e.registryTopicId){t=e.registryTopicId;const r=(await this.mirrorNode.getTopicInfo(t)).memo||"";if(!/^hcs-6:\d:\d+$/.test(r))throw new Error(`Topic ${t} is not a valid HCS-6 registry`)}else{const i=await this.createRegistry({ttl:e.ttl,submitKey:!0});if(!i.success||!i.topicId)throw new Error(i.error||"Failed to create HCS-6 registry");t=i.topicId,r=i.transactionId}if(e.data?.base64){i={type:"buffer",buffer:globalThis.Buffer.from(e.data.base64,"base64"),fileName:`data.${e.data.mimeType?.split("/")[1]||"bin"}`,mimeType:e.data.mimeType||"application/octet-stream"}}else i=e.data?.url?{type:"url",url:e.data.url}:{type:"buffer",buffer:globalThis.Buffer.from(JSON.stringify(e.metadata)),fileName:"metadata.json",mimeType:"application/json"};const o={...e.inscriptionOptions,mode:"hashinal",metadata:e.metadata,waitForConfirmation:!0},n=await Fa(i,{accountId:this.operatorId.toString(),privateKey:this.operatorCtx.operatorKey,network:this.network},o);if(!n.confirmed||!n.inscription)throw new Error("Failed to inscribe data");const s=n.inscription.jsonTopicId||n.inscription.topic_id;if(!s)throw new Error("No inscription topic ID available");const a=await this.registerEntryWithKey(t,{targetTopicId:s,memo:e.memo||"Dynamic hashinal registration"},e.submitKey);if(!a.success)throw new Error(a.error||"Failed to register entry");return{success:!0,registryTopicId:t,inscriptionTopicId:s,transactionId:r}}catch(eg){return{success:!1,error:String(eg)}}}},exports.HCS6Operation=K,exports.HCS6RegistryType=U,exports.HCS7BaseClient=Ya,exports.HCS7BrowserClient=class extends Ya{constructor(e){super(e),this.hwc=e.hwc}ensureConnected(){const e=this.hwc.getAccountInfo();if(!e?.accountId)throw new Error("No active wallet connection")}async createRegistry(e={}){try{this.ensureConnected();const t=e.ttl??86400;if(t<3600)throw new Error("TTL must be at least 3600 seconds");const r=this.generateRegistryMemo(t),i=await this.hwc.createTopic(r);return this.logger.info(`Created HCS-7 registry topic ${i}`),{success:!0,topicId:i}}catch(t){return this.logger.error("Failed to create HCS-7 registry in browser",t),{success:!1,error:String(t)}}}async registerConfig(e){const t=this.createConfigMessage({config:e.config,memo:e.memo});return this.submitWithWallet({topicId:e.registryTopicId,message:t})}async registerMetadata(e){const t=this.createMetadataMessage(e);return this.submitWithWallet({topicId:e.registryTopicId,message:t})}async submitWithWallet(e){try{this.ensureConnected();const{valid:t,errors:r}=this.validateMessage(e.message);if(!t)return{success:!1,error:`Invalid HCS-7 payload: ${r.join(", ")}`};const i=await this.hwc.submitMessageToTopic(e.topicId,JSON.stringify(e.message));return{success:!0,receipt:i,sequenceNumber:Xa(i)}}catch(t){return this.logger.error("Failed to submit HCS-7 browser message",t),{success:!1,error:String(t)}}}},exports.HCS7Client=class extends Ya{constructor(e){super(e),this.closed=!1,this.operatorCtx=oe({network:this.network,operatorId:e.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger}),this.client=this.operatorCtx.client}close(){this.closed||(this.closed=!0,this.logger.info("HCS-7 client closed"))}getKeyType(){return this.operatorCtx.keyType}async ensureInitialized(){await this.operatorCtx.ensureInitialized()}resolvePublicKey(e){if(e){if("boolean"==typeof e)return e?this.operatorCtx.operatorKey.publicKey:void 0;if("string"==typeof e)try{return i.PublicKey.fromString(e)}catch{return}return e.publicKey}}coercePrivateKey(e){if(e instanceof i.PrivateKey)return e;try{return i.PrivateKey.fromStringED25519(e)}catch{return i.PrivateKey.fromStringECDSA(e)}}async createRegistry(e={}){const t=e.ttl??86400;if(t<3600)return{success:!1,error:"TTL must be at least 3600 seconds"};try{await this.ensureInitialized();const r=this.resolvePublicKey(e.submitKey);let i=Za({ttl:t,submitKey:r,adminKey:this.resolvePublicKey(e.adminKey),operatorPublicKey:this.operatorCtx.operatorKey.publicKey});i=await i.freezeWith(this.client);const o=await i.execute(this.client),n=await o.getReceipt(this.client),s=n.topicId?.toString();return s?{success:!0,topicId:s,transactionId:o.transactionId?.toString()}:{success:!1,error:"Topic creation receipt did not include a topic ID"}}catch(r){return this.logger.error("Failed to create HCS-7 registry topic",r),{success:!1,error:String(r)}}}async registerConfig(e){await this.ensureInitialized();const t=this.createConfigMessage({config:e.config,memo:e.memo});return this.submitMessage({topicId:e.registryTopicId,message:t,submitKey:e.submitKey,transactionMemo:e.transactionMemo})}async registerMetadata(e){await this.ensureInitialized();const t=this.createMetadataMessage(e);return this.submitMessage({topicId:e.registryTopicId,message:t,submitKey:e.submitKey,transactionMemo:e.transactionMemo})}async submitMessage(e){const{valid:t,errors:r}=this.validateMessage(e.message);if(!t)return{success:!1,error:`Invalid HCS-7 payload: ${r.join(", ")}`};try{let t=Qa({topicId:e.topicId,message:e.message,transactionMemo:e.transactionMemo});if(e.submitKey){const r=this.coercePrivateKey(e.submitKey);t=await t.freezeWith(this.client),await t.sign(r);const i=await t.execute(this.client),o=await i.getReceipt(this.client);return{success:!0,receipt:o,sequenceNumber:o.topicSequenceNumber?.toNumber(),transactionId:i.transactionId?.toString()}}const r=await t.execute(this.client),i=await r.getReceipt(this.client);return{success:!0,receipt:i,sequenceNumber:i.topicSequenceNumber?.toNumber(),transactionId:r.transactionId?.toString()}}catch(i){return this.logger.error("Failed to submit HCS-7 message",i),{success:!1,error:String(i)}}}},exports.HCS7ConfigType=La,exports.HCS7Operation=Ua,exports.HRLResolver=Ql,exports.HTSParser=pa,exports.HashLinkResolver=Fu,exports.HashLinkScanner=Pu,exports.HashLinksRegistry=Cu,exports.Hcs10MemoType=Gd,exports.HederaHieroIssuer=cp,exports.HederaMirrorNode=G,exports.HieroDidResolver=ep,exports.InboundTopicType=yc,exports.InsufficientBalanceError=class extends Kp{constructor(e,t,r,i){super(`Insufficient balance for ${t}: required ${r}, available ${i}`),this.accountId=e,this.tick=t,this.required=r,this.available=i,this.name="InsufficientBalanceError"}},exports.InvalidAccountFormatError=jp,exports.InvalidMessageFormatError=class extends Kp{constructor(e,t){super(e),this.messageData=t,this.name="InvalidMessageFormatError"}},exports.InvalidNumberFormatError=class extends Kp{constructor(e,t){super(`Invalid number format for ${t}: ${e}`),this.value=e,this.field=t,this.name="InvalidNumberFormatError"}},exports.InvalidTickFormatError=class extends Kp{constructor(e){super(`Invalid tick format: ${e}`),this.tick=e,this.name="InvalidTickFormatError"}},exports.IssuerRegistry=op,exports.KeyType=Q,exports.KeyTypeDetector=te,exports.Logger=z,exports.MAINNET_EXAMPLES=Du,exports.MCPServerBuilder=class{constructor(){this.config={mcpServer:{}},this.socials=[],this.logger=z.getInstance({module:"MCPServerBuilder"})}setName(e){return this.config.name=e,this}setAlias(e){return this.config.alias=e,this}setBio(e){return this.config.bio=e,this}setDescription(e){return this.setBio(e)}setVersion(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.version=e,this}setConnectionInfo(e,t){this.config.mcpServer||(this.config.mcpServer={});const r={url:e,transport:t};return this.config.mcpServer.connectionInfo=r,this}setServerDescription(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.description=e,this}setServices(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.services=e,this}setHostRequirements(e){this.config.mcpServer||(this.config.mcpServer={});const t={minVersion:e};return this.config.mcpServer.host=t,this}setCapabilities(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.capabilities=e,this}addResource(e,t){this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.resources||(this.config.mcpServer.resources=[]);const r={name:e,description:t};return this.config.mcpServer.resources.push(r),this}setResources(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.resources=e,this}addTool(e,t){this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.tools||(this.config.mcpServer.tools=[]);const r={name:e,description:t};return this.config.mcpServer.tools.push(r),this}setTools(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.tools=e,this}setMaintainer(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.maintainer=e,this}setRepository(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.repository=e,this}setDocs(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.docs=e,this}setVerification(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.verification=e,this}addVerificationDNS(e,t){this.config.mcpServer||(this.config.mcpServer={});const r={type:fc.DNS,value:e,dns_field:t};return this.config.mcpServer.verification=r,this}addVerificationSignature(e){this.config.mcpServer||(this.config.mcpServer={});const t={type:fc.SIGNATURE,value:e};return this.config.mcpServer.verification=t,this}addVerificationChallenge(e){this.config.mcpServer||(this.config.mcpServer={});const t={type:fc.CHALLENGE,value:"",challenge_path:e};return this.config.mcpServer.verification=t,this}addSocial(e,t){const r=this.socials.find(t=>t.platform===e);if(r)r.handle=t;else{const r={platform:e,handle:t};this.socials.push(r)}return this}setSocials(e){return this.socials=e,this}setProfilePicture(e,t){return this.config.pfpBuffer=e,this.config.pfpFileName=t,this}setExistingProfilePicture(e){return this.config.existingPfpTopicId=e,this}setNetworkType(e){return this.config.network=e,this}setExistingAccount(e,t){return this.config.existingAccount={accountId:e,privateKey:t},this}build(){if(!this.config.name)throw new Error("MCP server name is required");if(!this.config.network)throw new Error("Network type is required");if(!this.config.mcpServer)throw new Error("MCP server details are required");if(!this.config.mcpServer.version)throw new Error("MCP server version is required");if(!this.config.mcpServer.connectionInfo)throw new Error("MCP server connection info is required");if(!this.config.mcpServer.services||0===this.config.mcpServer.services.length)throw new Error("At least one MCP service type is required");if(!this.config.mcpServer.description)throw new Error("MCP server description is required");return this.config.bio||this.logger.warn("No bio provided for MCP server profile"),this.config.pfpBuffer||this.config.existingPfpTopicId||this.logger.warn("No profile picture provided or referenced"),this.socials.length>0?{...this.config,socials:this.socials}:this.config}},exports.MCPServerCapability=mc,exports.MCPServerConnectionInfoSchema=kd,exports.MCPServerDetailsSchema=xd,exports.MCPServerHostSchema=vd,exports.MCPServerProfileSchema=Pd,exports.MCPServerResourceSchema=Ad,exports.MCPServerToolSchema=Cd,exports.MCPServerVerificationSchema=Ed,exports.MapCache=ec,exports.MintLimitExceededError=class extends Kp{constructor(e,t,r){super(`Mint limit exceeded for ${e}: requested ${t}, limit ${r}`),this.tick=e,this.requested=t,this.limit=r,this.name="MintLimitExceededError"}},exports.NodeCryptoAdapter=cd,exports.NodeHashAdapter=ed,exports.NodeHmacAdapter=nd,exports.PayloadSizeError=Xd,exports.PersonBuilder=class{constructor(){this.config={version:"1.0",type:0},this.logger=z.getInstance({module:"PersonBuilder"})}setName(e){return this.config.display_name=e,this}setAlias(e){return this.config.alias=e,this}setBio(e){return this.config.bio=e,this}setDescription(e){return this.setBio(e)}addSocial(e,t){this.config.socials||(this.config.socials=[]);const r=this.config.socials.find(t=>t.platform===e);return r?r.handle=t:this.config.socials.push({platform:e,handle:t}),this}setProfileImage(e){return this.config.profileImage=e,this}setProfilePicture(e,t){return this.config.pfpBuffer=e,this.config.pfpFileName=t,this}setExistingProfilePicture(e){return this.config.profileImage=`hcs://1/${e}`,this}addProperty(e,t){return this.config.properties||(this.config.properties={}),this.config.properties[e]=t,this}setInboundTopicId(e){return this.config.inboundTopicId=e,this}setOutboundTopicId(e){return this.config.outboundTopicId=e,this}getProfilePicture(){return{pfpBuffer:this.config.pfpBuffer,pfpFileName:this.config.pfpFileName}}build(){if(!this.config.display_name)throw new Error("Display name is required for the profile");return this.config.bio||this.logger.warn("No bio provided for person profile"),this.config.pfpBuffer||this.config.profileImage||this.logger.warn("No profile picture provided or referenced"),{version:this.config.version,type:0,display_name:this.config.display_name,alias:this.config.alias,bio:this.config.bio,socials:this.config.socials,profileImage:this.config.profileImage,properties:this.config.properties,inboundTopicId:this.config.inboundTopicId,outboundTopicId:this.config.outboundTopicId,pfpBuffer:this.config.pfpBuffer,pfpFileName:this.config.pfpFileName}}},exports.PersonalProfileSchema=Nd,exports.PointsBurnError=$p,exports.PointsDeploymentError=Up,exports.PointsMintError=class extends Kp{constructor(e,t,r,i){super(e),this.tick=t,this.requestedAmount=r,this.availableSupply=i,this.name="PointsMintError"}},exports.PointsNotFoundError=class extends Kp{constructor(e){super(`Points with tick "${e}" not found`),this.tick=e,this.name="PointsNotFoundError"}},exports.PointsTransferError=Lp,exports.PointsValidationError=Hp,exports.ProfileType=uc,exports.ProgressReporter=ps,exports.REFERENCE_THRESHOLD=51200,exports.RedisCache=class{constructor(e={}){const{host:t="localhost",port:r=6379,password:i,db:o=0,keyPrefix:n="",tls:s=!1,connectTimeout:a=5e3,retryStrategy:c,logLevel:l="info"}=e;this.prefix=n,this.logger=z.getInstance({level:l,module:"RedisCache"}),this.client=function(e,t){const r=function(){if("function"!=typeof require)return null;try{const e=require("ioredis");if("function"==typeof e)return e;if("function"==typeof e.default)return e.default}catch{return null}return null}();if(!r)return e.warn("ioredis is not installed; RedisCache will use an in-memory cache instead"),function(){const e=new Map;return{get:async t=>e.get(t)??null,set:async(t,r)=>(e.set(t,r),"OK"),setex:async(t,r,i)=>(e.set(t,i),"OK"),async del(...t){let r=0;for(const i of t)e.delete(i)&&(r+=1);return r},async keys(t){if(t.endsWith("*")){const r=t.slice(0,-1);return Array.from(e.keys()).filter(e=>e.startsWith(r))}return e.has(t)?[t]:[]},async quit(){e.clear()},on(){}}}();const i=new r({host:t.host,port:t.port,password:t.password,db:t.db,tls:t.tls,keyPrefix:t.keyPrefix,connectTimeout:t.connectTimeout,retryStrategy:t.retryStrategy,maxRetriesPerRequest:t.maxRetriesPerRequest});return i.on("error",t=>{e.error("Redis connection error:",t)}),i.on("connect",()=>{e.debug("Redis connected")}),i}(this.logger,{host:t,port:r,password:i,db:o,tls:s?{}:void 0,keyPrefix:n,connectTimeout:a,retryStrategy:c||(e=>Math.min(50*e,2e3)),maxRetriesPerRequest:3})}getKey(e){return`${this.prefix}${e}`}async get(e){try{return await this.client.get(this.getKey(e))||void 0}catch(t){throw this.logger.error("Redis get error:",t),t}}async set(e,t,r){try{const i=this.getKey(e);r?await this.client.setex(i,r,t):await this.client.set(i,t)}catch(i){throw this.logger.error("Redis set error:",i),i}}async delete(e){try{await this.client.del(this.getKey(e))}catch(t){throw this.logger.error("Redis delete error:",t),t}}async clear(){try{const e=await this.client.keys(`${this.prefix}*`);e.length>0&&await this.client.del(...e)}catch(e){throw this.logger.error("Redis clear error:",e),e}}async disconnect(){await this.client.quit()}setLogLevel(e){this.logger.setLogLevel(e)}},exports.Registration=zd,exports.RegistryBrokerClient=Yl,exports.RegistryBrokerError=Gl,exports.RegistryBrokerParseError=Jl,exports.RegistryType=ou,exports.ResolverRegistry=tp,exports.ResourceManager=class{constructor(e,t,r,i={}){this.cache=new Map,this.currentCacheSize=0,this.supportedImageTypes=new Set(["image/png","image/jpeg","image/jpg","image/gif","image/svg+xml","image/webp"]),this.dangerousJSPatterns=[/eval\s*\(/g,/Function\s*\(/g,/setTimeout\s*\(\s*["'].*["']/g,/setInterval\s*\(\s*["'].*["']/g,/document\.write/g,/innerHTML\s*=/g,/outerHTML\s*=/g],this.dangerousCSSPatterns=[/javascript\s*:/gi,/@import.*url\s*\(\s*["']?javascript:/gi,/expression\s*\(/gi,/behavior\s*:/gi],this.logger=t,this.hcs=r||new M,this.options={cacheTTL:i.cacheTTL||3e5,maxCacheSize:i.maxCacheSize||52428800,maxResourceSize:i.maxResourceSize||5242880}}async loadCSS(e){this.logger.debug("Loading CSS resource",{topicId:e});try{const t=await this.loadResource(e);if("text/css"!==t.contentType)throw new Error(`Expected CSS resource, got ${t.contentType}`);const r=t.content,i=this.sanitizeCSS(r);return this.logger.debug("CSS resource loaded successfully",{topicId:e,size:r.length,sanitized:i.length!==r.length}),i}catch(t){throw this.logger.error("Failed to load CSS resource",{topicId:e,error:t}),new Error(`Failed to load CSS resource: ${t instanceof Error?t.message:"Unknown error"}`)}}async loadJS(e){this.logger.debug("Loading JavaScript resource",{topicId:e});try{const t=await this.loadResource(e);if(!t.contentType.includes("javascript")&&!t.contentType.includes("ecmascript"))throw new Error(`Expected JavaScript resource, got ${t.contentType}`);const r=t.content;if(r.length>this.options.maxResourceSize)throw new Error("JavaScript resource too large");const i=this.sanitizeJavaScript(r);return this.logger.debug("JavaScript resource loaded successfully",{topicId:e,size:r.length,sanitized:i.length!==r.length}),i}catch(t){throw this.logger.error("Failed to load JavaScript resource",{topicId:e,error:t}),new Error(`Failed to load JavaScript resource: ${t instanceof Error?t.message:"Unknown error"}`)}}async loadImage(e){this.logger.debug("Loading image resource",{topicId:e});try{const t=await this.loadResource(e);if(!this.supportedImageTypes.has(t.contentType))throw new Error(`Unsupported image format: ${t.contentType}`);const r=t.content,i=new Uint8Array(r),o=new Blob([i.buffer],{type:t.contentType});return this.logger.debug("Image resource loaded successfully",{topicId:e,size:r.length,type:t.contentType}),o}catch(t){throw this.logger.error("Failed to load image resource",{topicId:e,error:t}),new Error(`Failed to load image resource: ${t instanceof Error?t.message:"Unknown error"}`)}}async loadTemplate(e){this.logger.debug("Loading template resource",{topicId:e});try{const t=(await this.loadResource(e)).content;this.validateTemplateSyntax(t);const r=this.sanitizeTemplate(t);return this.logger.debug("Template resource loaded successfully",{topicId:e,size:t.length}),r}catch(t){throw this.logger.error("Failed to load template resource",{topicId:e,error:t}),new Error(`Failed to load template resource: ${t instanceof Error?t.message:"Unknown error"}`)}}async loadWithIntegrityCheck(e,t){this.logger.debug("Loading resource with integrity check",{topicId:e,expectedHash:t});try{const r=await this.loadResource(e),i=await this.verifyIntegrity(r.content,t);if(!i)throw new Error("Resource integrity verification failed");return this.logger.debug("Resource integrity verified",{topicId:e}),{content:r.content,verified:i,contentType:r.contentType}}catch(r){throw this.logger.error("Resource integrity check failed",{topicId:e,error:r}),r}}async verifyIntegrity(e,t){try{if(od())return this.logger.warn("Integrity verification skipped in SSR environment"),!0;if("undefined"==typeof crypto||!crypto.subtle)return this.logger.warn("WebCrypto not available, skipping integrity verification"),!0;const r="string"==typeof e?(new TextEncoder).encode(e):e,i=r instanceof Uint8Array?r:new Uint8Array(r),o=new Uint8Array(i),n=await crypto.subtle.digest("SHA-256",o.buffer),s=Array.from(new Uint8Array(n));return s.map(e=>e.toString(16).padStart(2,"0")).join("")===t.toLowerCase()}catch(r){return this.logger.error("Error verifying integrity",{error:r}),!1}}async loadDependencies(e){this.logger.debug("Loading dependencies",{count:e.length});try{this.detectCircularDependencies(e);const t=this.topologicalSort(e),r=[];for(const e of t){let t;switch(e.type){case"css":t=await this.loadCSS(e.topicId);break;case"js":t=await this.loadJS(e.topicId);break;case"template":t=await this.loadTemplate(e.topicId);break;case"image":const r=await this.loadImage(e.topicId);t=new Uint8Array(await r.arrayBuffer());break;default:throw new Error(`Unsupported dependency type: ${e.type}`)}r.push({topicId:e.topicId,content:t,contentType:this.getContentTypeForType(e.type),type:e.type})}return this.logger.debug("Dependencies loaded successfully",{count:r.length}),r}catch(t){throw this.logger.error("Failed to load dependencies",{error:t}),t}}clearCache(){this.cache.clear(),this.currentCacheSize=0,this.logger.debug("Resource cache cleared")}getCacheSize(){return this.currentCacheSize}async loadResource(e){const t=this.getFromCache(e);if(t)return this.logger.debug("Resource loaded from cache",{topicId:e}),t;const r=await this.hcs.retrieveHCS1Data(e),i=r.type||"application/octet-stream";let o;o=i.startsWith("text/")||i.includes("javascript")||i.includes("json")?await r.text():new Uint8Array(await r.arrayBuffer());const n={content:o,contentType:i,size:r.size};return this.addToCache(e,n),n}getFromCache(e){const t=this.cache.get(e);return t?Date.now()-t.timestamp>this.options.cacheTTL?(this.removeFromCache(e),null):t.data:null}addToCache(e,t){const r="string"==typeof t.content?t.content.length:t.content.byteLength;if(r>this.options.maxCacheSize/2)return void this.logger.warn("Resource too large for cache",{topicId:e,size:r});for(;this.currentCacheSize+r>this.options.maxCacheSize&&this.cache.size>0;)this.evictOldestEntry();const i={data:t,timestamp:Date.now(),size:r};this.cache.set(e,i),this.currentCacheSize+=r,this.logger.debug("Resource added to cache",{topicId:e,size:r,totalCacheSize:this.currentCacheSize})}removeFromCache(e){const t=this.cache.get(e);t&&(this.cache.delete(e),this.currentCacheSize-=t.size)}evictOldestEntry(){let e=null,t=Date.now();for(const[r,i]of this.cache)i.timestamp<t&&(t=i.timestamp,e=r);e&&(this.removeFromCache(e),this.logger.debug("Evicted oldest cache entry",{topicId:e}))}sanitizeCSS(e){let t=e;for(const r of this.dangerousCSSPatterns)t=t.replace(r,"");return t}sanitizeJavaScript(e){let t=e;for(const r of this.dangerousJSPatterns)t=t.replace(r,"");return t}sanitizeTemplate(e){return e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/on\w+\s*=\s*["'][^"']*["']/gi,"").replace(/javascript\s*:/gi,"")}validateTemplateSyntax(e){if((e.match(/\{\{/g)||[]).length!==(e.match(/\}\}/g)||[]).length)throw new Error("Invalid template syntax: unmatched braces");if((e.match(/\{\{#\w+/g)||[]).length!==(e.match(/\{\{\/\w+/g)||[]).length)throw new Error("Invalid template syntax: unclosed block helpers")}detectCircularDependencies(e){const t=new Map;for(const n of e)t.set(n.topicId,n.depends||[]);const r=new Set,i=new Set,o=e=>{if(i.has(e))throw new Error("Circular dependency detected");if(r.has(e))return;i.add(e);const n=t.get(e)||[];for(const t of n)o(t);i.delete(e),r.add(e)};for(const n of e)o(n.topicId)}topologicalSort(e){const t=new Map,r=new Map;for(const s of e)t.set(s.topicId,s),r.set(s.topicId,s.depends||[]);const i=[],o=new Set,n=e=>{if(o.has(e))return;const s=r.get(e)||[];for(const t of s)n(t);o.add(e);const a=t.get(e);a&&i.push(a)};for(const s of e)n(s.topicId);return i}getContentTypeForType(e){switch(e){case"css":return"text/css";case"js":return"application/javascript";case"template":return"text/html";case"image":return"image/*";default:return"application/octet-stream"}}},exports.SUPPORTED_SOCIAL_PLATFORMS=["twitter","github","discord","telegram","linkedin","youtube","website","x"],exports.ScheduleParser=ba,exports.SocialLinkSchema=Td,exports.StateHashError=vh,exports.SupplyLimitExceededError=class extends Kp{constructor(e,t,r,i){super(`Supply limit exceeded for ${e}: max ${r}, current ${i}, requested ${t}`),this.tick=e,this.requested=t,this.maxSupply=r,this.currentSupply=i,this.name="SupplyLimitExceededError"}},exports.TESTNET_EXAMPLES=Ou,exports.TemplateEngine=class{constructor(e){this.templateCache=new Map,this.helpers=new Map,this.compiledTemplates=new Map,this.logger=e,this.setupBuiltinHelpers()}async render(e,t={}){this.logger.debug("Rendering template",{templateLength:e.length,context:JSON.stringify(t,null,2),attributesType:t.attributes?typeof t.attributes:"undefined",contextKeys:Object.keys(t)});try{const r=this.getCacheKey(e);let i=this.templateCache.get(r);i||(i=await this.compileTemplate(e),this.templateCache.set(r,i));const o=i.render(this.sanitizeContext(t));return this.logger.debug("Template rendered successfully",{resultLength:o.length}),o}catch(r){throw this.logger.error("Template rendering failed",{error:r,template:e}),new Error(`Template rendering failed: ${r instanceof Error?r.message:"Unknown error"}`)}}async precompile(e,t){this.logger.debug("Precompiling template",{name:e,templateLength:t.length});try{const r=await this.compileTemplate(t);this.compiledTemplates.set(e,r),this.logger.debug("Template precompiled successfully",{name:e})}catch(r){throw this.logger.error("Template precompilation failed",{error:r,name:e}),new Error(`Template precompilation failed: ${r instanceof Error?r.message:"Unknown error"}`)}}async renderCompiled(e,t={}){const r=this.compiledTemplates.get(e);if(!r)throw new Error(`Precompiled template '${e}' not found`);this.logger.debug("Rendering precompiled template",{name:e});try{const i=r.render(this.sanitizeContext(t));return this.logger.debug("Precompiled template rendered successfully",{name:e}),i}catch(i){throw this.logger.error("Precompiled template rendering failed",{error:i,name:e}),new Error(`Template rendering failed: ${i instanceof Error?i.message:"Unknown error"}`)}}registerHelper(e,t){this.helpers.set(e,t),this.logger.debug("Helper registered",{name:e})}clearCache(){this.templateCache.clear(),this.logger.debug("Template cache cleared")}getCacheSize(){return this.templateCache.size}async compileTemplate(e){this.validateTemplate(e);return{source:e,compiled:!0,render:t=>this.executeTemplate(e,t)}}executeTemplate(e,t){let r=e;return r=this.processHelpers(r,t),r=this.processLoops(r,t),r=this.processConditionals(r,t),r=this.processVariables(r,t),r}processConditionals(e,t){let r=e;r=r.replace(/\{\{#if\s+([^}]+)\}\}((?:[^{]|\{(?!\{)|\{\{(?!#if|\{#else|\{\/if))*?)\{\{#if\s+([^}]+)\}\}((?:[^{]|\{(?!\{)|\{\{(?!#if|#else|\/if))*?)\{\{else\}\}((?:[^{]|\{(?!\{)|\{\{(?!#if|#else|\/if))*?)\{\{\/if\}\}((?:[^{]|\{(?!\{)|\{\{(?!\/if))*?)\{\{\/if\}\}/gs,(e,r,i,o,n,s,a)=>{if(!this.evaluateCondition(r,t))return"";return i+(this.evaluateCondition(o,t)?n:s)+a});r=r.replace(/\{\{#if\s+([^}]+)\}\}((?:[^{]|\{(?!\{)|\{\{(?!else|\/if))*?)\{\{else\}\}((?:[^{]|\{(?!\{)|\{\{(?!\/if))*?)\{\{\/if\}\}/gs,(e,r,i,o)=>this.evaluateCondition(r,t)?i:o);r=r.replace(/\{\{#if\s+([^}]+)\}\}((?:[^{]|\{(?!\{)|\{\{(?!\/if))*?)\{\{\/if\}\}/gs,(e,r,i)=>this.evaluateCondition(r,t)?i:"");return r=r.replace(/\{\{#unless\s+([^}]+)\}\}((?:[^{]|\{(?!\{)|\{\{(?!\/unless))*?)\{\{\/unless\}\}/gs,(e,r,i)=>this.evaluateCondition(r,t)?"":i),r}processLoops(e,t){let r=e;return r=r.replace(/\{\{#each\s+([^}]+)\}\}(.*?)\{\{\/each\}\}/gs,(e,r,i)=>{const o=this.getNestedValue(r,t);if(!o)return"";let n="";if(Array.isArray(o))o.forEach((e,r)=>{let o=i;if(o=o.replace(/\{\{this\}\}/g,this.escapeHtml(String(e))),o=o.replace(/\{\{@index\}\}/g,String(r)),"object"==typeof e&&null!==e)for(const[t,i]of Object.entries(e)){const e=new RegExp(`\\{\\{${t}\\}\\}`,"g");o=o.replace(e,this.escapeHtml(String(i)))}o=o.replace(/\{\{\.\.\/([^}]+)\}\}/g,(e,r)=>{const i=this.getNestedValue(r,t);return this.escapeHtml(String(i||""))}),n+=o});else if("object"==typeof o)for(const[t,s]of Object.entries(o)){let e=i;e=e.replace(/\{\{@key\}\}/g,this.escapeHtml(t)),e=e.replace(/\{\{this\}\}/g,this.escapeHtml(String(s))),n+=e}return n}),r}processVariables(e,t){let r=e;r=r.replace(/\{\{\{([^}]+)\}\}\}/g,(e,r)=>{const i=this.getNestedValue(r.trim(),t);return this.sanitizeHtml(String(i||""))});return r=r.replace(/\{\{([^}#/]+)\}\}/g,(e,r)=>{const i=r.trim();if(i.startsWith("#")||i.startsWith("/")||i.startsWith("else"))return e;const o=this.getNestedValue(i,t);return 0===o||!1===o?this.escapeHtml(String(o)):this.escapeHtml(String(o||""))}),r}processHelpers(e,t){let r=e;r=r.replace(/\{\{#with\s+([^}]+)\}\}(.*?)\{\{\/with\}\}/gs,(e,r,i)=>{const o=this.getNestedValue(r.trim(),t);return o?this.executeTemplate(i,o):""});for(const[i,o]of this.helpers){const e=new RegExp(`\\{\\{${i}\\s+([^}]+)\\}\\}`,"g");r=r.replace(e,(e,r)=>{try{const e=this.getNestedValue(r.trim(),t);return this.escapeHtml(o.call(t,e))}catch(n){return this.logger.warn("Helper execution failed",{helperName:i,error:n}),""}})}return r}evaluateCondition(e,t){const r=this.getNestedValue(e.trim(),t);return Boolean(r)}getNestedValue(e,t){if(!e||!t)return;const r=e.split(".");let i=t;for(const o of r){if(null==i||"object"!=typeof i)return;i=i[o]}return i}sanitizeContext(e){if(null==e)return e;const t=new WeakSet,r=e=>{if(null===e||"object"!=typeof e)return e;if(t.has(e))return"[Circular]";if(t.add(e),Array.isArray(e))return e.map(r);const i={};for(const[t,o]of Object.entries(e))i[t]=r(o);return i};return r(e)}escapeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}sanitizeHtml(e){return e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"")}validateTemplate(e){if((e.match(/\{\{#\w+/g)||[]).length!==(e.match(/\{\{\/\w+/g)||[]).length)throw new Error("Invalid template syntax: unclosed block helpers");if(/\{\{[^}]*$|\{\{[^}]*\{\{/.test(e))throw new Error("Invalid template syntax: malformed handlebars")}getCacheKey(e){let t=0;for(let r=0;r<e.length;r++){t=(t<<5)-t+e.charCodeAt(r),t&=t}return t.toString()}setupBuiltinHelpers(){}},exports.TopicCreationError=Qd,exports.TopicRegistrationError=qp,exports.TransactionParser=va,exports.TransactionParsingError=hs,exports.VerificationType=fc,exports.WasmBridge=class{constructor(){this.wasm=null,this.WASM_VECTOR_LEN=0,this.cachedUint8Memory=null,this.cachedDataViewMemory=null,this.textEncoder=new TextEncoder,this.textDecoder=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),this.textDecoder.decode(),this.logger=z.getInstance({module:"WasmBridge"})}setLogLevel(e){this.logger.setLogLevel(e)}get wasmInstance(){if(!this.wasm)throw new Error("WASM not initialized");return this.wasm}getUint8Memory(){if(!this.wasm)throw new Error("WASM not initialized");return null!==this.cachedUint8Memory&&0!==this.cachedUint8Memory.byteLength||(this.cachedUint8Memory=new Uint8Array(this.wasm.memory.buffer)),this.cachedUint8Memory}getDataViewMemory(){if(!this.wasm)throw new Error("WASM not initialized");return null!==this.cachedDataViewMemory&&this.cachedDataViewMemory.buffer===this.wasm.memory.buffer||(this.cachedDataViewMemory=new DataView(this.wasm.memory.buffer)),this.cachedDataViewMemory}encodeString(e,t){if(0===e.length)return{read:0,written:0};const r=this.textEncoder.encode(e);return t.set(r),{read:e.length,written:r.length}}passStringToWasm(e,t,r){if(void 0===r){const r=this.textEncoder.encode(e),i=t(r.length,1);return this.getUint8Memory().set(r,i),this.WASM_VECTOR_LEN=r.length,i}let i=this.textEncoder.encode(e).length,o=t(i,1);const n=this.getUint8Memory();let s=0;for(;s<i;s++){const t=e.charCodeAt(s);if(t>127)break;n[o+s]=t}if(s!==i){0!==s&&(e=e.slice(s)),o=r(o,i,i=s+3*this.textEncoder.encode(e).length,1);const t=this.getUint8Memory().subarray(o+s,o+i);s+=this.encodeString(e,t).written}return this.WASM_VECTOR_LEN=s,o}getStringFromWasm(e,t){return e>>>=0,this.textDecoder.decode(this.getUint8Memory().subarray(e,e+t))}createWasmFunction(e){if(!this.wasm)throw new Error("WASM not initialized");return(...t)=>{const r=this.wasm.__wbindgen_add_to_stack_pointer(-16);let i=[0,0];try{const o=[r,...t.map(e=>[this.passStringToWasm(e,this.wasm.__wbindgen_malloc,this.wasm.__wbindgen_realloc),this.WASM_VECTOR_LEN]).flat()];e.apply(this.wasm,o);const n=this.getDataViewMemory().getInt32(r+0,!0),s=this.getDataViewMemory().getInt32(r+4,!0);return i=[n,s],this.getStringFromWasm(n,s)}finally{this.wasm.__wbindgen_add_to_stack_pointer(16),this.wasm.__wbindgen_free(i[0],i[1],1)}}}async initWasm(e){const t=this,r={__wbindgen_placeholder__:{__wbindgen_throw:function(e,r){const i=t.getStringFromWasm(e,r);throw t.logger.error(`WASM error: ${i}`),new Error(i)}}};try{this.logger.debug("Compiling WASM module");const t=await WebAssembly.compile(e);this.logger.debug("Instantiating WASM module");const i=await WebAssembly.instantiate(t,r);return this.wasm=i.exports,this.logger.info("WASM module initialized successfully"),this.wasm}catch(i){throw this.logger.error("Failed to initialize WASM module",i),i}}createStateData(e,t={}){let r={};return e?.c?.inputType?.stateData&&(t.latestRoundData&&Object.keys(e.c.inputType.stateData).every(e=>e in t.latestRoundData)?(r.latestRoundData={},Object.entries(e.c.inputType.stateData).forEach(([e,i])=>{r.latestRoundData[e]=String(t.latestRoundData[e])})):Object.entries(e.c.inputType.stateData).forEach(([e,i])=>{const o=t[e];o&&"object"==typeof o&&"values"in o&&o.values.length>0?r[e]=String(o.values[0]):r[e]=this.getDefaultValueForType(i)})),r}getDefaultValueForType(e){return e.startsWith("uint")||e.startsWith("int")||"number"===e?"0":"bool"===e?"false":""}executeWasm(e,t){if(!this.wasm)throw this.logger.error("WASM not initialized"),new Error("WASM not initialized");try{this.logger.debug("Executing WASM with stateData",e);return this.createWasmFunction(this.wasmInstance.process_state)(JSON.stringify(e),JSON.stringify(t))}catch(r){throw this.logger.error("Error executing WASM",r),r}}getParams(){return this.createWasmFunction(this.wasmInstance.get_params)()}},exports.WasmExecutor=_u,exports.WasmValidator=class{constructor(e){this.cryptoAdapter=ud(),this.REQUIRED_EXPORTS=["INFO","POST","GET"],this.ALLOWED_IMPORTS=new Set(["env.console_log","env.get_network","env.submit_hcs_message","env.memory"]),this.MAX_INITIAL_MEMORY=256,this.WARN_MODULE_SIZE=1048576,this.MAX_MODULE_SIZE=5242880,this.logger=e}async validate(e){const t=[],r=[],i={isValid:!0,errors:t,warnings:r};try{if(e.length>this.WARN_MODULE_SIZE&&r.push(`Large module size: ${(e.length/1024/1024).toFixed(2)} MB`),e.length>this.MAX_MODULE_SIZE&&(t.push("Module size exceeds maximum allowed"),i.isValid=!1),!this.validateMagicNumber(e))return t.push("Invalid WASM magic number"),i.isValid=!1,i;const o=this.getWasmVersion(e);if(i.version=o,1!==o)return t.push(`Unsupported WASM version: ${o}`),i.isValid=!1,i;const n=await this.parseModule(e);i.exports=n.exports;for(const e of this.REQUIRED_EXPORTS)n.exports.includes(e)||(t.push(`Missing required export: ${e}`),i.isValid=!1);i.imports=n.imports;for(const e of n.imports){const r=`${e.module}.${e.name}`;this.ALLOWED_IMPORTS.has(r)||(t.push(`Disallowed import: ${r}`),i.isValid=!1)}n.memory&&(i.memoryRequirements=n.memory,n.memory.initial>this.MAX_INITIAL_MEMORY&&(t.push(`Excessive initial memory: ${n.memory.initial} pages`),i.isValid=!1)),n.hasStartFunction&&r.push("Module has start function - may execute code on load"),n.functionCount>100&&r.push(`High function count: ${n.functionCount}`),this.hasSuspiciousPatterns(e)&&r.push("Potentially unsafe operation detected"),i.exportSignatures=n.exportSignatures}catch(o){this.logger.error("WASM validation failed",{error:o}),t.push(`Validation error: ${o instanceof Error?o.message:"Unknown error"}`),i.isValid=!1}return i}async validateInfoFunction(e){const t=[],r=[];try{const i=await e(),o=JSON.parse(i);return o.name&&o.version&&o.hashlinks_version?{isValid:!0,errors:t,warnings:r,moduleInfo:o}:(t.push("INFO missing required fields"),{isValid:!1,errors:t,warnings:r})}catch(i){return t.push("INFO function returned invalid JSON"),{isValid:!1,errors:t,warnings:r}}}async validateActionSchemas(e){const t=[];if(e.validation_rules)for(const[r,i]of Object.entries(e.validation_rules))"object"!=typeof i&&t.push(`Invalid validation rule for action: ${r}`);return{isValid:0===t.length,errors:t,warnings:[]}}async extractMetadata(e){return{size:e.length,hash:await this.calculateHash(e),producers:{language:["Unknown"]}}}async calculateHash(e){if(od())return this.createSSRSafeHash(e);const t=this.cryptoAdapter.createHash("sha256").update(globalThis.Buffer.from(e)).digest("hex"),r=t instanceof Promise?await t:t;return"string"==typeof r?r:r.toString("hex")}createSSRSafeHash(e){let t=0;for(let r=0;r<Math.min(e.length,1024);r++)t=(t<<5)-t+e[r]&4294967295;return`ssr-wasm-${e.length}-${Math.abs(t).toString(16).padStart(8,"0")}`}validateMagicNumber(e){return e.length>=4&&0===e[0]&&97===e[1]&&115===e[2]&&109===e[3]}getWasmVersion(e){return e.length<8?0:e[4]|e[5]<<8|e[6]<<16|e[7]<<24}async parseModule(e){const t=e.slice(8),r=new TextDecoder("utf-8",{fatal:!1}).decode(t),i=[];r.includes("INFO")&&i.push("INFO"),r.includes("POST")&&i.push("POST"),r.includes("GET")&&i.push("GET"),0===i.length&&e.length>8&&i.push("INFO","POST","GET");const o=[],n=r.split("import:");for(let u=1;u<n.length;u++){const e=n[u].match(/^([a-zA-Z_]+[a-zA-Z0-9_]*)\.([a-zA-Z_]+[a-zA-Z0-9_]*)/);e&&o.push({module:e[1],name:e[2],type:"function"})}let s=1,a=16;const c=r.match(/memory:(\d+)(?:-(\d+))?/);c&&(s=parseInt(c[1]),c[2]&&(a=parseInt(c[2])));let l=10;const d=r.match(/functions:(\d+)/);d&&(l=parseInt(d[1]));return{exports:i,imports:o,memory:{initial:s,maximum:a},functionCount:l,hasStartFunction:r.includes("start:true"),exportSignatures:{INFO:{type:"function",params:[],results:["i32"]},POST:{type:"function",params:["i32","i32","i32","i32"],results:["i32"]},GET:{type:"function",params:["i32","i32","i32"],results:["i32"]}}}}hasSuspiciousPatterns(e){const t=new TextDecoder("utf-8",{fatal:!1}).decode(e);return["eval","__proto__","constructor"].some(e=>t.includes(e))}},exports.WebCryptoAdapter=ld,exports.WebHashAdapter=td,exports.WebHmacAdapter=sd,exports.accountIdsToExemptKeys=oc,exports.actionRegistrationSchema=pu,exports.assemblyMessageSchema=bu,exports.assemblyRegistrationSchema=wu,exports.baseMessageSchema=yp,exports.blockRegistrationSchema=hu,exports.buildHcs10ConfirmConnectionTx=Hd,exports.buildHcs10CreateConnectionTopicTx=Ud,exports.buildHcs10CreateInboundTopicTx=Md,exports.buildHcs10CreateOutboundTopicTx=Kd,exports.buildHcs10CreateRegistryTopicTx=Ld,exports.buildHcs10OutboundConnectionCreatedRecordTx=jd,exports.buildHcs10OutboundConnectionRequestRecordTx=qd,exports.buildHcs10RegistryDeleteTx=function(e){const t={p:"hcs-10",op:"delete",uid:e.uid,m:e.memo};return X({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:Bd(1,0)})},exports.buildHcs10RegistryMigrateTx=function(e){const t={p:"hcs-10",op:"migrate",t_id:e.targetTopicId,m:e.memo};return X({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:Bd(2,0)})},exports.buildHcs10RegistryRegisterTx=Vd,exports.buildHcs10SendMessageTx=Wd,exports.buildHcs10SubmitConnectionRequestTx=$d,exports.buildHcs12AddActionToAssemblyTx=function(e){return X({topicId:e.assemblyTopicId,message:JSON.stringify(e.operation)})},exports.buildHcs12AddBlockToAssemblyTx=function(e){return X({topicId:e.assemblyTopicId,message:JSON.stringify(e.operation)})},exports.buildHcs12CreateRegistryTopicTx=function(e){var t;return Y({memo:e.memoOverride??(t=e.registry,`hcs-12:1:${e.ttl}:${{action:0,assembly:2,hashlinks:3}[t]}`),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})},exports.buildHcs12RegisterAssemblyTx=function(e){return X({topicId:e.assemblyTopicId,message:JSON.stringify(e.registration)})},exports.buildHcs12SubmitMessageTx=function(e){const t="string"==typeof e.payload?e.payload:JSON.stringify(e.payload);return X({topicId:e.topicId,message:t,transactionMemo:e.transactionMemo})},exports.buildHcs12UpdateAssemblyTx=function(e){return X({topicId:e.assemblyTopicId,message:JSON.stringify(e.operation)})},exports.buildHcs15BaseAccountCreateTx=ch,exports.buildHcs15PetalAccountCreateTx=lh,exports.buildHcs16CreateAccountTx=mh,exports.buildHcs16CreateFloraTopicTx=gh,exports.buildHcs16CreateTransactionTopicTx=function(e){const t=(new i.TopicCreateTransaction).setTopicMemo(e.memo);if(e.adminKey&&t.setAdminKey(e.adminKey),e.submitKey&&t.setSubmitKey(e.submitKey),e.feeScheduleKey&&t.setFeeScheduleKey(e.feeScheduleKey),e.customFees&&e.customFees.length>0){const r=e.customFees.map(e=>{const t=(new i.CustomFixedFee).setAmount(e.amount).setFeeCollectorAccountId(i.AccountId.fromString(e.feeCollectorAccountId));return e.denominatingTokenId&&t.setDenominatingTokenId(i.TokenId.fromString(e.denominatingTokenId)),t});t.setCustomFees(r)}if(e.feeExemptKeys&&e.feeExemptKeys.length>0)throw new Error("feeExemptKeys not supported by installed @hashgraph/sdk");return t},exports.buildHcs16FloraCreatedTx=yh,exports.buildHcs16FloraJoinAcceptedTx=Sh,exports.buildHcs16FloraJoinRequestTx=Ih,exports.buildHcs16FloraJoinVoteTx=Th,exports.buildHcs16MessageTx=fh,exports.buildHcs16ScheduleAccountKeyUpdateTx=function(e){const t=(new i.AccountUpdateTransaction).setAccountId(i.AccountId.fromString(e.floraAccountId)).setKey(e.newKeyList);return e.memo&&t.setTransactionMemo(e.memo),(new i.ScheduleCreateTransaction).setScheduledTransaction(t)},exports.buildHcs16ScheduleTopicKeyUpdateTx=function(e){const t=(new i.TopicUpdateTransaction).setTopicId(e.topicId);return e.adminKey&&t.setAdminKey(e.adminKey),e.submitKey&&t.setSubmitKey(e.submitKey),e.memo&&t.setTransactionMemo(e.memo),(new i.ScheduleCreateTransaction).setScheduledTransaction(t)},exports.buildHcs16StateUpdateTx=wh,exports.buildHcs16TransactionTx=bh,exports.buildHcs17CreateTopicTx=Nh,exports.buildHcs17MessageTx=_h,exports.buildHcs18AnnounceMessage=$h,exports.buildHcs18CompleteMessage=jh,exports.buildHcs18CreateDiscoveryTopicTx=Uh,exports.buildHcs18DiscoveryMemo=Kh,exports.buildHcs18ProposeMessage=Hh,exports.buildHcs18RespondMessage=qh,exports.buildHcs18SubmitDiscoveryMessageTx=Lh,exports.buildHcs18WithdrawMessage=Wh,exports.buildHcs1Hrl=up,exports.buildHcs20BurnTx=Yp,exports.buildHcs20DeployTx=Vp,exports.buildHcs20MintTx=Gp,exports.buildHcs20RegisterTx=Xp,exports.buildHcs20SubmitMessageTx=function(e){const t="string"==typeof e.payload?e.payload:JSON.stringify(e.payload);return X({topicId:e.topicId,message:t,transactionMemo:e.transactionMemo})},exports.buildHcs20TransferTx=Jp,exports.buildHcs21CreateRegistryTx=nh,exports.buildHcs21MessageTx=sh,exports.buildHcs21RegistryMemo=oh,exports.buildHcs2CreateRegistryTx=Ep,exports.buildHcs2DeleteTx=function(e){const t={p:"hcs-2",op:gp.DELETE,uid:e.uid,m:e.memo};return X({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})},exports.buildHcs2MigrateTx=function(e){const t={p:"hcs-2",op:gp.MIGRATE,t_id:e.targetTopicId,metadata:e.metadata,m:e.memo};return X({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})},exports.buildHcs2RegisterTx=function(e){const t={p:"hcs-2",op:gp.REGISTER,t_id:e.targetTopicId,metadata:e.metadata,m:e.memo};return X({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})},exports.buildHcs2UpdateTx=function(e){const t={p:"hcs-2",op:gp.UPDATE,uid:e.uid,t_id:e.targetTopicId,metadata:e.metadata,m:e.memo};return X({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})},exports.buildHcs5MintTx=hp,exports.buildHcs5MintWithHrlTx=function(e){const t=up(e.metadataTopicId);return hp({tokenId:e.tokenId,metadata:t,transactionMemo:e.transactionMemo})},exports.buildHcs6CreateRegistryTx=Z,exports.buildHcs6Hrl=L,exports.buildHcs6RegisterEntryTx=function(e){const t={p:"hcs-6",op:K.REGISTER,t_id:e.targetTopicId,m:e.memo};return X({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})},exports.buildHcs7CreateRegistryTx=Za,exports.buildHcs7EvmMessageTx=function(e){const t={p:"hcs-7",op:Ua.REGISTER_CONFIG,t:La.EVM,c:{contractAddress:e.config.contractAddress,abi:e.config.abi},m:e.config.memo??""};return Qa({topicId:e.topicId,message:t,transactionMemo:e.transactionMemo})},exports.buildHcs7SubmitMessageTx=Qa,exports.buildHcs7WasmMessageTx=function(e){const t={p:"hcs-7",op:Ua.REGISTER_CONFIG,t:La.WASM,c:{wasmTopicId:e.config.wasmTopicId,inputType:e.config.inputType,outputType:e.config.outputType},m:e.config.memo??""};return Qa({topicId:e.topicId,message:t,transactionMemo:e.transactionMemo})},exports.canonicalizeAgentData=Uu,exports.canonicalizeLedgerNetwork=dc,exports.capabilityNameToCapabilityMap=bc,exports.createLoggerAdapter=rc,exports.createPrivateKeySigner=Ul,exports.createUaid=Wu,exports.defaultIssuerRegistry=np,exports.defaultResolverRegistry=rp,exports.deleteMessageSchema=Ip,exports.detectCryptoEnvironment=id,exports.detectKeyTypeFromString=re,exports.ensureLoggerType=function(e){return ic(e)?e:rc(e)},exports.extractReferenceId=function(e){const t=e.trim(),r=t.match(/^content-ref:([a-f0-9]+)$/);if(r)return r[1];const i=t.match(/content-ref:([a-f0-9]+)/);return i?i[1]:null},exports.generateHCS17Memo=Ch,exports.generateHCS6RegistryMemo=V,exports.generateQuote=Ba,exports.getCryptoAdapter=ud,exports.getExampleTopics=function(e){return"mainnet"===e?Du:Ou},exports.getHumanReadableTransactionType=Ea,exports.getOrCreateSDK=Ra,exports.getParserConfig=function(e){return wa[e]},exports.getSchedulableTransactionType=function(e){for(const[t,r]of Object.entries(Sa))if(e[t])return r;return"unknown"},exports.getSupportedTransactionTypes=function(){return Object.keys(wa)},exports.getTopicId=Ka,exports.getTransactionTypeFromBody=ka,exports.hash=async function(e,t="sha256"){const r=ud().createHash(t),i="string"==typeof e?globalThis.Buffer.from(e):e,o=r.update(i).digest("hex");return o instanceof Promise?await o:o},exports.hashLinksRegistrationSchema=Iu,exports.hcs17MessageSchema=Eh,exports.hcs2MessageSchema=Sp,exports.hcs6BaseMessageSchema=H,exports.hcs6MessageSchema=j,exports.hcs6RegisterMessageSchema=q,exports.hcs6TopicIdSchema=$,exports.hcs7MessageSchema=Ja,exports.humanReadableTypeRegistry=Ta,exports.inscribe=Fa,exports.inscribeWithSigner=Oa,exports.isAnnounceMessage=function(e){if(!zh(e))return!1;const t=e;if("announce"!==t.op)return!1;if(!Fh(t.data))return!1;const r=t.data;if(!Oh(r.account))return!1;if(!Fh(r.petal))return!1;const i=r.petal;return!(!Oh(i.name)||!Dh(i.priority))&&(!!Fh(r.capabilities)&&(!!function(e){return Array.isArray(e)&&e.every(Oh)}(r.capabilities.protocols)&&!("valid_for"in r&&void 0!==r.valid_for&&null!==r.valid_for&&!Dh(r.valid_for))))},exports.isBrowser=Aa,exports.isCompleteMessage=function(e){if(!zh(e))return!1;const t=e;if("complete"!==t.op)return!1;if(!Fh(t.data))return!1;const r=t.data;if(!Oh(r.proposer))return!1;if(!Dh(r.proposal_seq))return!1;if(!Oh(r.flora_account))return!1;if(!Fh(r.topics))return!1;const i=r.topics;return!!(Oh(i.communication)&&Oh(i.transaction)&&Oh(i.state))},exports.isConcreteLogger=ic,exports.isCryptoAvailable=function(){return"none"!==id().preferredAPI},exports.isDiscoveryMessage=zh,exports.isEip155Caip10=wd,exports.isHederaCaip10=md,exports.isHederaNetwork=hd,exports.isPartialRegisterAgentResponse=e=>"partial"===e.status&&!1===e.success,exports.isPendingRegisterAgentResponse=e=>"pending"===e.status,exports.isProposeMessage=function(e){if(!zh(e))return!1;const t=e;if("propose"!==t.op)return!1;if(!Fh(t.data))return!1;const r=t.data;if(!Oh(r.proposer))return!1;if(!function(e){return Array.isArray(e)}(r.members))return!1;if(!r.members.every(e=>{if(!Fh(e))return!1;const t=e;return!!Oh(t.account)&&(!(!("priority"in t)||!Dh(t.priority))&&!("announce_seq"in t&&void 0!==t.announce_seq&&null!==t.announce_seq&&!Dh(t.announce_seq)))}))return!1;if(!Fh(r.config))return!1;const i=r.config;return!(!Oh(i.name)||!Dh(i.threshold))},exports.isRespondMessage=function(e){if(!zh(e))return!1;const t=e;if("respond"!==t.op)return!1;if(!Fh(t.data))return!1;const r=t.data;return!!Oh(r.responder)&&(!!Dh(r.proposal_seq)&&(!!Oh(r.decision)&&!!["accept","reject"].includes(r.decision)))},exports.isSSREnvironment=od,exports.isSuccessRegisterAgentResponse=e=>!0===e.success&&"pending"!==e.status,exports.isTransactionTypeSupported=function(e){return e in wa},exports.isWithdrawMessage=function(e){if(!zh(e))return!1;const t=e;if("withdraw"!==t.op)return!1;if(!Fh(t.data))return!1;const r=t.data;return!!Oh(r.account)&&(!!Dh(r.announce_seq)&&!("reason"in r&&void 0!==r.reason&&null!==r.reason&&!Oh(r.reason)))},exports.mcpServiceNameToCapabilityMap={resource_provider:0,tool_provider:1,prompt_template_provider:2,local_file_access:3,database_integration:4,api_integration:5,web_access:6,knowledge_base:7,memory_persistence:8,code_analysis:9,content_generation:10,communication:11,document_processing:12,calendar_schedule:13,search:14,assistant_orchestration:15},exports.migrateMessageSchema=Tp,exports.packageDeclarationSchema=rh,exports.parseHCS17Memo=xh,exports.parseHcs14Did=Vu,exports.parseHederaCaip10=yd,exports.protoFieldToTypeRegistry=Ia,exports.registerDefaultResolvers=ip,exports.registerMessageSchema=bp,exports.resolveTransactionSummary=ca,exports.retrieveInscription=Da,exports.safeValidate=function(e,t){const r=e.safeParse(t);return r.success?{success:!0,data:r.data}:{success:!1,errors:r.error}},exports.schedulableTransactionTypeRegistry=Sa,exports.setLoggerFactory=function(e){D=e,z.clearInstances()},exports.shouldUseReference=function(e){return("string"==typeof e?globalThis.Buffer.byteLength(e,"utf8"):e.length)>51200},exports.sleep=B,exports.toEip155Caip10=Id,exports.toHederaCaip10=fd,exports.topicIdSchema=fp,exports.transactionParserRegistry=wa,exports.transactionSummaryRegistry=aa,exports.updateMessageSchema=wp,exports.validateActionRegistration=Tu,exports.validateAssemblyMessage=Su,exports.validateAssemblyRegistration=function(e){return wu.parse(e)},exports.validateBlockRegistration=function(e){return hu.parse(e)},exports.validateHCS6RegistryMemo=function(e){const t=e.match(/^hcs-6:(\d):(\d+)$/);if(!t)return!1;const r=parseInt(t[1]),i=parseInt(t[2]);return 1===r&&W(i)},exports.validateHCS6TTL=W,exports.validateHashLinksRegistration=function(e){return Iu.parse(e)},exports.validateWithSchema=ku,exports.waitForInscriptionConfirmation=Ma;
10
+ !function(e){const t=ae,r=fe,i="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=l,e.SlowBuffer=function(e){+e!=e&&(e=0);return l.alloc(+e)},e.INSPECT_MAX_BYTES=50;const o=2147483647;e.kMaxLength=o;const{Uint8Array:n,ArrayBuffer:s,SharedArrayBuffer:a}=globalThis;function c(e){if(e>o)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new n(e);return Object.setPrototypeOf(t,l.prototype),t}function l(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return p(e)}return d(e,t,r)}function d(e,t,r){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!l.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|f(e,t);let i=c(r);const o=i.write(e,t);o!==r&&(i=i.slice(0,o));return i}(e,t);if(s.isView(e))return function(e){if(Y(e,n)){const t=new n(e);return g(t.buffer,t.byteOffset,t.byteLength)}return h(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(Y(e,s)||e&&Y(e.buffer,s))return g(e,t,r);if(void 0!==a&&(Y(e,a)||e&&Y(e.buffer,a)))return g(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const i=e.valueOf&&e.valueOf();if(null!=i&&i!==e)return l.from(i,t,r);const o=function(e){if(l.isBuffer(e)){const t=0|m(e.length),r=c(t);return 0===r.length||e.copy(r,0,0,t),r}if(void 0!==e.length)return"number"!=typeof e.length||X(e.length)?c(0):h(e);if("Buffer"===e.type&&Array.isArray(e.data))return h(e.data)}(e);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return l.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function u(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function p(e){return u(e),c(e<0?0:0|m(e))}function h(e){const t=e.length<0?0:0|m(e.length),r=c(t);for(let i=0;i<t;i+=1)r[i]=255&e[i];return r}function g(e,t,r){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(r||0))throw new RangeError('"length" is outside of buffer bounds');let i;return i=void 0===t&&void 0===r?new n(e):void 0===r?new n(e,t):new n(e,t,r),Object.setPrototypeOf(i,l.prototype),i}function m(e){if(e>=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function f(e,t){if(l.isBuffer(e))return e.length;if(s.isView(e)||Y(e,s))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const r=e.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===r)return 0;let o=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return V(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return G(e).length;default:if(o)return i?-1:V(e).length;t=(""+t).toLowerCase(),o=!0}}function y(e,t,r){let i=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return _(this,t,r);case"utf8":case"utf-8":return C(this,t,r);case"ascii":return R(this,t,r);case"latin1":case"binary":return N(this,t,r);case"base64":return A(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return P(this,t,r);default:if(i)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),i=!0}}function b(e,t,r){const i=e[t];e[t]=e[r],e[r]=i}function w(e,t,r,i,o){if(0===e.length)return-1;if("string"==typeof r?(i=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),X(r=+r)&&(r=o?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(o)return-1;r=e.length-1}else if(r<0){if(!o)return-1;r=0}if("string"==typeof t&&(t=l.from(t,i)),l.isBuffer(t))return 0===t.length?-1:I(e,t,r,i,o);if("number"==typeof t)return t&=255,"function"==typeof n.prototype.indexOf?o?n.prototype.indexOf.call(e,t,r):n.prototype.lastIndexOf.call(e,t,r):I(e,[t],r,i,o);throw new TypeError("val must be string, number or Buffer")}function I(e,t,r,i,o){let n,s=1,a=e.length,c=t.length;if(void 0!==i&&("ucs2"===(i=String(i).toLowerCase())||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){if(e.length<2||t.length<2)return-1;s=2,a/=2,c/=2,r/=2}function l(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(o){let i=-1;for(n=r;n<a;n++)if(l(e,n)===l(t,-1===i?0:n-i)){if(-1===i&&(i=n),n-i+1===c)return i*s}else-1!==i&&(n-=n-i),i=-1}else for(r+c>a&&(r=a-c),n=r;n>=0;n--){let r=!0;for(let i=0;i<c;i++)if(l(e,n+i)!==l(t,i)){r=!1;break}if(r)return n}return-1}function T(e,t,r,i){r=Number(r)||0;const o=e.length-r;i?(i=Number(i))>o&&(i=o):i=o;const n=t.length;let s;for(i>n/2&&(i=n/2),s=0;s<i;++s){const i=parseInt(t.substr(2*s,2),16);if(X(i))return s;e[r+s]=i}return s}function S(e,t,r,i){return J(V(t,e.length-r),e,r,i)}function k(e,t,r,i){return J(function(e){const t=[];for(let r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}(t),e,r,i)}function E(e,t,r,i){return J(G(t),e,r,i)}function v(e,t,r,i){return J(function(e,t){let r,i,o;const n=[];for(let s=0;s<e.length&&!((t-=2)<0);++s)r=e.charCodeAt(s),i=r>>8,o=r%256,n.push(o),n.push(i);return n}(t,e.length-r),e,r,i)}function A(e,r,i){return 0===r&&i===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(r,i))}function C(e,t,r){r=Math.min(e.length,r);const i=[];let o=t;for(;o<r;){const t=e[o];let n=null,s=t>239?4:t>223?3:t>191?2:1;if(o+s<=r){let r,i,a,c;switch(s){case 1:t<128&&(n=t);break;case 2:r=e[o+1],128==(192&r)&&(c=(31&t)<<6|63&r,c>127&&(n=c));break;case 3:r=e[o+1],i=e[o+2],128==(192&r)&&128==(192&i)&&(c=(15&t)<<12|(63&r)<<6|63&i,c>2047&&(c<55296||c>57343)&&(n=c));break;case 4:r=e[o+1],i=e[o+2],a=e[o+3],128==(192&r)&&128==(192&i)&&128==(192&a)&&(c=(15&t)<<18|(63&r)<<12|(63&i)<<6|63&a,c>65535&&c<1114112&&(n=c))}}null===n?(n=65533,s=1):n>65535&&(n-=65536,i.push(n>>>10&1023|55296),n=56320|1023&n),i.push(n),o+=s}return function(e){const t=e.length;if(t<=x)return String.fromCharCode.apply(String,e);let r="",i=0;for(;i<t;)r+=String.fromCharCode.apply(String,e.slice(i,i+=x));return r}(i)}l.TYPED_ARRAY_SUPPORT=function(){try{const e=new n(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,n.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),l.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(l.prototype,"parent",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.buffer}}),Object.defineProperty(l.prototype,"offset",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.byteOffset}}),l.poolSize=8192,l.from=function(e,t,r){return d(e,t,r)},Object.setPrototypeOf(l.prototype,n.prototype),Object.setPrototypeOf(l,n),l.alloc=function(e,t,r){return function(e,t,r){return u(e),e<=0?c(e):void 0!==t?"string"==typeof r?c(e).fill(t,r):c(e).fill(t):c(e)}(e,t,r)},l.allocUnsafe=function(e){return p(e)},l.allocUnsafeSlow=function(e){return p(e)},l.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==l.prototype},l.compare=function(e,t){if(Y(e,n)&&(e=l.from(e,e.offset,e.byteLength)),Y(t,n)&&(t=l.from(t,t.offset,t.byteLength)),!l.isBuffer(e)||!l.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let r=e.length,i=t.length;for(let o=0,n=Math.min(r,i);o<n;++o)if(e[o]!==t[o]){r=e[o],i=t[o];break}return r<i?-1:i<r?1:0},l.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},l.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return l.alloc(0);let r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;const i=l.allocUnsafe(t);let o=0;for(r=0;r<e.length;++r){let t=e[r];if(Y(t,n))o+t.length>i.length?(l.isBuffer(t)||(t=l.from(t)),t.copy(i,o)):n.prototype.set.call(i,t,o);else{if(!l.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(i,o)}o+=t.length}return i},l.byteLength=f,l.prototype._isBuffer=!0,l.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)b(this,t,t+1);return this},l.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)b(this,t,t+3),b(this,t+1,t+2);return this},l.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)b(this,t,t+7),b(this,t+1,t+6),b(this,t+2,t+5),b(this,t+3,t+4);return this},l.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?C(this,0,e):y.apply(this,arguments)},l.prototype.toLocaleString=l.prototype.toString,l.prototype.equals=function(e){if(!l.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===l.compare(this,e)},l.prototype.inspect=function(){let t="";const r=e.INSPECT_MAX_BYTES;return t=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(t+=" ... "),"<Buffer "+t+">"},i&&(l.prototype[i]=l.prototype.inspect),l.prototype.compare=function(e,t,r,i,o){if(Y(e,n)&&(e=l.from(e,e.offset,e.byteLength)),!l.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===i&&(i=0),void 0===o&&(o=this.length),t<0||r>e.length||i<0||o>this.length)throw new RangeError("out of range index");if(i>=o&&t>=r)return 0;if(i>=o)return-1;if(t>=r)return 1;if(this===e)return 0;let s=(o>>>=0)-(i>>>=0),a=(r>>>=0)-(t>>>=0);const c=Math.min(s,a),d=this.slice(i,o),u=e.slice(t,r);for(let n=0;n<c;++n)if(d[n]!==u[n]){s=d[n],a=u[n];break}return s<a?-1:a<s?1:0},l.prototype.includes=function(e,t,r){return-1!==this.indexOf(e,t,r)},l.prototype.indexOf=function(e,t,r){return w(this,e,t,r,!0)},l.prototype.lastIndexOf=function(e,t,r){return w(this,e,t,r,!1)},l.prototype.write=function(e,t,r,i){if(void 0===t)i="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)i=t,r=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(r)?(r>>>=0,void 0===i&&(i="utf8")):(i=r,r=void 0)}const o=this.length-t;if((void 0===r||r>o)&&(r=o),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");let n=!1;for(;;)switch(i){case"hex":return T(this,e,t,r);case"utf8":case"utf-8":return S(this,e,t,r);case"ascii":case"latin1":case"binary":return k(this,e,t,r);case"base64":return E(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return v(this,e,t,r);default:if(n)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),n=!0}},l.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const x=4096;function R(e,t,r){let i="";r=Math.min(e.length,r);for(let o=t;o<r;++o)i+=String.fromCharCode(127&e[o]);return i}function N(e,t,r){let i="";r=Math.min(e.length,r);for(let o=t;o<r;++o)i+=String.fromCharCode(e[o]);return i}function _(e,t,r){const i=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>i)&&(r=i);let o="";for(let n=t;n<r;++n)o+=Z[e[n]];return o}function P(e,t,r){const i=e.slice(t,r);let o="";for(let n=0;n<i.length-1;n+=2)o+=String.fromCharCode(i[n]+256*i[n+1]);return o}function F(e,t,r){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>r)throw new RangeError("Trying to access beyond buffer length")}function z(e,t,r,i,o,n){if(!l.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||t<n)throw new RangeError('"value" argument is out of bounds');if(r+i>e.length)throw new RangeError("Index out of range")}function O(e,t,r,i,o){H(t,i,o,e,r,7);let n=Number(t&BigInt(4294967295));e[r++]=n,n>>=8,e[r++]=n,n>>=8,e[r++]=n,n>>=8,e[r++]=n;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=s,s>>=8,e[r++]=s,s>>=8,e[r++]=s,s>>=8,e[r++]=s,r}function D(e,t,r,i,o){H(t,i,o,e,r,7);let n=Number(t&BigInt(4294967295));e[r+7]=n,n>>=8,e[r+6]=n,n>>=8,e[r+5]=n,n>>=8,e[r+4]=n;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=s,s>>=8,e[r+2]=s,s>>=8,e[r+1]=s,s>>=8,e[r]=s,r+8}function M(e,t,r,i,o,n){if(r+i>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function B(e,t,i,o,n){return t=+t,i>>>=0,n||M(e,0,i,4),r.write(e,t,i,o,23,4),i+4}function K(e,t,i,o,n){return t=+t,i>>>=0,n||M(e,0,i,8),r.write(e,t,i,o,52,8),i+8}l.prototype.slice=function(e,t){const r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t<e&&(t=e);const i=this.subarray(e,t);return Object.setPrototypeOf(i,l.prototype),i},l.prototype.readUintLE=l.prototype.readUIntLE=function(e,t,r){e>>>=0,t>>>=0,r||F(e,t,this.length);let i=this[e],o=1,n=0;for(;++n<t&&(o*=256);)i+=this[e+n]*o;return i},l.prototype.readUintBE=l.prototype.readUIntBE=function(e,t,r){e>>>=0,t>>>=0,r||F(e,t,this.length);let i=this[e+--t],o=1;for(;t>0&&(o*=256);)i+=this[e+--t]*o;return i},l.prototype.readUint8=l.prototype.readUInt8=function(e,t){return e>>>=0,t||F(e,1,this.length),this[e]},l.prototype.readUint16LE=l.prototype.readUInt16LE=function(e,t){return e>>>=0,t||F(e,2,this.length),this[e]|this[e+1]<<8},l.prototype.readUint16BE=l.prototype.readUInt16BE=function(e,t){return e>>>=0,t||F(e,2,this.length),this[e]<<8|this[e+1]},l.prototype.readUint32LE=l.prototype.readUInt32LE=function(e,t){return e>>>=0,t||F(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},l.prototype.readUint32BE=l.prototype.readUInt32BE=function(e,t){return e>>>=0,t||F(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},l.prototype.readBigUInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||j(e,this.length-8);const i=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,o=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(i)+(BigInt(o)<<BigInt(32))}),l.prototype.readBigUInt64BE=Q(function(e){q(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||j(e,this.length-8);const i=t*2**24+65536*this[++e]+256*this[++e]+this[++e],o=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(i)<<BigInt(32))+BigInt(o)}),l.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||F(e,t,this.length);let i=this[e],o=1,n=0;for(;++n<t&&(o*=256);)i+=this[e+n]*o;return o*=128,i>=o&&(i-=Math.pow(2,8*t)),i},l.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||F(e,t,this.length);let i=t,o=1,n=this[e+--i];for(;i>0&&(o*=256);)n+=this[e+--i]*o;return o*=128,n>=o&&(n-=Math.pow(2,8*t)),n},l.prototype.readInt8=function(e,t){return e>>>=0,t||F(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},l.prototype.readInt16LE=function(e,t){e>>>=0,t||F(e,2,this.length);const r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},l.prototype.readInt16BE=function(e,t){e>>>=0,t||F(e,2,this.length);const r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},l.prototype.readInt32LE=function(e,t){return e>>>=0,t||F(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},l.prototype.readInt32BE=function(e,t){return e>>>=0,t||F(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},l.prototype.readBigInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||j(e,this.length-8);const i=this[e+4]+256*this[e+5]+65536*this[e+6]+(r<<24);return(BigInt(i)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)}),l.prototype.readBigInt64BE=Q(function(e){q(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||j(e,this.length-8);const i=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(i)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+r)}),l.prototype.readFloatLE=function(e,t){return e>>>=0,t||F(e,4,this.length),r.read(this,e,!0,23,4)},l.prototype.readFloatBE=function(e,t){return e>>>=0,t||F(e,4,this.length),r.read(this,e,!1,23,4)},l.prototype.readDoubleLE=function(e,t){return e>>>=0,t||F(e,8,this.length),r.read(this,e,!0,52,8)},l.prototype.readDoubleBE=function(e,t){return e>>>=0,t||F(e,8,this.length),r.read(this,e,!1,52,8)},l.prototype.writeUintLE=l.prototype.writeUIntLE=function(e,t,r,i){if(e=+e,t>>>=0,r>>>=0,!i){z(this,e,t,r,Math.pow(2,8*r)-1,0)}let o=1,n=0;for(this[t]=255&e;++n<r&&(o*=256);)this[t+n]=e/o&255;return t+r},l.prototype.writeUintBE=l.prototype.writeUIntBE=function(e,t,r,i){if(e=+e,t>>>=0,r>>>=0,!i){z(this,e,t,r,Math.pow(2,8*r)-1,0)}let o=r-1,n=1;for(this[t+o]=255&e;--o>=0&&(n*=256);)this[t+o]=e/n&255;return t+r},l.prototype.writeUint8=l.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||z(this,e,t,1,255,0),this[t]=255&e,t+1},l.prototype.writeUint16LE=l.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||z(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},l.prototype.writeUint16BE=l.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||z(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},l.prototype.writeUint32LE=l.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||z(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},l.prototype.writeUint32BE=l.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||z(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},l.prototype.writeBigUInt64LE=Q(function(e,t=0){return O(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),l.prototype.writeBigUInt64BE=Q(function(e,t=0){return D(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),l.prototype.writeIntLE=function(e,t,r,i){if(e=+e,t>>>=0,!i){const i=Math.pow(2,8*r-1);z(this,e,t,r,i-1,-i)}let o=0,n=1,s=0;for(this[t]=255&e;++o<r&&(n*=256);)e<0&&0===s&&0!==this[t+o-1]&&(s=1),this[t+o]=(e/n|0)-s&255;return t+r},l.prototype.writeIntBE=function(e,t,r,i){if(e=+e,t>>>=0,!i){const i=Math.pow(2,8*r-1);z(this,e,t,r,i-1,-i)}let o=r-1,n=1,s=0;for(this[t+o]=255&e;--o>=0&&(n*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/n|0)-s&255;return t+r},l.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||z(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},l.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||z(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},l.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||z(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},l.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||z(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},l.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||z(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},l.prototype.writeBigInt64LE=Q(function(e,t=0){return O(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),l.prototype.writeBigInt64BE=Q(function(e,t=0){return D(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),l.prototype.writeFloatLE=function(e,t,r){return B(this,e,t,!0,r)},l.prototype.writeFloatBE=function(e,t,r){return B(this,e,t,!1,r)},l.prototype.writeDoubleLE=function(e,t,r){return K(this,e,t,!0,r)},l.prototype.writeDoubleBE=function(e,t,r){return K(this,e,t,!1,r)},l.prototype.copy=function(e,t,r,i){if(!l.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),i||0===i||(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i<r&&(i=r),i===r)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t<i-r&&(i=e.length-t+r);const o=i-r;return this===e&&"function"==typeof n.prototype.copyWithin?this.copyWithin(t,r,i):n.prototype.set.call(e,this.subarray(r,i),t),o},l.prototype.fill=function(e,t,r,i){if("string"==typeof e){if("string"==typeof t?(i=t,t=0,r=this.length):"string"==typeof r&&(i=r,r=this.length),void 0!==i&&"string"!=typeof i)throw new TypeError("encoding must be a string");if("string"==typeof i&&!l.isEncoding(i))throw new TypeError("Unknown encoding: "+i);if(1===e.length){const t=e.charCodeAt(0);("utf8"===i&&t<128||"latin1"===i)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<r)throw new RangeError("Out of range index");if(r<=t)return this;let o;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o<r;++o)this[o]=e;else{const n=l.isBuffer(e)?e:l.from(e,i),s=n.length;if(0===s)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(o=0;o<r-t;++o)this[o+t]=n[o%s]}return this};const U={};function L(e,t,r){U[e]=class extends r{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function $(e){let t="",r=e.length;const i="-"===e[0]?1:0;for(;r>=i+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function H(e,t,r,i,o,n){if(e>r||e<t){const r="bigint"==typeof t?"n":"";let i;throw i=0===t||t===BigInt(0)?`>= 0${r} and < 2${r} ** ${8*(n+1)}${r}`:`>= -(2${r} ** ${8*(n+1)-1}${r}) and < 2 ** ${8*(n+1)-1}${r}`,new U.ERR_OUT_OF_RANGE("value",i,e)}!function(e,t,r){q(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||j(t,e.length-(r+1))}(i,o,n)}function q(e,t){if("number"!=typeof e)throw new U.ERR_INVALID_ARG_TYPE(t,"number",e)}function j(e,t,r){if(Math.floor(e)!==e)throw q(e,r),new U.ERR_OUT_OF_RANGE("offset","an integer",e);if(t<0)throw new U.ERR_BUFFER_OUT_OF_BOUNDS;throw new U.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${t}`,e)}L("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),L("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),L("ERR_OUT_OF_RANGE",function(e,t,r){let i=`The value of "${e}" is out of range.`,o=r;return Number.isInteger(r)&&Math.abs(r)>2**32?o=$(String(r)):"bigint"==typeof r&&(o=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(o=$(o)),o+="n"),i+=` It must be ${t}. Received ${o}`,i},RangeError);const W=/[^+/0-9A-Za-z-_]/g;function V(e,t){let r;t=t||1/0;const i=e.length;let o=null;const n=[];for(let s=0;s<i;++s){if(r=e.charCodeAt(s),r>55295&&r<57344){if(!o){if(r>56319){(t-=3)>-1&&n.push(239,191,189);continue}if(s+1===i){(t-=3)>-1&&n.push(239,191,189);continue}o=r;continue}if(r<56320){(t-=3)>-1&&n.push(239,191,189),o=r;continue}r=65536+(o-55296<<10|r-56320)}else o&&(t-=3)>-1&&n.push(239,191,189);if(o=null,r<128){if((t-=1)<0)break;n.push(r)}else if(r<2048){if((t-=2)<0)break;n.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;n.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;n.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return n}function G(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(W,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function J(e,t,r,i){let o;for(o=0;o<i&&!(o+r>=t.length||o>=e.length);++o)t[o+r]=e[o];return o}function Y(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function X(e){return e!=e}const Z=function(){const e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){const i=16*r;for(let o=0;o<16;++o)t[i+o]=e[r]+e[o]}return t}();function Q(e){return"undefined"==typeof BigInt?ee:e}function ee(){throw new Error("BigInt not supported")}}(se);const ye=se.Buffer,be=se.Buffer,we=globalThis||self;function Ie(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Te,Se,ke={exports:{}},Ee=ke.exports={};function ve(){throw new Error("setTimeout has not been defined")}function Ae(){throw new Error("clearTimeout has not been defined")}function Ce(e){if(Te===setTimeout)return setTimeout(e,0);if((Te===ve||!Te)&&setTimeout)return Te=setTimeout,setTimeout(e,0);try{return Te(e,0)}catch(t){try{return Te.call(null,e,0)}catch(r){return Te.call(this,e,0)}}}!function(){try{Te="function"==typeof setTimeout?setTimeout:ve}catch(e){Te=ve}try{Se="function"==typeof clearTimeout?clearTimeout:Ae}catch(e){Se=Ae}}();var xe,Re=[],Ne=!1,_e=-1;function Pe(){Ne&&xe&&(Ne=!1,xe.length?Re=xe.concat(Re):_e=-1,Re.length&&Fe())}function Fe(){if(!Ne){var e=Ce(Pe);Ne=!0;for(var t=Re.length;t;){for(xe=Re,Re=[];++_e<t;)xe&&xe[_e].run();_e=-1,t=Re.length}xe=null,Ne=!1,function(e){if(Se===clearTimeout)return clearTimeout(e);if((Se===Ae||!Se)&&clearTimeout)return Se=clearTimeout,clearTimeout(e);try{return Se(e)}catch(t){try{return Se.call(null,e)}catch(r){return Se.call(this,e)}}}(e)}}function ze(e,t){this.fun=e,this.array=t}function Oe(){}Ee.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];Re.push(new ze(e,t)),1!==Re.length||Ne||Ce(Fe)},ze.prototype.run=function(){this.fun.apply(null,this.array)},Ee.title="browser",Ee.browser=!0,Ee.env={},Ee.argv=[],Ee.version="",Ee.versions={},Ee.on=Oe,Ee.addListener=Oe,Ee.once=Oe,Ee.off=Oe,Ee.removeListener=Oe,Ee.removeAllListeners=Oe,Ee.emit=Oe,Ee.prependListener=Oe,Ee.prependOnceListener=Oe,Ee.listeners=function(e){return[]},Ee.binding=function(e){throw new Error("process.binding is not supported")},Ee.cwd=function(){return"/"},Ee.chdir=function(e){throw new Error("process.chdir is not supported")},Ee.umask=function(){return 0};const De=Ie(ke.exports);function Me(e,t){return function(){return e.apply(t,arguments)}}const{toString:Be}=Object.prototype,{getPrototypeOf:Ke}=Object,{iterator:Ue,toStringTag:Le}=Symbol,$e=(e=>t=>{const r=Be.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),He=e=>(e=e.toLowerCase(),t=>$e(t)===e),qe=e=>t=>typeof t===e,{isArray:je}=Array,We=qe("undefined");function Ve(e){return null!==e&&!We(e)&&null!==e.constructor&&!We(e.constructor)&&Ye(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const Ge=He("ArrayBuffer");const Je=qe("string"),Ye=qe("function"),Xe=qe("number"),Ze=e=>null!==e&&"object"==typeof e,Qe=e=>{if("object"!==$e(e))return!1;const t=Ke(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Le in e||Ue in e)},et=He("Date"),tt=He("File"),rt=He("Blob"),it=He("FileList"),ot=He("URLSearchParams"),[nt,st,at,ct]=["ReadableStream","Request","Response","Headers"].map(He);function lt(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let i,o;if("object"!=typeof e&&(e=[e]),je(e))for(i=0,o=e.length;i<o;i++)t.call(null,e[i],i,e);else{if(Ve(e))return;const o=r?Object.getOwnPropertyNames(e):Object.keys(e),n=o.length;let s;for(i=0;i<n;i++)s=o[i],t.call(null,e[s],s,e)}}function dt(e,t){if(Ve(e))return null;t=t.toLowerCase();const r=Object.keys(e);let i,o=r.length;for(;o-- >0;)if(i=r[o],t===i.toLowerCase())return i;return null}const ut="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:we,pt=e=>!We(e)&&e!==ut;const ht=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&Ke(Uint8Array)),gt=He("HTMLFormElement"),mt=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),ft=He("RegExp"),yt=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),i={};lt(r,(r,o)=>{let n;!1!==(n=t(r,o,e))&&(i[o]=n||r)}),Object.defineProperties(e,i)};const bt=He("AsyncFunction"),wt=(It="function"==typeof setImmediate,Tt=Ye(ut.postMessage),It?setImmediate:Tt?(St=`axios@${Math.random()}`,kt=[],ut.addEventListener("message",({source:e,data:t})=>{e===ut&&t===St&&kt.length&&kt.shift()()},!1),e=>{kt.push(e),ut.postMessage(St,"*")}):e=>setTimeout(e));var It,Tt,St,kt;const Et="undefined"!=typeof queueMicrotask?queueMicrotask.bind(ut):void 0!==De&&De.nextTick||wt,vt={isArray:je,isArrayBuffer:Ge,isBuffer:Ve,isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||Ye(e.append)&&("formdata"===(t=$e(e))||"object"===t&&Ye(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&Ge(e.buffer),t},isString:Je,isNumber:Xe,isBoolean:e=>!0===e||!1===e,isObject:Ze,isPlainObject:Qe,isEmptyObject:e=>{if(!Ze(e)||Ve(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(t){return!1}},isReadableStream:nt,isRequest:st,isResponse:at,isHeaders:ct,isUndefined:We,isDate:et,isFile:tt,isBlob:rt,isRegExp:ft,isFunction:Ye,isStream:e=>Ze(e)&&Ye(e.pipe),isURLSearchParams:ot,isTypedArray:ht,isFileList:it,forEach:lt,merge:function e(){const{caseless:t}=pt(this)&&this||{},r={},i=(i,o)=>{const n=t&&dt(r,o)||o;Qe(r[n])&&Qe(i)?r[n]=e(r[n],i):Qe(i)?r[n]=e({},i):je(i)?r[n]=i.slice():r[n]=i};for(let o=0,n=arguments.length;o<n;o++)arguments[o]&&lt(arguments[o],i);return r},extend:(e,t,r,{allOwnKeys:i}={})=>(lt(t,(t,i)=>{r&&Ye(t)?e[i]=Me(t,r):e[i]=t},{allOwnKeys:i}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,r,i)=>{e.prototype=Object.create(t.prototype,i),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject:(e,t,r,i)=>{let o,n,s;const a={};if(t=t||{},null==e)return t;do{for(o=Object.getOwnPropertyNames(e),n=o.length;n-- >0;)s=o[n],i&&!i(s,e,t)||a[s]||(t[s]=e[s],a[s]=!0);e=!1!==r&&Ke(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:$e,kindOfTest:He,endsWith:(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const i=e.indexOf(t,r);return-1!==i&&i===r},toArray:e=>{if(!e)return null;if(je(e))return e;let t=e.length;if(!Xe(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{const r=(e&&e[Ue]).call(e);let i;for(;(i=r.next())&&!i.done;){const r=i.value;t.call(e,r[0],r[1])}},matchAll:(e,t)=>{let r;const i=[];for(;null!==(r=e.exec(t));)i.push(r);return i},isHTMLForm:gt,hasOwnProperty:mt,hasOwnProp:mt,reduceDescriptors:yt,freezeMethods:e=>{yt(e,(t,r)=>{if(Ye(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const i=e[r];Ye(i)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")}))})},toObjectSet:(e,t)=>{const r={},i=e=>{e.forEach(e=>{r[e]=!0})};return je(e)?i(e):i(String(e).split(t)),r},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(e,t,r){return t.toUpperCase()+r}),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:dt,global:ut,isContextDefined:pt,isSpecCompliantForm:function(e){return!!(e&&Ye(e.append)&&"FormData"===e[Le]&&e[Ue])},toJSONObject:e=>{const t=new Array(10),r=(e,i)=>{if(Ze(e)){if(t.indexOf(e)>=0)return;if(Ve(e))return e;if(!("toJSON"in e)){t[i]=e;const o=je(e)?[]:{};return lt(e,(e,t)=>{const n=r(e,i+1);!We(n)&&(o[t]=n)}),t[i]=void 0,o}}return e};return r(e,0)},isAsyncFn:bt,isThenable:e=>e&&(Ze(e)||Ye(e))&&Ye(e.then)&&Ye(e.catch),setImmediate:wt,asap:Et,isIterable:e=>null!=e&&Ye(e[Ue])};function At(e,t,r,i,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),i&&(this.request=i),o&&(this.response=o,this.status=o.status?o.status:null)}vt.inherits(At,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:vt.toJSONObject(this.config),code:this.code,status:this.status}}});const Ct=At.prototype,xt={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{xt[e]={value:e}}),Object.defineProperties(At,xt),Object.defineProperty(Ct,"isAxiosError",{value:!0}),At.from=(e,t,r,i,o,n)=>{const s=Object.create(Ct);return vt.toFlatObject(e,s,function(e){return e!==Error.prototype},e=>"isAxiosError"!==e),At.call(s,e.message,t,r,i,o),s.cause=e,s.name=e.name,n&&Object.assign(s,n),s};function Rt(e){return vt.isPlainObject(e)||vt.isArray(e)}function Nt(e){return vt.endsWith(e,"[]")?e.slice(0,-2):e}function _t(e,t,r){return e?e.concat(t).map(function(e,t){return e=Nt(e),!r&&t?"["+e+"]":e}).join(r?".":""):t}const Pt=vt.toFlatObject(vt,{},null,function(e){return/^is[A-Z]/.test(e)});function Ft(e,t,r){if(!vt.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const i=(r=vt.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!vt.isUndefined(t[e])})).metaTokens,o=r.visitor||l,n=r.dots,s=r.indexes,a=(r.Blob||"undefined"!=typeof Blob&&Blob)&&vt.isSpecCompliantForm(t);if(!vt.isFunction(o))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(vt.isDate(e))return e.toISOString();if(vt.isBoolean(e))return e.toString();if(!a&&vt.isBlob(e))throw new At("Blob is not supported. Use a Buffer instead.");return vt.isArrayBuffer(e)||vt.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):ye.from(e):e}function l(e,r,o){let a=e;if(e&&!o&&"object"==typeof e)if(vt.endsWith(r,"{}"))r=i?r:r.slice(0,-2),e=JSON.stringify(e);else if(vt.isArray(e)&&function(e){return vt.isArray(e)&&!e.some(Rt)}(e)||(vt.isFileList(e)||vt.endsWith(r,"[]"))&&(a=vt.toArray(e)))return r=Nt(r),a.forEach(function(e,i){!vt.isUndefined(e)&&null!==e&&t.append(!0===s?_t([r],i,n):null===s?r:r+"[]",c(e))}),!1;return!!Rt(e)||(t.append(_t(o,r,n),c(e)),!1)}const d=[],u=Object.assign(Pt,{defaultVisitor:l,convertValue:c,isVisitable:Rt});if(!vt.isObject(e))throw new TypeError("data must be an object");return function e(r,i){if(!vt.isUndefined(r)){if(-1!==d.indexOf(r))throw Error("Circular reference detected in "+i.join("."));d.push(r),vt.forEach(r,function(r,n){!0===(!(vt.isUndefined(r)||null===r)&&o.call(t,r,vt.isString(n)?n.trim():n,i,u))&&e(r,i?i.concat(n):[n])}),d.pop()}}(e),t}function zt(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function Ot(e,t){this._pairs=[],e&&Ft(e,this,t)}const Dt=Ot.prototype;function Mt(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Bt(e,t,r){if(!t)return e;const i=r&&r.encode||Mt;vt.isFunction(r)&&(r={serialize:r});const o=r&&r.serialize;let n;if(n=o?o(t,r):vt.isURLSearchParams(t)?t.toString():new Ot(t,r).toString(i),n){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+n}return e}Dt.append=function(e,t){this._pairs.push([e,t])},Dt.toString=function(e){const t=e?function(t){return e.call(this,t,zt)}:zt;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};class Kt{constructor(){this.handlers=[]}use(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){vt.forEach(this.handlers,function(t){null!==t&&e(t)})}}const Ut={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Lt={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:Ot,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},$t="undefined"!=typeof window&&"undefined"!=typeof document,Ht="object"==typeof navigator&&navigator||void 0,qt=$t&&(!Ht||["ReactNative","NativeScript","NS"].indexOf(Ht.product)<0),jt="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,Wt=$t&&window.location.href||"http://localhost",Vt={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:$t,hasStandardBrowserEnv:qt,hasStandardBrowserWebWorkerEnv:jt,navigator:Ht,origin:Wt},Symbol.toStringTag,{value:"Module"})),...Lt};function Gt(e){function t(e,r,i,o){let n=e[o++];if("__proto__"===n)return!0;const s=Number.isFinite(+n),a=o>=e.length;if(n=!n&&vt.isArray(i)?i.length:n,a)return vt.hasOwnProp(i,n)?i[n]=[i[n],r]:i[n]=r,!s;i[n]&&vt.isObject(i[n])||(i[n]=[]);return t(e,r,i[n],o)&&vt.isArray(i[n])&&(i[n]=function(e){const t={},r=Object.keys(e);let i;const o=r.length;let n;for(i=0;i<o;i++)n=r[i],t[n]=e[n];return t}(i[n])),!s}if(vt.isFormData(e)&&vt.isFunction(e.entries)){const r={};return vt.forEachEntry(e,(e,i)=>{t(function(e){return vt.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0])}(e),i,r,0)}),r}return null}const Jt={transitional:Ut,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const r=t.getContentType()||"",i=r.indexOf("application/json")>-1,o=vt.isObject(e);o&&vt.isHTMLForm(e)&&(e=new FormData(e));if(vt.isFormData(e))return i?JSON.stringify(Gt(e)):e;if(vt.isArrayBuffer(e)||vt.isBuffer(e)||vt.isStream(e)||vt.isFile(e)||vt.isBlob(e)||vt.isReadableStream(e))return e;if(vt.isArrayBufferView(e))return e.buffer;if(vt.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let n;if(o){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return Ft(e,new Vt.classes.URLSearchParams,{visitor:function(e,t,r,i){return Vt.isNode&&vt.isBuffer(e)?(this.append(t,e.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},...t})}(e,this.formSerializer).toString();if((n=vt.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return Ft(n?{"files[]":e}:e,t&&new t,this.formSerializer)}}return o||i?(t.setContentType("application/json",!1),function(e,t,r){if(vt.isString(e))try{return(t||JSON.parse)(e),vt.trim(e)}catch(i){if("SyntaxError"!==i.name)throw i}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||Jt.transitional,r=t&&t.forcedJSONParsing,i="json"===this.responseType;if(vt.isResponse(e)||vt.isReadableStream(e))return e;if(e&&vt.isString(e)&&(r&&!this.responseType||i)){const r=!(t&&t.silentJSONParsing)&&i;try{return JSON.parse(e)}catch(o){if(r){if("SyntaxError"===o.name)throw At.from(o,At.ERR_BAD_RESPONSE,this,null,this.response);throw o}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Vt.classes.FormData,Blob:Vt.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};vt.forEach(["delete","get","head","post","put","patch"],e=>{Jt.headers[e]={}});const Yt=vt.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),Xt=Symbol("internals");function Zt(e){return e&&String(e).trim().toLowerCase()}function Qt(e){return!1===e||null==e?e:vt.isArray(e)?e.map(Qt):String(e)}function er(e,t,r,i,o){return vt.isFunction(i)?i.call(this,t,r):(o&&(t=r),vt.isString(t)?vt.isString(i)?-1!==t.indexOf(i):vt.isRegExp(i)?i.test(t):void 0:void 0)}let tr=class{constructor(e){e&&this.set(e)}set(e,t,r){const i=this;function o(e,t,r){const o=Zt(t);if(!o)throw new Error("header name must be a non-empty string");const n=vt.findKey(i,o);(!n||void 0===i[n]||!0===r||void 0===r&&!1!==i[n])&&(i[n||t]=Qt(e))}const n=(e,t)=>vt.forEach(e,(e,r)=>o(e,r,t));if(vt.isPlainObject(e)||e instanceof this.constructor)n(e,t);else if(vt.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))n((e=>{const t={};let r,i,o;return e&&e.split("\n").forEach(function(e){o=e.indexOf(":"),r=e.substring(0,o).trim().toLowerCase(),i=e.substring(o+1).trim(),!r||t[r]&&Yt[r]||("set-cookie"===r?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)}),t})(e),t);else if(vt.isObject(e)&&vt.isIterable(e)){let r,i,o={};for(const t of e){if(!vt.isArray(t))throw TypeError("Object iterator must return a key-value pair");o[i=t[0]]=(r=o[i])?vt.isArray(r)?[...r,t[1]]:[r,t[1]]:t[1]}n(o,t)}else null!=e&&o(t,e,r);return this}get(e,t){if(e=Zt(e)){const r=vt.findKey(this,e);if(r){const e=this[r];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let i;for(;i=r.exec(e);)t[i[1]]=i[2];return t}(e);if(vt.isFunction(t))return t.call(this,e,r);if(vt.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=Zt(e)){const r=vt.findKey(this,e);return!(!r||void 0===this[r]||t&&!er(0,this[r],r,t))}return!1}delete(e,t){const r=this;let i=!1;function o(e){if(e=Zt(e)){const o=vt.findKey(r,e);!o||t&&!er(0,r[o],o,t)||(delete r[o],i=!0)}}return vt.isArray(e)?e.forEach(o):o(e),i}clear(e){const t=Object.keys(this);let r=t.length,i=!1;for(;r--;){const o=t[r];e&&!er(0,this[o],o,e,!0)||(delete this[o],i=!0)}return i}normalize(e){const t=this,r={};return vt.forEach(this,(i,o)=>{const n=vt.findKey(r,o);if(n)return t[n]=Qt(i),void delete t[o];const s=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,r)=>t.toUpperCase()+r)}(o):String(o).trim();s!==o&&delete t[o],t[s]=Qt(i),r[s]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return vt.forEach(this,(r,i)=>{null!=r&&!1!==r&&(t[i]=e&&vt.isArray(r)?r.join(", "):r)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const r=new this(e);return t.forEach(e=>r.set(e)),r}static accessor(e){const t=(this[Xt]=this[Xt]={accessors:{}}).accessors,r=this.prototype;function i(e){const i=Zt(e);t[i]||(!function(e,t){const r=vt.toCamelCase(" "+t);["get","set","has"].forEach(i=>{Object.defineProperty(e,i+r,{value:function(e,r,o){return this[i].call(this,t,e,r,o)},configurable:!0})})}(r,e),t[i]=!0)}return vt.isArray(e)?e.forEach(i):i(e),this}};function rr(e,t){const r=this||Jt,i=t||r,o=tr.from(i.headers);let n=i.data;return vt.forEach(e,function(e){n=e.call(r,n,o.normalize(),t?t.status:void 0)}),o.normalize(),n}function ir(e){return!(!e||!e.__CANCEL__)}function or(e,t,r){At.call(this,null==e?"canceled":e,At.ERR_CANCELED,t,r),this.name="CanceledError"}function nr(e,t,r){const i=r.config.validateStatus;r.status&&i&&!i(r.status)?t(new At("Request failed with status code "+r.status,[At.ERR_BAD_REQUEST,At.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}tr.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),vt.reduceDescriptors(tr.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}}),vt.freezeMethods(tr),vt.inherits(or,At,{__CANCEL__:!0});const sr=(e,t,r=3)=>{let i=0;const o=function(e,t){e=e||10;const r=new Array(e),i=new Array(e);let o,n=0,s=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),l=i[s];o||(o=c),r[n]=a,i[n]=c;let d=s,u=0;for(;d!==n;)u+=r[d++],d%=e;if(n=(n+1)%e,n===s&&(s=(s+1)%e),c-o<t)return;const p=l&&c-l;return p?Math.round(1e3*u/p):void 0}}(50,250);return function(e,t){let r,i,o=0,n=1e3/t;const s=(t,n=Date.now())=>{o=n,r=null,i&&(clearTimeout(i),i=null),e(...t)};return[(...e)=>{const t=Date.now(),a=t-o;a>=n?s(e,t):(r=e,i||(i=setTimeout(()=>{i=null,s(r)},n-a)))},()=>r&&s(r)]}(r=>{const n=r.loaded,s=r.lengthComputable?r.total:void 0,a=n-i,c=o(a);i=n;e({loaded:n,total:s,progress:s?n/s:void 0,bytes:a,rate:c||void 0,estimated:c&&s&&n<=s?(s-n)/c:void 0,event:r,lengthComputable:null!=s,[t?"download":"upload"]:!0})},r)},ar=(e,t)=>{const r=null!=e;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},cr=e=>(...t)=>vt.asap(()=>e(...t)),lr=Vt.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,Vt.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(Vt.origin),Vt.navigator&&/(msie|trident)/i.test(Vt.navigator.userAgent)):()=>!0,dr=Vt.hasStandardBrowserEnv?{write(e,t,r,i,o,n){const s=[e+"="+encodeURIComponent(t)];vt.isNumber(r)&&s.push("expires="+new Date(r).toGMTString()),vt.isString(i)&&s.push("path="+i),vt.isString(o)&&s.push("domain="+o),!0===n&&s.push("secure"),document.cookie=s.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function ur(e,t,r){let i=!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t);return e&&(i||0==r)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const pr=e=>e instanceof tr?{...e}:e;function hr(e,t){t=t||{};const r={};function i(e,t,r,i){return vt.isPlainObject(e)&&vt.isPlainObject(t)?vt.merge.call({caseless:i},e,t):vt.isPlainObject(t)?vt.merge({},t):vt.isArray(t)?t.slice():t}function o(e,t,r,o){return vt.isUndefined(t)?vt.isUndefined(e)?void 0:i(void 0,e,0,o):i(e,t,0,o)}function n(e,t){if(!vt.isUndefined(t))return i(void 0,t)}function s(e,t){return vt.isUndefined(t)?vt.isUndefined(e)?void 0:i(void 0,e):i(void 0,t)}function a(r,o,n){return n in t?i(r,o):n in e?i(void 0,r):void 0}const c={url:n,method:n,data:n,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:a,headers:(e,t,r)=>o(pr(e),pr(t),0,!0)};return vt.forEach(Object.keys({...e,...t}),function(i){const n=c[i]||o,s=n(e[i],t[i],i);vt.isUndefined(s)&&n!==a||(r[i]=s)}),r}const gr=e=>{const t=hr({},e);let r,{data:i,withXSRFToken:o,xsrfHeaderName:n,xsrfCookieName:s,headers:a,auth:c}=t;if(t.headers=a=tr.from(a),t.url=Bt(ur(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),vt.isFormData(i))if(Vt.hasStandardBrowserEnv||Vt.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(!1!==(r=a.getContentType())){const[e,...t]=r?r.split(";").map(e=>e.trim()).filter(Boolean):[];a.setContentType([e||"multipart/form-data",...t].join("; "))}if(Vt.hasStandardBrowserEnv&&(o&&vt.isFunction(o)&&(o=o(t)),o||!1!==o&&lr(t.url))){const e=n&&s&&dr.read(s);e&&a.set(n,e)}return t},mr="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise(function(t,r){const i=gr(e);let o=i.data;const n=tr.from(i.headers).normalize();let s,a,c,l,d,{responseType:u,onUploadProgress:p,onDownloadProgress:h}=i;function g(){l&&l(),d&&d(),i.cancelToken&&i.cancelToken.unsubscribe(s),i.signal&&i.signal.removeEventListener("abort",s)}let m=new XMLHttpRequest;function f(){if(!m)return;const i=tr.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders());nr(function(e){t(e),g()},function(e){r(e),g()},{data:u&&"text"!==u&&"json"!==u?m.response:m.responseText,status:m.status,statusText:m.statusText,headers:i,config:e,request:m}),m=null}m.open(i.method.toUpperCase(),i.url,!0),m.timeout=i.timeout,"onloadend"in m?m.onloadend=f:m.onreadystatechange=function(){m&&4===m.readyState&&(0!==m.status||m.responseURL&&0===m.responseURL.indexOf("file:"))&&setTimeout(f)},m.onabort=function(){m&&(r(new At("Request aborted",At.ECONNABORTED,e,m)),m=null)},m.onerror=function(){r(new At("Network Error",At.ERR_NETWORK,e,m)),m=null},m.ontimeout=function(){let t=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const o=i.transitional||Ut;i.timeoutErrorMessage&&(t=i.timeoutErrorMessage),r(new At(t,o.clarifyTimeoutError?At.ETIMEDOUT:At.ECONNABORTED,e,m)),m=null},void 0===o&&n.setContentType(null),"setRequestHeader"in m&&vt.forEach(n.toJSON(),function(e,t){m.setRequestHeader(t,e)}),vt.isUndefined(i.withCredentials)||(m.withCredentials=!!i.withCredentials),u&&"json"!==u&&(m.responseType=i.responseType),h&&([c,d]=sr(h,!0),m.addEventListener("progress",c)),p&&m.upload&&([a,l]=sr(p),m.upload.addEventListener("progress",a),m.upload.addEventListener("loadend",l)),(i.cancelToken||i.signal)&&(s=t=>{m&&(r(!t||t.type?new or(null,e,m):t),m.abort(),m=null)},i.cancelToken&&i.cancelToken.subscribe(s),i.signal&&(i.signal.aborted?s():i.signal.addEventListener("abort",s)));const y=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(i.url);y&&-1===Vt.protocols.indexOf(y)?r(new At("Unsupported protocol "+y+":",At.ERR_BAD_REQUEST,e)):m.send(o||null)})},fr=(e,t)=>{const{length:r}=e=e?e.filter(Boolean):[];if(t||r){let r,i=new AbortController;const o=function(e){if(!r){r=!0,s();const t=e instanceof Error?e:this.reason;i.abort(t instanceof At?t:new or(t instanceof Error?t.message:t))}};let n=t&&setTimeout(()=>{n=null,o(new At(`timeout ${t} of ms exceeded`,At.ETIMEDOUT))},t);const s=()=>{e&&(n&&clearTimeout(n),n=null,e.forEach(e=>{e.unsubscribe?e.unsubscribe(o):e.removeEventListener("abort",o)}),e=null)};e.forEach(e=>e.addEventListener("abort",o));const{signal:a}=i;return a.unsubscribe=()=>vt.asap(s),a}},yr=function*(e,t){let r=e.byteLength;if(r<t)return void(yield e);let i,o=0;for(;o<r;)i=o+t,yield e.slice(o,i),o=i},br=async function*(e){if(e[Symbol.asyncIterator])return void(yield*e);const t=e.getReader();try{for(;;){const{done:e,value:r}=await t.read();if(e)break;yield r}}finally{await t.cancel()}},wr=(e,t,r,i)=>{const o=async function*(e,t){for await(const r of br(e))yield*yr(r,t)}(e,t);let n,s=0,a=e=>{n||(n=!0,i&&i(e))};return new ReadableStream({async pull(e){try{const{done:t,value:i}=await o.next();if(t)return a(),void e.close();let n=i.byteLength;if(r){let e=s+=n;r(e)}e.enqueue(new Uint8Array(i))}catch(t){throw a(t),t}},cancel:e=>(a(e),o.return())},{highWaterMark:2})},Ir="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,Tr=Ir&&"function"==typeof ReadableStream,Sr=Ir&&("function"==typeof TextEncoder?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),kr=(e,...t)=>{try{return!!e(...t)}catch(r){return!1}},Er=Tr&&kr(()=>{let e=!1;const t=new Request(Vt.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),vr=Tr&&kr(()=>vt.isReadableStream(new Response("").body)),Ar={stream:vr&&(e=>e.body)};var Cr;Ir&&(Cr=new Response,["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!Ar[e]&&(Ar[e]=vt.isFunction(Cr[e])?t=>t[e]():(t,r)=>{throw new At(`Response type '${e}' is not supported`,At.ERR_NOT_SUPPORT,r)})}));const xr=async(e,t)=>{const r=vt.toFiniteNumber(e.getContentLength());return null==r?(async e=>{if(null==e)return 0;if(vt.isBlob(e))return e.size;if(vt.isSpecCompliantForm(e)){const t=new Request(Vt.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return vt.isArrayBufferView(e)||vt.isArrayBuffer(e)?e.byteLength:(vt.isURLSearchParams(e)&&(e+=""),vt.isString(e)?(await Sr(e)).byteLength:void 0)})(t):r},Rr={http:null,xhr:mr,fetch:Ir&&(async e=>{let{url:t,method:r,data:i,signal:o,cancelToken:n,timeout:s,onDownloadProgress:a,onUploadProgress:c,responseType:l,headers:d,withCredentials:u="same-origin",fetchOptions:p}=gr(e);l=l?(l+"").toLowerCase():"text";let h,g=fr([o,n&&n.toAbortSignal()],s);const m=g&&g.unsubscribe&&(()=>{g.unsubscribe()});let f;try{if(c&&Er&&"get"!==r&&"head"!==r&&0!==(f=await xr(d,i))){let e,r=new Request(t,{method:"POST",body:i,duplex:"half"});if(vt.isFormData(i)&&(e=r.headers.get("content-type"))&&d.setContentType(e),r.body){const[e,t]=ar(f,sr(cr(c)));i=wr(r.body,65536,e,t)}}vt.isString(u)||(u=u?"include":"omit");const o="credentials"in Request.prototype;h=new Request(t,{...p,signal:g,method:r.toUpperCase(),headers:d.normalize().toJSON(),body:i,duplex:"half",credentials:o?u:void 0});let n=await fetch(h,p);const s=vr&&("stream"===l||"response"===l);if(vr&&(a||s&&m)){const e={};["status","statusText","headers"].forEach(t=>{e[t]=n[t]});const t=vt.toFiniteNumber(n.headers.get("content-length")),[r,i]=a&&ar(t,sr(cr(a),!0))||[];n=new Response(wr(n.body,65536,r,()=>{i&&i(),m&&m()}),e)}l=l||"text";let y=await Ar[vt.findKey(Ar,l)||"text"](n,e);return!s&&m&&m(),await new Promise((t,r)=>{nr(t,r,{data:y,headers:tr.from(n.headers),status:n.status,statusText:n.statusText,config:e,request:h})})}catch(y){if(m&&m(),y&&"TypeError"===y.name&&/Load failed|fetch/i.test(y.message))throw Object.assign(new At("Network Error",At.ERR_NETWORK,e,h),{cause:y.cause||y});throw At.from(y,y&&y.code,e,h)}})};vt.forEach(Rr,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(r){}Object.defineProperty(e,"adapterName",{value:t})}});const Nr=e=>`- ${e}`,_r=e=>vt.isFunction(e)||null===e||!1===e,Pr=e=>{e=vt.isArray(e)?e:[e];const{length:t}=e;let r,i;const o={};for(let n=0;n<t;n++){let t;if(r=e[n],i=r,!_r(r)&&(i=Rr[(t=String(r)).toLowerCase()],void 0===i))throw new At(`Unknown adapter '${t}'`);if(i)break;o[t||"#"+n]=i}if(!i){const e=Object.entries(o).map(([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build"));throw new At("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(Nr).join("\n"):" "+Nr(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return i};function Fr(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new or(null,e)}function zr(e){Fr(e),e.headers=tr.from(e.headers),e.data=rr.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return Pr(e.adapter||Jt.adapter)(e).then(function(t){return Fr(e),t.data=rr.call(e,e.transformResponse,t),t.headers=tr.from(t.headers),t},function(t){return ir(t)||(Fr(e),t&&t.response&&(t.response.data=rr.call(e,e.transformResponse,t.response),t.response.headers=tr.from(t.response.headers))),Promise.reject(t)})}const Or="1.11.0",Dr={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Dr[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const Mr={};Dr.transitional=function(e,t,r){function i(e,t){return"[Axios v"+Or+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,o,n)=>{if(!1===e)throw new At(i(o," has been removed"+(t?" in "+t:"")),At.ERR_DEPRECATED);return t&&!Mr[o]&&(Mr[o]=!0,console.warn(i(o," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,o,n)}},Dr.spelling=function(e){return(t,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};const Br={assertOptions:function(e,t,r){if("object"!=typeof e)throw new At("options must be an object",At.ERR_BAD_OPTION_VALUE);const i=Object.keys(e);let o=i.length;for(;o-- >0;){const n=i[o],s=t[n];if(s){const t=e[n],r=void 0===t||s(t,n,e);if(!0!==r)throw new At("option "+n+" must be "+r,At.ERR_BAD_OPTION_VALUE);continue}if(!0!==r)throw new At("Unknown option "+n,At.ERR_BAD_OPTION)}},validators:Dr},Kr=Br.validators;let Ur=class{constructor(e){this.defaults=e||{},this.interceptors={request:new Kt,response:new Kt}}async request(e,t){try{return await this._request(e,t)}catch(r){if(r instanceof Error){let e={};Error.captureStackTrace?Error.captureStackTrace(e):e=new Error;const t=e.stack?e.stack.replace(/^.+\n/,""):"";try{r.stack?t&&!String(r.stack).endsWith(t.replace(/^.+\n.+\n/,""))&&(r.stack+="\n"+t):r.stack=t}catch(i){}}throw r}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=hr(this.defaults,t);const{transitional:r,paramsSerializer:i,headers:o}=t;void 0!==r&&Br.assertOptions(r,{silentJSONParsing:Kr.transitional(Kr.boolean),forcedJSONParsing:Kr.transitional(Kr.boolean),clarifyTimeoutError:Kr.transitional(Kr.boolean)},!1),null!=i&&(vt.isFunction(i)?t.paramsSerializer={serialize:i}:Br.assertOptions(i,{encode:Kr.function,serialize:Kr.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Br.assertOptions(t,{baseUrl:Kr.spelling("baseURL"),withXsrfToken:Kr.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let n=o&&vt.merge(o.common,o[t.method]);o&&vt.forEach(["delete","get","head","post","put","patch","common"],e=>{delete o[e]}),t.headers=tr.concat(n,o);const s=[];let a=!0;this.interceptors.request.forEach(function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,s.unshift(e.fulfilled,e.rejected))});const c=[];let l;this.interceptors.response.forEach(function(e){c.push(e.fulfilled,e.rejected)});let d,u=0;if(!a){const e=[zr.bind(this),void 0];for(e.unshift(...s),e.push(...c),d=e.length,l=Promise.resolve(t);u<d;)l=l.then(e[u++],e[u++]);return l}d=s.length;let p=t;for(u=0;u<d;){const e=s[u++],t=s[u++];try{p=e(p)}catch(h){t.call(this,h);break}}try{l=zr.call(this,p)}catch(h){return Promise.reject(h)}for(u=0,d=c.length;u<d;)l=l.then(c[u++],c[u++]);return l}getUri(e){return Bt(ur((e=hr(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};vt.forEach(["delete","get","head","options"],function(e){Ur.prototype[e]=function(t,r){return this.request(hr(r||{},{method:e,url:t,data:(r||{}).data}))}}),vt.forEach(["post","put","patch"],function(e){function t(t){return function(r,i,o){return this.request(hr(o||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:i}))}}Ur.prototype[e]=t(),Ur.prototype[e+"Form"]=t(!0)});const Lr={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Lr).forEach(([e,t])=>{Lr[t]=e});const $r=function e(t){const r=new Ur(t),i=Me(Ur.prototype.request,r);return vt.extend(i,Ur.prototype,r,{allOwnKeys:!0}),vt.extend(i,r,null,{allOwnKeys:!0}),i.create=function(r){return e(hr(t,r))},i}(Jt);$r.Axios=Ur,$r.CanceledError=or,$r.CancelToken=class e{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(e){t=e});const r=this;this.promise.then(e=>{if(!r._listeners)return;let t=r._listeners.length;for(;t-- >0;)r._listeners[t](e);r._listeners=null}),this.promise.then=e=>{let t;const i=new Promise(e=>{r.subscribe(e),t=e}).then(e);return i.cancel=function(){r.unsubscribe(t)},i},e(function(e,i,o){r.reason||(r.reason=new or(e,i,o),t(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let t;return{token:new e(function(e){t=e}),cancel:t}}},$r.isCancel=ir,$r.VERSION=Or,$r.toFormData=Ft,$r.AxiosError=At,$r.Cancel=$r.CanceledError,$r.all=function(e){return Promise.all(e)},$r.spread=function(e){return function(t){return e.apply(null,t)}},$r.isAxiosError=function(e){return vt.isObject(e)&&!0===e.isAxiosError},$r.mergeConfig=hr,$r.AxiosHeaders=tr,$r.formToJSON=e=>Gt(vt.isHTMLForm(e)?new FormData(e):e),$r.getAdapter=Pr,$r.HttpStatusCode=Lr,$r.default=$r;const{Axios:Hr,AxiosError:qr,CanceledError:jr,isCancel:Wr,CancelToken:Vr,VERSION:Gr,all:Jr,Cancel:Yr,isAxiosError:Xr,spread:Zr,toFormData:Qr,AxiosHeaders:ei,HttpStatusCode:ti,formToJSON:ri,getAdapter:ii,mergeConfig:oi}=$r,ni=class e{constructor(){ne(this,"isProduction"),this.isProduction="production"===De.env.NODE_ENV}static getInstance(){return e.instance||(e.instance=new e),e.instance}debug(e,...t){this.isProduction||console.debug(e,...t)}info(e,...t){this.isProduction||console.info(e,...t)}warn(e,...t){console.warn(e,...t)}error(e,...t){console.error(e,...t)}};ne(ni,"instance");let si=ni;class ai extends Error{constructor(e){super(e),this.name="ValidationError"}}class ci{constructor(e){if(ne(this,"accountId"),ne(this,"privateKey"),ne(this,"baseUrl"),ne(this,"network"),this.accountId=e.accountId,"string"==typeof e.privateKey){const t=s.detectKeyTypeFromString(e.privateKey);this.privateKey=t.privateKey}else this.privateKey=e.privateKey;this.network=e.network||"mainnet",this.baseUrl=e.baseUrl||"https://kiloscribe.com"}async authenticate(){var e,t,r;const i=await $r.get(`${this.baseUrl}/api/auth/request-signature`,{headers:{"x-session":this.accountId}});if(!(null==(e=i.data)?void 0:e.message))throw new Error("Failed to get signature message");const o=i.data.message,n=await this.signMessage(o),s=await $r.post(`${this.baseUrl}/api/auth/authenticate`,{authData:{id:this.accountId,signature:n,data:o,network:this.network},include:"apiKey"});if(!(null==(r=null==(t=s.data)?void 0:t.user)?void 0:r.sessionToken))throw new Error("Authentication failed");return{apiKey:s.data.apiKey}}async signMessage(e){const t=(new TextEncoder).encode(e),r=await this.privateKey.sign(t);return be.from(r).toString("hex")}}class li{constructor(e){ne(this,"accountId"),ne(this,"signer"),ne(this,"baseUrl"),ne(this,"network"),ne(this,"logger"),this.accountId=e.accountId,this.signer=e.signer,this.network=e.network||"mainnet",this.baseUrl=e.baseUrl||"https://kiloscribe.com",this.logger=e.logger}async authenticate(){var e,t,r;const i=await $r.get(`${this.baseUrl}/api/auth/request-signature`,{headers:{"x-session":this.accountId}});if(!(null==(e=i.data)?void 0:e.message))throw new Error("Failed to get signature message");const o=i.data.message,n=await this.signMessage(JSON.stringify(o)),s=await $r.post(`${this.baseUrl}/api/auth/authenticate`,{authData:{id:this.accountId,signature:n,data:o,network:this.network},include:"apiKey"});if(!(null==(r=null==(t=s.data)?void 0:t.user)?void 0:r.sessionToken))throw new Error("Authentication failed");return{apiKey:s.data.apiKey}}async signMessage(e){try{const t=(new TextEncoder).encode(e);this.logger.debug("signing message");const r=await this.signer.sign([t],{encoding:"utf-8"});return be.from(null==r?void 0:r[0].signature).toString("hex")}catch(t){throw this.logger.error("Failed to sign message",t),new Error("Failed to sign message")}}}function di(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function ui(e){return new DataView(e.buffer,e.byteOffset)}const pi={len:1,get:(e,t)=>ui(e).getUint8(t),put:(e,t,r)=>(ui(e).setUint8(t,r),t+1)},hi={len:2,get:(e,t)=>ui(e).getUint16(t,!0),put:(e,t,r)=>(ui(e).setUint16(t,r,!0),t+2)},gi={len:2,get:(e,t)=>ui(e).getUint16(t),put:(e,t,r)=>(ui(e).setUint16(t,r),t+2)},mi={len:4,get:(e,t)=>ui(e).getUint32(t,!0),put:(e,t,r)=>(ui(e).setUint32(t,r,!0),t+4)},fi={len:4,get:(e,t)=>ui(e).getUint32(t),put:(e,t,r)=>(ui(e).setUint32(t,r),t+4)},yi={len:4,get:(e,t)=>ui(e).getInt32(t),put:(e,t,r)=>(ui(e).setInt32(t,r),t+4)},bi={len:8,get:(e,t)=>ui(e).getBigUint64(t,!0),put:(e,t,r)=>(ui(e).setBigUint64(t,r,!0),t+8)};class wi{constructor(e,t){if(this.len=e,t&&"windows-1252"===t.toLowerCase())this.decoder=wi.decodeWindows1252;else{const e=new TextDecoder(t);this.decoder=t=>e.decode(t)}}get(e,t=0){const r=e.subarray(t,t+this.len);return this.decoder(r)}static decodeWindows1252(e){let t="";for(let r=0;r<e.length;r++){const i=e[r];t+=i<128||i>=160?String.fromCharCode(i):wi.win1252Map[i-128]}return t}}wi.win1252Map="€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ";class Ii extends Error{constructor(){super("End-Of-Stream"),this.name="EndOfStreamError"}}class Ti extends Error{constructor(e="The operation was aborted"){super(e),this.name="AbortError"}}class Si{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(e,t=!1){const r=await this.read(e,t);return this.peekQueue.push(e.subarray(0,r)),r}async read(e,t=!1){if(0===e.length)return 0;let r=this.readFromPeekBuffer(e);if(this.endOfStream||(r+=await this.readRemainderFromStream(e.subarray(r),t)),0===r&&!t)throw new Ii;return r}readFromPeekBuffer(e){let t=e.length,r=0;for(;this.peekQueue.length>0&&t>0;){const i=this.peekQueue.pop();if(!i)throw new Error("peekData should be defined");const o=Math.min(i.length,t);e.set(i.subarray(0,o),r),r+=o,t-=o,o<i.length&&this.peekQueue.push(i.subarray(o))}return r}async readRemainderFromStream(e,t){let r=0;for(;r<e.length&&!this.endOfStream;){if(this.interrupted)throw new Ti;const i=await this.readFromStream(e.subarray(r),t);if(0===i)break;r+=i}if(!t&&r<e.length)throw new Ii;return r}}class ki extends Si{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}}class Ei extends ki{async readFromStream(e,t){if(0===e.length)return 0;const r=await this.reader.read(new Uint8Array(e.length),{min:t?void 0:e.length});return r.done&&(this.endOfStream=r.done),r.value?(e.set(r.value),r.value.length):0}}class vi extends Si{constructor(e){super(),this.reader=e,this.buffer=null}writeChunk(e,t){const r=Math.min(t.length,e.length);return e.set(t.subarray(0,r)),r<t.length?this.buffer=t.subarray(r):this.buffer=null,r}async readFromStream(e,t){if(0===e.length)return 0;let r=0;for(this.buffer&&(r+=this.writeChunk(e,this.buffer));r<e.length&&!this.endOfStream;){const t=await this.reader.read();if(t.done){this.endOfStream=!0;break}t.value&&(r+=this.writeChunk(e.subarray(r),t.value))}if(!t&&0===r&&this.endOfStream)throw new Ii;return r}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}}class Ai{constructor(e){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=null==e?void 0:e.onClose,(null==e?void 0:e.abortSignal)&&e.abortSignal.addEventListener("abort",()=>{this.abort()})}async readToken(e,t=this.position){const r=new Uint8Array(e.len);if(await this.readBuffer(r,{position:t})<e.len)throw new Ii;return e.get(r,0)}async peekToken(e,t=this.position){const r=new Uint8Array(e.len);if(await this.peekBuffer(r,{position:t})<e.len)throw new Ii;return e.get(r,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new Ii;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new Ii;return e.get(this.numBuffer,0)}async ignore(e){if(void 0!==this.fileInfo.size){const t=this.fileInfo.size-this.position;if(e>t)return this.position+=t,t}return this.position+=e,e}async close(){var e;await this.abort(),await(null==(e=this.onClose)?void 0:e.call(this))}normalizeOptions(e,t){if(!this.supportsRandomAccess()&&t&&void 0!==t.position&&t.position<this.position)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");return{mayBeLess:!1,offset:0,length:e.length,position:this.position,...t}}abort(){return Promise.resolve()}}class Ci extends Ai{constructor(e,t){super(t),this.streamReader=e,this.fileInfo=(null==t?void 0:t.fileInfo)??{}}async readBuffer(e,t){const r=this.normalizeOptions(e,t),i=r.position-this.position;if(i>0)return await this.ignore(i),this.readBuffer(e,t);if(i<0)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");if(0===r.length)return 0;const o=await this.streamReader.read(e.subarray(0,r.length),r.mayBeLess);if(this.position+=o,(!t||!t.mayBeLess)&&o<r.length)throw new Ii;return o}async peekBuffer(e,t){const r=this.normalizeOptions(e,t);let i=0;if(r.position){const t=r.position-this.position;if(t>0){const o=new Uint8Array(r.length+t);return i=await this.peekBuffer(o,{mayBeLess:r.mayBeLess}),e.set(o.subarray(t)),i-t}if(t<0)throw new Error("Cannot peek from a negative offset in a stream")}if(r.length>0){try{i=await this.streamReader.peek(e.subarray(0,r.length),r.mayBeLess)}catch(o){if((null==t?void 0:t.mayBeLess)&&o instanceof Ii)return 0;throw o}if(!r.mayBeLess&&i<r.length)throw new Ii}return i}async ignore(e){const t=Math.min(256e3,e),r=new Uint8Array(t);let i=0;for(;i<e;){const o=e-i,n=await this.readBuffer(r,{length:Math.min(t,o)});if(n<0)return n;i+=n}return i}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}}class xi extends Ai{constructor(e,t){super(t),this.uint8Array=e,this.fileInfo={...(null==t?void 0:t.fileInfo)??{},size:e.length}}async readBuffer(e,t){(null==t?void 0:t.position)&&(this.position=t.position);const r=await this.peekBuffer(e,t);return this.position+=r,r}async peekBuffer(e,t){const r=this.normalizeOptions(e,t),i=Math.min(this.uint8Array.length-r.position,r.length);if(!r.mayBeLess&&i<r.length)throw new Ii;return e.set(this.uint8Array.subarray(r.position,r.position+i)),i}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}}function Ri(e,t){const r=function(e){try{const t=e.getReader({mode:"byob"});return t instanceof ReadableStreamDefaultReader?new vi(t):new Ei(t)}catch(t){if(t instanceof TypeError)return new vi(e.getReader());throw t}}(e),i=t??{},o=i.onClose;return i.onClose=async()=>{if(await r.close(),o)return o()},new Ci(r,i)}var Ni=Uint8Array,_i=Uint16Array,Pi=Int32Array,Fi=new Ni([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),zi=new Ni([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Oi=new Ni([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Di=function(e,t){for(var r=new _i(31),i=0;i<31;++i)r[i]=t+=1<<e[i-1];var o=new Pi(r[30]);for(i=1;i<30;++i)for(var n=r[i];n<r[i+1];++n)o[n]=n-r[i]<<5|i;return{b:r,r:o}},Mi=Di(Fi,2),Bi=Mi.b,Ki=Mi.r;Bi[28]=258,Ki[258]=28;for(var Ui=Di(zi,0).b,Li=new _i(32768),$i=0;$i<32768;++$i){var Hi=(43690&$i)>>1|(21845&$i)<<1;Hi=(61680&(Hi=(52428&Hi)>>2|(13107&Hi)<<2))>>4|(3855&Hi)<<4,Li[$i]=((65280&Hi)>>8|(255&Hi)<<8)>>1}var qi=function(e,t,r){for(var i=e.length,o=0,n=new _i(t);o<i;++o)e[o]&&++n[e[o]-1];var s,a=new _i(t);for(o=1;o<t;++o)a[o]=a[o-1]+n[o-1]<<1;s=new _i(1<<t);var c=15-t;for(o=0;o<i;++o)if(e[o])for(var l=o<<4|e[o],d=t-e[o],u=a[e[o]-1]++<<d,p=u|(1<<d)-1;u<=p;++u)s[Li[u]>>c]=l;return s},ji=new Ni(288);for($i=0;$i<144;++$i)ji[$i]=8;for($i=144;$i<256;++$i)ji[$i]=9;for($i=256;$i<280;++$i)ji[$i]=7;for($i=280;$i<288;++$i)ji[$i]=8;var Wi=new Ni(32);for($i=0;$i<32;++$i)Wi[$i]=5;var Vi=qi(ji,9),Gi=qi(Wi,5),Ji=function(e){for(var t=e[0],r=1;r<e.length;++r)e[r]>t&&(t=e[r]);return t},Yi=function(e,t,r){var i=t/8|0;return(e[i]|e[i+1]<<8)>>(7&t)&r},Xi=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(7&t)},Zi=function(e){return(e+7)/8|0},Qi=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],eo=function(e,t,r){var i=new Error(t||Qi[e]);if(i.code=e,Error.captureStackTrace&&Error.captureStackTrace(i,eo),!r)throw i;return i},to=function(e,t,r,i){var o=e.length;if(!o||t.f&&!t.l)return r||new Ni(0);var n=!r,s=n||2!=t.i,a=t.i;n&&(r=new Ni(3*o));var c=function(e){var t=r.length;if(e>t){var i=new Ni(Math.max(2*t,e));i.set(r),r=i}},l=t.f||0,d=t.p||0,u=t.b||0,p=t.l,h=t.d,g=t.m,m=t.n,f=8*o;do{if(!p){l=Yi(e,d,1);var y=Yi(e,d+1,3);if(d+=3,!y){var b=e[(R=Zi(d)+4)-4]|e[R-3]<<8,w=R+b;if(w>o){a&&eo(0);break}s&&c(u+b),r.set(e.subarray(R,w),u),t.b=u+=b,t.p=d=8*w,t.f=l;continue}if(1==y)p=Vi,h=Gi,g=9,m=5;else if(2==y){var I=Yi(e,d,31)+257,T=Yi(e,d+10,15)+4,S=I+Yi(e,d+5,31)+1;d+=14;for(var k=new Ni(S),E=new Ni(19),v=0;v<T;++v)E[Oi[v]]=Yi(e,d+3*v,7);d+=3*T;var A=Ji(E),C=(1<<A)-1,x=qi(E,A);for(v=0;v<S;){var R,N=x[Yi(e,d,C)];if(d+=15&N,(R=N>>4)<16)k[v++]=R;else{var _=0,P=0;for(16==R?(P=3+Yi(e,d,3),d+=2,_=k[v-1]):17==R?(P=3+Yi(e,d,7),d+=3):18==R&&(P=11+Yi(e,d,127),d+=7);P--;)k[v++]=_}}var F=k.subarray(0,I),z=k.subarray(I);g=Ji(F),m=Ji(z),p=qi(F,g),h=qi(z,m)}else eo(1);if(d>f){a&&eo(0);break}}s&&c(u+131072);for(var O=(1<<g)-1,D=(1<<m)-1,M=d;;M=d){var B=(_=p[Xi(e,d)&O])>>4;if((d+=15&_)>f){a&&eo(0);break}if(_||eo(2),B<256)r[u++]=B;else{if(256==B){M=d,p=null;break}var K=B-254;if(B>264){var U=Fi[v=B-257];K=Yi(e,d,(1<<U)-1)+Bi[v],d+=U}var L=h[Xi(e,d)&D],$=L>>4;L||eo(3),d+=15&L;z=Ui[$];if($>3){U=zi[$];z+=Xi(e,d)&(1<<U)-1,d+=U}if(d>f){a&&eo(0);break}s&&c(u+131072);var H=u+K;if(u<z){var q=0-z,j=Math.min(z,H);for(q+u<0&&eo(3);u<j;++u)r[u]=i[q+u]}for(;u<H;++u)r[u]=r[u-z]}}t.l=p,t.p=M,t.b=u,t.f=l,p&&(l=1,t.m=g,t.d=h,t.n=m)}while(!l);return u!=r.length&&n?function(e,t,r){return(null==r||r>e.length)&&(r=e.length),new Ni(e.subarray(t,r))}(r,0,u):r.subarray(0,u)},ro=new Ni(0);function io(e,t){var r,i,o=function(e){31==e[0]&&139==e[1]&&8==e[2]||eo(6,"invalid gzip data");var t=e[3],r=10;4&t&&(r+=2+(e[10]|e[11]<<8));for(var i=(t>>3&1)+(t>>4&1);i>0;i-=!e[r++]);return r+(2&t)}(e);return o+8>e.length&&eo(6,"invalid gzip data"),to(e.subarray(o,-8),{i:2},new Ni((i=(r=e).length,(r[i-4]|r[i-3]<<8|r[i-2]<<16|r[i-1]<<24)>>>0)),t)}function oo(e,t){return to(e.subarray(((8!=(15&(r=e)[0])||r[0]>>4>7||(r[0]<<8|r[1])%31)&&eo(6,"invalid zlib data"),1==(r[1]>>5&1)&&eo(6,"invalid zlib data: "+(32&r[1]?"need":"unexpected")+" dictionary"),2+(r[1]>>3&4)),-4),{i:2},t,t);var r}function no(e,t){return 31==e[0]&&139==e[1]&&8==e[2]?io(e,t):8!=(15&e[0])||e[0]>>4>7||(e[0]<<8|e[1])%31?function(e,t){return to(e,{i:2},t,t)}(e,t):oo(e,t)}var so="undefined"!=typeof TextDecoder&&new TextDecoder;try{so.decode(ro,{stream:!0})}catch($g){}var ao,co,lo,uo,po,ho={exports:{}};function go(){if(co)return ao;co=1;var e=1e3,t=60*e,r=60*t,i=24*r,o=7*i,n=365.25*i;function s(e,t,r,i){var o=t>=1.5*r;return Math.round(e/r)+" "+i+(o?"s":"")}return ao=function(a,c){c=c||{};var l=typeof a;if("string"===l&&a.length>0)return function(s){if((s=String(s)).length>100)return;var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(s);if(!a)return;var c=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*n;case"weeks":case"week":case"w":return c*o;case"days":case"day":case"d":return c*i;case"hours":case"hour":case"hrs":case"hr":case"h":return c*r;case"minutes":case"minute":case"mins":case"min":case"m":return c*t;case"seconds":case"second":case"secs":case"sec":case"s":return c*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(a);if("number"===l&&isFinite(a))return c.long?function(o){var n=Math.abs(o);if(n>=i)return s(o,n,i,"day");if(n>=r)return s(o,n,r,"hour");if(n>=t)return s(o,n,t,"minute");if(n>=e)return s(o,n,e,"second");return o+" ms"}(a):function(o){var n=Math.abs(o);if(n>=i)return Math.round(o/i)+"d";if(n>=r)return Math.round(o/r)+"h";if(n>=t)return Math.round(o/t)+"m";if(n>=e)return Math.round(o/e)+"s";return o+"ms"}(a);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(a))}}var mo=(po||(po=1,function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let i=0,o=0;t[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(i++,"%c"===e&&(o=i))}),t.splice(o,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(r){}},t.load=function(){let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(r){}return!e&&void 0!==De&&"env"in De&&(e=De.env.DEBUG),e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=(uo||(uo=1,lo=function(e){function t(e){let i,o,n,s=null;function a(...e){if(!a.enabled)return;const r=a,o=Number(new Date),n=o-(i||o);r.diff=n,r.prev=i,r.curr=o,i=o,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let s=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(i,o)=>{if("%%"===i)return"%";s++;const n=t.formatters[o];if("function"==typeof n){const t=e[s];i=n.call(r,t),e.splice(s,1),s--}return i}),t.formatArgs.call(r,e),(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==s?s:(o!==t.namespaces&&(o=t.namespaces,n=t.enabled(e)),n),set:e=>{s=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const i=t(this.namespace+(void 0===r?":":r)+e);return i.log=this.log,i}function i(e,t){let r=0,i=0,o=-1,n=0;for(;r<e.length;)if(i<t.length&&(t[i]===e[r]||"*"===t[i]))"*"===t[i]?(o=i,n=r,i++):(r++,i++);else{if(-1===o)return!1;i=o+1,n++,r=n}for(;i<t.length&&"*"===t[i];)i++;return i===t.length}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names,...t.skips.map(e=>"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const i of r)"-"===i[0]?t.skips.push(i.slice(1)):t.names.push(i)},t.enabled=function(e){for(const r of t.skips)if(i(e,r))return!1;for(const r of t.names)if(i(e,r))return!0;return!1},t.humanize=go(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach(r=>{t[r]=e[r]}),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t}),lo)(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}(ho,ho.exports)),ho.exports);const fo=di(mo),yo=67324752,bo=134695760,wo=33639248,Io=101010256,To={get:e=>(hi.get(e,6),{signature:mi.get(e,0),compressedSize:mi.get(e,8),uncompressedSize:mi.get(e,12)}),len:16},So={get(e){const t=hi.get(e,6);return{signature:mi.get(e,0),minVersion:hi.get(e,4),dataDescriptor:!!(8&t),compressedMethod:hi.get(e,8),compressedSize:mi.get(e,18),uncompressedSize:mi.get(e,22),filenameLength:hi.get(e,26),extraFieldLength:hi.get(e,28),filename:null}},len:30},ko={get:e=>({signature:mi.get(e,0),nrOfThisDisk:hi.get(e,4),nrOfThisDiskWithTheStart:hi.get(e,6),nrOfEntriesOnThisDisk:hi.get(e,8),nrOfEntriesOfSize:hi.get(e,10),sizeOfCd:mi.get(e,12),offsetOfStartOfCd:mi.get(e,16),zipFileCommentLength:hi.get(e,20)}),len:22},Eo={get(e){const t=hi.get(e,8);return{signature:mi.get(e,0),minVersion:hi.get(e,6),dataDescriptor:!!(8&t),compressedMethod:hi.get(e,10),compressedSize:mi.get(e,20),uncompressedSize:mi.get(e,24),filenameLength:hi.get(e,28),extraFieldLength:hi.get(e,30),fileCommentLength:hi.get(e,32),relativeOffsetOfLocalHeader:mi.get(e,42),filename:null}},len:46};function vo(e){const t=new Uint8Array(mi.len);return mi.put(t,0,e),t}const Ao=fo("tokenizer:inflate"),Co=262144,xo=vo(bo),Ro=vo(Io);class No{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(Co)}async isZip(){return await this.peekSignature()===yo}peekSignature(){return this.tokenizer.peekToken(mi)}async findEndOfCentralDirectoryLocator(){const e=this.tokenizer,t=Math.min(16384,e.fileInfo.size),r=this.syncBuffer.subarray(0,t);await this.tokenizer.readBuffer(r,{position:e.fileInfo.size-t});for(let i=r.length-4;i>=0;i--)if(r[i]===Ro[0]&&r[i+1]===Ro[1]&&r[i+2]===Ro[2]&&r[i+3]===Ro[3])return e.fileInfo.size-t+i;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess())return void Ao("Cannot reading central-directory without random-read support");Ao("Reading central-directory...");const e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){Ao("Central-directory 32-bit signature found");const r=await this.tokenizer.readToken(ko,t),i=[];this.tokenizer.setPosition(r.offsetOfStartOfCd);for(let e=0;e<r.nrOfEntriesOfSize;++e){const t=await this.tokenizer.readToken(Eo);if(t.signature!==wo)throw new Error("Expected Central-File-Header signature");t.filename=await this.tokenizer.readToken(new wi(t.filenameLength,"utf-8")),await this.tokenizer.ignore(t.extraFieldLength),await this.tokenizer.ignore(t.fileCommentLength),i.push(t),Ao(`Add central-directory file-entry: n=${e+1}/${i.length}: filename=${i[e].filename}`)}return this.tokenizer.setPosition(e),i}this.tokenizer.setPosition(e)}async unzip(e){const t=await this.readCentralDirectory();if(t)return this.iterateOverCentralDirectory(t,e);let r=!1;do{const t=await this.readLocalFileHeader();if(!t)break;const i=e(t);let o;if(r=!!i.stop,await this.tokenizer.ignore(t.extraFieldLength),t.dataDescriptor&&0===t.compressedSize){const e=[];let r=Co;Ao("Compressed-file-size unknown, scanning for next data-descriptor-signature....");let o=-1;for(;o<0&&r===Co;){r=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),o=_o(this.syncBuffer.subarray(0,r),xo);const t=o>=0?o:r;if(i.handler){const r=new Uint8Array(t);await this.tokenizer.readBuffer(r),e.push(r)}else await this.tokenizer.ignore(t)}Ao(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),i.handler&&await this.inflate(t,Po(e),i.handler)}else i.handler?(Ao(`Reading compressed-file-data: ${t.compressedSize} bytes`),o=new Uint8Array(t.compressedSize),await this.tokenizer.readBuffer(o),await this.inflate(t,o,i.handler)):(Ao(`Ignoring compressed-file-data: ${t.compressedSize} bytes`),await this.tokenizer.ignore(t.compressedSize));if(Ao(`Reading data-descriptor at pos=${this.tokenizer.position}`),t.dataDescriptor){if(134695760!==(await this.tokenizer.readToken(To)).signature)throw new Error("Expected data-descriptor-signature at position "+(this.tokenizer.position-To.len))}}while(!r)}async iterateOverCentralDirectory(e,t){for(const r of e){const e=t(r);if(e.handler){this.tokenizer.setPosition(r.relativeOffsetOfLocalHeader);const t=await this.readLocalFileHeader();if(t){await this.tokenizer.ignore(t.extraFieldLength);const i=new Uint8Array(r.compressedSize);await this.tokenizer.readBuffer(i),await this.inflate(t,i,e.handler)}}if(e.stop)break}}inflate(e,t,r){if(0===e.compressedMethod)return r(t);Ao(`Decompress filename=${e.filename}, compressed-size=${t.length}`);return r(no(t))}async readLocalFileHeader(){const e=await this.tokenizer.peekToken(mi);if(e===yo){const e=await this.tokenizer.readToken(So);return e.filename=await this.tokenizer.readToken(new wi(e.filenameLength,"utf-8")),e}if(e===wo)return!1;if(3759263696===e)throw new Error("Encrypted ZIP");throw new Error("Unexpected signature")}}function _o(e,t){const r=e.length,i=t.length;if(i>r)return-1;for(let o=0;o<=r-i;o++){let r=!0;for(let n=0;n<i;n++)if(e[o+n]!==t[n]){r=!1;break}if(r)return o}return-1}function Po(e){const t=e.reduce((e,t)=>e+t.length,0),r=new Uint8Array(t);let i=0;for(const o of e)r.set(o,i),i+=o.length;return r}function Fo(e){const{byteLength:t}=e;return 6===t?e.getUint16(0)*2**32+e.getUint32(2):5===t?e.getUint8(0)*2**32+e.getUint32(1):4===t?e.getUint32(0):3===t?65536*e.getUint8(0)+e.getUint16(1):2===t?e.getUint16(0):1===t?e.getUint8(0):void 0}new globalThis.TextDecoder("utf8"),new globalThis.TextEncoder,Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));const zo={get:(e,t)=>127&e[t+3]|e[t+2]<<7|e[t+1]<<14|e[t]<<21,len:4},Oo=4100;function Do(e){switch(e=e.toLowerCase()){case"application/epub+zip":return{ext:"epub",mime:e};case"application/vnd.oasis.opendocument.text":return{ext:"odt",mime:e};case"application/vnd.oasis.opendocument.text-template":return{ext:"ott",mime:e};case"application/vnd.oasis.opendocument.spreadsheet":return{ext:"ods",mime:e};case"application/vnd.oasis.opendocument.spreadsheet-template":return{ext:"ots",mime:e};case"application/vnd.oasis.opendocument.presentation":return{ext:"odp",mime:e};case"application/vnd.oasis.opendocument.presentation-template":return{ext:"otp",mime:e};case"application/vnd.oasis.opendocument.graphics":return{ext:"odg",mime:e};case"application/vnd.oasis.opendocument.graphics-template":return{ext:"otg",mime:e};case"application/vnd.openxmlformats-officedocument.presentationml.slideshow":return{ext:"ppsx",mime:e};case"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":return{ext:"xlsx",mime:e};case"application/vnd.ms-excel.sheet.macroenabled":return{ext:"xlsm",mime:"application/vnd.ms-excel.sheet.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.spreadsheetml.template":return{ext:"xltx",mime:e};case"application/vnd.ms-excel.template.macroenabled":return{ext:"xltm",mime:"application/vnd.ms-excel.template.macroenabled.12"};case"application/vnd.ms-powerpoint.slideshow.macroenabled":return{ext:"ppsm",mime:"application/vnd.ms-powerpoint.slideshow.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.wordprocessingml.document":return{ext:"docx",mime:e};case"application/vnd.ms-word.document.macroenabled":return{ext:"docm",mime:"application/vnd.ms-word.document.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.wordprocessingml.template":return{ext:"dotx",mime:e};case"application/vnd.ms-word.template.macroenabledtemplate":return{ext:"dotm",mime:"application/vnd.ms-word.template.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.presentationml.template":return{ext:"potx",mime:e};case"application/vnd.ms-powerpoint.template.macroenabled":return{ext:"potm",mime:"application/vnd.ms-powerpoint.template.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.presentationml.presentation":return{ext:"pptx",mime:e};case"application/vnd.ms-powerpoint.presentation.macroenabled":return{ext:"pptm",mime:"application/vnd.ms-powerpoint.presentation.macroenabled.12"};case"application/vnd.ms-visio.drawing":return{ext:"vsdx",mime:"application/vnd.visio"};case"application/vnd.ms-package.3dmanufacturing-3dmodel+xml":return{ext:"3mf",mime:"model/3mf"}}}function Mo(e,t,r){r={offset:0,...r};for(const[i,o]of t.entries())if(r.mask){if(o!==(r.mask[i]&e[i+r.offset]))return!1}else if(o!==e[i+r.offset])return!1;return!0}class Bo{constructor(e){ne(this,"detectConfident",async e=>{if(this.buffer=new Uint8Array(Oo),void 0===e.fileInfo.size&&(e.fileInfo.size=Number.MAX_SAFE_INTEGER),this.tokenizer=e,await e.peekBuffer(this.buffer,{length:12,mayBeLess:!0}),this.check([66,77]))return{ext:"bmp",mime:"image/bmp"};if(this.check([11,119]))return{ext:"ac3",mime:"audio/vnd.dolby.dd-raw"};if(this.check([120,1]))return{ext:"dmg",mime:"application/x-apple-diskimage"};if(this.check([77,90]))return{ext:"exe",mime:"application/x-msdownload"};if(this.check([37,33]))return await e.peekBuffer(this.buffer,{length:24,mayBeLess:!0}),this.checkString("PS-Adobe-",{offset:2})&&this.checkString(" EPSF-",{offset:14})?{ext:"eps",mime:"application/eps"}:{ext:"ps",mime:"application/postscript"};if(this.check([31,160])||this.check([31,157]))return{ext:"Z",mime:"application/x-compress"};if(this.check([199,113]))return{ext:"cpio",mime:"application/x-cpio"};if(this.check([96,234]))return{ext:"arj",mime:"application/x-arj"};if(this.check([239,187,191]))return this.tokenizer.ignore(3),this.detectConfident(e);if(this.check([71,73,70]))return{ext:"gif",mime:"image/gif"};if(this.check([73,73,188]))return{ext:"jxr",mime:"image/vnd.ms-photo"};if(this.check([31,139,8]))return{ext:"gz",mime:"application/gzip"};if(this.check([66,90,104]))return{ext:"bz2",mime:"application/x-bzip2"};if(this.checkString("ID3")){await e.ignore(6);const t=await e.readToken(zo);return e.position+t>e.fileInfo.size?{ext:"mp3",mime:"audio/mpeg"}:(await e.ignore(t),this.fromTokenizer(e))}if(this.checkString("MP+"))return{ext:"mpc",mime:"audio/x-musepack"};if((67===this.buffer[0]||70===this.buffer[0])&&this.check([87,83],{offset:1}))return{ext:"swf",mime:"application/x-shockwave-flash"};if(this.check([255,216,255]))return this.check([247],{offset:3})?{ext:"jls",mime:"image/jls"}:{ext:"jpg",mime:"image/jpeg"};if(this.check([79,98,106,1]))return{ext:"avro",mime:"application/avro"};if(this.checkString("FLIF"))return{ext:"flif",mime:"image/flif"};if(this.checkString("8BPS"))return{ext:"psd",mime:"image/vnd.adobe.photoshop"};if(this.checkString("MPCK"))return{ext:"mpc",mime:"audio/x-musepack"};if(this.checkString("FORM"))return{ext:"aif",mime:"audio/aiff"};if(this.checkString("icns",{offset:0}))return{ext:"icns",mime:"image/icns"};if(this.check([80,75,3,4])){let r;return await new No(e).unzip(e=>{switch(e.filename){case"META-INF/mozilla.rsa":return r={ext:"xpi",mime:"application/x-xpinstall"},{stop:!0};case"META-INF/MANIFEST.MF":return r={ext:"jar",mime:"application/java-archive"},{stop:!0};case"mimetype":return{async handler(e){const t=new TextDecoder("utf-8").decode(e).trim();r=Do(t)},stop:!0};case"[Content_Types].xml":return{async handler(e){let t=new TextDecoder("utf-8").decode(e);const i=t.indexOf('.main+xml"');if(-1===i){const e="application/vnd.ms-package.3dmanufacturing-3dmodel+xml";t.includes(`ContentType="${e}"`)&&(r=Do(e))}else{t=t.slice(0,Math.max(0,i));const e=t.lastIndexOf('"'),o=t.slice(Math.max(0,e+1));r=Do(o)}},stop:!0};default:return/classes\d*\.dex/.test(e.filename)?(r={ext:"apk",mime:"application/vnd.android.package-archive"},{stop:!0}):{}}}),r??{ext:"zip",mime:"application/zip"}}if(this.checkString("OggS")){await e.ignore(28);const i=new Uint8Array(8);return await e.readBuffer(i),Mo(i,[79,112,117,115,72,101,97,100])?{ext:"opus",mime:"audio/ogg; codecs=opus"}:Mo(i,[128,116,104,101,111,114,97])?{ext:"ogv",mime:"video/ogg"}:Mo(i,[1,118,105,100,101,111,0])?{ext:"ogm",mime:"video/ogg"}:Mo(i,[127,70,76,65,67])?{ext:"oga",mime:"audio/ogg"}:Mo(i,[83,112,101,101,120,32,32])?{ext:"spx",mime:"audio/ogg"}:Mo(i,[1,118,111,114,98,105,115])?{ext:"ogg",mime:"audio/ogg"}:{ext:"ogx",mime:"application/ogg"}}if(this.check([80,75])&&(3===this.buffer[2]||5===this.buffer[2]||7===this.buffer[2])&&(4===this.buffer[3]||6===this.buffer[3]||8===this.buffer[3]))return{ext:"zip",mime:"application/zip"};if(this.checkString("MThd"))return{ext:"mid",mime:"audio/midi"};if(this.checkString("wOFF")&&(this.check([0,1,0,0],{offset:4})||this.checkString("OTTO",{offset:4})))return{ext:"woff",mime:"font/woff"};if(this.checkString("wOF2")&&(this.check([0,1,0,0],{offset:4})||this.checkString("OTTO",{offset:4})))return{ext:"woff2",mime:"font/woff2"};if(this.check([212,195,178,161])||this.check([161,178,195,212]))return{ext:"pcap",mime:"application/vnd.tcpdump.pcap"};if(this.checkString("DSD "))return{ext:"dsf",mime:"audio/x-dsf"};if(this.checkString("LZIP"))return{ext:"lz",mime:"application/x-lzip"};if(this.checkString("fLaC"))return{ext:"flac",mime:"audio/flac"};if(this.check([66,80,71,251]))return{ext:"bpg",mime:"image/bpg"};if(this.checkString("wvpk"))return{ext:"wv",mime:"audio/wavpack"};if(this.checkString("%PDF"))return{ext:"pdf",mime:"application/pdf"};if(this.check([0,97,115,109]))return{ext:"wasm",mime:"application/wasm"};if(this.check([73,73])){const o=await this.readTiffHeader(!1);if(o)return o}if(this.check([77,77])){const n=await this.readTiffHeader(!0);if(n)return n}if(this.checkString("MAC "))return{ext:"ape",mime:"audio/ape"};if(this.check([26,69,223,163])){async function s(){const t=await e.peekNumber(pi);let r=128,i=0;for(;0===(t&r)&&0!==r;)++i,r>>=1;const o=new Uint8Array(i+1);return await e.readBuffer(o),o}async function a(){const e=await s(),t=await s();t[0]^=128>>t.length-1;const r=Math.min(6,t.length),i=new DataView(e.buffer),o=new DataView(t.buffer,t.length-r,r);return{id:Fo(i),len:Fo(o)}}async function c(t){for(;t>0;){const r=await a();if(17026===r.id){return(await e.readToken(new wi(r.len))).replaceAll(/\00.*$/g,"")}await e.ignore(r.len),--t}}const l=await a();switch(await c(l.len)){case"webm":return{ext:"webm",mime:"video/webm"};case"matroska":return{ext:"mkv",mime:"video/matroska"};default:return}}if(this.checkString("SQLi"))return{ext:"sqlite",mime:"application/x-sqlite3"};if(this.check([78,69,83,26]))return{ext:"nes",mime:"application/x-nintendo-nes-rom"};if(this.checkString("Cr24"))return{ext:"crx",mime:"application/x-google-chrome-extension"};if(this.checkString("MSCF")||this.checkString("ISc("))return{ext:"cab",mime:"application/vnd.ms-cab-compressed"};if(this.check([237,171,238,219]))return{ext:"rpm",mime:"application/x-rpm"};if(this.check([197,208,211,198]))return{ext:"eps",mime:"application/eps"};if(this.check([40,181,47,253]))return{ext:"zst",mime:"application/zstd"};if(this.check([127,69,76,70]))return{ext:"elf",mime:"application/x-elf"};if(this.check([33,66,68,78]))return{ext:"pst",mime:"application/vnd.ms-outlook"};if(this.checkString("PAR1")||this.checkString("PARE"))return{ext:"parquet",mime:"application/vnd.apache.parquet"};if(this.checkString("ttcf"))return{ext:"ttc",mime:"font/collection"};if(this.check([207,250,237,254]))return{ext:"macho",mime:"application/x-mach-binary"};if(this.check([4,34,77,24]))return{ext:"lz4",mime:"application/x-lz4"};if(this.check([79,84,84,79,0]))return{ext:"otf",mime:"font/otf"};if(this.checkString("#!AMR"))return{ext:"amr",mime:"audio/amr"};if(this.checkString("{\\rtf"))return{ext:"rtf",mime:"application/rtf"};if(this.check([70,76,86,1]))return{ext:"flv",mime:"video/x-flv"};if(this.checkString("IMPM"))return{ext:"it",mime:"audio/x-it"};if(this.checkString("-lh0-",{offset:2})||this.checkString("-lh1-",{offset:2})||this.checkString("-lh2-",{offset:2})||this.checkString("-lh3-",{offset:2})||this.checkString("-lh4-",{offset:2})||this.checkString("-lh5-",{offset:2})||this.checkString("-lh6-",{offset:2})||this.checkString("-lh7-",{offset:2})||this.checkString("-lzs-",{offset:2})||this.checkString("-lz4-",{offset:2})||this.checkString("-lz5-",{offset:2})||this.checkString("-lhd-",{offset:2}))return{ext:"lzh",mime:"application/x-lzh-compressed"};if(this.check([0,0,1,186])){if(this.check([33],{offset:4,mask:[241]}))return{ext:"mpg",mime:"video/MP1S"};if(this.check([68],{offset:4,mask:[196]}))return{ext:"mpg",mime:"video/MP2P"}}if(this.checkString("ITSF"))return{ext:"chm",mime:"application/vnd.ms-htmlhelp"};if(this.check([202,254,186,190]))return{ext:"class",mime:"application/java-vm"};if(this.checkString(".RMF"))return{ext:"rm",mime:"application/vnd.rn-realmedia"};if(this.checkString("DRACO"))return{ext:"drc",mime:"application/vnd.google.draco"};if(this.check([253,55,122,88,90,0]))return{ext:"xz",mime:"application/x-xz"};if(this.checkString("<?xml "))return{ext:"xml",mime:"application/xml"};if(this.check([55,122,188,175,39,28]))return{ext:"7z",mime:"application/x-7z-compressed"};if(this.check([82,97,114,33,26,7])&&(0===this.buffer[6]||1===this.buffer[6]))return{ext:"rar",mime:"application/x-rar-compressed"};if(this.checkString("solid "))return{ext:"stl",mime:"model/stl"};if(this.checkString("AC")){const d=new wi(4,"latin1").get(this.buffer,2);if(d.match("^d*")&&d>=1e3&&d<=1050)return{ext:"dwg",mime:"image/vnd.dwg"}}if(this.checkString("070707"))return{ext:"cpio",mime:"application/x-cpio"};if(this.checkString("BLENDER"))return{ext:"blend",mime:"application/x-blender"};if(this.checkString("!<arch>")){await e.ignore(8);return"debian-binary"===await e.readToken(new wi(13,"ascii"))?{ext:"deb",mime:"application/x-deb"}:{ext:"ar",mime:"application/x-unix-archive"}}if(this.checkString("WEBVTT")&&["\n","\r","\t"," ","\0"].some(e=>this.checkString(e,{offset:6})))return{ext:"vtt",mime:"text/vtt"};if(this.check([137,80,78,71,13,10,26,10])){async function u(){return{length:await e.readToken(yi),type:await e.readToken(new wi(4,"latin1"))}}await e.ignore(8);do{const p=await u();if(p.length<0)return;switch(p.type){case"IDAT":return{ext:"png",mime:"image/png"};case"acTL":return{ext:"apng",mime:"image/apng"};default:await e.ignore(p.length+4)}}while(e.position+8<e.fileInfo.size);return{ext:"png",mime:"image/png"}}if(this.check([65,82,82,79,87,49,0,0]))return{ext:"arrow",mime:"application/vnd.apache.arrow.file"};if(this.check([103,108,84,70,2,0,0,0]))return{ext:"glb",mime:"model/gltf-binary"};if(this.check([102,114,101,101],{offset:4})||this.check([109,100,97,116],{offset:4})||this.check([109,111,111,118],{offset:4})||this.check([119,105,100,101],{offset:4}))return{ext:"mov",mime:"video/quicktime"};if(this.check([73,73,82,79,8,0,0,0,24]))return{ext:"orf",mime:"image/x-olympus-orf"};if(this.checkString("gimp xcf "))return{ext:"xcf",mime:"image/x-xcf"};if(this.checkString("ftyp",{offset:4})&&96&this.buffer[8]){const h=new wi(4,"latin1").get(this.buffer,8).replace("\0"," ").trim();switch(h){case"avif":case"avis":return{ext:"avif",mime:"image/avif"};case"mif1":return{ext:"heic",mime:"image/heif"};case"msf1":return{ext:"heic",mime:"image/heif-sequence"};case"heic":case"heix":return{ext:"heic",mime:"image/heic"};case"hevc":case"hevx":return{ext:"heic",mime:"image/heic-sequence"};case"qt":return{ext:"mov",mime:"video/quicktime"};case"M4V":case"M4VH":case"M4VP":return{ext:"m4v",mime:"video/x-m4v"};case"M4P":return{ext:"m4p",mime:"video/mp4"};case"M4B":return{ext:"m4b",mime:"audio/mp4"};case"M4A":return{ext:"m4a",mime:"audio/x-m4a"};case"F4V":return{ext:"f4v",mime:"video/mp4"};case"F4P":return{ext:"f4p",mime:"video/mp4"};case"F4A":return{ext:"f4a",mime:"audio/mp4"};case"F4B":return{ext:"f4b",mime:"audio/mp4"};case"crx":return{ext:"cr3",mime:"image/x-canon-cr3"};default:return h.startsWith("3g")?h.startsWith("3g2")?{ext:"3g2",mime:"video/3gpp2"}:{ext:"3gp",mime:"video/3gpp"}:{ext:"mp4",mime:"video/mp4"}}}if(this.check([82,73,70,70])){if(this.checkString("WEBP",{offset:8}))return{ext:"webp",mime:"image/webp"};if(this.check([65,86,73],{offset:8}))return{ext:"avi",mime:"video/vnd.avi"};if(this.check([87,65,86,69],{offset:8}))return{ext:"wav",mime:"audio/wav"};if(this.check([81,76,67,77],{offset:8}))return{ext:"qcp",mime:"audio/qcelp"}}if(this.check([73,73,85,0,24,0,0,0,136,231,116,216]))return{ext:"rw2",mime:"image/x-panasonic-rw2"};if(this.check([48,38,178,117,142,102,207,17,166,217])){async function g(){const t=new Uint8Array(16);return await e.readBuffer(t),{id:t,size:Number(await e.readToken(bi))}}for(await e.ignore(30);e.position+24<e.fileInfo.size;){const m=await g();let f=m.size-24;if(Mo(m.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){const y=new Uint8Array(16);if(f-=await e.readBuffer(y),Mo(y,[64,158,105,248,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:"asf",mime:"audio/x-ms-asf"};if(Mo(y,[192,239,25,188,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:"asf",mime:"video/x-ms-asf"};break}await e.ignore(f)}return{ext:"asf",mime:"application/vnd.ms-asf"}}if(this.check([171,75,84,88,32,49,49,187,13,10,26,10]))return{ext:"ktx",mime:"image/ktx"};if((this.check([126,16,4])||this.check([126,24,4]))&&this.check([48,77,73,69],{offset:4}))return{ext:"mie",mime:"application/x-mie"};if(this.check([39,10,0,0,0,0,0,0,0,0,0,0],{offset:2}))return{ext:"shp",mime:"application/x-esri-shape"};if(this.check([255,79,255,81]))return{ext:"j2c",mime:"image/j2c"};if(this.check([0,0,0,12,106,80,32,32,13,10,135,10])){await e.ignore(20);switch(await e.readToken(new wi(4,"ascii"))){case"jp2 ":return{ext:"jp2",mime:"image/jp2"};case"jpx ":return{ext:"jpx",mime:"image/jpx"};case"jpm ":return{ext:"jpm",mime:"image/jpm"};case"mjp2":return{ext:"mj2",mime:"image/mj2"};default:return}}if(this.check([255,10])||this.check([0,0,0,12,74,88,76,32,13,10,135,10]))return{ext:"jxl",mime:"image/jxl"};if(this.check([254,255]))return this.check([0,60,0,63,0,120,0,109,0,108],{offset:2})?{ext:"xml",mime:"application/xml"}:void 0;if(this.check([208,207,17,224,161,177,26,225]))return{ext:"cfb",mime:"application/x-cfb"};if(await e.peekBuffer(this.buffer,{length:Math.min(256,e.fileInfo.size),mayBeLess:!0}),this.check([97,99,115,112],{offset:36}))return{ext:"icc",mime:"application/vnd.iccprofile"};if(this.checkString("**ACE",{offset:7})&&this.checkString("**",{offset:12}))return{ext:"ace",mime:"application/x-ace-compressed"};if(this.checkString("BEGIN:")){if(this.checkString("VCARD",{offset:6}))return{ext:"vcf",mime:"text/vcard"};if(this.checkString("VCALENDAR",{offset:6}))return{ext:"ics",mime:"text/calendar"}}if(this.checkString("FUJIFILMCCD-RAW"))return{ext:"raf",mime:"image/x-fujifilm-raf"};if(this.checkString("Extended Module:"))return{ext:"xm",mime:"audio/x-xm"};if(this.checkString("Creative Voice File"))return{ext:"voc",mime:"audio/x-voc"};if(this.check([4,0,0,0])&&this.buffer.length>=16){const b=new DataView(this.buffer.buffer).getUint32(12,!0);if(b>12&&this.buffer.length>=b+16)try{const w=(new TextDecoder).decode(this.buffer.subarray(16,b+16));if(JSON.parse(w).files)return{ext:"asar",mime:"application/x-asar"}}catch{}}return this.check([6,14,43,52,2,5,1,1,13,1,2,1,1,2])?{ext:"mxf",mime:"application/mxf"}:this.checkString("SCRM",{offset:44})?{ext:"s3m",mime:"audio/x-s3m"}:this.check([71])&&this.check([71],{offset:188})||this.check([71],{offset:4})&&this.check([71],{offset:196})?{ext:"mts",mime:"video/mp2t"}:this.check([66,79,79,75,77,79,66,73],{offset:60})?{ext:"mobi",mime:"application/x-mobipocket-ebook"}:this.check([68,73,67,77],{offset:128})?{ext:"dcm",mime:"application/dicom"}:this.check([76,0,0,0,1,20,2,0,0,0,0,0,192,0,0,0,0,0,0,70])?{ext:"lnk",mime:"application/x.ms.shortcut"}:this.check([98,111,111,107,0,0,0,0,109,97,114,107,0,0,0,0])?{ext:"alias",mime:"application/x.apple.alias"}:this.checkString("Kaydara FBX Binary \0")?{ext:"fbx",mime:"application/x.autodesk.fbx"}:this.check([76,80],{offset:34})&&(this.check([0,0,1],{offset:8})||this.check([1,0,2],{offset:8})||this.check([2,0,2],{offset:8}))?{ext:"eot",mime:"application/vnd.ms-fontobject"}:this.check([6,6,237,245,216,29,70,229,189,49,239,231,254,116,183,29])?{ext:"indd",mime:"application/x-indesign"}:(await e.peekBuffer(this.buffer,{length:Math.min(512,e.fileInfo.size),mayBeLess:!0}),this.checkString("ustar",{offset:257})&&(this.checkString("\0",{offset:262})||this.checkString(" ",{offset:262}))||this.check([0,0,0,0,0,0],{offset:257})&&function(e,t=0){const r=Number.parseInt(new wi(6).get(e,148).replace(/\0.*$/,"").trim(),8);if(Number.isNaN(r))return!1;let i=256;for(let o=t;o<t+148;o++)i+=e[o];for(let o=t+156;o<t+512;o++)i+=e[o];return r===i}(this.buffer)?{ext:"tar",mime:"application/x-tar"}:this.check([255,254])?this.check([60,0,63,0,120,0,109,0,108,0],{offset:2})?{ext:"xml",mime:"application/xml"}:this.check([255,14,83,0,107,0,101,0,116,0,99,0,104,0,85,0,112,0,32,0,77,0,111,0,100,0,101,0,108,0],{offset:2})?{ext:"skp",mime:"application/vnd.sketchup.skp"}:void 0:this.checkString("-----BEGIN PGP MESSAGE-----")?{ext:"pgp",mime:"application/pgp-encrypted"}:void 0)}),ne(this,"detectImprecise",async e=>{if(this.buffer=new Uint8Array(Oo),await e.peekBuffer(this.buffer,{length:Math.min(8,e.fileInfo.size),mayBeLess:!0}),this.check([0,0,1,186])||this.check([0,0,1,179]))return{ext:"mpg",mime:"video/mpeg"};if(this.check([0,1,0,0,0]))return{ext:"ttf",mime:"font/ttf"};if(this.check([0,0,1,0]))return{ext:"ico",mime:"image/x-icon"};if(this.check([0,0,2,0]))return{ext:"cur",mime:"image/x-icon"};if(await e.peekBuffer(this.buffer,{length:Math.min(2+this.options.mpegOffsetTolerance,e.fileInfo.size),mayBeLess:!0}),this.buffer.length>=2+this.options.mpegOffsetTolerance)for(let t=0;t<=this.options.mpegOffsetTolerance;++t){const e=this.scanMpeg(t);if(e)return e}}),this.options={mpegOffsetTolerance:0,...e},this.detectors=[...(null==e?void 0:e.customDetectors)??[],{id:"core",detect:this.detectConfident},{id:"core.imprecise",detect:this.detectImprecise}],this.tokenizerOptions={abortSignal:null==e?void 0:e.signal}}async fromTokenizer(e){const t=e.position;for(const r of this.detectors){const i=await r.detect(e);if(i)return i;if(t!==e.position)return}}async fromBuffer(e){if(!(e instanceof Uint8Array||e instanceof ArrayBuffer))throw new TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``);const t=e instanceof Uint8Array?e:new Uint8Array(e);var r,i;if((null==t?void 0:t.length)>1)return this.fromTokenizer((r=t,i=this.tokenizerOptions,new xi(r,i)))}async fromBlob(e){return this.fromStream(e.stream())}async fromStream(e){const t=await Ri(e,this.tokenizerOptions);try{return await this.fromTokenizer(t)}finally{await t.close()}}async toDetectionStream(e,t){const{sampleSize:r=Oo}=t;let i,o;const n=e.getReader({mode:"byob"});try{const{value:e,done:t}=await n.read(new Uint8Array(r));if(o=e,!t&&e)try{i=await this.fromBuffer(e.subarray(0,r))}catch(c){if(!(c instanceof Ii))throw c;i=void 0}o=e}finally{n.releaseLock()}const s=new TransformStream({async start(e){e.enqueue(o)},transform(e,t){t.enqueue(e)}}),a=e.pipeThrough(s);return a.fileType=i,a}check(e,t){return Mo(this.buffer,e,t)}checkString(e,t){return this.check((r=e,[...r].map(e=>e.charCodeAt(0))),t);var r}async readTiffTag(e){const t=await this.tokenizer.readToken(e?gi:hi);switch(this.tokenizer.ignore(10),t){case 50341:return{ext:"arw",mime:"image/x-sony-arw"};case 50706:return{ext:"dng",mime:"image/x-adobe-dng"}}}async readTiffIFD(e){const t=await this.tokenizer.readToken(e?gi:hi);for(let r=0;r<t;++r){const t=await this.readTiffTag(e);if(t)return t}}async readTiffHeader(e){const t=(e?gi:hi).get(this.buffer,2),r=(e?fi:mi).get(this.buffer,4);if(42===t){if(r>=6){if(this.checkString("CR",{offset:8}))return{ext:"cr2",mime:"image/x-canon-cr2"};if(r>=8){const t=(e?gi:hi).get(this.buffer,8),r=(e?gi:hi).get(this.buffer,10);if(28===t&&254===r||31===t&&11===r)return{ext:"nef",mime:"image/x-nikon-nef"}}}await this.tokenizer.ignore(r);return await this.readTiffIFD(e)??{ext:"tif",mime:"image/tiff"}}if(43===t)return{ext:"tif",mime:"image/tiff"}}scanMpeg(e){if(this.check([255,224],{offset:e,mask:[255,224]})){if(this.check([16],{offset:e+1,mask:[22]}))return this.check([8],{offset:e+1,mask:[8]}),{ext:"aac",mime:"audio/aac"};if(this.check([2],{offset:e+1,mask:[6]}))return{ext:"mp3",mime:"audio/mpeg"};if(this.check([4],{offset:e+1,mask:[6]}))return{ext:"mp2",mime:"audio/mpeg"};if(this.check([6],{offset:e+1,mask:[6]}))return{ext:"mp1",mime:"audio/mpeg"}}}}new Set(["jpg","png","apng","gif","webp","flif","xcf","cr2","cr3","orf","arw","dng","nef","rw2","raf","tif","bmp","icns","jxr","psd","indd","zip","tar","rar","gz","bz2","7z","dmg","mp4","mid","mkv","webm","mov","avi","mpg","mp2","mp3","m4a","oga","ogg","ogv","opus","flac","wav","spx","amr","pdf","epub","elf","macho","exe","swf","rtf","wasm","woff","woff2","eot","ttf","otf","ttc","ico","flv","ps","xz","sqlite","nes","crx","xpi","cab","deb","ar","rpm","Z","lz","cfb","mxf","mts","blend","bpg","docx","pptx","xlsx","3gp","3g2","j2c","jp2","jpm","jpx","mj2","aif","qcp","odt","ods","odp","xml","mobi","heic","cur","ktx","ape","wv","dcm","ics","glb","pcap","dsf","lnk","alias","voc","ac3","m4v","m4p","m4b","f4v","f4p","f4b","f4a","mie","asf","ogm","ogx","mpc","arrow","shp","aac","mp1","it","s3m","xm","skp","avif","eps","lzh","pgp","asar","stl","chm","3mf","zst","jxl","vcf","jls","pst","dwg","parquet","class","arj","cpio","ace","avro","icc","fbx","vsdx","vtt","apk","drc","lz4","potx","xltx","dotx","xltm","ott","ots","otp","odg","otg","xlsm","docm","dotm","potm","pptm","jar","rm","ppsm","ppsx"]),new Set(["image/jpeg","image/png","image/gif","image/webp","image/flif","image/x-xcf","image/x-canon-cr2","image/x-canon-cr3","image/tiff","image/bmp","image/vnd.ms-photo","image/vnd.adobe.photoshop","application/x-indesign","application/epub+zip","application/x-xpinstall","application/vnd.ms-powerpoint.slideshow.macroenabled.12","application/vnd.oasis.opendocument.text","application/vnd.oasis.opendocument.spreadsheet","application/vnd.oasis.opendocument.presentation","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.openxmlformats-officedocument.presentationml.slideshow","application/zip","application/x-tar","application/x-rar-compressed","application/gzip","application/x-bzip2","application/x-7z-compressed","application/x-apple-diskimage","application/vnd.apache.arrow.file","video/mp4","audio/midi","video/matroska","video/webm","video/quicktime","video/vnd.avi","audio/wav","audio/qcelp","audio/x-ms-asf","video/x-ms-asf","application/vnd.ms-asf","video/mpeg","video/3gpp","audio/mpeg","audio/mp4","video/ogg","audio/ogg","audio/ogg; codecs=opus","application/ogg","audio/flac","audio/ape","audio/wavpack","audio/amr","application/pdf","application/x-elf","application/x-mach-binary","application/x-msdownload","application/x-shockwave-flash","application/rtf","application/wasm","font/woff","font/woff2","application/vnd.ms-fontobject","font/ttf","font/otf","font/collection","image/x-icon","video/x-flv","application/postscript","application/eps","application/x-xz","application/x-sqlite3","application/x-nintendo-nes-rom","application/x-google-chrome-extension","application/vnd.ms-cab-compressed","application/x-deb","application/x-unix-archive","application/x-rpm","application/x-compress","application/x-lzip","application/x-cfb","application/x-mie","application/mxf","video/mp2t","application/x-blender","image/bpg","image/j2c","image/jp2","image/jpx","image/jpm","image/mj2","audio/aiff","application/xml","application/x-mobipocket-ebook","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/icns","image/ktx","application/dicom","audio/x-musepack","text/calendar","text/vcard","text/vtt","model/gltf-binary","application/vnd.tcpdump.pcap","audio/x-dsf","application/x.ms.shortcut","application/x.apple.alias","audio/x-voc","audio/vnd.dolby.dd-raw","audio/x-m4a","image/apng","image/x-olympus-orf","image/x-sony-arw","image/x-adobe-dng","image/x-nikon-nef","image/x-panasonic-rw2","image/x-fujifilm-raf","video/x-m4v","video/3gpp2","application/x-esri-shape","audio/aac","audio/x-it","audio/x-s3m","audio/x-xm","video/MP1S","video/MP2P","application/vnd.sketchup.skp","image/avif","application/x-lzh-compressed","application/pgp-encrypted","application/x-asar","model/stl","application/vnd.ms-htmlhelp","model/3mf","image/jxl","application/zstd","image/jls","application/vnd.ms-outlook","image/vnd.dwg","application/vnd.apache.parquet","application/java-vm","application/x-arj","application/x-cpio","application/x-ace-compressed","application/avro","application/vnd.iccprofile","application/x.autodesk.fbx","application/vnd.visio","application/vnd.android.package-archive","application/vnd.google.draco","application/x-lz4","application/vnd.openxmlformats-officedocument.presentationml.template","application/vnd.openxmlformats-officedocument.spreadsheetml.template","application/vnd.openxmlformats-officedocument.wordprocessingml.template","application/vnd.ms-excel.template.macroenabled.12","application/vnd.oasis.opendocument.text-template","application/vnd.oasis.opendocument.spreadsheet-template","application/vnd.oasis.opendocument.presentation-template","application/vnd.oasis.opendocument.graphics","application/vnd.oasis.opendocument.graphics-template","application/vnd.ms-excel.sheet.macroenabled.12","application/vnd.ms-word.document.macroenabled.12","application/vnd.ms-word.template.macroenabled.12","application/vnd.ms-powerpoint.template.macroenabled.12","application/vnd.ms-powerpoint.presentation.macroenabled.12","application/java-archive","application/vnd.rn-realmedia"]);const Ko=Object.create(null);Ko.open="0",Ko.close="1",Ko.ping="2",Ko.pong="3",Ko.message="4",Ko.upgrade="5",Ko.noop="6";const Uo=Object.create(null);Object.keys(Ko).forEach(e=>{Uo[Ko[e]]=e});const Lo={type:"error",data:"parser error"},$o="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),Ho="function"==typeof ArrayBuffer,qo=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,jo=({type:e,data:t},r,i)=>$o&&t instanceof Blob?r?i(t):Wo(t,i):Ho&&(t instanceof ArrayBuffer||qo(t))?r?i(t):Wo(new Blob([t]),i):i(Ko[e]+(t||"")),Wo=(e,t)=>{const r=new FileReader;return r.onload=function(){const e=r.result.split(",")[1];t("b"+(e||""))},r.readAsDataURL(e)};function Vo(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let Go;const Jo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Yo="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let qg=0;qg<64;qg++)Yo[Jo.charCodeAt(qg)]=qg;const Xo="function"==typeof ArrayBuffer,Zo=(e,t)=>{if("string"!=typeof e)return{type:"message",data:en(e,t)};const r=e.charAt(0);if("b"===r)return{type:"message",data:Qo(e.substring(1),t)};return Uo[r]?e.length>1?{type:Uo[r],data:e.substring(1)}:{type:Uo[r]}:Lo},Qo=(e,t)=>{if(Xo){const r=(e=>{let t,r,i,o,n,s=.75*e.length,a=e.length,c=0;"="===e[e.length-1]&&(s--,"="===e[e.length-2]&&s--);const l=new ArrayBuffer(s),d=new Uint8Array(l);for(t=0;t<a;t+=4)r=Yo[e.charCodeAt(t)],i=Yo[e.charCodeAt(t+1)],o=Yo[e.charCodeAt(t+2)],n=Yo[e.charCodeAt(t+3)],d[c++]=r<<2|i>>4,d[c++]=(15&i)<<4|o>>2,d[c++]=(3&o)<<6|63&n;return l})(e);return en(r,t)}return{base64:!0,data:e}},en=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,tn=String.fromCharCode(30);function rn(){return new TransformStream({transform(e,t){!function(e,t){$o&&e.data instanceof Blob?e.data.arrayBuffer().then(Vo).then(t):Ho&&(e.data instanceof ArrayBuffer||qo(e.data))?t(Vo(e.data)):jo(e,!1,e=>{Go||(Go=new TextEncoder),t(Go.encode(e))})}(e,r=>{const i=r.length;let o;if(i<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,i);else if(i<65536){o=new Uint8Array(3);const e=new DataView(o.buffer);e.setUint8(0,126),e.setUint16(1,i)}else{o=new Uint8Array(9);const e=new DataView(o.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(i))}e.data&&"string"!=typeof e.data&&(o[0]|=128),t.enqueue(o),t.enqueue(r)})}})}let on;function nn(e){return e.reduce((e,t)=>e+t.length,0)}function sn(e,t){if(e[0].length===t)return e.shift();const r=new Uint8Array(t);let i=0;for(let o=0;o<t;o++)r[o]=e[0][i++],i===e[0].length&&(e.shift(),i=0);return e.length&&i<e[0].length&&(e[0]=e[0].slice(i)),r}function an(e){if(e)return function(e){for(var t in an.prototype)e[t]=an.prototype[t];return e}(e)}an.prototype.on=an.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},an.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},an.prototype.off=an.prototype.removeListener=an.prototype.removeAllListeners=an.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,i=this._callbacks["$"+e];if(!i)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var o=0;o<i.length;o++)if((r=i[o])===t||r.fn===t){i.splice(o,1);break}return 0===i.length&&delete this._callbacks["$"+e],this},an.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),r=this._callbacks["$"+e],i=1;i<arguments.length;i++)t[i-1]=arguments[i];if(r){i=0;for(var o=(r=r.slice(0)).length;i<o;++i)r[i].apply(this,t)}return this},an.prototype.emitReserved=an.prototype.emit,an.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},an.prototype.hasListeners=function(e){return!!this.listeners(e).length};const cn="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),ln="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function dn(e,...t){return t.reduce((t,r)=>(e.hasOwnProperty(r)&&(t[r]=e[r]),t),{})}const un=ln.setTimeout,pn=ln.clearTimeout;function hn(e,t){t.useNativeTimers?(e.setTimeoutFn=un.bind(ln),e.clearTimeoutFn=pn.bind(ln)):(e.setTimeoutFn=ln.setTimeout.bind(ln),e.clearTimeoutFn=ln.clearTimeout.bind(ln))}function gn(e){return"string"==typeof e?function(e){let t=0,r=0;for(let i=0,o=e.length;i<o;i++)t=e.charCodeAt(i),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(i++,r+=4);return r}(e):Math.ceil(1.33*(e.byteLength||e.size))}function mn(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class fn extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}}class yn extends an{constructor(e){super(),this.writable=!1,hn(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,r){return super.emitReserved("error",new fn(e,t,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=Zo(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t}(e);return t.length?"?"+t:""}}class bn extends yn{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once("pollComplete",function(){--e||t()})),this.writable||(e++,this.once("drain",function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const r=e.split(tn),i=[];for(let o=0;o<r.length;o++){const e=Zo(r[o],t);if(i.push(e),"error"===e.type)break}return i})(e,this.socket.binaryType).forEach(e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)}),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const r=e.length,i=new Array(r);let o=0;e.forEach((e,n)=>{jo(e,!1,e=>{i[n]=e,++o===r&&t(i.join(tn))})})})(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=mn()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let wn=!1;try{wn="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(Hg){}const In=wn;function Tn(){}class Sn extends bn{constructor(e){if(super(e),"undefined"!=typeof location){const t="https:"===location.protocol;let r=location.port;r||(r=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||r!==e.port}}doWrite(e,t){const r=this.request({method:"POST",data:e});r.on("success",t),r.on("error",(e,t)=>{this.onError("xhr post error",e,t)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(e,t)=>{this.onError("xhr poll error",e,t)}),this.pollXhr=e}}let kn=class e extends an{constructor(e,t,r){super(),this.createRequest=e,hn(this,r),this._opts=r,this._method=r.method||"GET",this._uri=t,this._data=void 0!==r.data?r.data:null,this._create()}_create(){var t;const r=dn(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");r.xdomain=!!this._opts.xd;const i=this._xhr=this.createRequest(r);try{i.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){i.setDisableHeaderCheck&&i.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&i.setRequestHeader(e,this._opts.extraHeaders[e])}}catch($g){}if("POST"===this._method)try{i.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch($g){}try{i.setRequestHeader("Accept","*/*")}catch($g){}null===(t=this._opts.cookieJar)||void 0===t||t.addCookies(i),"withCredentials"in i&&(i.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(i.timeout=this._opts.requestTimeout),i.onreadystatechange=()=>{var e;3===i.readyState&&(null===(e=this._opts.cookieJar)||void 0===e||e.parseCookies(i.getResponseHeader("set-cookie"))),4===i.readyState&&(200===i.status||1223===i.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof i.status?i.status:0)},0))},i.send(this._data)}catch($g){return void this.setTimeoutFn(()=>{this._onError($g)},0)}"undefined"!=typeof document&&(this._index=e.requestsCount++,e.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(t){if(void 0!==this._xhr&&null!==this._xhr){if(this._xhr.onreadystatechange=Tn,t)try{this._xhr.abort()}catch($g){}"undefined"!=typeof document&&delete e.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};if(kn.requestsCount=0,kn.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",En);else if("function"==typeof addEventListener){addEventListener("onpagehide"in ln?"pagehide":"unload",En,!1)}function En(){for(let e in kn.requests)kn.requests.hasOwnProperty(e)&&kn.requests[e].abort()}const vn=function(){const e=An({xdomain:!1});return e&&null!==e.responseType}();function An(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||In))return new XMLHttpRequest}catch($g){}if(!t)try{return new(ln[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch($g){}}const Cn="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class xn extends yn{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,r=Cn?{}:dn(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,r)}catch(Hg){return this.emitReserved("error",Hg)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],i=t===e.length-1;jo(r,this.supportsBinary,e=>{try{this.doWrite(r,e)}catch($g){}i&&cn(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=mn()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const Rn=ln.WebSocket||ln.MozWebSocket;const Nn={websocket:class extends xn{createSocket(e,t,r){return Cn?new Rn(e,t,r):t?new Rn(e,t):new Rn(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends yn{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(Hg){return this.emitReserved("error",Hg)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=function(e,t){on||(on=new TextDecoder);const r=[];let i=0,o=-1,n=!1;return new TransformStream({transform(s,a){for(r.push(s);;){if(0===i){if(nn(r)<1)break;const e=sn(r,1);n=!(128&~e[0]),o=127&e[0],i=o<126?3:126===o?1:2}else if(1===i){if(nn(r)<2)break;const e=sn(r,2);o=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),i=3}else if(2===i){if(nn(r)<8)break;const e=sn(r,8),t=new DataView(e.buffer,e.byteOffset,e.length),n=t.getUint32(0);if(n>Math.pow(2,21)-1){a.enqueue(Lo);break}o=n*Math.pow(2,32)+t.getUint32(4),i=3}else{if(nn(r)<o)break;const e=sn(r,o);a.enqueue(Zo(n?e:on.decode(e),t)),i=0}if(0===o||o>e){a.enqueue(Lo);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),i=rn();i.readable.pipeTo(e.writable),this._writer=i.writable.getWriter();const o=()=>{r.read().then(({done:e,value:t})=>{e||(this.onPacket(t),o())}).catch(e=>{})};o();const n={type:"open"};this.query.sid&&(n.data=`{"sid":"${this.query.sid}"}`),this._writer.write(n).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],i=t===e.length-1;this._writer.write(r).then(()=>{i&&cn(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this._transport)||void 0===e||e.close()}},polling:class extends Sn{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=vn&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new kn(An,this.uri(),e)}}},_n=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Pn=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Fn(e){if(e.length>8e3)throw"URI too long";const t=e,r=e.indexOf("["),i=e.indexOf("]");-1!=r&&-1!=i&&(e=e.substring(0,r)+e.substring(r,i).replace(/:/g,";")+e.substring(i,e.length));let o=_n.exec(e||""),n={},s=14;for(;s--;)n[Pn[s]]=o[s]||"";return-1!=r&&-1!=i&&(n.source=t,n.host=n.host.substring(1,n.host.length-1).replace(/;/g,":"),n.authority=n.authority.replace("[","").replace("]","").replace(/;/g,":"),n.ipv6uri=!0),n.pathNames=function(e,t){const r=/\/{2,9}/g,i=t.replace(r,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||i.splice(0,1);"/"==t.slice(-1)&&i.splice(i.length-1,1);return i}(0,n.path),n.queryKey=function(e,t){const r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,i){t&&(r[t]=i)}),r}(0,n.query),n}const zn="function"==typeof addEventListener&&"function"==typeof removeEventListener,On=[];zn&&addEventListener("offline",()=>{On.forEach(e=>e())},!1);class Dn extends an{constructor(e,t){if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&"object"==typeof e&&(t=e,e=null),e){const r=Fn(e);t.hostname=r.host,t.secure="https"===r.protocol||"wss"===r.protocol,t.port=r.port,r.query&&(t.query=r.query)}else t.host&&(t.hostname=Fn(t.host).host);hn(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{const t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},r=e.split("&");for(let i=0,o=r.length;i<o;i++){let e=r[i].split("=");t[decodeURIComponent(e[0])]=decodeURIComponent(e[1])}return t}(this.opts.query)),zn&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},On.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const r=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](r)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const e=this.opts.rememberUpgrade&&Dn.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",e=>this._onClose("transport close",e))}onOpen(){this.readyState="open",Dn.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){const r=this.writeBuffer[t].data;if(r&&(e+=gn(r)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,cn(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,r){return this._sendPacket("message",e,t,r),this}send(e,t,r){return this._sendPacket("message",e,t,r),this}_sendPacket(e,t,r,i){if("function"==typeof t&&(i=t,t=void 0),"function"==typeof r&&(i=r,r=null),"closing"===this.readyState||"closed"===this.readyState)return;(r=r||{}).compress=!1!==r.compress;const o={type:e,data:t,options:r};this.emitReserved("packetCreate",o),this.writeBuffer.push(o),i&&this.once("flush",i),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},r=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():e()}):this.upgrading?r():e()),this}_onError(e){if(Dn.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),zn&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const e=On.indexOf(this._offlineEventListener);-1!==e&&On.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}Dn.protocol=4;class Mn extends Dn{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),r=!1;Dn.priorWebsocketSuccess=!1;const i=()=>{r||(t.send([{type:"ping",data:"probe"}]),t.once("packet",e=>{if(!r)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Dn.priorWebsocketSuccess="websocket"===t.name,this.transport.pause(()=>{r||"closed"!==this.readyState&&(l(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}}))};function o(){r||(r=!0,l(),t.close(),t=null)}const n=e=>{const r=new Error("probe error: "+e);r.transport=t.name,o(),this.emitReserved("upgradeError",r)};function s(){n("transport closed")}function a(){n("socket closed")}function c(e){t&&e.name!==t.name&&o()}const l=()=>{t.removeListener("open",i),t.removeListener("error",n),t.removeListener("close",s),this.off("close",a),this.off("upgrading",c)};t.once("open",i),t.once("error",n),t.once("close",s),this.once("close",a),this.once("upgrading",c),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn(()=>{r||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let r=0;r<e.length;r++)~this.transports.indexOf(e[r])&&t.push(e[r]);return t}}let Bn=class extends Mn{constructor(e,t={}){const r="object"==typeof e?e:t;(!r.transports||r.transports&&"string"==typeof r.transports[0])&&(r.transports=(r.transports||["polling","websocket","webtransport"]).map(e=>Nn[e]).filter(e=>!!e)),super(e,r)}};const Kn="function"==typeof ArrayBuffer,Un=Object.prototype.toString,Ln="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Un.call(Blob),$n="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Un.call(File);function Hn(e){return Kn&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||Ln&&e instanceof Blob||$n&&e instanceof File}function qn(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if(qn(e[t]))return!0;return!1}if(Hn(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return qn(e.toJSON(),!0);for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&qn(e[r]))return!0;return!1}function jn(e){const t=[],r=e.data,i=e;return i.data=Wn(r,t),i.attachments=t.length,{packet:i,buffers:t}}function Wn(e,t){if(!e)return e;if(Hn(e)){const r={_placeholder:!0,num:t.length};return t.push(e),r}if(Array.isArray(e)){const r=new Array(e.length);for(let i=0;i<e.length;i++)r[i]=Wn(e[i],t);return r}if("object"==typeof e&&!(e instanceof Date)){const r={};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=Wn(e[i],t));return r}return e}function Vn(e,t){return e.data=Gn(e.data,t),delete e.attachments,e}function Gn(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let r=0;r<e.length;r++)e[r]=Gn(e[r],t);else if("object"==typeof e)for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=Gn(e[r],t));return e}const Jn=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Yn,Xn;(Xn=Yn||(Yn={}))[Xn.CONNECT=0]="CONNECT",Xn[Xn.DISCONNECT=1]="DISCONNECT",Xn[Xn.EVENT=2]="EVENT",Xn[Xn.ACK=3]="ACK",Xn[Xn.CONNECT_ERROR=4]="CONNECT_ERROR",Xn[Xn.BINARY_EVENT=5]="BINARY_EVENT",Xn[Xn.BINARY_ACK=6]="BINARY_ACK";function Zn(e){return"[object Object]"===Object.prototype.toString.call(e)}class Qn extends an{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const r=t.type===Yn.BINARY_EVENT;r||t.type===Yn.BINARY_ACK?(t.type=r?Yn.EVENT:Yn.ACK,this.reconstructor=new es(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!Hn(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const r={type:Number(e.charAt(0))};if(void 0===Yn[r.type])throw new Error("unknown packet type "+r.type);if(r.type===Yn.BINARY_EVENT||r.type===Yn.BINARY_ACK){const i=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const o=e.substring(i,t);if(o!=Number(o)||"-"!==e.charAt(t))throw new Error("Illegal attachments");r.attachments=Number(o)}if("/"===e.charAt(t+1)){const i=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}r.nsp=e.substring(i,t)}else r.nsp="/";const i=e.charAt(t+1);if(""!==i&&Number(i)==i){const i=t+1;for(;++t;){const r=e.charAt(t);if(null==r||Number(r)!=r){--t;break}if(t===e.length)break}r.id=Number(e.substring(i,t+1))}if(e.charAt(++t)){const i=this.tryParse(e.substr(t));if(!Qn.isPayloadValid(r.type,i))throw new Error("invalid payload");r.data=i}return r}tryParse(e){try{return JSON.parse(e,this.reviver)}catch($g){return!1}}static isPayloadValid(e,t){switch(e){case Yn.CONNECT:return Zn(t);case Yn.DISCONNECT:return void 0===t;case Yn.CONNECT_ERROR:return"string"==typeof t||Zn(t);case Yn.EVENT:case Yn.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===Jn.indexOf(t[0]));case Yn.ACK:case Yn.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class es{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=Vn(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const ts=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Qn,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==Yn.EVENT&&e.type!==Yn.ACK||!qn(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===Yn.EVENT?Yn.BINARY_EVENT:Yn.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==Yn.BINARY_EVENT&&e.type!==Yn.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=jn(e),r=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(r),i}},get PacketType(){return Yn},protocol:5},Symbol.toStringTag,{value:"Module"}));function rs(e,t,r){return e.on(t,r),function(){e.off(t,r)}}const is=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class os extends an{constructor(e,t,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[rs(e,"open",this.onopen.bind(this)),rs(e,"packet",this.onpacket.bind(this)),rs(e,"error",this.onerror.bind(this)),rs(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var r,i,o;if(is.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const n={type:Yn.EVENT,data:t,options:{}};if(n.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,r=t.pop();this._registerAckCallback(e,r),n.id=e}const s=null===(i=null===(r=this.io.engine)||void 0===r?void 0:r.transport)||void 0===i?void 0:i.writable,a=this.connected&&!(null===(o=this.io.engine)||void 0===o?void 0:o._hasPingExpired());return this.flags.volatile&&!s||(a?(this.notifyOutgoingListeners(n),this.packet(n)):this.sendBuffer.push(n)),this.flags={},this}_registerAckCallback(e,t){var r;const i=null!==(r=this.flags.timeout)&&void 0!==r?r:this._opts.ackTimeout;if(void 0===i)return void(this.acks[e]=t);const o=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))},i),n=(...e)=>{this.io.clearTimeoutFn(o),t.apply(this,e)};n.withError=!0,this.acks[e]=n}emitWithAck(e,...t){return new Promise((r,i)=>{const o=(e,t)=>e?i(e):r(t);o.withError=!0,t.push(o),this.emit(e,...t)})}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...i)=>{if(r!==this._queue[0])return;return null!==e?r.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...i)),r.pending=!1,this._drainQueue()}),this._queue.push(r),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Yn.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){const t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Yn.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Yn.EVENT:case Yn.BINARY_EVENT:this.onevent(e);break;case Yn.ACK:case Yn.BINARY_ACK:this.onack(e);break;case Yn.DISCONNECT:this.ondisconnect();break;case Yn.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const r of t)r.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let r=!1;return function(...i){r||(r=!0,t.packet({type:Yn.ACK,id:e,data:i}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Yn.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const r of t)r.apply(this,e.data)}}}function ns(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}ns.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*e);e=1&Math.floor(10*t)?e+r:e-r}return 0|Math.min(e,this.max)},ns.prototype.reset=function(){this.attempts=0},ns.prototype.setMin=function(e){this.ms=e},ns.prototype.setMax=function(e){this.max=e},ns.prototype.setJitter=function(e){this.jitter=e};class ss extends an{constructor(e,t){var r;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,hn(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(r=t.randomizationFactor)&&void 0!==r?r:.5),this.backoff=new ns({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const i=t.parser||ts;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new Bn(this.uri,this.opts);const t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const i=rs(t,"open",function(){r.onopen(),e&&e()}),o=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},n=rs(t,"error",o);if(!1!==this._timeout){const e=this._timeout,r=this.setTimeoutFn(()=>{i(),o(new Error("timeout")),t.close()},e);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}return this.subs.push(i),this.subs.push(n),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(rs(e,"ping",this.onping.bind(this)),rs(e,"data",this.ondata.bind(this)),rs(e,"error",this.onerror.bind(this)),rs(e,"close",this.onclose.bind(this)),rs(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch($g){this.onclose("parse error",$g)}}ondecoded(e){cn(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new os(this,e,t),this.nsps[e]=r),r}_destroy(e){const t=Object.keys(this.nsps);for(const r of t){if(this.nsps[r].active)return}this._close()}_packet(e){const t=this.encoder.encode(e);for(let r=0;r<t.length;r++)this.engine.write(t[r],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var r;this.cleanup(),null===(r=this.engine)||void 0===r||r.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()}))},t);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const as={};function cs(e,t){"object"==typeof e&&(t=e,e=void 0);const r=function(e,t="",r){let i=e;r=r||"undefined"!=typeof location&&location,null==e&&(e=r.protocol+"//"+r.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?r.protocol+e:r.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==r?r.protocol+"//"+e:"https://"+e),i=Fn(e)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";const o=-1!==i.host.indexOf(":")?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+o+":"+i.port+t,i.href=i.protocol+"://"+o+(r&&r.port===i.port?"":":"+i.port),i}(e,(t=t||{}).path||"/socket.io"),i=r.source,o=r.id,n=r.path,s=as[o]&&n in as[o].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||s?a=new ss(i,t):(as[o]||(as[o]=new ss(i,t)),a=as[o]),r.query&&!t.query&&(t.query=r.queryKey),a.socket(r.path,t)}Object.assign(cs,{Manager:ss,Socket:os,io:cs,connect:cs});const ls=class e{constructor(e){if(ne(this,"client"),ne(this,"config"),ne(this,"logger",si.getInstance()),ne(this,"socket",null),ne(this,"socketConnected",!1),ne(this,"connectionMode","auto"),ne(this,"wsBaseUrl",null),this.config=e,!e.apiKey)throw new ai("API key is required");if(!e.network)throw new ai("Network is required");const t={"x-api-key":e.apiKey,"Content-Type":"application/json"};this.client=$r.create({baseURL:"https://v2-api.tier.bot/api",headers:t}),this.logger=si.getInstance(),e.wsBaseUrl&&(this.wsBaseUrl=e.wsBaseUrl),this.connectionMode=e.connectionMode||"websocket",this.wsBaseUrl||"http"===this.connectionMode||this.fetchWebSocketServers().catch(e=>this.logger.warn("Failed to fetch WebSocket servers:",e))}async getFileMetadata(e){try{const t=await $r.get(e),r=t.headers["content-type"]||"";return{size:parseInt(t.headers["content-length"]||"0",10),mimeType:r}}catch(t){throw this.logger.error("Error fetching file metadata:",t),new ai("Unable to fetch file metadata")}}getMimeType(t){const r=t.toLowerCase().split(".").pop();if(!r)throw new ai("File must have an extension");const i=e.VALID_MIME_TYPES[r];if(!i)throw new ai(`Unsupported file type: ${r}`);return i}validateRequest(t){if(this.logger.debug("Validating request:",t),!t.holderId||""===t.holderId.trim())throw this.logger.warn("holderId is missing or empty"),new ai("holderId is required");if(!e.VALID_MODES.includes(t.mode))throw new ai(`Invalid mode: ${t.mode}. Must be one of: ${e.VALID_MODES.join(", ")}`);if("hashinal"===t.mode&&!t.jsonFileURL&&!t.metadataObject)throw new ai("Hashinal mode requires either jsonFileURL or metadataObject");if(t.onlyJSONCollection&&"hashinal-collection"!==t.mode)throw new ai("onlyJSONCollection can only be used with hashinal-collection mode");this.validateFileInput(t.file)}normalizeMimeType(e){return"image/vnd.microsoft.icon"===e?(this.logger.debug("Normalizing MIME type from image/vnd.microsoft.icon to image/x-icon"),"image/x-icon"):e}validateMimeType(t){return!!Object.values(e.VALID_MIME_TYPES).includes(t)||"image/vnd.microsoft.icon"===t&&(this.logger.debug("Accepting alternative MIME type for ICO: image/vnd.microsoft.icon"),!0)}validateFileInput(t){if("base64"===t.type){if(!t.base64)throw new ai("Base64 data is required");const r=t.base64.replace(/^data:.*?;base64,/,"");if(Math.ceil(.75*r.length)>e.MAX_BASE64_SIZE)throw new ai(`File size exceeds maximum limit of ${e.MAX_BASE64_SIZE/1024/1024}MB`);const i=t.mimeType||this.getMimeType(t.fileName);if(!this.validateMimeType(i))throw new ai("File must have one of the supported MIME types");"image/vnd.microsoft.icon"===t.mimeType&&(t.mimeType=this.normalizeMimeType(t.mimeType))}else if("url"===t.type&&!t.url)throw new ai("URL is required")}async detectMimeTypeFromBase64(e){if(e.startsWith("data:")){const t=e.match(/^data:([^;]+);base64,/);if(t&&t.length>1)return t[1]}try{const t=e.replace(/\s/g,""),r=ye.from(t,"base64"),i=await async function(e,t){return new Bo(t).fromBuffer(e)}(r);return(null==i?void 0:i.mime)||"application/octet-stream"}catch(Hg){return this.logger.warn("Failed to detect MIME type from buffer"),"application/octet-stream"}}async startInscription(t){var r,i;try{this.validateRequest(t);let r=t.file.mimeType;if("url"===t.file.type){const i=await this.getFileMetadata(t.file.url);if(r=i.mimeType||r,i.size>e.MAX_URL_FILE_SIZE)throw new ai(`File size exceeds maximum URL file limit of ${e.MAX_URL_FILE_SIZE/1024/1024}MB`)}else"base64"===t.file.type&&(r=await this.detectMimeTypeFromBase64(t.file.base64));if("image/vnd.microsoft.icon"===r&&(r=this.normalizeMimeType(r)),t.jsonFileURL){if("application/json"!==(await this.getFileMetadata(t.jsonFileURL)).mimeType)throw new ai("JSON file must be of type application/json")}const i={holderId:t.holderId,mode:t.mode,network:this.config.network,onlyJSONCollection:t.onlyJSONCollection?1:0,creator:t.creator,description:t.description,fileStandard:t.fileStandard,metadataObject:t.metadataObject,jsonFileURL:t.jsonFileURL};let o;return o="url"===t.file.type?await this.client.post("/inscriptions/start-inscription",{...i,fileURL:t.file.url}):await this.client.post("/inscriptions/start-inscription",{...i,fileBase64:t.file.base64,fileName:t.file.fileName,fileMimeType:r||this.getMimeType(t.file.fileName)}),o.data}catch(o){if(o instanceof ai)throw o;if($r.isAxiosError(o))throw new Error((null==(i=null==(r=o.response)?void 0:r.data)?void 0:i.message)||"Failed to start inscription");throw o}}async executeTransaction(e,t){var r,o;try{const n="mainnet"===t.network?i.Client.forMainnet():i.Client.forTestnet(),a=new s.HederaMirrorNode(t.network),c=await a.requestAccount(t.accountId),l=null==(r=null==c?void 0:c.key)?void 0:r._type,d="string"==typeof t.privateKey;let u;if(l&&d)u=(null==(o=null==l?void 0:l.toLowerCase())?void 0:o.includes("ecdsa"))?i.PrivateKey.fromStringECDSA(t.privateKey):i.PrivateKey.fromStringED25519(t.privateKey);else if(!l&&d){const e=d?s.detectKeyTypeFromString(t.privateKey):void 0;u="ed25519"===(null==e?void 0:e.detectedType)?i.PrivateKey.fromStringED25519(t.privateKey):i.PrivateKey.fromStringECDSA(t.privateKey)}else u=t.privateKey;n.setOperator(t.accountId,u);const p=i.TransferTransaction.fromBytes(ye.from(e,"base64")),h=await p.sign(u),g=await h.execute(n),m=(await g.getReceipt(n)).status.toString();if("SUCCESS"!==m)throw new Error(`Transaction failed with status: ${m}`);return g.transactionId.toString()}catch(n){throw new Error(`Failed to execute transaction: ${n instanceof Error?n.message:"Unknown error"}`)}}async executeTransactionWithSigner(e,t){try{const r=i.TransferTransaction.fromBytes(ye.from(e,"base64")),o=await r.executeWithSigner(t),n=(await o.getReceiptWithSigner(t)).status.toString();if("SUCCESS"!==n)throw new Error(`Transaction failed with status: ${n}`);return o.transactionId.toString()}catch(r){throw new Error(`Failed to execute transaction: ${r instanceof Error?r.message:"Unknown error"}`)}}async inscribeAndExecute(e,t,r,i){const o=(null==i?void 0:i.waitForCompletion)??!0,n=(null==i?void 0:i.maxWaitTime)??12e4,s=(null==i?void 0:i.checkInterval)??2e3;if(this.logger.debug("inscribeAndExecute called",{hasProgressCallback:!!r,connectionMode:this.connectionMode,wsBaseUrl:this.wsBaseUrl}),"http"!==this.connectionMode){const i="websocket"===this.connectionMode||"auto"===this.connectionMode&&await this.detectBestConnection();if(i)try{return await this.inscribeViaWebSocket(e,t,r)}catch(d){throw this.logger.error("WebSocket inscription failed, falling back to HTTP:",d),d}else this.logger.info(`Not using WebSocket: useWebSocket=${i}, wsBaseUrl=${this.wsBaseUrl}`)}else this.logger.info(`Not using WebSocket: hasCallback=${!!r}, connectionMode=${this.connectionMode}`);const a=await this.startInscription(e);if(!a.transactionBytes)throw this.logger.error("No transaction bytes returned from inscription request",a),new Error("No transaction bytes returned from inscription request");this.logger.info("executing transaction");const c=await this.executeTransaction(a.transactionBytes,t),l={jobId:a.tx_id,transactionId:c};if(o){r&&r({stage:"confirming",message:"Transaction executed, waiting for inscription to complete",progressPercent:5});const e=Math.floor(n/s),t=await this.waitForInscription(c,e,s,!0,r);return{...l,topicId:t.topic_id,status:t.status,completed:t.completed}}return l}async fetchWebSocketServers(){try{const e=await this.client.get("/inscriptions/websocket-servers"),{servers:t,recommended:r}=e.data;if(r)this.wsBaseUrl=r;else if(t&&t.length>0){const e=t.filter(e=>"active"===e.status);if(e.length>0){const t=e[0];this.wsBaseUrl=t.url}}}catch(e){this.logger.debug("Could not fetch WebSocket servers, will use HTTP only")}}async detectBestConnection(){if(!this.wsBaseUrl)return!1;try{const e=cs(this.wsBaseUrl,{auth:{apiKey:this.config.apiKey},transports:["websocket"],timeout:3e3});return new Promise(t=>{const r=setTimeout(()=>{e.disconnect(),t(!1)},3e3);e.on("connect",()=>{clearTimeout(r),e.disconnect(),t(!0)}),e.on("connect_error",()=>{clearTimeout(r),e.disconnect(),t(!1)})})}catch($g){return!1}}async inscribeViaWebSocket(e,t,r){if(!this.wsBaseUrl){const e=(await this.client.get("/inscriptions/websocket-servers")).data.recommended;if(!e)throw new Error("No WebSocket servers available");this.wsBaseUrl=e}return await this.connectWebSocket(),new Promise((i,o)=>{if(!this.socket)return o(new Error("WebSocket not connected"));let n,s,a,c;const l=()=>{var e,t,r;c&&clearTimeout(c),null==(e=this.socket)||e.off("inscription-progress",p),null==(t=this.socket)||t.off("inscription-complete",d),null==(r=this.socket)||r.off("inscription-error",u)};c=setTimeout(()=>{this.logger.error("WebSocket inscription timeout after 60 seconds",{jobId:n,transactionId:s,lastTopicId:a}),l(),i({jobId:n,transactionId:s,topicId:a,topic_id:a,status:"timeout",completed:!1})},6e4);const d=e=>{l(),i({jobId:n,transactionId:s,topicId:e.topicId||e.topic_id,topic_id:e.topicId||e.topic_id,status:"completed",completed:!0})},u=e=>{l(),o(new Error(e.error||"Inscription failed"))},p=e=>{this.logger.debug("Progress event received:",{jobId:e.jobId,status:e.status,progress:e.progress,topicId:e.topicId||e.topic_id,topic_id:e.topicId||e.topic_id}),(e.topicId||e.topic_id)&&(a=e.topicId||e.topic_id),r&&r({stage:"completed"===e.status?"completed":"confirming",message:`Processing inscription: ${e.status}`,progressPercent:e.progress||0,details:e}),"completed"!==e.status&&100!==e.progress||(this.logger.info("Inscription completed via progress handler",{status:e.status,progress:e.progress,topicId:e.topicId||e.topic_id||a,topic_id:e.topicId||e.topic_id||a}),l(),i({jobId:n,transactionId:s,topicId:e.topicId||e.topic_id||a,topic_id:e.topicId||e.topic_id||a,status:"completed",completed:!0}))};this.socket.on("inscription-progress",p),this.socket.on("inscription-complete",d),this.socket.on("inscription-error",u),this.socket.emit("start-inscription",{...e,network:this.config.network},async e=>{if(!e.success)return l(),o(new Error(e.error||"Inscription failed"));try{if(!e.transactionBytes)throw new Error("No transaction bytes returned from WebSocket inscription");if(s=await this.executeTransaction(e.transactionBytes,t),n=e.jobId||e.tx_id,!n)throw new Error("No job ID returned from WebSocket inscription");r&&r({stage:"confirming",message:"Transaction executed, inscribing to HCS...",progressPercent:5}),this.logger.info("Transaction executed, waiting for inscription completion...",{jobId:n,transactionId:s})}catch(i){l(),o(i)}})})}async connectWebSocket(){if(!this.socketConnected||!this.socket){if(!this.wsBaseUrl)throw new Error("WebSocket URL not configured");return new Promise((e,t)=>{this.socket=cs(this.wsBaseUrl,{auth:{apiKey:this.config.apiKey},transports:["websocket","polling"]});const r=setTimeout(()=>{t(new Error("WebSocket connection timeout"))},1e4);this.socket.on("connect",()=>{clearTimeout(r),this.socketConnected=!0,this.logger.info("WebSocket connected"),e()}),this.socket.on("connect_error",e=>{clearTimeout(r),this.socketConnected=!1,t(new Error(`WebSocket connection failed: ${e.message}`))}),this.socket.on("disconnect",()=>{this.socketConnected=!1,this.logger.info("WebSocket disconnected")})})}}disconnect(){this.socket&&(this.socket.disconnect(),this.socket=null,this.socketConnected=!1)}async inscribe(e,t){const r=await this.startInscription(e);if(!r.transactionBytes)throw this.logger.error("No transaction bytes returned from inscription request",r),new Error("No transaction bytes returned from inscription request");this.logger.info("executing transaction");const i=await this.executeTransactionWithSigner(r.transactionBytes,t);return{jobId:r.tx_id,transactionId:i}}async retryWithBackoff(e,t=3,r=1e3){for(let o=0;o<t;o++)try{return await e()}catch(i){if(o===t-1)throw i;const e=r*Math.pow(2,o);await new Promise(t=>setTimeout(t,e)),this.logger.debug(`Retry attempt ${o+1}/${t} after ${e}ms delay`)}throw new Error("Retry operation failed")}async retrieveInscription(e){if(!e)throw new ai("Transaction ID is required");try{const t=e.includes("@")?`${e.split("@")[0]}-${e.split("@")[1].replace(/\./g,"-")}`:e;return await this.retryWithBackoff(async()=>{const e=(await this.client.get(`/inscriptions/retrieve-inscription?id=${t}`)).data;return{...e,jobId:e.id}})}catch(t){throw this.logger.error("Failed to retrieve inscription:",t),t}}async getInscriptionNumbers(e={}){try{return(await this.client.get("/inscriptions/numbers",{params:e})).data}catch(t){throw this.logger.error("Failed to fetch inscription numbers:",t),t}}static async authenticate(e){return new ci(e).authenticate()}static async createWithAuth(t){const r="client"===t.type?new li({...t,logger:si.getInstance()}):new ci(t),{apiKey:i}=await r.authenticate();return new e({apiKey:i,network:t.network||"mainnet",wsBaseUrl:t.wsBaseUrl,connectionMode:t.connectionMode||"websocket"})}async waitForInscription(e,t=30,r=4e3,i=!1,o){var n;let s=0,a=0;const c=(r,i,n,c)=>{if(o)try{a=Math.max(a,n),o({stage:r,message:i,progressPercent:a,details:{...c,txId:e,currentAttempt:s,maxAttempts:t}})}catch(Hg){this.logger.warn(`Error in progress callback: ${Hg}`)}};for(c("confirming","Starting inscription verification",0);s<t;){c("confirming",`Verifying inscription status (attempt ${s+1}/${t})`,5,{attempt:s+1});const o=await this.retrieveInscription(e);if(o.error)throw c("verifying",`Error: ${o.error}`,100,{error:o.error}),new Error(o.error);let a=5;void 0!==o.messages&&void 0!==o.maxMessages&&o.maxMessages>0?(a=Math.min(95,5+o.messages/o.maxMessages*90),o.completed&&(a=100)):"processing"===o.status?a=10:o.completed&&(a=100),c(o.completed?"completed":"confirming",o.completed?"Inscription completed successfully":`Processing inscription (${o.status})`,a,{status:o.status,messagesProcessed:o.messages,maxMessages:o.maxMessages,messageCount:o.messages,completed:o.completed,confirmedMessages:o.confirmedMessages,result:o});const l="hashinal"===o.mode,d="hashinal-collection"===o.mode,u="6"===(null==(n=o.fileStandard)?void 0:n.toString());if(d&&o.completed&&(!i||o.completed))return c("completed","Inscription verification complete",100,{result:o}),o;if(l&&o.topic_id&&o.jsonTopicId&&(!i||o.completed))return c("completed","Inscription verification complete",100,{result:o}),o;if(!l&&!u&&o.topic_id&&(!i||o.completed))return c("completed","Inscription verification complete",100,{result:o}),o;if(u&&o.topic_id&&o.jsonTopicId&&o.registryTopicId&&(!i||o.completed))return c("completed","Inscription verification complete",100,{result:o}),o;await new Promise(e=>setTimeout(e,r)),s++}throw c("verifying",`Inscription ${e} did not complete within ${t} attempts`,100,{timedOut:!0}),new Error(`Inscription ${e} did not complete within ${t} attempts`)}async getHolderInscriptions(e){var t,r;if(!e.holderId)throw new ai("Holder ID is required");try{const t={holderId:e.holderId};e.includeCollections&&(t.includeCollections="1");return(await this.client.get("/inscriptions/holder-inscriptions",{params:t})).data}catch(i){if(this.logger.error("Failed to fetch holder inscriptions:",i),$r.isAxiosError(i))throw new Error((null==(r=null==(t=i.response)?void 0:t.data)?void 0:r.message)||"Failed to fetch holder inscriptions");throw i}}};ne(ls,"VALID_MODES",["file","upload","hashinal","hashinal-collection"]),ne(ls,"MAX_BASE64_SIZE",2097152),ne(ls,"MAX_URL_FILE_SIZE",104857600),ne(ls,"VALID_MIME_TYPES",{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",ico:"image/x-icon",heic:"image/heic",heif:"image/heif",bmp:"image/bmp",webp:"image/webp",tiff:"image/tiff",tif:"image/tiff",svg:"image/svg+xml",mp4:"video/mp4",webm:"video/webm",mp3:"audio/mpeg",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",html:"text/html",htm:"text/html",css:"text/css",php:"application/x-httpd-php",java:"text/x-java-source",js:"application/javascript",mjs:"application/javascript",csv:"text/csv",json:"application/json",txt:"text/plain",glb:"model/gltf-binary",wav:"audio/wav",ogg:"audio/ogg",oga:"audio/ogg",flac:"audio/flac",aac:"audio/aac",m4a:"audio/mp4",avi:"video/x-msvideo",mov:"video/quicktime",mkv:"video/x-matroska",m4v:"video/mp4",mpg:"video/mpeg",mpeg:"video/mpeg",ts:"application/typescript",zip:"application/zip",rar:"application/vnd.rar",tar:"application/x-tar",gz:"application/gzip","7z":"application/x-7z-compressed",xml:"application/xml",yaml:"application/yaml",yml:"application/yaml",md:"text/markdown",markdown:"text/markdown",rtf:"application/rtf",gltf:"model/gltf+json",usdz:"model/vnd.usdz+zip",obj:"model/obj",stl:"model/stl",fbx:"application/octet-stream",ttf:"font/ttf",otf:"font/otf",woff:"font/woff",woff2:"font/woff2",eot:"application/vnd.ms-fontobject",psd:"application/vnd.adobe.photoshop",ai:"application/postscript",eps:"application/postscript",ps:"application/postscript",sqlite:"application/x-sqlite3",db:"application/x-sqlite3",apk:"application/vnd.android.package-archive",ics:"text/calendar",vcf:"text/vcard",py:"text/x-python",rb:"text/x-ruby",go:"text/x-go",rs:"text/x-rust",typescript:"application/typescript",jsx:"text/jsx",tsx:"text/tsx",sql:"application/sql",toml:"application/toml",avif:"image/avif",jxl:"image/jxl",weba:"audio/webm",wasm:"application/wasm"});let ds=ls;class us{constructor(e={}){this.module=e.module||"Progress",this.callback=e.callback,this.logger=e.logger||new O({level:"info",module:"ProgressReporter"}),this.logProgress=e.logProgress??!0,this.minPercent=e.minPercent??0,this.maxPercent=e.maxPercent??100,this.lastReportedPercent=-1,this.lastReportedTime=0,this.throttleMs=100}static getInstance(e={}){return us.instance?(e.callback&&us.instance.setCallback(e.callback),e.module&&us.instance.setModule(e.module),e.logger&&us.instance.setLogger(e.logger),void 0!==e.minPercent&&us.instance.setMinPercent(e.minPercent),void 0!==e.maxPercent&&us.instance.setMaxPercent(e.maxPercent)):us.instance=new us(e),us.instance}setCallback(e){this.callback=e}setModule(e){this.module=e}setLogger(e){this.logger=e}setMinPercent(e){this.minPercent=e}setMaxPercent(e){this.maxPercent=e}createSubProgress(e){const t=new us({module:this.module,logger:this.logger,logProgress:this.logProgress,minPercent:e.minPercent,maxPercent:e.maxPercent}),r=e.logPrefix||"";return t.setCallback(t=>{const i=this.scalePercent(t.progressPercent,e.minPercent,e.maxPercent);let o=t.message;r&&!o.startsWith(r)&&(o=`${r}: ${o}`),this.report({stage:t.stage,message:o,progressPercent:i,details:t.details})}),t}report(e){const t=e.progressPercent,r=Math.max(0,Math.min(100,t)),i=this.scalePercent(r,0,100),o=Date.now();if(i===this.lastReportedPercent&&o-this.lastReportedTime<this.throttleMs&&"completed"!==e.stage&&"failed"!==e.stage)return;this.lastReportedPercent=i,this.lastReportedTime=o;const n={...e,progressPercent:i};if(this.logProgress&&this.logger.debug(`[${this.module}] [${e.stage.toUpperCase()}] ${e.message} (${i.toFixed(1)}%)`,e.details),this.callback)try{this.callback(n)}catch(Hg){this.logger.warn(`Error in progress callback: ${Hg}`)}}scalePercent(e,t,r){const i=(this.maxPercent-this.minPercent)/(r-t);return this.minPercent+(e-t)*i}preparing(e,t,r){this.report({stage:"preparing",message:e,progressPercent:t,details:r})}submitting(e,t,r){this.report({stage:"submitting",message:e,progressPercent:t,details:r})}confirming(e,t,r){this.report({stage:"confirming",message:e,progressPercent:t,details:r})}verifying(e,t,r){this.report({stage:"verifying",message:e,progressPercent:t,details:r})}completed(e,t){this.report({stage:"completed",message:e,progressPercent:100,details:t})}failed(e,t){this.report({stage:"failed",message:e,progressPercent:this.lastReportedPercent,details:t})}}class ps extends Error{constructor(e,t="PARSING_FAILED",r,i){super(e),this.name="TransactionParsingError",this.code=t,this.originalError=r,this.transactionBytes=i,Error.captureStackTrace&&Error.captureStackTrace(this,ps)}}const hs=(e,t)=>e.replace(/\{([^}]+)\}/g,(e,r)=>{const i=((e,t)=>{const r=t.split(".");let i=e;for(const o of r){if(null==i)return;i=i[o]}return i})(t,String(r).trim());return null==i?"(Unknown)":String(i)}),gs=e=>{const t=[],r=[];if(Array.isArray(e.transfers))for(const i of e.transfers){const e=parseFloat(i.amount);let o=i.amount;o.startsWith("-")&&(o=o.substring(1)),o=o.replace(/\s*ℏ$/,""),e<0?t.push(`${i.accountId} (${o} ℏ)`):e>0&&r.push(`${i.accountId} (${o} ℏ)`)}return t.length>0&&r.length>0?`Transfer of HBAR from ${t.join(", ")} to ${r.join(", ")}`:e.humanReadableType},ms=e=>{if(!e.contractCall)return e.humanReadableType;let t=`Contract call to ${e.contractCall.contractId} with ${e.contractCall.gas} gas`;return e.contractCall.amount>0&&(t+=` and ${e.contractCall.amount} HBAR`),e.contractCall.functionName&&(t+=` calling function ${e.contractCall.functionName}`),t},fs=e=>e.tokenMint?`Mint ${e.tokenMint.amount} tokens for token ${e.tokenMint.tokenId}`:e.humanReadableType,ys=e=>e.tokenBurn?`Burn ${e.tokenBurn.amount} tokens for token ${e.tokenBurn.tokenId}`:e.humanReadableType,bs=e=>{if(!e.tokenCreation)return e.humanReadableType;let t=`Create token ${e.tokenCreation.tokenName||"(No Name)"} (${e.tokenCreation.tokenSymbol||"(No Symbol)"})`;return e.tokenCreation.initialSupply&&(t+=` with initial supply ${e.tokenCreation.initialSupply}`),e.tokenCreation.customFees&&e.tokenCreation.customFees.length>0&&(t+=` including ${e.tokenCreation.customFees.length} custom fee(s)`),t},ws=e=>{if(!e.consensusCreateTopic)return e.humanReadableType;let t="Create new topic";return e.consensusCreateTopic.memo&&(t+=` with memo "${e.consensusCreateTopic.memo}"`),e.consensusCreateTopic.autoRenewAccountId&&(t+=`, auto-renew by ${e.consensusCreateTopic.autoRenewAccountId}`),t},Is=e=>{if(!e.consensusSubmitMessage)return e.humanReadableType;let t="Submit message";if(e.consensusSubmitMessage.topicId&&(t+=` to topic ${e.consensusSubmitMessage.topicId}`),e.consensusSubmitMessage.message)if("utf8"===e.consensusSubmitMessage.messageEncoding){t+=`: "${e.consensusSubmitMessage.message.substring(0,70)}${e.consensusSubmitMessage.message.length>70?"...":""}"`}else{t+=` (binary message data, length: ${globalThis.Buffer.from(e.consensusSubmitMessage.message,"base64").length} bytes)`}return e.consensusSubmitMessage.chunkInfoNumber&&e.consensusSubmitMessage.chunkInfoTotal&&(t+=` (chunk ${e.consensusSubmitMessage.chunkInfoNumber}/${e.consensusSubmitMessage.chunkInfoTotal})`),t},Ts=e=>{if(!e.fileCreate)return e.humanReadableType;let t="Create File";return e.fileCreate.memo&&(t+=` with memo "${e.fileCreate.memo}"`),e.fileCreate.contents&&(t+=" (includes content)"),t},Ss=e=>e.fileAppend?`Append to File ${e.fileAppend.fileId||"(Unknown ID)"}`:e.humanReadableType,ks=e=>e.fileUpdate?`Update File ${e.fileUpdate.fileId||"(Unknown ID)"}`:e.humanReadableType,Es=e=>e.fileDelete?`Delete File ${e.fileDelete.fileId||"(Unknown ID)"}`:e.humanReadableType,vs=e=>e.consensusUpdateTopic?`Update Topic ${e.consensusUpdateTopic.topicId||"(Unknown ID)"}`:e.humanReadableType,As=e=>e.consensusDeleteTopic?`Delete Topic ${e.consensusDeleteTopic.topicId||"(Unknown ID)"}`:e.humanReadableType,Cs=e=>e.tokenFreeze?`Freeze Token ${e.tokenFreeze.tokenId} for Account ${e.tokenFreeze.accountId}`:e.humanReadableType,xs=e=>e.tokenUnfreeze?`Unfreeze Token ${e.tokenUnfreeze.tokenId} for Account ${e.tokenUnfreeze.accountId}`:e.humanReadableType,Rs=e=>e.tokenGrantKyc?`Grant KYC for Token ${e.tokenGrantKyc.tokenId} to Account ${e.tokenGrantKyc.accountId}`:e.humanReadableType,Ns=e=>e.tokenRevokeKyc?`Revoke KYC for Token ${e.tokenRevokeKyc.tokenId} from Account ${e.tokenRevokeKyc.accountId}`:e.humanReadableType,_s=e=>e.tokenPause?`Pause Token ${e.tokenPause.tokenId}`:e.humanReadableType,Ps=e=>e.tokenUnpause?`Unpause Token ${e.tokenUnpause.tokenId}`:e.humanReadableType,Fs=e=>{if(e.tokenWipeAccount){let t=`Wipe Token ${e.tokenWipeAccount.tokenId} from Account ${e.tokenWipeAccount.accountId}`;return e.tokenWipeAccount.serialNumbers&&e.tokenWipeAccount.serialNumbers.length>0&&(t+=` (Serials: ${e.tokenWipeAccount.serialNumbers.join(", ")})`),e.tokenWipeAccount.amount&&(t+=` (Amount: ${e.tokenWipeAccount.amount})`),t}return e.humanReadableType},zs=e=>e.tokenDelete?`Delete Token ${e.tokenDelete.tokenId}`:e.humanReadableType,Os=e=>e.tokenAssociate?`Associate Account ${e.tokenAssociate.accountId} with Tokens: ${(e.tokenAssociate.tokenIds||[]).join(", ")}`:e.humanReadableType,Ds=e=>e.tokenDissociate?`Dissociate Account ${e.tokenDissociate.accountId} from Tokens: ${(e.tokenDissociate.tokenIds||[]).join(", ")}`:e.humanReadableType,Ms=e=>e.cryptoDelete?`Delete Account ${e.cryptoDelete.deleteAccountId}`:e.humanReadableType,Bs=e=>{if(!e.cryptoCreateAccount)return e.humanReadableType;let t="Create Account";return e.cryptoCreateAccount.initialBalance&&"0"!==e.cryptoCreateAccount.initialBalance&&(t+=` with balance ${e.cryptoCreateAccount.initialBalance}`),e.cryptoCreateAccount.alias&&(t+=` (Alias: ${e.cryptoCreateAccount.alias})`),t},Ks=e=>e.cryptoUpdateAccount?`Update Account ${e.cryptoUpdateAccount.accountIdToUpdate||"(Unknown ID)"}`:e.humanReadableType,Us=e=>{if(e.cryptoApproveAllowance){let t=0;return e.cryptoApproveAllowance.hbarAllowances&&(t+=e.cryptoApproveAllowance.hbarAllowances.length),e.cryptoApproveAllowance.tokenAllowances&&(t+=e.cryptoApproveAllowance.tokenAllowances.length),e.cryptoApproveAllowance.nftAllowances&&(t+=e.cryptoApproveAllowance.nftAllowances.length),`Approve ${t} Crypto Allowance(s)`}return e.humanReadableType},Ls=e=>{if(e.cryptoDeleteAllowance){return`Delete ${(e.cryptoDeleteAllowance.nftAllowancesToRemove||[]).length} NFT Crypto Allowance(s)`}return e.humanReadableType},$s=e=>{if(e.contractCreate){let t="Create Contract";return e.contractCreate.memo&&(t+=` (Memo: ${e.contractCreate.memo})`),t}return e.humanReadableType},Hs=e=>e.contractUpdate?`Update Contract ${e.contractUpdate.contractIdToUpdate||"(Unknown ID)"}`:e.humanReadableType,qs=e=>{if(e.contractDelete){let t=`Delete Contract ${e.contractDelete.contractIdToDelete||"(Unknown ID)"}`;return e.contractDelete.transferAccountId?t+=` (Transfer to Account: ${e.contractDelete.transferAccountId})`:e.contractDelete.transferContractId&&(t+=` (Transfer to Contract: ${e.contractDelete.transferContractId})`),t}return e.humanReadableType},js=e=>e.tokenUpdate?`Update Token ${e.tokenUpdate.tokenId||"(Unknown ID)"}`:e.humanReadableType,Ws=e=>e.tokenFeeScheduleUpdate?`Update Fee Schedule for Token ${e.tokenFeeScheduleUpdate.tokenId||"(Unknown ID)"}`:e.humanReadableType,Vs=e=>{if(!e.tokenAirdrop||!e.tokenAirdrop.tokenTransfers)return e.humanReadableType;let t=0,r=0;for(const i of e.tokenAirdrop.tokenTransfers)t+=1,r+=Array.isArray(i.transfers)?i.transfers.length:0;return`Token Airdrop across ${t} token(s), ${r} transfer(s)`},Gs=e=>{if(!e.scheduleCreate)return e.humanReadableType;let t="Create Schedule";return e.scheduleCreate.memo&&(t+=` (Memo: ${e.scheduleCreate.memo})`),t},Js=e=>e.scheduleSign?"Sign Schedule":e.humanReadableType,Ys=e=>e.scheduleDelete?"Delete Schedule":e.humanReadableType,Xs=e=>e.systemDelete?e.systemDelete.fileId?`System Delete File ${e.systemDelete.fileId}`:e.systemDelete.contractId?`System Delete Contract ${e.systemDelete.contractId}`:"System Delete":e.humanReadableType,Zs=e=>e.systemUndelete?e.systemUndelete.fileId?`System Undelete File ${e.systemUndelete.fileId}`:e.systemUndelete.contractId?`System Undelete Contract ${e.systemUndelete.contractId}`:"System Undelete":e.humanReadableType,Qs=e=>"Network Freeze",ea=e=>"Ethereum Transaction",ta=e=>e.uncheckedSubmit&&e.uncheckedSubmit.topicId?`Unchecked Submit to topic ${e.uncheckedSubmit.topicId}`:"Unchecked Submit",ra=e=>"Create Node",ia=e=>"Update Node",oa=e=>"Delete Node",na=e=>`Atomic Batch (${Array.isArray(e.atomicBatch?.transactions)?e.atomicBatch.transactions.length:0} transaction(s))`,sa={CRYPTOTRANSFER:{fn:gs},cryptoTransfer:{fn:gs},CONTRACTCALL:{fn:ms},contractCall:{fn:ms},TOKENMINT:{fn:fs},tokenMint:{fn:fs},TOKENBURN:{fn:ys},tokenBurn:{fn:ys},TOKENCREATE:{fn:bs},tokenCreation:{fn:bs},TOPICCREATE:{fn:ws},consensusCreateTopic:{fn:ws},CONSENSUSSUBMITMESSAGE:{fn:Is},consensusSubmitMessage:{fn:Is},TOPICUPDATE:{fn:vs},consensusUpdateTopic:{fn:vs},TOPICDELETE:{fn:As},consensusDeleteTopic:{fn:As},FILECREATE:{fn:Ts},fileCreate:{fn:Ts},FILEAPPEND:{fn:Ss},fileAppend:{fn:Ss},FILEUPDATE:{fn:ks},fileUpdate:{fn:ks},FILEDELETE:{fn:Es},fileDelete:{fn:Es},TOKENUPDATE:{fn:js},tokenUpdate:{fn:js},TOKENFEESCHEDULEUPDATE:{fn:Ws},tokenFeeScheduleUpdate:{fn:Ws},TOKENFREEZE:{fn:Cs},tokenFreeze:{fn:Cs},TOKENUNFREEZE:{fn:xs},tokenUnfreeze:{fn:xs},TOKENGRANTKYC:{fn:Rs},tokenGrantKyc:{fn:Rs},TOKENREVOKEKYC:{fn:Ns},tokenRevokeKyc:{fn:Ns},TOKENPAUSE:{fn:_s},tokenPause:{fn:_s},TOKENUNPAUSE:{fn:Ps},tokenUnpause:{fn:Ps},TOKENWIPE:{fn:Fs},TOKENWIPEACCOUNT:{fn:Fs},tokenWipe:{fn:Fs},tokenWipeAccount:{fn:Fs},TOKENDELETE:{fn:zs},tokenDelete:{fn:zs},TOKENASSOCIATE:{fn:Os},tokenAssociate:{fn:Os},TOKENDISSOCIATE:{fn:Ds},tokenDissociate:{fn:Ds},ACCOUNTDELETE:{fn:Ms},cryptoDelete:{fn:Ms},ACCOUNTCREATE:{fn:Bs},cryptoCreateAccount:{fn:Bs},ACCOUNTUPDATE:{fn:Ks},cryptoUpdateAccount:{fn:Ks},APPROVEALLOWANCE:{fn:Us},cryptoApproveAllowance:{fn:Us},DELETEALLOWANCE:{fn:Ls},cryptoDeleteAllowance:{fn:Ls},CONTRACTCREATE:{fn:$s},contractCreate:{fn:$s},CONTRACTUPDATE:{fn:Hs},contractUpdate:{fn:Hs},CONTRACTDELETE:{fn:qs},contractDelete:{fn:qs},TOKENAIRDROP:{fn:Vs},tokenAirdrop:{fn:Vs},SCHEDULECREATE:{fn:Gs},scheduleCreate:{fn:Gs},SCHEDULESIGN:{fn:Js},scheduleSign:{fn:Js},SCHEDULEDELETE:{fn:Ys},scheduleDelete:{fn:Ys},SYSTEMDELETE:{fn:Xs},systemDelete:{fn:Xs},SYSTEMUNDELETE:{fn:Zs},systemUndelete:{fn:Zs},FREEZE:{fn:Qs},freeze:{fn:Qs},ETHEREUMTRANSACTION:{fn:ea},ethereumTransaction:{fn:ea},UNCHECKEDSUBMIT:{fn:ta},uncheckedSubmit:{fn:ta},NODECREATE:{fn:ra},nodeCreate:{fn:ra},NODEUPDATE:{fn:ia},nodeUpdate:{fn:ia},NODEDELETE:{fn:oa},nodeDelete:{fn:oa},ATOMICBATCH:{fn:na},atomicBatch:{fn:na}},aa=e=>{const t=sa[e.type];if(t){if(t.fn)return t.fn(e);if(t.template)return hs(t.template,e)}const r=sa[e.humanReadableType];if(r){if(r.fn)return r.fn(e);if(r.template)return hs(r.template,e)}return"cryptoTransfer"===e.type||"CRYPTOTRANSFER"===e.type?gs(e):e.contractCall?ms(e):Array.isArray(e.tokenTransfers)&&e.tokenTransfers.length>0?(e=>{const t=[],r=(e=>{const t={};for(const r of e)t[r.tokenId]||(t[r.tokenId]=[]),t[r.tokenId].push(r);return t})(e.tokenTransfers||[]);for(const[i,o]of Object.entries(r)){const e=[],r=[];for(const t of o){const i=parseFloat(String(t.amount));i<0?e.push(`${t.accountId} (${Math.abs(i)})`):i>0&&r.push(`${t.accountId} (${i})`)}e.length>0&&r.length>0&&t.push(`Transfer of token ${i} from ${e.join(", ")} to ${r.join(", ")}`)}return t.length>0?t.join("; "):e.humanReadableType})(e):e.humanReadableType&&"Unknown Transaction"!==e.humanReadableType?e.humanReadableType:"Unknown Transaction"};function ca(e){if(e){if(e.contractID)return`ContractID: ${new i.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()}`;if(e.ed25519)return`ED25519: ${a.Buffer.from(e.ed25519).toString("hex")}`;if(e.ECDSASecp256k1)return`ECDSA_secp256k1: ${a.Buffer.from(e.ECDSASecp256k1).toString("hex")}`;if(e?.keyList?.keys?.length>0){const t=e.keyList.keys.map(e=>ca(e)).filter(Boolean);return`KeyList (${t.length} keys): [${t.join(", ")}]`}if(e?.thresholdKey?.keys?.keys?.length>0){const t=e.thresholdKey.keys.keys.map(e=>ca(e)).filter(Boolean);return`ThresholdKey (${e.thresholdKey.threshold} of ${t.length}): [${t.join(", ")}]`}return e.delegatableContractId?`DelegatableContractID: ${new i.ContractId(e.delegatableContractId.shardNum??0,e.delegatableContractId.realmNum??0,e.delegatableContractId.contractNum??0).toString()}`:0===Object.keys(e).length?"Empty Key Structure":"Unknown or Unset Key Type"}}function la(e){try{const t=e.toBytes?e.toBytes():void 0;if(!t)return null;const r=n.proto.TransactionList.decode(t);if(!r.transactionList||0===r.transactionList.length)return null;const i=r.transactionList[0];if(i.bodyBytes&&i.bodyBytes.length>0)return n.proto.TransactionBody.decode(i.bodyBytes);if(i.signedTransactionBytes&&i.signedTransactionBytes.length>0){const e=n.proto.SignedTransaction.decode(i.signedTransactionBytes);if(e.bodyBytes)return n.proto.TransactionBody.decode(e.bodyBytes)}return null}catch(t){return null}}function da(e,t){const r=la(e);return!(!r||!r[t])}class ua{static parseHTSTransaction(e){try{const t=e._transactionBody;if(!t)return{};if(t.tokenCreation){const e=this.parseTokenCreate(t.tokenCreation);if(e)return{type:"TOKENCREATE",humanReadableType:"Token Creation",tokenCreation:e}}if(t.tokenMint){const e=this.parseTokenMint(t.tokenMint);if(e)return{type:"TOKENMINT",humanReadableType:"Token Mint",tokenMint:e}}if(t.tokenBurn){const e=this.parseTokenBurn(t.tokenBurn);if(e)return{type:"TOKENBURN",humanReadableType:"Token Burn",tokenBurn:e}}if(t.tokenUpdate){const e=this.parseTokenUpdate(t.tokenUpdate);if(e)return{type:"TOKENUPDATE",humanReadableType:"Token Update",tokenUpdate:e}}if(t.tokenFreeze){const e=this.parseTokenFreeze(t.tokenFreeze);if(e)return{type:"TOKENFREEZE",humanReadableType:"Token Freeze",tokenFreeze:e}}if(t.tokenUnfreeze){const e=this.parseTokenUnfreeze(t.tokenUnfreeze);if(e)return{type:"TOKENUNFREEZE",humanReadableType:"Token Unfreeze",tokenUnfreeze:e}}if(t.tokenGrantKyc){const e=this.parseTokenGrantKyc(t.tokenGrantKyc);if(e)return{type:"TOKENGRANTKYC",humanReadableType:"Token Grant KYC",tokenGrantKyc:e}}if(t.tokenRevokeKyc){const e=this.parseTokenRevokeKyc(t.tokenRevokeKyc);if(e)return{type:"TOKENREVOKEKYC",humanReadableType:"Token Revoke KYC",tokenRevokeKyc:e}}if(t.tokenPause){const e=this.parseTokenPause(t.tokenPause);if(e)return{type:"TOKENPAUSE",humanReadableType:"Token Pause",tokenPause:e}}if(t.tokenUnpause){const e=this.parseTokenUnpause(t.tokenUnpause);if(e)return{type:"TOKENUNPAUSE",humanReadableType:"Token Unpause",tokenUnpause:e}}if(t.tokenWipe){const e=this.parseTokenWipeAccount(t.tokenWipe);if(e)return{type:"TOKENWIPEACCOUNT",humanReadableType:"Token Wipe Account",tokenWipeAccount:e}}if(t.tokenDeletion){const e=this.parseTokenDelete(t.tokenDeletion);if(e)return{type:"TOKENDELETE",humanReadableType:"Token Delete",tokenDelete:e}}if(t.tokenAssociate){const e=this.parseTokenAssociate(t.tokenAssociate);if(e)return{type:"TOKENASSOCIATE",humanReadableType:"Token Associate",tokenAssociate:e}}if(t.tokenDissociate){const e=this.parseTokenDissociate(t.tokenDissociate);if(e)return{type:"TOKENDISSOCIATE",humanReadableType:"Token Dissociate",tokenDissociate:e}}if(t.tokenFeeScheduleUpdate){const e=this.parseTokenFeeScheduleUpdate(t.tokenFeeScheduleUpdate);if(e)return{type:"TOKENFEESCHEDULEUPDATE",humanReadableType:"Token Fee Schedule Update",tokenFeeScheduleUpdate:e}}const r=this.parseTokenAirdrop(e);return r?{type:"TOKENAIRDROP",humanReadableType:"Token Airdrop",tokenAirdrop:r}:{}}catch(t){return console.warn("[HTSParser] Failed to parse HTS transaction:",t),{}}}static parseTokenCreate(e){if(!e)return;const t={};return e.name&&(t.tokenName=e.name),e.symbol&&(t.tokenSymbol=e.symbol),e.treasury&&(t.treasuryAccountId=new i.AccountId(e.treasury.shardNum??0,e.treasury.realmNum??0,e.treasury.accountNum??0).toString()),e.initialSupply&&(t.initialSupply=i.Long.fromValue(e.initialSupply).toString()),void 0!==e.decimals&&null!==e.decimals&&(t.decimals=i.Long.fromValue(e.decimals).toNumber()),e.maxSupply&&(t.maxSupply=i.Long.fromValue(e.maxSupply).toString()),e.memo&&(t.memo=e.memo),null!==e.tokenType&&void 0!==e.tokenType&&(t.tokenType=n.proto.TokenType[e.tokenType]),null!==e.supplyType&&void 0!==e.supplyType&&(t.supplyType=n.proto.TokenSupplyType[e.supplyType]),t.adminKey=ca(e.adminKey),t.kycKey=ca(e.kycKey),t.freezeKey=ca(e.freezeKey),t.wipeKey=ca(e.wipeKey),t.supplyKey=ca(e.supplyKey),t.feeScheduleKey=ca(e.feeScheduleKey),t.pauseKey=ca(e.pauseKey),e.autoRenewAccount&&(t.autoRenewAccount=new i.AccountId(e.autoRenewAccount.shardNum??0,e.autoRenewAccount.realmNum??0,e.autoRenewAccount.accountNum??0).toString()),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=i.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.customFees&&e.customFees.length>0&&(t.customFees=e.customFees.map(e=>{const t={feeCollectorAccountId:e.feeCollectorAccountId?new i.AccountId(e.feeCollectorAccountId.shardNum??0,e.feeCollectorAccountId.realmNum??0,e.feeCollectorAccountId.accountNum??0).toString():"Not Set",allCollectorsAreExempt:e.allCollectorsAreExempt||!1};if(e.fixedFee)return{...t,feeType:"FIXED_FEE",fixedFee:{amount:i.Long.fromValue(e.fixedFee.amount||0).toString(),denominatingTokenId:e.fixedFee.denominatingTokenId?new i.TokenId(e.fixedFee.denominatingTokenId.shardNum??0,e.fixedFee.denominatingTokenId.realmNum??0,e.fixedFee.denominatingTokenId.tokenNum??0).toString():void 0}};if(e.fractionalFee)return{...t,feeType:"FRACTIONAL_FEE",fractionalFee:{numerator:i.Long.fromValue(e.fractionalFee.fractionalAmount?.numerator||0).toString(),denominator:i.Long.fromValue(e.fractionalFee.fractionalAmount?.denominator||1).toString(),minimumAmount:i.Long.fromValue(e.fractionalFee.minimumAmount||0).toString(),maximumAmount:i.Long.fromValue(e.fractionalFee.maximumAmount||0).toString(),netOfTransfers:e.fractionalFee.netOfTransfers||!1}};if(e.royaltyFee){let r;return e.royaltyFee.fallbackFee&&(r={amount:i.Long.fromValue(e.royaltyFee.fallbackFee.amount||0).toString(),denominatingTokenId:e.royaltyFee.fallbackFee.denominatingTokenId?new i.TokenId(e.royaltyFee.fallbackFee.denominatingTokenId.shardNum??0,e.royaltyFee.fallbackFee.denominatingTokenId.realmNum??0,e.royaltyFee.fallbackFee.denominatingTokenId.tokenNum??0).toString():void 0}),{...t,feeType:"ROYALTY_FEE",royaltyFee:{numerator:i.Long.fromValue(e.royaltyFee.exchangeValueFraction?.numerator||0).toString(),denominator:i.Long.fromValue(e.royaltyFee.exchangeValueFraction?.denominator||1).toString(),fallbackFee:r}}}return{...t,feeType:"FIXED_FEE",fixedFee:{amount:"0"}}})),t}static parseTokenMint(e){if(!e||!e.token||null===e.amount||void 0===e.amount)return;const t={tokenId:new i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString(),amount:i.Long.fromValue(e.amount).toNumber()};return e.metadata&&e.metadata.length>0&&(t.metadata=e.metadata.map(e=>a.Buffer.from(e).toString("base64"))),t}static parseTokenBurn(e){if(!e||!e.token||null===e.amount||void 0===e.amount)return;const t={tokenId:new i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString(),amount:i.Long.fromValue(e.amount).toNumber()};return e.serialNumbers&&e.serialNumbers.length>0&&(t.serialNumbers=e.serialNumbers.map(e=>i.Long.fromValue(e).toNumber())),t}static parseTokenUpdate(e){if(!e)return;const t={};return e.token&&(t.tokenId=new i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.name&&(t.name=e.name),e.symbol&&(t.symbol=e.symbol),e.treasury&&(t.treasuryAccountId=new i.AccountId(e.treasury.shardNum??0,e.treasury.realmNum??0,e.treasury.accountNum??0).toString()),t.adminKey=ca(e.adminKey),t.kycKey=ca(e.kycKey),t.freezeKey=ca(e.freezeKey),t.wipeKey=ca(e.wipeKey),t.supplyKey=ca(e.supplyKey),t.feeScheduleKey=ca(e.feeScheduleKey),t.pauseKey=ca(e.pauseKey),e.autoRenewAccount&&(t.autoRenewAccountId=new i.AccountId(e.autoRenewAccount.shardNum??0,e.autoRenewAccount.realmNum??0,e.autoRenewAccount.accountNum??0).toString()),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=i.Long.fromValue(e.autoRenewPeriod.seconds).toString()),void 0!==e.memo?.value&&(t.memo=e.memo.value),e.expiry?.seconds&&(t.expiry=`${i.Long.fromValue(e.expiry.seconds).toString()}.${e.expiry.nanos}`),t}static parseTokenFeeScheduleUpdate(e){if(!e)return;const t={};return e.tokenId&&(t.tokenId=new i.TokenId(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString()),e.customFees&&e.customFees.length>0&&(t.customFees=e.customFees.map(e=>{const t={feeCollectorAccountId:e.feeCollectorAccountId?new i.AccountId(e.feeCollectorAccountId.shardNum??0,e.feeCollectorAccountId.realmNum??0,e.feeCollectorAccountId.accountNum??0).toString():"Not Set",allCollectorsAreExempt:e.allCollectorsAreExempt||!1};if(e.fixedFee)return{...t,feeType:"FIXED_FEE",fixedFee:{amount:i.Long.fromValue(e.fixedFee.amount||0).toString(),denominatingTokenId:e.fixedFee.denominatingTokenId?new i.TokenId(e.fixedFee.denominatingTokenId.shardNum??0,e.fixedFee.denominatingTokenId.realmNum??0,e.fixedFee.denominatingTokenId.tokenNum??0).toString():void 0}};if(e.fractionalFee)return{...t,feeType:"FRACTIONAL_FEE",fractionalFee:{numerator:i.Long.fromValue(e.fractionalFee.fractionalAmount?.numerator||0).toString(),denominator:i.Long.fromValue(e.fractionalFee.fractionalAmount?.denominator||1).toString(),minimumAmount:i.Long.fromValue(e.fractionalFee.minimumAmount||0).toString(),maximumAmount:i.Long.fromValue(e.fractionalFee.maximumAmount||0).toString(),netOfTransfers:e.fractionalFee.netOfTransfers||!1}};if(e.royaltyFee){let r;return e.royaltyFee.fallbackFee&&(r={amount:i.Long.fromValue(e.royaltyFee.fallbackFee.amount||0).toString(),denominatingTokenId:e.royaltyFee.fallbackFee.denominatingTokenId?new i.TokenId(e.royaltyFee.fallbackFee.denominatingTokenId.shardNum??0,e.royaltyFee.fallbackFee.denominatingTokenId.realmNum??0,e.royaltyFee.fallbackFee.denominatingTokenId.tokenNum??0).toString():void 0}),{...t,feeType:"ROYALTY_FEE",royaltyFee:{numerator:i.Long.fromValue(e.royaltyFee.exchangeValueFraction?.numerator||0).toString(),denominator:i.Long.fromValue(e.royaltyFee.exchangeValueFraction?.denominator||1).toString(),fallbackFee:r}}}return{...t,feeType:"FIXED_FEE",fixedFee:{amount:"0"}}})),t}static parseTokenFreeze(e){if(!e)return;const t={};return e.token&&(t.tokenId=new i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new i.AccountId(e.account.shardNum??0,e.account.realmNum??0,e.account.accountNum??0).toString()),t}static parseTokenUnfreeze(e){if(!e)return;const t={};return e.token&&(t.tokenId=new i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new i.AccountId(e.account.shardNum??0,e.account.realmNum??0,e.account.accountNum??0).toString()),t}static parseTokenGrantKyc(e){if(!e)return;const t={};return e.token&&(t.tokenId=new i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new i.AccountId(e.account.shardNum??0,e.account.realmNum??0,e.account.accountNum??0).toString()),t}static parseTokenRevokeKyc(e){if(!e)return;const t={};return e.token&&(t.tokenId=new i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new i.AccountId(e.account.shardNum??0,e.account.realmNum??0,e.account.accountNum??0).toString()),t}static parseTokenPause(e){if(!e)return;const t={};return e.token&&(t.tokenId=new i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),t}static parseTokenUnpause(e){if(!e)return;const t={};return e.token&&(t.tokenId=new i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),t}static parseTokenWipeAccount(e){if(!e)return;const t={};return e.token&&(t.tokenId=new i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new i.AccountId(e.account.shardNum??0,e.account.realmNum??0,e.account.accountNum??0).toString()),e.serialNumbers&&e.serialNumbers.length>0&&(t.serialNumbers=e.serialNumbers.map(e=>i.Long.fromValue(e).toString())),e.amount&&(t.amount=i.Long.fromValue(e.amount).toString()),t}static parseTokenDelete(e){if(!e)return;const t={};return e.token&&(t.tokenId=new i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),t}static parseTokenAssociate(e){if(!e)return;const t={};return e.account&&(t.accountId=new i.AccountId(e.account.shardNum??0,e.account.realmNum??0,e.account.accountNum??0).toString()),e.tokens&&e.tokens.length>0&&(t.tokenIds=e.tokens.map(e=>new i.TokenId(e.shardNum??0,e.realmNum??0,e.tokenNum??0).toString())),t}static parseTokenDissociate(e){if(!e)return;const t={};return e.account&&(t.accountId=new i.AccountId(e.account.shardNum??0,e.account.realmNum??0,e.account.accountNum??0).toString()),e.tokens&&e.tokens.length>0&&(t.tokenIds=e.tokens.map(e=>new i.TokenId(e.shardNum??0,e.realmNum??0,e.tokenNum??0).toString())),t}static parseTokenAirdrop(e){try{const t=e._transactionBody;if(t?.tokenAirdrop){return{tokenTransfers:(t.tokenAirdrop.tokenTransfers||[]).map(e=>({tokenId:e.token?.toString()||"Unknown",transfers:(e.transfers||[]).map(e=>({accountId:e.accountID?.toString()||"Unknown",amount:e.amount?.toString()||"0",serialNumbers:e.serialNumbers?.map(e=>e.toString())}))}))}}if(da(e,"tokenAirdrop")){const t=la(e);if(t?.tokenAirdrop)return this.parseTokenAirdropFromProto(t.tokenAirdrop)}const r=e._tokenTransfers||[];return r.length>0?{tokenTransfers:r.map(e=>({tokenId:e.tokenId?.toString()||"Unknown",transfers:(e.transfers||[]).map(e=>({accountId:e.accountId?.toString()||"Unknown",amount:e.amount?.toString()||"0",serialNumbers:e.serialNumbers?.map(e=>e.toString())}))}))}:null}catch(t){return console.warn("[HTSParser] Failed to parse token airdrop:",t),null}}static parseTokenAirdropFromProto(e){const t=[];if(e.tokenTransfers)for(const r of e.tokenTransfers){const e=r.token?new i.TokenId(r.token.shardNum??0,r.token.realmNum??0,r.token.tokenNum??0):null,o=[];if(r.transfers)for(const t of r.transfers){const e=t.accountID?new i.AccountId(t.accountID.shardNum??0,t.accountID.realmNum??0,t.accountID.accountNum??0):null;o.push({accountId:e?.toString()||"Unknown",amount:t.amount?i.Long.fromValue(t.amount).toString():"0",serialNumbers:t.serialNumbers?.map(e=>i.Long.fromValue(e).toString())})}t.push({tokenId:e?.toString()||"Unknown",transfers:o})}return{tokenTransfers:t}}static extractTokenCreationFromTransaction(e){try{const t=e;if(t._tokenName||t._tokenSymbol){const e={tokenName:t._tokenName||"Unknown Token",tokenSymbol:t._tokenSymbol||"UNKNOWN",initialSupply:t._initialSupply?.toString()||"0",decimals:Number(t._decimals||0),treasuryAccountId:t._treasuryAccountId?.toString()||"Unknown"};return t._maxSupply&&(e.maxSupply=t._maxSupply.toString()),t._tokenType&&(e.tokenType=t._tokenType.toString?t._tokenType.toString():String(t._tokenType)),t._supplyType&&(e.supplyType=t._supplyType.toString?t._supplyType.toString():String(t._supplyType)),t._tokenMemo&&(e.memo=t._tokenMemo),t._adminKey&&(e.adminKey=t._adminKey.toString()),t._kycKey&&(e.kycKey=t._kycKey.toString()),t._freezeKey&&(e.freezeKey=t._freezeKey.toString()),t._wipeKey&&(e.wipeKey=t._wipeKey.toString()),t._supplyKey&&(e.supplyKey=t._supplyKey.toString()),t._feeScheduleKey&&(e.feeScheduleKey=t._feeScheduleKey.toString()),t._pauseKey&&(e.pauseKey=t._pauseKey.toString()),t._metadataKey&&(e.metadataKey=t._metadataKey.toString()),t._autoRenewAccountId&&(e.autoRenewAccount=t._autoRenewAccountId.toString()),t._autoRenewPeriod&&(e.autoRenewPeriod=t._autoRenewPeriod.seconds?.toString()||t._autoRenewPeriod.toString()),t._expirationTime&&(e.expiry=t._expirationTime.seconds?.toString()||t._expirationTime.toString()),t._customFees&&Array.isArray(t._customFees)&&t._customFees.length>0&&(e.customFees=t._customFees.map(e=>{const t={feeCollectorAccountId:e.feeCollectorAccountId?.toString()||"",feeType:"FIXED_FEE"};return e.fixedFee?(t.feeType="FIXED_FEE",t.fixedFee={amount:e.fixedFee.amount?.toString()||"0",denominatingTokenId:e.fixedFee.denominatingTokenId?.toString()}):e.fractionalFee?(t.feeType="FRACTIONAL_FEE",t.fractionalFee={numerator:e.fractionalFee.numerator?.toString()||"0",denominator:e.fractionalFee.denominator?.toString()||"1",minimumAmount:e.fractionalFee.minimumAmount?.toString()||"0",maximumAmount:e.fractionalFee.maximumAmount?.toString()||"0",netOfTransfers:e.fractionalFee.netOfTransfers||!1}):e.royaltyFee&&(t.feeType="ROYALTY_FEE",t.royaltyFee={numerator:e.royaltyFee.numerator?.toString()||"0",denominator:e.royaltyFee.denominator?.toString()||"1",fallbackFee:e.royaltyFee.fallbackFee?{amount:e.royaltyFee.fallbackFee.amount?.toString()||"0",denominatingTokenId:e.royaltyFee.fallbackFee.denominatingTokenId?.toString()}:void 0}),t.allCollectorsAreExempt=e.allCollectorsAreExempt||!1,t})),e}return null}catch(t){return null}}static extractTokenAirdropFromTransaction(e){try{const t=e;if(t._tokenAirdrops&&Array.isArray(t._tokenAirdrops)){return{tokenTransfers:t._tokenAirdrops.map(e=>({tokenId:e.tokenId?.toString()||"Unknown",transfers:(e.transfers||[]).map(e=>({accountId:e.accountId?.toString()||"Unknown",amount:e.amount?.toString()||"0",serialNumbers:e.serialNumbers?.map(e=>e.toString())||[]}))}))}}return null}catch(t){return null}}static parseFromTransactionObject(e){try{try{const t=e.toBytes?e.toBytes():void 0;if(t){const e=n.proto.TransactionList.decode(t);if(e.transactionList&&e.transactionList.length>0){const t=e.transactionList[0];let r=null;if(t.bodyBytes&&t.bodyBytes.length>0)r=n.proto.TransactionBody.decode(t.bodyBytes);else if(t.signedTransactionBytes&&t.signedTransactionBytes.length>0){const e=n.proto.SignedTransaction.decode(t.signedTransactionBytes);e.bodyBytes&&(r=n.proto.TransactionBody.decode(e.bodyBytes))}if(r){if(r.tokenCreation){const e=this.parseTokenCreate(r.tokenCreation);if(e)return{type:"TOKENCREATE",humanReadableType:"Token Creation",tokenCreation:e}}if(r.tokenMint){const e=this.parseTokenMint(r.tokenMint);if(e)return{type:"TOKENMINT",humanReadableType:"Token Mint",tokenMint:e}}if(r.tokenBurn){const e=this.parseTokenBurn(r.tokenBurn);if(e)return{type:"TOKENBURN",humanReadableType:"Token Burn",tokenBurn:e}}if(r.tokenUpdate){const e=this.parseTokenUpdate(r.tokenUpdate);if(e)return{type:"TOKENUPDATE",humanReadableType:"Token Update",tokenUpdate:e}}if(r.tokenFreeze){const e=this.parseTokenFreeze(r.tokenFreeze);if(e)return{type:"TOKENFREEZE",humanReadableType:"Token Freeze",tokenFreeze:e}}if(r.tokenUnfreeze){const e=this.parseTokenUnfreeze(r.tokenUnfreeze);if(e)return{type:"TOKENUNFREEZE",humanReadableType:"Token Unfreeze",tokenUnfreeze:e}}if(r.tokenGrantKyc){const e=this.parseTokenGrantKyc(r.tokenGrantKyc);if(e)return{type:"TOKENGRANTKYC",humanReadableType:"Token Grant KYC",tokenGrantKyc:e}}if(r.tokenRevokeKyc){const e=this.parseTokenRevokeKyc(r.tokenRevokeKyc);if(e)return{type:"TOKENREVOKEKYC",humanReadableType:"Token Revoke KYC",tokenRevokeKyc:e}}if(r.tokenPause){const e=this.parseTokenPause(r.tokenPause);if(e)return{type:"TOKENPAUSE",humanReadableType:"Token Pause",tokenPause:e}}if(r.tokenUnpause){const e=this.parseTokenUnpause(r.tokenUnpause);if(e)return{type:"TOKENUNPAUSE",humanReadableType:"Token Unpause",tokenUnpause:e}}if(r.tokenWipe){const e=this.parseTokenWipeAccount(r.tokenWipe);if(e)return{type:"TOKENWIPEACCOUNT",humanReadableType:"Token Wipe Account",tokenWipeAccount:e}}if(r.tokenDeletion){const e=this.parseTokenDelete(r.tokenDeletion);if(e)return{type:"TOKENDELETE",humanReadableType:"Token Delete",tokenDelete:e}}if(r.tokenAssociate){const e=this.parseTokenAssociate(r.tokenAssociate);if(e)return{type:"TOKENASSOCIATE",humanReadableType:"Token Associate",tokenAssociate:e}}if(r.tokenDissociate){const e=this.parseTokenDissociate(r.tokenDissociate);if(e)return{type:"TOKENDISSOCIATE",humanReadableType:"Token Dissociate",tokenDissociate:e}}if(r.tokenFeeScheduleUpdate){const e=this.parseTokenFeeScheduleUpdate(r.tokenFeeScheduleUpdate);if(e)return{type:"TOKENFEESCHEDULEUPDATE",humanReadableType:"Token Fee Schedule Update",tokenFeeScheduleUpdate:e}}if(r.tokenAirdrop){const e=this.parseTokenAirdropFromProto(r.tokenAirdrop);if(e)return{type:"TOKENAIRDROP",humanReadableType:"Token Airdrop",tokenAirdrop:e}}}}}}catch($g){}const t=this.parseHTSTransaction(e);if(t.type)return t;const r=this.extractTokenCreationFromTransaction(e),i=this.extractTokenAirdropFromTransaction(e);return r?{type:"TOKENCREATE",humanReadableType:"Token Creation",tokenCreation:r}:i?{type:"TOKENAIRDROP",humanReadableType:"Token Airdrop",tokenAirdrop:i}:{}}catch(t){return{}}}}class pa{static parseConsensusCreateTopic(e){if(!e)return;const t={};return e.memo&&(t.memo=e.memo),t.adminKey=ca(e.adminKey),t.submitKey=ca(e.submitKey),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=i.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.autoRenewAccount&&(t.autoRenewAccountId=new i.AccountId(e.autoRenewAccount.shardNum??0,e.autoRenewAccount.realmNum??0,e.autoRenewAccount.accountNum??0).toString()),t}static parseConsensusSubmitMessage(e){if(!e)return;const t={};if(e.topicID&&(t.topicId=`${e.topicID.shardNum??0}.${e.topicID.realmNum??0}.${e.topicID.topicNum??0}`),e.message?.length>0){const r=a.Buffer.from(e.message),i=r.toString("utf8");/[\x00-\x08\x0B\x0E-\x1F\x7F]/.test(i)||i.includes("�")?(t.message=r.toString("base64"),t.messageEncoding="base64"):(t.message=i,t.messageEncoding="utf8")}if(e.chunkInfo){if(e.chunkInfo.initialTransactionID){const r=e.chunkInfo.initialTransactionID.accountID,i=e.chunkInfo.initialTransactionID.transactionValidStart;r&&i&&(t.chunkInfoInitialTransactionID=`${r.shardNum??0}.${r.realmNum??0}.${r.accountNum??0}@${i.seconds??0}.${i.nanos??0}`)}void 0!==e.chunkInfo.number&&null!==e.chunkInfo.number&&(t.chunkInfoNumber=e.chunkInfo.number),void 0!==e.chunkInfo.total&&null!==e.chunkInfo.total&&(t.chunkInfoTotal=e.chunkInfo.total)}return t}static parseConsensusUpdateTopic(e){if(!e)return;const t={};return e.topicID&&(t.topicId=`${e.topicID.shardNum}.${e.topicID.realmNum}.${e.topicID.topicNum}`),void 0!==e.memo?.value&&(t.memo=e.memo.value),null===e.adminKey?(t.clearAdminKey=!0,t.adminKey=void 0):e.adminKey?t.adminKey=ca(e.adminKey):t.adminKey=void 0,null===e.submitKey?(t.clearSubmitKey=!0,t.submitKey=void 0):e.submitKey?t.submitKey=ca(e.submitKey):t.submitKey=void 0,e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=i.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.autoRenewAccount&&(t.autoRenewAccountId=new i.AccountId(e.autoRenewAccount.shardNum??0,e.autoRenewAccount.realmNum??0,e.autoRenewAccount.accountNum??0).toString()),t}static parseConsensusDeleteTopic(e){if(!e)return;const t={};return e.topicID&&(t.topicId=`${e.topicID.shardNum}.${e.topicID.realmNum??0}.${e.topicID.topicNum??0}`),t}static parseFromTransactionObject(e){try{const t=e._transactionBody;if(!t)return{};if(t.consensusCreateTopic){const e=this.parseConsensusCreateTopic(t.consensusCreateTopic);if(e)return{type:"TOPICCREATE",humanReadableType:"Topic Create",consensusCreateTopic:e}}if(t.consensusSubmitMessage){const e=this.parseConsensusSubmitMessage(t.consensusSubmitMessage);if(e)return{type:"CONSENSUSSUBMITMESSAGE",humanReadableType:"Submit Message",consensusSubmitMessage:e}}if(t.consensusUpdateTopic){const e=this.parseConsensusUpdateTopic(t.consensusUpdateTopic);if(e)return{type:"TOPICUPDATE",humanReadableType:"Topic Update",consensusUpdateTopic:e}}if(t.consensusDeleteTopic){const e=this.parseConsensusDeleteTopic(t.consensusDeleteTopic);if(e)return{type:"TOPICDELETE",humanReadableType:"Topic Delete",consensusDeleteTopic:e}}return{}}catch(t){return{}}}}class ha{static parseFileTransaction(e,t){try{if(t||e.toBytes)try{const r=t||e.toBytes(),i=n.proto.TransactionList.decode(r);if(i.transactionList&&i.transactionList.length>0){const e=i.transactionList[0];let t=null;if(e.bodyBytes&&e.bodyBytes.length>0)t=n.proto.TransactionBody.decode(e.bodyBytes);else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const r=n.proto.SignedTransaction.decode(e.signedTransactionBytes);r.bodyBytes&&(t=n.proto.TransactionBody.decode(r.bodyBytes))}if(t){const e=this.parseFromProtobufTxBody(t);if(e.type&&"UNKNOWN"!==e.type)return e}}}catch(r){}return this.parseFromTransactionInternals(e)}catch(i){return{type:"UNKNOWN",humanReadableType:"Unknown File Transaction"}}}static parseFromProtobufTxBody(e){if(e.fileCreate){const t=this.parseFileCreate(e.fileCreate);if(t)return{type:"FILECREATE",humanReadableType:"File Create",fileCreate:t}}if(e.fileAppend){const t=this.parseFileAppend(e.fileAppend);if(t)return{type:"FILEAPPEND",humanReadableType:"File Append",fileAppend:t}}if(e.fileUpdate){const t=this.parseFileUpdate(e.fileUpdate);if(t)return{type:"FILEUPDATE",humanReadableType:"File Update",fileUpdate:t}}if(e.fileDelete){const t=this.parseFileDelete(e.fileDelete);if(t)return{type:"FILEDELETE",humanReadableType:"File Delete",fileDelete:t}}return{}}static parseFromTransactionInternals(e){try{const t=e;if(da(e,"fileCreate")){const e={};if(t._contents){const r=this.analyzeContent(t._contents);e.contents=r.encoded,r.contentType&&(e.contentType=r.contentType),r.size&&(e.contentSize=r.size)}if(t._keys&&t._keys.length>0){const r={keys:t._keys};e.keys=ca({keyList:r})}return t._expirationTime&&(e.expirationTime=t._expirationTime.toString()),t._memo&&(e.memo=t._memo),{type:"FILECREATE",humanReadableType:"File Create",fileCreate:e}}if(da(e,"fileAppend")){const e={fileId:t._fileId.toString()};if(t._contents){const r=this.analyzeContent(t._contents);e.contents=r.encoded,r.size&&(e.contentSize=r.size)}return{type:"FILEAPPEND",humanReadableType:"File Append",fileAppend:e}}if(da(e,"fileUpdate")){const e={fileId:t._fileId.toString()};if(t._contents){const r=this.analyzeContent(t._contents);e.contents=r.encoded,r.size&&(e.contentSize=r.size)}if(t._keys&&t._keys.length>0){const r={keys:t._keys};e.keys=ca({keyList:r})}return t._expirationTime&&(e.expirationTime=t._expirationTime.toString()),t._memo&&(e.memo=t._memo),{type:"FILEUPDATE",humanReadableType:"File Update",fileUpdate:e}}if(da(e,"fileDelete")){return{type:"FILEDELETE",humanReadableType:"File Delete",fileDelete:{fileId:t._fileId.toString()}}}return{}}catch(t){return{}}}static analyzeContent(e){const t=e.length,r=a.Buffer.from(e);let i,o;if(t>=4){i={"89504e47":"image/png",ffd8ffe0:"image/jpeg",ffd8ffe1:"image/jpeg",47494638:"image/gif",25504446:"application/pdf","504b0304":"application/zip","7f454c46":"application/x-executable",d0cf11e0:"application/msoffice"}[r.subarray(0,4).toString("hex").toLowerCase()]}if(!i)try{const e=r.toString("utf8"),t=/[\x00-\x08\x0B\x0E-\x1F\x7F]/.test(e),o=e.includes("�");i=t||o?"application/octet-stream":e.trim().startsWith("{")&&e.trim().endsWith("}")?"application/json":e.includes("<?xml")||e.includes("<html")?"text/xml":e.includes("<!DOCTYPE html")?"text/html":"text/plain"}catch{i="application/octet-stream"}if(i?.startsWith("text/")||"application/json"===i)try{o=r.toString("utf8"),(o.includes("�")||/[\x00-\x08\x0B\x0E-\x1F\x7F]/.test(o))&&(o=r.toString("base64"))}catch{o=r.toString("base64")}else o=r.toString("base64");return{encoded:o,contentType:i,size:t}}static parseFileCreate(e){if(!e)return;const t={};return e.expirationTime?.seconds&&(t.expirationTime=`${i.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.keys&&(t.keys=ca({keyList:e.keys})),e.contents&&(t.contents=a.Buffer.from(e.contents).toString("base64")),e.memo&&(t.memo=e.memo),t}static parseFileAppend(e){if(!e)return;const t={};return e.fileID&&(t.fileId=`${e.fileID.shardNum??0}.${e.fileID.realmNum??0}.${e.fileID.fileNum??0}`),e.contents&&(t.contents=a.Buffer.from(e.contents).toString("base64")),t}static parseFileUpdate(e){if(!e)return;const t={};return e.fileID&&(t.fileId=`${e.fileID.shardNum??0}.${e.fileID.realmNum??0}.${e.fileID.fileNum??0}`),e.expirationTime?.seconds&&(t.expirationTime=`${i.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.keys&&(t.keys=ca({keyList:e.keys})),e.contents&&(t.contents=a.Buffer.from(e.contents).toString("base64")),void 0!==e.memo?.value&&(t.memo=e.memo.value),t}static parseFileDelete(e){if(!e)return;const t={};return e.fileID&&(t.fileId=`${e.fileID.shardNum??0}.${e.fileID.realmNum??0}.${e.fileID.fileNum??0}`),t}static parseFromTransactionObject(e){return this.parseFileTransaction(e)}}class ga{static parseCryptoTransfers(e,t){if(e.transfers?.accountAmounts&&(t.transfers=e.transfers.accountAmounts.map(e=>{const t=new i.AccountId(e.accountID.shardNum??0,e.accountID.realmNum??0,e.accountID.accountNum??0),r=i.Hbar.fromTinybars(i.Long.fromValue(e.amount));return{accountId:t.toString(),amount:r.toString(i.HbarUnit.Hbar),isDecimal:!0}})),e.tokenTransfers)for(const r of e.tokenTransfers){const e=new i.TokenId(r.token.shardNum??0,r.token.realmNum??0,r.token.tokenNum??0);if(r.transfers)for(const o of r.transfers){const r=new i.AccountId(o.accountID.shardNum??0,o.accountID.realmNum??0,o.accountID.accountNum??0),n=i.Long.fromValue(o.amount).toNumber();t.tokenTransfers.push({tokenId:e.toString(),accountId:r.toString(),amount:n})}}}static parseCryptoDelete(e){if(!e)return;const t={};return e.deleteAccountID&&(t.deleteAccountId=new i.AccountId(e.deleteAccountID.shardNum??0,e.deleteAccountID.realmNum??0,e.deleteAccountID.accountNum??0).toString()),e.transferAccountID&&(t.transferAccountId=new i.AccountId(e.transferAccountID.shardNum??0,e.transferAccountID.realmNum??0,e.transferAccountID.accountNum??0).toString()),t}static parseCryptoCreateAccount(e){if(!e)return;const t={};return e.initialBalance&&(t.initialBalance=i.Hbar.fromTinybars(i.Long.fromValue(e.initialBalance)).toString(i.HbarUnit.Hbar)),e.key&&(t.key=ca(e.key)),void 0!==e.receiverSigRequired&&(t.receiverSigRequired=e.receiverSigRequired),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=i.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.memo&&(t.memo=e.memo),void 0!==e.maxAutomaticTokenAssociations&&(t.maxAutomaticTokenAssociations=e.maxAutomaticTokenAssociations),e.stakedAccountId?t.stakedAccountId=new i.AccountId(e.stakedAccountId.shardNum??0,e.stakedAccountId.realmNum??0,e.stakedAccountId.accountNum??0).toString():null!==e.stakedNodeId&&void 0!==e.stakedNodeId&&(t.stakedNodeId=i.Long.fromValue(e.stakedNodeId).toString()),void 0!==e.declineReward&&(t.declineReward=e.declineReward),e.alias&&e.alias.length>0&&(t.alias=globalThis.Buffer.from(e.alias).toString("hex")),t}static parseCryptoUpdateAccount(e){if(!e)return;const t={};return e.accountIDToUpdate&&(t.accountIdToUpdate=new i.AccountId(e.accountIDToUpdate.shardNum??0,e.accountIDToUpdate.realmNum??0,e.accountIDToUpdate.accountNum??0).toString()),e.key&&(t.key=ca(e.key)),e.expirationTime?.seconds&&(t.expirationTime=`${i.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),null!==e.receiverSigRequired&&void 0!==e.receiverSigRequired&&(t.receiverSigRequired=Boolean(e.receiverSigRequired)),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=i.Long.fromValue(e.autoRenewPeriod.seconds).toString()),void 0!==e.memo?.value&&(t.memo=e.memo.value),void 0!==e.maxAutomaticTokenAssociations?.value&&(t.maxAutomaticTokenAssociations=e.maxAutomaticTokenAssociations.value),e.stakedAccountId?(t.stakedAccountId=new i.AccountId(e.stakedAccountId.shardNum??0,e.stakedAccountId.realmNum??0,e.stakedAccountId.accountNum??0).toString(),t.stakedNodeId=void 0):null!==e.stakedNodeId&&void 0!==e.stakedNodeId?(t.stakedNodeId=i.Long.fromValue(e.stakedNodeId).toString(),t.stakedAccountId=void 0):(t.stakedAccountId=void 0,t.stakedNodeId=void 0),null!==e.declineReward&&void 0!==e.declineReward&&(t.declineReward=Boolean(e.declineReward)),t}static parseCryptoApproveAllowance(e){if(!e)return;const t={};return e.cryptoAllowances&&e.cryptoAllowances.length>0&&(t.hbarAllowances=e.cryptoAllowances.map(e=>({ownerAccountId:new i.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),spenderAccountId:new i.AccountId(e.spender.shardNum??0,e.spender.realmNum??0,e.spender.accountNum??0).toString(),amount:i.Hbar.fromTinybars(i.Long.fromValue(e.amount)).toString(i.HbarUnit.Hbar)}))),e.tokenAllowances&&e.tokenAllowances.length>0&&(t.tokenAllowances=e.tokenAllowances.map(e=>({tokenId:new i.TokenId(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString(),ownerAccountId:new i.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),spenderAccountId:new i.AccountId(e.spender.shardNum??0,e.spender.realmNum??0,e.spender.accountNum??0).toString(),amount:i.Long.fromValue(e.amount).toString()}))),e.nftAllowances&&e.nftAllowances.length>0&&(t.nftAllowances=e.nftAllowances.map(e=>{const t={};return e.tokenId&&(t.tokenId=new i.TokenId(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString()),e.owner&&(t.ownerAccountId=new i.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString()),e.spender&&(t.spenderAccountId=new i.AccountId(e.spender.shardNum??0,e.spender.realmNum??0,e.spender.accountNum??0).toString()),e.serialNumbers&&e.serialNumbers.length>0&&(t.serialNumbers=e.serialNumbers.map(e=>i.Long.fromValue(e).toString())),void 0!==e.approvedForAll?.value&&(t.approvedForAll=e.approvedForAll.value),e.delegatingSpender&&(t.delegatingSpender=new i.AccountId(e.delegatingSpender.shardNum??0,e.delegatingSpender.realmNum??0,e.delegatingSpender.accountNum??0).toString()),t})),t}static parseCryptoDeleteAllowance(e){if(!e)return;const t={};return e.nftAllowances&&e.nftAllowances.length>0&&(t.nftAllowancesToRemove=e.nftAllowances.map(e=>({ownerAccountId:new i.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),tokenId:new i.TokenId(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString(),serialNumbers:e.serialNumbers?e.serialNumbers.map(e=>i.Long.fromValue(e).toString()):[]}))),t}static extractHbarTransfersFromTransaction(e){const t=[];try{const r=e._hbarTransfers;Array.isArray(r)&&r.forEach(e=>{if(e.accountId&&e.amount){const r=e.amount.toTinybars(),i=Number(r)/1e8;t.push({accountId:e.accountId.toString(),amount:i})}})}catch(r){}return t}static extractTokenTransfersFromTransaction(e){const t=[];try{const r=e._tokenTransfers;Array.isArray(r)&&r.forEach(e=>{if(e.tokenId&&Array.isArray(e.transfers)){const r=e.transfers.map(e=>({accountId:e.accountId?.toString()||"Unknown",amount:Number(e.amount||0)}));t.push({tokenId:e.tokenId.toString(),transfers:r})}})}catch(r){}return t}static parseFromTransactionObject(e){try{const t=this.extractHbarTransfersFromTransaction(e),r=this.extractTokenTransfersFromTransaction(e);if(t.length>0||r.length>0){const e=t.map(e=>({accountId:e.accountId,amount:e.amount.toString()+" ℏ",isDecimal:!0})),i=r.flatMap(e=>e.transfers.map(t=>({tokenId:e.tokenId,accountId:t.accountId,amount:t.amount})));if(t.length>0)return{type:"CRYPTOTRANSFER",humanReadableType:"Crypto Transfer",transfers:e,tokenTransfers:i};if(r.length>0)return{type:"TOKENTRANSFER",humanReadableType:"Token Transfer",transfers:e,tokenTransfers:i}}return{}}catch(t){return{}}}}class ma{static parseSCSTransaction(e,t){try{if(t||e.toBytes)try{const r=t||e.toBytes(),i=n.proto.TransactionList.decode(r);if(i.transactionList&&i.transactionList.length>0){const e=i.transactionList[0];let t=null;if(e.bodyBytes&&e.bodyBytes.length>0)t=n.proto.TransactionBody.decode(e.bodyBytes);else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const r=n.proto.SignedTransaction.decode(e.signedTransactionBytes);r.bodyBytes&&(t=n.proto.TransactionBody.decode(r.bodyBytes))}if(t){const e=this.parseFromProtobufTxBody(t);if(e.type&&"UNKNOWN"!==e.type)return e}}}catch(r){}return this.parseFromTransactionInternals(e)}catch(i){return{type:"UNKNOWN",humanReadableType:"Unknown Contract Transaction"}}}static parseFromProtobufTxBody(e){if(e.contractCall){const t=this.parseContractCall(e.contractCall);if(t)return{type:"CONTRACTCALL",humanReadableType:"Contract Call",contractCall:t}}if(e.contractCreateInstance){const t=this.parseContractCreate(e.contractCreateInstance);if(t)return{type:"CONTRACTCREATE",humanReadableType:"Contract Create",contractCreate:t}}if(e.contractUpdateInstance){const t=this.parseContractUpdate(e.contractUpdateInstance);if(t)return{type:"CONTRACTUPDATE",humanReadableType:"Contract Update",contractUpdate:t}}if(e.contractDeleteInstance){const t=this.parseContractDelete(e.contractDeleteInstance);if(t)return{type:"CONTRACTDELETE",humanReadableType:"Contract Delete",contractDelete:t}}if(e.ethereumTransaction){const t=this.parseEthereumTransaction(e.ethereumTransaction);if(t)return{type:"ETHEREUMTRANSACTION",humanReadableType:"Ethereum Transaction",ethereumTransaction:t}}return{}}static parseFromTransactionInternals(e){try{const t=e;if(t._contractId&&t._gas){const e={contractId:t._contractId.toString(),gas:"number"==typeof t._gas?t._gas:i.Long.fromValue(t._gas).toNumber(),amount:t._amount?parseFloat(t._amount.toString()):0};if(t._functionParameters){const r=a.Buffer.from(t._functionParameters).toString("hex");e.functionParameters=r,e.functionName=this.extractFunctionName(r)}return{type:"CONTRACTCALL",humanReadableType:"Contract Call",contractCall:e}}if(da(e,"contractCreateInstance")){const e={gas:t._gas.toString(),initialBalance:t._initialBalance?.toString()||"0"};return t._fileId?(e.initcodeSource="fileID",e.initcode=t._fileId.toString()):t._bytecode&&(e.initcodeSource="bytes",e.initcode=a.Buffer.from(t._bytecode).toString("hex")),t._constructorParameters&&(e.constructorParameters=a.Buffer.from(t._constructorParameters).toString("hex")),t._memo&&(e.memo=t._memo),t._adminKey&&(e.adminKey=ca(t._adminKey)),void 0!==t._maxAutomaticTokenAssociations&&(e.maxAutomaticTokenAssociations=t._maxAutomaticTokenAssociations),t._stakedAccountId?e.stakedAccountId=t._stakedAccountId.toString():null!==t._stakedNodeId&&void 0!==t._stakedNodeId&&(e.stakedNodeId=i.Long.fromValue(t._stakedNodeId).toString()),void 0!==t._declineReward&&(e.declineReward=t._declineReward),t._autoRenewPeriod&&(e.autoRenewPeriod=t._autoRenewPeriod.toString()),{type:"CONTRACTCREATE",humanReadableType:"Contract Create",contractCreate:e}}if(da(e,"contractUpdateInstance")){const e={contractIdToUpdate:t._contractId.toString()};return t._memo&&(e.memo=t._memo),t._adminKey&&(e.adminKey=ca(t._adminKey)),void 0!==t._maxAutomaticTokenAssociations&&(e.maxAutomaticTokenAssociations=t._maxAutomaticTokenAssociations),t._stakedAccountId?e.stakedAccountId=t._stakedAccountId.toString():null!==t._stakedNodeId&&void 0!==t._stakedNodeId&&(e.stakedNodeId=i.Long.fromValue(t._stakedNodeId).toString()),void 0!==t._declineReward&&(e.declineReward=t._declineReward),t._autoRenewPeriod&&(e.autoRenewPeriod=t._autoRenewPeriod.toString()),{type:"CONTRACTUPDATE",humanReadableType:"Contract Update",contractUpdate:e}}if(da(e,"contractDeleteInstance")){const e={contractIdToDelete:t._contractId.toString()};return t._transferAccountId?e.transferAccountId=t._transferAccountId.toString():t._transferContractId&&(e.transferContractId=t._transferContractId.toString()),{type:"CONTRACTDELETE",humanReadableType:"Contract Delete",contractDelete:e}}return{}}catch(t){return{}}}static extractFunctionName(e){if(e.length<8)return"unknown";const t=e.substring(0,8);return{a9059cbb:"transfer","095ea7b3":"approve","23b872dd":"transferFrom","70a08231":"balanceOf",dd62ed3e:"allowance","18160ddd":"totalSupply","06fdde03":"name","95d89b41":"symbol","313ce567":"decimals","42842e0e":"safeTransferFrom",b88d4fde:"safeTransferFrom",e985e9c5:"isApprovedForAll",a22cb465:"setApprovalForAll","6352211e":"ownerOf",c87b56dd:"tokenURI","01ffc9a7":"supportsInterface","40c10f19":"mint","42966c68":"burn",f2fde38b:"transferOwnership","715018a6":"renounceOwnership","8da5cb5b":"owner"}[t]||t}static parseEthereumTransaction(e){if(!e)return;const t={contractId:"EVM",gas:e.maxGasAllowance?i.Long.fromValue(e.maxGasAllowance).toNumber():0,amount:0};if(e.ethereumData&&e.ethereumData.length>0){const r=a.Buffer.from(e.ethereumData).toString("hex");t.functionParameters=r,r.length>=8&&(t.functionName=this.extractFunctionName(r))}return t}static parseContractCall(e){if(!e)return;const t=i.Hbar.fromTinybars(i.Long.fromValue(e.amount??0)),r={contractId:new i.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString(),gas:i.Long.fromValue(e.gas??0).toNumber(),amount:parseFloat(t.toString(i.HbarUnit.Hbar))};return e.functionParameters&&(r.functionParameters=a.Buffer.from(e.functionParameters).toString("hex"),r.functionParameters.length>=8&&(r.functionName=this.extractFunctionName(r.functionParameters))),r}static parseContractCreate(e){if(!e)return;const t={};return e.initialBalance&&(t.initialBalance=i.Hbar.fromTinybars(i.Long.fromValue(e.initialBalance)).toString(i.HbarUnit.Hbar)),e.gas&&(t.gas=i.Long.fromValue(e.gas).toString()),e.adminKey&&(t.adminKey=ca(e.adminKey)),e.constructorParameters&&(t.constructorParameters=a.Buffer.from(e.constructorParameters).toString("hex")),e.memo&&(t.memo=e.memo),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=i.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.stakedAccountId?t.stakedAccountId=new i.AccountId(e.stakedAccountId.shardNum??0,e.stakedAccountId.realmNum??0,e.stakedAccountId.accountNum??0).toString():null!==e.stakedNodeId&&void 0!==e.stakedNodeId&&(t.stakedNodeId=i.Long.fromValue(e.stakedNodeId).toString()),void 0!==e.declineReward&&(t.declineReward=e.declineReward),void 0!==e.maxAutomaticTokenAssociations&&(t.maxAutomaticTokenAssociations=e.maxAutomaticTokenAssociations),e.fileID?(t.initcodeSource="fileID",t.initcode=new i.FileId(e.fileID.shardNum??0,e.fileID.realmNum??0,e.fileID.fileNum??0).toString()):e.initcode&&e.initcode.length>0&&(t.initcodeSource="bytes",t.initcode=a.Buffer.from(e.initcode).toString("hex")),t}static parseContractUpdate(e){if(!e)return;const t={};if(e.contractID&&(t.contractIdToUpdate=new i.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),e.adminKey&&(t.adminKey=ca(e.adminKey)),e.expirationTime?.seconds&&(t.expirationTime=`${i.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=i.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.memo){const r=e.memo;if(r&&"object"==typeof r&&Object.prototype.hasOwnProperty.call(r,"value")){const e=r.value;t.memo=null==e?void 0:String(e)}else t.memo="string"==typeof r?r:void 0}else t.memo=void 0;return e.stakedAccountId?(t.stakedAccountId=new i.AccountId(e.stakedAccountId.shardNum??0,e.stakedAccountId.realmNum??0,e.stakedAccountId.accountNum??0).toString(),t.stakedNodeId=void 0):null!==e.stakedNodeId&&void 0!==e.stakedNodeId&&i.Long.fromValue(e.stakedNodeId).notEquals(-1)?(t.stakedNodeId=i.Long.fromValue(e.stakedNodeId).toString(),t.stakedAccountId=void 0):(t.stakedNodeId=void 0,t.stakedAccountId=void 0),void 0!==e.declineReward?.value&&(t.declineReward=e.declineReward.value),void 0!==e.maxAutomaticTokenAssociations?.value&&(t.maxAutomaticTokenAssociations=e.maxAutomaticTokenAssociations.value),e.autoRenewAccountId&&(t.autoRenewAccountId=new i.AccountId(e.autoRenewAccountId.shardNum??0,e.autoRenewAccountId.realmNum??0,e.autoRenewAccountId.accountNum??0).toString()),t}static parseContractDelete(e){if(!e)return;const t={};return e.contractID&&(t.contractIdToDelete=new i.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),e.transferAccountID?t.transferAccountId=new i.AccountId(e.transferAccountID.shardNum??0,e.transferAccountID.realmNum??0,e.transferAccountID.accountNum??0).toString():e.transferContractID&&(t.transferContractId=new i.ContractId(e.transferContractID.shardNum??0,e.transferContractID.realmNum??0,e.transferContractID.contractNum??0).toString()),t}static parseFromTransactionObject(e){return this.parseSCSTransaction(e)}}class fa{static parseUtilTransaction(e,t){try{if(t||e.toBytes)try{const r=t||e.toBytes(),i=n.proto.TransactionList.decode(r);if(i.transactionList&&i.transactionList.length>0){const e=i.transactionList[0];let t=null;if(e.bodyBytes&&e.bodyBytes.length>0)t=n.proto.TransactionBody.decode(e.bodyBytes);else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const r=n.proto.SignedTransaction.decode(e.signedTransactionBytes);r.bodyBytes&&(t=n.proto.TransactionBody.decode(r.bodyBytes))}if(t){const e=this.parseFromProtobufTxBody(t);if(e.type&&"UNKNOWN"!==e.type)return e}}}catch(r){}return this.parseFromTransactionInternals(e)}catch(i){return{type:"UNKNOWN",humanReadableType:"Unknown Utility Transaction"}}}static parseFromProtobufTxBody(e){if(e.utilPrng){const t=this.parseUtilPrng(e.utilPrng);if(t)return{type:"PRNG",humanReadableType:"Pseudo Random Number",utilPrng:t}}if(e.freeze){const t=this.parseNetworkFreezeFromProto(e.freeze);if(t)return{type:"FREEZE",humanReadableType:"Network Freeze",freeze:t}}if(e.systemDelete){const t=this.parseSystemDeleteFromProto(e.systemDelete);if(t)return{type:"SYSTEMDELETE",humanReadableType:"System Delete",systemDelete:t}}if(e.systemUndelete){const t=this.parseSystemUndeleteFromProto(e.systemUndelete);if(t)return{type:"SYSTEMUNDELETE",humanReadableType:"System Undelete",systemUndelete:t}}if(e.nodeCreate){const t=this.parseNodeCreateFromProto(e.nodeCreate);if(t)return{type:"NODECREATE",humanReadableType:"Node Create",nodeCreate:t}}if(e.nodeUpdate){const t=this.parseNodeUpdateFromProto(e.nodeUpdate);if(t)return{type:"NODEUPDATE",humanReadableType:"Node Update",nodeUpdate:t}}if(e.nodeDelete){const t=this.parseNodeDeleteFromProto(e.nodeDelete);if(t)return{type:"NODEDELETE",humanReadableType:"Node Delete",nodeDelete:t}}return{}}static parseFromTransactionInternals(e){try{const t=e;if(da(e,"utilPrng")){const e={};return t._range&&0!==t._range&&(e.range=t._range),{type:"PRNG",humanReadableType:"Pseudo Random Number",utilPrng:e}}if(da(e,"freeze")){const e={};return t._startTime&&(e.startTime=t._startTime.toString()),t._endTime&&(e.endTime=t._endTime.toString()),t._updateFile&&(e.updateFile=t._updateFile.toString()),t._fileHash&&(e.fileHash=globalThis.Buffer.from(t._fileHash).toString("hex")),t._freezeType&&(e.freezeType=t._freezeType),{type:"FREEZE",humanReadableType:"Network Freeze",freeze:e}}if(da(e,"systemDelete")){const e={};return t._fileId?e.fileId=t._fileId.toString():t._contractId&&(e.contractId=t._contractId.toString()),t._expirationTime&&(e.expirationTime=t._expirationTime.toString()),{type:"SYSTEMDELETE",humanReadableType:"System Delete",systemDelete:e}}if(da(e,"systemUndelete")){const e={};return t._fileId?e.fileId=t._fileId.toString():t._contractId&&(e.contractId=t._contractId.toString()),{type:"SYSTEMUNDELETE",humanReadableType:"System Undelete",systemUndelete:e}}return{}}catch(t){return{}}}static parseNetworkFreezeFromProto(e){if(!e)return;const t={};if(e.startTime?.seconds&&(t.startTime=`${i.Long.fromValue(e.startTime.seconds).toString()}.${e.startTime.nanos??0}`),e.updateFile&&(t.updateFile=new i.FileId(e.updateFile.shardNum??0,e.updateFile.realmNum??0,e.updateFile.fileNum??0).toString()),e.fileHash&&e.fileHash.length>0&&(t.fileHash=globalThis.Buffer.from(e.fileHash).toString("hex")),void 0!==e.freezeType){const r=["FREEZE_ONLY","PREPARE_UPGRADE","FREEZE_UPGRADE","FREEZE_ABORT"];t.freezeType=r[e.freezeType]||"FREEZE_ONLY"}return t}static parseSystemDeleteFromProto(e){if(!e)return;const t={};return e.fileID?t.fileId=new i.FileId(e.fileID.shardNum??0,e.fileID.realmNum??0,e.fileID.fileNum??0).toString():e.contractID&&(t.contractId=new i.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),e.expirationTime?.seconds&&(t.expirationTime=i.Long.fromValue(e.expirationTime.seconds).toString()),t}static parseSystemUndeleteFromProto(e){if(!e)return;const t={};return e.fileID?t.fileId=new i.FileId(e.fileID.shardNum??0,e.fileID.realmNum??0,e.fileID.fileNum??0).toString():e.contractID&&(t.contractId=new i.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),t}static parseNodeCreateFromProto(e){if(!e)return;const t={};return void 0!==e.nodeId&&(t.nodeId=i.Long.fromValue(e.nodeId).toNumber()),t}static parseNodeUpdateFromProto(e){if(!e)return;const t={};return void 0!==e.nodeId&&(t.nodeId=i.Long.fromValue(e.nodeId).toNumber()),t}static parseNodeDeleteFromProto(e){if(!e)return;const t={};return void 0!==e.nodeId&&(t.nodeId=i.Long.fromValue(e.nodeId).toNumber()),t}static parseUtilPrng(e){if(!e)return;const t={};return e.range&&0!==e.range&&(t.range=e.range),t}static parseFreeze(e){return this.parseNetworkFreezeFromProto(e)}static parseFromTransactionObject(e){return this.parseUtilTransaction(e)}}class ya{static parseScheduleTransaction(e,t){try{if(t||e.toBytes)try{const r=t||e.toBytes(),i=n.proto.TransactionList.decode(r);if(i.transactionList&&i.transactionList.length>0){const e=i.transactionList[0];let t=null;if(e.bodyBytes&&e.bodyBytes.length>0)t=n.proto.TransactionBody.decode(e.bodyBytes);else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const r=n.proto.SignedTransaction.decode(e.signedTransactionBytes);r.bodyBytes&&(t=n.proto.TransactionBody.decode(r.bodyBytes))}if(t){const e=this.parseFromProtobufTxBody(t);if(e.type&&"UNKNOWN"!==e.type)return e}}}catch(r){}return this.parseFromTransactionInternals(e)}catch(i){return{type:"UNKNOWN",humanReadableType:"Unknown Schedule Transaction"}}}static parseFromProtobufTxBody(e){if(e.scheduleCreate){const t=this.parseScheduleCreateFromProto(e.scheduleCreate);if(t)return{type:"SCHEDULECREATE",humanReadableType:"Schedule Create",scheduleCreate:t}}if(e.scheduleSign){const t=this.parseScheduleSignFromProto(e.scheduleSign);if(t)return{type:"SCHEDULESIGN",humanReadableType:"Schedule Sign",scheduleSign:t}}if(e.scheduleDelete){const t=this.parseScheduleDeleteFromProto(e.scheduleDelete);if(t)return{type:"SCHEDULEDELETE",humanReadableType:"Schedule Delete",scheduleDelete:t}}return{}}static parseFromTransactionInternals(e){try{const t=e;if(da(e,"scheduleCreate")){return{type:"SCHEDULECREATE",humanReadableType:"Schedule Create",scheduleCreate:{scheduledTransactionBody:globalThis.Buffer.from(t._scheduledTransaction).toString("base64"),memo:t._scheduleMemo,adminKey:t._adminKey?ca(t._adminKey):void 0,payerAccountId:t._payerAccountId?.toString(),expirationTime:t._expirationTime?.toString(),waitForExpiry:t._waitForExpiry||!1}}}if(da(e,"scheduleSign")){return{type:"SCHEDULESIGN",humanReadableType:"Schedule Sign",scheduleSign:{scheduleId:t._scheduleId.toString()}}}if(da(e,"scheduleDelete")){return{type:"SCHEDULEDELETE",humanReadableType:"Schedule Delete",scheduleDelete:{scheduleId:t._scheduleId.toString()}}}return{}}catch(t){return{}}}static parseScheduleCreateFromProto(e){if(!e)return;const t={};if(e.scheduledTransactionBody){const r=n.proto.SchedulableTransactionBody.encode(n.proto.SchedulableTransactionBody.create(e.scheduledTransactionBody)).finish();t.scheduledTransactionBody=globalThis.Buffer.from(r).toString("base64")}return e.memo&&(t.memo=e.memo),e.adminKey&&(t.adminKey=ca(e.adminKey)),e.payerAccountID&&(t.payerAccountId=new i.AccountId(e.payerAccountID.shardNum??0,e.payerAccountID.realmNum??0,e.payerAccountID.accountNum??0).toString()),e.expirationTime?.seconds&&(t.expirationTime=`${i.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos??0}`),void 0!==e.waitForExpiry&&(t.waitForExpiry=e.waitForExpiry),t}static parseScheduleSignFromProto(e){if(!e)return;const t={};return e.scheduleID&&(t.scheduleId=new i.ScheduleId(e.scheduleID.shardNum??0,e.scheduleID.realmNum??0,e.scheduleID.scheduleNum??0).toString()),t}static parseScheduleDeleteFromProto(e){if(!e)return;const t={};return e.scheduleID&&(t.scheduleId=new i.ScheduleId(e.scheduleID.shardNum??0,e.scheduleID.realmNum??0,e.scheduleID.scheduleNum??0).toString()),t}static parseScheduleCreate(e){try{return this.parseScheduleTransaction(e).scheduleCreate||null}catch(t){return console.warn("[ScheduleParser] Failed to parse schedule create:",t),null}}static parseScheduleSign(e){try{return this.parseScheduleTransaction(e).scheduleSign||null}catch(t){return console.warn("[ScheduleParser] Failed to parse schedule sign:",t),null}}static parseScheduleDelete(e){try{return this.parseScheduleTransaction(e).scheduleDelete||null}catch(t){return console.warn("[ScheduleParser] Failed to parse schedule delete:",t),null}}static extractScheduleInfo(e){try{const t=e._transactionBody;if(t?.scheduleRef)return{isScheduled:!0,scheduleRef:t.scheduleRef.toString()};const r=e;return r._scheduleId||r.scheduleId?{isScheduled:!0,scheduleRef:(r._scheduleId||r.scheduleId)?.toString()}:{isScheduled:!1}}catch(t){return{isScheduled:!1}}}static parseScheduledTransactionBody(e){try{let t;if(e.startsWith("0x")){const r=e.slice(2);t=new Uint8Array(globalThis.Buffer.from(r,"hex"))}else t=new Uint8Array(globalThis.Buffer.from(e,"base64"));const r=n.proto.SchedulableTransactionBody.decode(t),i=Object.keys(r).find(e=>null!==r[e]&&"transactionFee"!==e&&"memo"!==e);return i?{type:i.toUpperCase(),body:r[i],memo:r.memo,transactionFee:r.transactionFee?.toString()}:null}catch(t){return console.warn("[ScheduleParser] Failed to parse scheduled transaction body:",t),null}}static parseFromTransactionObject(e){return this.parseScheduleTransaction(e)}}const ba={TOKENCREATE:{bodyField:"tokenCreation",parser:ua.parseTokenCreate,resultField:"tokenCreation"},TOKENMINT:{bodyField:"tokenMint",parser:ua.parseTokenMint,resultField:"tokenMint"},TOKENBURN:{bodyField:"tokenBurn",parser:ua.parseTokenBurn,resultField:"tokenBurn"},TOKENUPDATE:{bodyField:"tokenUpdate",parser:ua.parseTokenUpdate,resultField:"tokenUpdate"},TOKENDELETE:{bodyField:"tokenDeletion",parser:ua.parseTokenDelete,resultField:"tokenDelete"},TOKENASSOCIATE:{bodyField:"tokenAssociate",parser:ua.parseTokenAssociate,resultField:"tokenAssociate"},TOKENDISSOCIATE:{bodyField:"tokenDissociate",parser:ua.parseTokenDissociate,resultField:"tokenDissociate"},TOKENFREEZE:{bodyField:"tokenFreeze",parser:ua.parseTokenFreeze,resultField:"tokenFreeze"},TOKENUNFREEZE:{bodyField:"tokenUnfreeze",parser:ua.parseTokenUnfreeze,resultField:"tokenUnfreeze"},TOKENGRANTKYC:{bodyField:"tokenGrantKyc",parser:ua.parseTokenGrantKyc,resultField:"tokenGrantKyc"},TOKENREVOKEKYC:{bodyField:"tokenRevokeKyc",parser:ua.parseTokenRevokeKyc,resultField:"tokenRevokeKyc"},TOKENPAUSE:{bodyField:"tokenPause",parser:ua.parseTokenPause,resultField:"tokenPause"},TOKENUNPAUSE:{bodyField:"tokenUnpause",parser:ua.parseTokenUnpause,resultField:"tokenUnpause"},TOKENWIPEACCOUNT:{bodyField:"tokenWipe",parser:ua.parseTokenWipeAccount,resultField:"tokenWipeAccount"},TOKENFEESCHEDULEUPDATE:{bodyField:"tokenFeeScheduleUpdate",parser:ua.parseTokenFeeScheduleUpdate,resultField:"tokenFeeScheduleUpdate"},TOKENAIRDROP:{bodyField:"tokenAirdrop",parser:ua.parseTokenAirdropFromProto,resultField:"tokenAirdrop"},TOPICCREATE:{bodyField:"consensusCreateTopic",parser:pa.parseConsensusCreateTopic,resultField:"consensusCreateTopic"},CONSENSUSSUBMITMESSAGE:{bodyField:"consensusSubmitMessage",parser:pa.parseConsensusSubmitMessage,resultField:"consensusSubmitMessage"},TOPICUPDATE:{bodyField:"consensusUpdateTopic",parser:pa.parseConsensusUpdateTopic,resultField:"consensusUpdateTopic"},TOPICDELETE:{bodyField:"consensusDeleteTopic",parser:pa.parseConsensusDeleteTopic,resultField:"consensusDeleteTopic"},ACCOUNTCREATE:{bodyField:"cryptoCreateAccount",parser:ga.parseCryptoCreateAccount,resultField:"cryptoCreateAccount"},ACCOUNTUPDATE:{bodyField:"cryptoUpdateAccount",parser:ga.parseCryptoUpdateAccount,resultField:"cryptoUpdateAccount"},ACCOUNTDELETE:{bodyField:"cryptoDelete",parser:ga.parseCryptoDelete,resultField:"cryptoDelete"},CRYPTOTRANSFER:{bodyField:"cryptoTransfer",parser:e=>{const t={transfers:[],tokenTransfers:[]};return ga.parseCryptoTransfers(e,t),t},resultField:"transfers",spreadResult:!0},APPROVEALLOWANCE:{bodyField:"cryptoApproveAllowance",parser:ga.parseCryptoApproveAllowance,resultField:"cryptoApproveAllowance"},DELETEALLOWANCE:{bodyField:"cryptoDeleteAllowance",parser:ga.parseCryptoDeleteAllowance,resultField:"cryptoDeleteAllowance"},FILECREATE:{bodyField:"fileCreate",parser:ha.parseFileCreate,resultField:"fileCreate"},FILEUPDATE:{bodyField:"fileUpdate",parser:ha.parseFileUpdate,resultField:"fileUpdate"},FILEDELETE:{bodyField:"fileDelete",parser:ha.parseFileDelete,resultField:"fileDelete"},FILEAPPEND:{bodyField:"fileAppend",parser:ha.parseFileAppend,resultField:"fileAppend"},CONTRACTCREATE:{bodyField:"contractCreateInstance",parser:ma.parseContractCreate,resultField:"contractCreate"},CONTRACTUPDATE:{bodyField:"contractUpdateInstance",parser:ma.parseContractUpdate,resultField:"contractUpdate"},CONTRACTDELETE:{bodyField:"contractDeleteInstance",parser:ma.parseContractDelete,resultField:"contractDelete"},CONTRACTCALL:{bodyField:"contractCall",parser:ma.parseContractCall,resultField:"contractCall"},ETHEREUMTRANSACTION:{bodyField:"ethereumTransaction",parser:ma.parseEthereumTransaction,resultField:"ethereumTransaction"},SCHEDULECREATE:{bodyField:"scheduleCreate",parser:ya.parseScheduleCreateFromProto,resultField:"scheduleCreate"},SCHEDULESIGN:{bodyField:"scheduleSign",parser:ya.parseScheduleSignFromProto,resultField:"scheduleSign"},SCHEDULEDELETE:{bodyField:"scheduleDelete",parser:ya.parseScheduleDeleteFromProto,resultField:"scheduleDelete"},PRNG:{bodyField:"utilPrng",parser:fa.parseUtilPrng,resultField:"utilPrng"},FREEZE:{bodyField:"freeze",parser:fa.parseFreeze,resultField:"freeze"},SYSTEMDELETE:{bodyField:"systemDelete",parser:e=>({fileId:e.fileID?`${e.fileID.shardNum}.${e.fileID.realmNum}.${e.fileID.fileNum}`:void 0,contractId:e.contractID?`${e.contractID.shardNum}.${e.contractID.realmNum}.${e.contractID.contractNum}`:void 0,expirationTime:e.expirationTime?.seconds?e.expirationTime.seconds.toString():void 0}),resultField:"systemDelete"},SYSTEMUNDELETE:{bodyField:"systemUndelete",parser:e=>({fileId:e.fileID?`${e.fileID.shardNum}.${e.fileID.realmNum}.${e.fileID.fileNum}`:void 0,contractId:e.contractID?`${e.contractID.shardNum}.${e.contractID.realmNum}.${e.contractID.contractNum}`:void 0}),resultField:"systemUndelete"},TOKENCANCELAIRDROP:{bodyField:"tokenCancelAirdrop",parser:e=>({pendingAirdrops:e.pendingAirdrops||[]}),resultField:"tokenCancelAirdrop"},TOKENCLAIMAIRDROP:{bodyField:"tokenClaimAirdrop",parser:e=>({pendingAirdrops:e.pendingAirdrops||[]}),resultField:"tokenClaimAirdrop"},TOKENREJECT:{bodyField:"tokenReject",parser:e=>({owner:e.owner?`${e.owner.shardNum}.${e.owner.realmNum}.${e.owner.accountNum}`:void 0,rejections:e.rejections||[]}),resultField:"tokenReject"},TOKENUPDATENFTS:{bodyField:"tokenUpdateNfts",parser:e=>({tokenId:e.token?`${e.token.shardNum}.${e.token.realmNum}.${e.token.tokenNum}`:void 0,serialNumbers:e.serialNumbers||[],metadata:e.metadata}),resultField:"tokenUpdateNfts"},TOKENWIPE:{bodyField:"tokenWipe",parser:ua.parseTokenWipeAccount,resultField:"tokenWipeAccount"},CRYPTOADDLIVEHASH:{bodyField:"cryptoAddLiveHash",parser:e=>({accountId:e.accountID?`${e.accountID.shardNum}.${e.accountID.realmNum}.${e.accountID.accountNum}`:void 0,liveHash:e.liveHash}),resultField:"cryptoAddLiveHash"},CRYPTODELETELIVEHASH:{bodyField:"cryptoDeleteLiveHash",parser:e=>({accountId:e.accountOfLiveHash?`${e.accountOfLiveHash.shardNum}.${e.accountOfLiveHash.realmNum}.${e.accountOfLiveHash.accountNum}`:void 0,liveHashToDelete:e.liveHashToDelete}),resultField:"cryptoDeleteLiveHash"},UNCHECKEDSUBMIT:{bodyField:"uncheckedSubmit",parser:e=>({topicId:e.topicID?`${e.topicID.shardNum}.${e.topicID.realmNum}.${e.topicID.topicNum}`:void 0,message:e.message}),resultField:"uncheckedSubmit"},NODECREATE:{bodyField:"nodeCreate",parser:e=>({accountId:e.accountId?`${e.accountId.shardNum}.${e.accountId.realmNum}.${e.accountId.accountNum}`:void 0,description:e.description,gossipEndpoint:e.gossipEndpoint,serviceEndpoint:e.serviceEndpoint,gossipCaCertificate:e.gossipCaCertificate,grpcCertificateHash:e.grpcCertificateHash,adminKey:e.adminKey}),resultField:"nodeCreate"},NODEUPDATE:{bodyField:"nodeUpdate",parser:e=>({nodeId:e.nodeId?.toString(),accountId:e.accountId?`${e.accountId.shardNum}.${e.accountId.realmNum}.${e.accountId.accountNum}`:void 0,description:e.description,gossipEndpoint:e.gossipEndpoint,serviceEndpoint:e.serviceEndpoint,gossipCaCertificate:e.gossipCaCertificate,grpcCertificateHash:e.grpcCertificateHash,adminKey:e.adminKey}),resultField:"nodeUpdate"},NODEDELETE:{bodyField:"nodeDelete",parser:e=>({nodeId:e.nodeId?.toString()}),resultField:"nodeDelete"},NODESTAKEUPDATE:{bodyField:"nodeStakeUpdate",parser:e=>({nodeId:e.nodeId?.toString(),maxStake:e.maxStake?.toString(),minStake:e.minStake?.toString(),rewardRate:e.rewardRate?.toString()}),resultField:"nodeStakeUpdate"},ATOMICBATCH:{bodyField:"atomicBatch",parser:e=>({transactions:e.transactions||[]}),resultField:"atomicBatch"},STATESIGNATURETRANSACTION:{bodyField:"stateSignatureTransaction",parser:e=>({signature:e.signature,round:e.round?.toString()}),resultField:"stateSignatureTransaction"},HISTORYPROOFSIGNATURE:{bodyField:"historyProofSignature",parser:e=>({signature:e.signature,round:e.round?.toString()}),resultField:"historyProofSignature"},HISTORYPROOFKEYPUBLICATION:{bodyField:"historyProofKeyPublication",parser:e=>({publicKey:e.publicKey,round:e.round?.toString()}),resultField:"historyProofKeyPublication"},HISTORYPROOFVOTE:{bodyField:"historyProofVote",parser:e=>({vote:e.vote,round:e.round?.toString()}),resultField:"historyProofVote"},HINTSPREPROCESSINGVOTE:{bodyField:"hintsPreprocessingVote",parser:e=>({vote:e.vote,round:e.round?.toString()}),resultField:"hintsPreprocessingVote"},HINTSKEYPUBLICATION:{bodyField:"hintsKeyPublication",parser:e=>({publicKey:e.publicKey,round:e.round?.toString()}),resultField:"hintsKeyPublication"},HINTSPARTIALSIGNATURE:{bodyField:"hintsPartialSignature",parser:e=>({signature:e.signature,round:e.round?.toString()}),resultField:"hintsPartialSignature"},CRSPUBLICATION:{bodyField:"crsPublication",parser:e=>({crs:e.crs,round:e.round?.toString()}),resultField:"crsPublication"}};const wa={tokenCreation:{type:"TOKENCREATE",humanReadableType:"Token Creation"},tokenAirdrop:{type:"TOKENAIRDROP",humanReadableType:"Token Airdrop"},tokenMint:{type:"TOKENMINT",humanReadableType:"Token Mint"},tokenBurn:{type:"TOKENBURN",humanReadableType:"Token Burn"},tokenUpdate:{type:"TOKENUPDATE",humanReadableType:"Token Update"},tokenDeletion:{type:"TOKENDELETE",humanReadableType:"Token Deletion"},tokenAssociate:{type:"TOKENASSOCIATE",humanReadableType:"Token Association"},tokenDissociate:{type:"TOKENDISSOCIATE",humanReadableType:"Token Dissociation"},tokenFreeze:{type:"TOKENFREEZE",humanReadableType:"Token Freeze"},tokenUnfreeze:{type:"TOKENUNFREEZE",humanReadableType:"Token Unfreeze"},tokenGrantKyc:{type:"TOKENGRANTKYC",humanReadableType:"Token Grant KYC"},tokenRevokeKyc:{type:"TOKENREVOKEKYC",humanReadableType:"Token Revoke KYC"},tokenPause:{type:"TOKENPAUSE",humanReadableType:"Token Pause"},tokenUnpause:{type:"TOKENUNPAUSE",humanReadableType:"Token Unpause"},tokenWipe:{type:"TOKENWIPE",humanReadableType:"Token Wipe"},tokenFeeScheduleUpdate:{type:"TOKENFEESCHEDULEUPDATE",humanReadableType:"Token Fee Schedule Update"},tokenCancelAirdrop:{type:"TOKENCANCELAIRDROP",humanReadableType:"Cancel Token Airdrop"},tokenClaimAirdrop:{type:"TOKENCLAIMAIRDROP",humanReadableType:"Claim Token Airdrop"},tokenReject:{type:"TOKENREJECT",humanReadableType:"Token Reject"},tokenUpdateNfts:{type:"TOKENUPDATENFTS",humanReadableType:"Update NFT Metadata"},cryptoTransfer:{type:"CRYPTOTRANSFER",humanReadableType:"Crypto Transfer"},cryptoCreateAccount:{type:"ACCOUNTCREATE",humanReadableType:"Account Creation"},cryptoUpdateAccount:{type:"ACCOUNTUPDATE",humanReadableType:"Account Update"},cryptoDelete:{type:"ACCOUNTDELETE",humanReadableType:"Account Deletion"},cryptoApproveAllowance:{type:"APPROVEALLOWANCE",humanReadableType:"Approve Allowance"},cryptoDeleteAllowance:{type:"DELETEALLOWANCE",humanReadableType:"Delete Allowance"},cryptoAddLiveHash:{type:"CRYPTOADDLIVEHASH",humanReadableType:"Add Live Hash"},cryptoDeleteLiveHash:{type:"CRYPTODELETELIVEHASH",humanReadableType:"Delete Live Hash"},consensusCreateTopic:{type:"TOPICCREATE",humanReadableType:"Topic Creation"},consensusSubmitMessage:{type:"CONSENSUSSUBMITMESSAGE",humanReadableType:"Submit Message"},consensusUpdateTopic:{type:"TOPICUPDATE",humanReadableType:"Topic Update"},consensusDeleteTopic:{type:"TOPICDELETE",humanReadableType:"Topic Deletion"},uncheckedSubmit:{type:"UNCHECKEDSUBMIT",humanReadableType:"Unchecked Submit"},contractCall:{type:"CONTRACTCALL",humanReadableType:"Contract Call"},contractCreateInstance:{type:"CONTRACTCREATE",humanReadableType:"Contract Creation"},contractUpdateInstance:{type:"CONTRACTUPDATE",humanReadableType:"Contract Update"},contractDeleteInstance:{type:"CONTRACTDELETE",humanReadableType:"Contract Deletion"},ethereumTransaction:{type:"ETHEREUMTRANSACTION",humanReadableType:"Ethereum Transaction"},fileCreate:{type:"FILECREATE",humanReadableType:"File Creation"},fileUpdate:{type:"FILEUPDATE",humanReadableType:"File Update"},fileDelete:{type:"FILEDELETE",humanReadableType:"File Deletion"},fileAppend:{type:"FILEAPPEND",humanReadableType:"File Append"},scheduleCreate:{type:"SCHEDULECREATE",humanReadableType:"Schedule Creation"},scheduleSign:{type:"SCHEDULESIGN",humanReadableType:"Schedule Sign"},scheduleDelete:{type:"SCHEDULEDELETE",humanReadableType:"Schedule Deletion"},freeze:{type:"FREEZE",humanReadableType:"Network Freeze"},systemDelete:{type:"SYSTEMDELETE",humanReadableType:"System Delete"},systemUndelete:{type:"SYSTEMUNDELETE",humanReadableType:"System Undelete"},nodeCreate:{type:"NODECREATE",humanReadableType:"Node Creation"},nodeUpdate:{type:"NODEUPDATE",humanReadableType:"Node Update"},nodeDelete:{type:"NODEDELETE",humanReadableType:"Node Deletion"},nodeStakeUpdate:{type:"NODESTAKEUPDATE",humanReadableType:"Node Stake Update"},utilPrng:{type:"PRNG",humanReadableType:"Pseudo Random Number"},atomicBatch:{type:"ATOMICBATCH",humanReadableType:"Atomic Batch"},stateSignatureTransaction:{type:"STATESIGNATURETRANSACTION",humanReadableType:"State Signature"},historyProofSignature:{type:"HISTORYPROOFSIGNATURE",humanReadableType:"History Proof Signature"},historyProofKeyPublication:{type:"HISTORYPROOFKEYPUBLICATION",humanReadableType:"History Proof Key Publication"},historyProofVote:{type:"HISTORYPROOFVOTE",humanReadableType:"History Proof Vote"},hintsPreprocessingVote:{type:"HINTSPREPROCESSINGVOTE",humanReadableType:"Hints Preprocessing Vote"},hintsKeyPublication:{type:"HINTSKEYPUBLICATION",humanReadableType:"Hints Key Publication"},hintsPartialSignature:{type:"HINTSPARTIALSIGNATURE",humanReadableType:"Hints Partial Signature"},crsPublication:{type:"CRSPUBLICATION",humanReadableType:"CRS Publication"},transactionID:{type:"UNKNOWN",humanReadableType:"Unknown Transaction"},nodeAccountID:{type:"UNKNOWN",humanReadableType:"Unknown Transaction"},transactionFee:{type:"UNKNOWN",humanReadableType:"Unknown Transaction"},transactionValidDuration:{type:"UNKNOWN",humanReadableType:"Unknown Transaction"},generateRecord:{type:"UNKNOWN",humanReadableType:"Unknown Transaction"},memo:{type:"UNKNOWN",humanReadableType:"Unknown Transaction"},batchKey:{type:"UNKNOWN",humanReadableType:"Unknown Transaction"},maxCustomFees:{type:"UNKNOWN",humanReadableType:"Unknown Transaction"}},Ia={cryptoTransfer:"HBAR Transfer",CRYPTOTRANSFER:"HBAR Transfer",cryptoCreateAccount:"Create Account",ACCOUNTCREATE:"Create Account",cryptoUpdateAccount:"Update Account",ACCOUNTUPDATE:"Update Account",cryptoDeleteAccount:"Delete Account",cryptoDelete:"Delete Account",ACCOUNTDELETE:"Delete Account",cryptoApproveAllowance:"Approve Allowance",APPROVEALLOWANCE:"Approve Allowance",cryptoDeleteAllowance:"Delete Allowance",DELETEALLOWANCE:"Delete Allowance",CRYPTOADDLIVEHASH:"Add Live Hash",CRYPTODELETELIVEHASH:"Delete Live Hash",consensusCreateTopic:"Create Topic",TOPICCREATE:"Create Topic",consensusUpdateTopic:"Update Topic",TOPICUPDATE:"Update Topic",consensusSubmitMessage:"Submit Message",CONSENSUSSUBMITMESSAGE:"Submit Message",consensusDeleteTopic:"Delete Topic",TOPICDELETE:"Delete Topic",UNCHECKEDSUBMIT:"Unchecked Submit",fileCreate:"Create File",FILECREATE:"Create File",fileAppend:"Append File",FILEAPPEND:"Append File",fileUpdate:"Update File",FILEUPDATE:"Update File",fileDelete:"Delete File",FILEDELETE:"Delete File",contractCall:"Contract Call",CONTRACTCALL:"Contract Call",contractCreate:"Create Contract",CONTRACTCREATE:"Create Contract",contractUpdate:"Update Contract",CONTRACTUPDATE:"Update Contract",contractDelete:"Delete Contract",CONTRACTDELETE:"Delete Contract",ethereumTransaction:"Ethereum Transaction",ETHEREUMTRANSACTION:"Ethereum Transaction",tokenCreate:"Create Token",TOKENCREATE:"Create Token",tokenUpdate:"Update Token",TOKENUPDATE:"Update Token",tokenDelete:"Delete Token",TOKENDELETE:"Delete Token",tokenAssociate:"Associate Token",TOKENASSOCIATE:"Associate Token",tokenDissociate:"Dissociate Token",TOKENDISSOCIATE:"Dissociate Token",tokenMint:"Mint Token",TOKENMINT:"Mint Token",tokenBurn:"Burn Token",TOKENBURN:"Burn Token",tokenFeeScheduleUpdate:"Update Token Fee Schedule",TOKENFEESCHEDULEUPDATE:"Update Token Fee Schedule",tokenFreeze:"Freeze Token",TOKENFREEZE:"Freeze Token",tokenUnfreeze:"Unfreeze Token",TOKENUNFREEZE:"Unfreeze Token",tokenGrantKyc:"Grant KYC",TOKENGRANTKYC:"Grant KYC",tokenRevokeKyc:"Revoke KYC",TOKENREVOKEKYC:"Revoke KYC",tokenPause:"Pause Token",TOKENPAUSE:"Pause Token",tokenUnpause:"Unpause Token",TOKENUNPAUSE:"Unpause Token",tokenWipe:"Wipe Token",TOKENWIPE:"Wipe Token",tokenAirdrop:"Token Airdrop",TOKENAIRDROP:"Token Airdrop",TOKENCANCELAIRDROP:"Cancel Token Airdrop",TOKENCLAIMAIRDROP:"Claim Token Airdrop",TOKENREJECT:"Token Reject",TOKENUPDATENFTS:"Update NFT Metadata",scheduleCreate:"Create Schedule",SCHEDULECREATE:"Create Schedule",scheduleSign:"Sign Schedule",SCHEDULESIGN:"Sign Schedule",SCHEDULEDELETE:"Delete Schedule",FREEZE:"Network Freeze",SYSTEMDELETE:"System Delete",SYSTEMUNDELETE:"System Undelete",NODECREATE:"Create Node",NODEUPDATE:"Update Node",NODEDELETE:"Delete Node",NODESTAKEUPDATE:"Update Node Stake",utilPrng:"Generate Random Number",PRNG:"Generate Random Number",ATOMICBATCH:"Atomic Batch",STATESIGNATURETRANSACTION:"State Signature",HISTORYPROOFSIGNATURE:"History Proof Signature",HISTORYPROOFKEYPUBLICATION:"History Proof Key Publication",HISTORYPROOFVOTE:"History Proof Vote",HINTSPREPROCESSINGVOTE:"Hints Preprocessing Vote",HINTSKEYPUBLICATION:"Hints Key Publication",HINTSPARTIALSIGNATURE:"Hints Partial Signature",CRSPUBLICATION:"CRS Publication",unknown:"Unknown Transaction",UNKNOWN:"Unknown Transaction"},Ta={tokenCreation:"tokenCreate",tokenAirdrop:"tokenAirdrop",cryptoTransfer:"cryptoTransfer",consensusSubmitMessage:"consensusSubmitMessage",contractCall:"contractCall",cryptoCreateAccount:"cryptoCreateAccount",cryptoUpdateAccount:"cryptoUpdateAccount",cryptoApproveAllowance:"cryptoApproveAllowance",cryptoDeleteAllowance:"cryptoDeleteAllowance",cryptoDelete:"cryptoDelete",consensusCreateTopic:"consensusCreateTopic",consensusUpdateTopic:"consensusUpdateTopic",consensusDeleteTopic:"consensusDeleteTopic",fileCreate:"fileCreate",fileAppend:"fileAppend",fileUpdate:"fileUpdate",fileDelete:"fileDelete",contractCreateInstance:"contractCreate",contractUpdateInstance:"contractUpdate",contractDeleteInstance:"contractDelete",tokenUpdate:"tokenUpdate",tokenDeletion:"tokenDelete",tokenAssociate:"tokenAssociate",tokenDissociate:"tokenDissociate",tokenMint:"tokenMint",tokenBurn:"tokenBurn",tokenFeeScheduleUpdate:"tokenFeeScheduleUpdate",tokenFreeze:"tokenFreeze",tokenUnfreeze:"tokenUnfreeze",tokenGrantKyc:"tokenGrantKyc",tokenRevokeKyc:"tokenRevokeKyc",tokenPause:"tokenPause",tokenUnpause:"tokenUnpause",tokenWipe:"tokenWipe",utilPrng:"utilPrng"};function Sa(e){for(const[t,r]of Object.entries(wa))if(e[t])return r;return{type:"UNKNOWN",humanReadableType:"Unknown Transaction"}}function ka(e){return Ia[e]||"Unknown Transaction"}class Ea{static async parseTransactionBytes(e,t={}){const{enableFallback:r=!0,strictMode:i=!1,includeRaw:o=!0,maxRetries:n=2}=t,s=this.validateTransactionBytes(e);if(!s.isValid&&i)throw new ps(`Invalid transaction bytes format: ${s.error}`,"INVALID_FORMAT",void 0,e);let a,c=0;for(;c<=n;)try{const r=await this.parseTransaction(e,t);return r.formatDetection={originalFormat:s.format||"base64",wasConverted:"hex"===s.format,length:e.length},r}catch(d){if(a=d instanceof Error?d:new Error(String(d)),c++,!r||c>n){if(i)throw new ps("Failed to parse transaction after all attempts","PARSING_FAILED",a,e);break}try{const r=this.parseScheduledTransaction(e,t);return r.formatDetection={originalFormat:s.format||"base64",wasConverted:!1,length:e.length},r}catch(u){}}const l=this.createFallbackResult(e,a,void 0);return l.details&&(l.details.parseAttempts=Math.max(c,1)),l}static parseTransactionObject(e,t,r={}){let i,o;!t||a.Buffer.isBuffer(t)||t instanceof Uint8Array?(i=t,o=r):(o=t,i=void 0);try{const t=this.extractTransactionMetadata(e),r=ua.parseFromTransactionObject(e),a=ga.parseFromTransactionObject(e),c=pa.parseFromTransactionObject(e),l=ha.parseFromTransactionObject(e),d=ma.parseFromTransactionObject(e),u=ya.parseFromTransactionObject(e),p=fa.parseFromTransactionObject(e),h=[r,a,c,l,d,u,p].find(e=>e.type&&"UNKNOWN"!==e.type)||{};let g,m="UNKNOWN",f="Unknown Transaction",y={};if(i||e.toBytes)try{const t=i||e.toBytes(),r=n.proto.TransactionList.decode(t);if(r.transactionList&&r.transactionList.length>0){const e=r.transactionList[0];if(e.bodyBytes&&e.bodyBytes.length>0){const t=n.proto.TransactionBody.decode(e.bodyBytes),r=this.detectTransactionTypeFromBody(t);m=r.type,f=r.humanReadableType,y=this.parseTransactionBodyDetails(t,m),y.tokenCreation&&(g=y.tokenCreation)}else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const t=n.proto.SignedTransaction.decode(e.signedTransactionBytes);if(t.bodyBytes){const e=n.proto.TransactionBody.decode(t.bodyBytes),r=this.detectTransactionTypeFromBody(e);m=r.type,f=r.humanReadableType,y=this.parseTransactionBodyDetails(e,m),y.tokenCreation&&(g=y.tokenCreation)}}}}catch(s){}"UNKNOWN"===m&&h.type&&(m=h.type,f=h.humanReadableType||f);const b={type:m,humanReadableType:f,transfers:[],tokenTransfers:[],...t,...h,raw:o.includeRaw?e._transactionBody||{}:void 0};return this.mergeProtoParsingResults(b,y,r,e,i),b.transfers=a.transfers||b.transfers||[],b.tokenTransfers=a.tokenTransfers||b.tokenTransfers||[],b}catch(c){return{type:"UNKNOWN",humanReadableType:"Unknown Transaction",transfers:[],tokenTransfers:[],raw:o.includeRaw?{}:void 0,details:{error:`Failed to parse Transaction object: ${c instanceof Error?c.message:String(c)}`}}}}static parseTransactionBody(e){try{const t=c.ethers.decodeBase64(e),r=n.proto.SchedulableTransactionBody.decode(t),o=this.getTransactionType(r),s={type:o,humanReadableType:this.getHumanReadableType(o),transfers:[],tokenTransfers:[],raw:r};if(r.memo&&(s.memo=r.memo),r.transactionFee){const e=i.Hbar.fromTinybars(i.Long.fromValue(r.transactionFee));s.transactionFee=e.toString(i.HbarUnit.Hbar)}return this.applySchedulableTransactionParsing(r,s),s}catch(t){return{type:"UNKNOWN",humanReadableType:"Unknown Transaction",transfers:[],tokenTransfers:[],raw:void 0,details:{error:`Failed to parse transaction body: ${t instanceof Error?t.message:String(t)}`}}}}static detectTransactionTypeFromBody(e){return Sa(e)}static parseScheduleResponse(e){if(!e.transaction_body)return{type:"UNKNOWN",humanReadableType:"Unknown Transaction",transfers:[],tokenTransfers:[],raw:void 0,details:{error:"Schedule response missing transaction_body"}};const t=this.parseTransactionBody(e.transaction_body);return e.memo&&(t.memo=e.memo),t}static getTransactionType(e){return Sa(e).type}static getHumanReadableType(e){return ka(e)}static getTransactionSummary(e){return aa(e)}static validateTransactionBytes(e){if(!e||"string"!=typeof e)return{isValid:!1,error:"Transaction bytes must be a non-empty string"};const t=this.detectTransactionFormat(e),r=/^[A-Za-z0-9+/]*={0,2}$/;let i,o=!1;return"hex"===t?(o=/^0x[0-9a-fA-F]+$/.test(e)&&e.length>2,o||(i="Invalid hex format")):(o=r.test(e)&&e.length>0,o||(i="Invalid base64 format")),{isValid:o,format:t,error:i,length:e.length}}static detectTransactionFormat(e){return e.startsWith("0x")?"hex":"base64"}static decodeTransactionBytes(e){try{if("hex"===this.detectTransactionFormat(e)){const t=e.slice(2);return new Uint8Array(a.Buffer.from(t,"hex"))}return new Uint8Array(a.Buffer.from(e,"base64"))}catch(t){throw new ps("Failed to decode transaction bytes","DECODE_ERROR",t instanceof Error?t:void 0,e)}}static async isValidHederaTransaction(e){try{if(!this.validateTransactionBytes(e).isValid)return!1;const t=this.decodeTransactionBytes(e);return i.Transaction.fromBytes(t),!0}catch{return!1}}static decodeBytesLegacy(e){return this.decodeTransactionBytes(e)}static async parseTransaction(e,t={}){try{const r=this.decodeTransactionBytes(e),o=i.Transaction.fromBytes(r),n=this.extractTransactionMetadataEnhanced(o),s=this.runAllParsers(o),a=s.find(e=>e.type&&"UNKNOWN"!==e.type)||{},c=this.parseFromProtobuf(r),l=c.type||a.type||"UNKNOWN",d={type:l,humanReadableType:c.humanReadableType||a.humanReadableType||"Unknown Transaction",transfers:[],tokenTransfers:[],details:{...n},memo:"string"==typeof n.memo?n.memo:void 0,transactionId:"string"==typeof n.transactionId?n.transactionId:void 0,nodeAccountIds:Array.isArray(n.nodeAccountIds)?n.nodeAccountIds:[],maxTransactionFee:"string"==typeof n.maxTransactionFee?n.maxTransactionFee:void 0,validStart:"string"==typeof n.validStart?n.validStart:void 0,validDuration:"string"==typeof n.validDuration?n.validDuration:void 0,raw:t.includeRaw?{}:void 0};return this.mergeAllResults(d,c,a,s),d}catch(r){throw new ps("Failed to parse as regular transaction","REGULAR_PARSING_FAILED",r instanceof Error?r:void 0,e)}}static parseScheduledTransaction(e,t={}){try{const t=this.parseTransactionBody(e),r=this.validateTransactionBytes(e);return{...t,details:{...t.details||{},parseMethod:"scheduled",validation:r,parseAttempts:t.details?.parseAttempts||1},formatDetection:{originalFormat:r.format||"base64",wasConverted:!1,length:e.length}}}catch(r){throw new ps("Failed to parse as scheduled transaction","SCHEDULED_PARSING_FAILED",r instanceof Error?r:void 0,e)}}static extractTransactionMetadata(e){return{transactionId:e.transactionId?.toString(),nodeAccountIds:e.nodeAccountIds?.map(e=>e.toString())||[],maxTransactionFee:e.maxTransactionFee?.toTinybars().toString()||"0",memo:e._transactionMemo||void 0,transfers:[],tokenTransfers:[]}}static extractTransactionMetadataEnhanced(e){return{transactionId:e.transactionId?.toString(),nodeAccountIds:e.nodeAccountIds?.map(e=>e.toString())||[],maxTransactionFee:e.maxTransactionFee?.toTinybars().toString()||"0",memo:e._transactionMemo||void 0,validStart:e._transactionValidStart?.toString(),validDuration:e._transactionValidDuration?.toString()}}static runAllParsers(e){return[ua.parseFromTransactionObject(e),ga.parseFromTransactionObject(e),pa.parseFromTransactionObject(e),ha.parseFromTransactionObject(e),ma.parseFromTransactionObject(e),ya.parseFromTransactionObject(e),fa.parseFromTransactionObject(e)]}static parseFromProtobuf(e){const t={};try{const r=n.proto.TransactionList.decode(e);if(r.transactionList&&r.transactionList.length>0){const e=r.transactionList[0];let i=null;if(e.bodyBytes&&e.bodyBytes.length>0)i=n.proto.TransactionBody.decode(e.bodyBytes);else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const t=n.proto.SignedTransaction.decode(e.signedTransactionBytes);t.bodyBytes&&(i=n.proto.TransactionBody.decode(t.bodyBytes))}if(i){const e=this.detectTransactionTypeFromBody(i);t.type=e.type,t.humanReadableType=e.humanReadableType;const r=this.parseTransactionBodyDetails(i,e.type);Object.assign(t,r)}}}catch(r){}return t}static mergeAllResults(e,t,r,i){const o=i.find(e=>e.transfers||e.tokenTransfers)||{};e.transfers=o.transfers||e.transfers||[],e.tokenTransfers=o.tokenTransfers||e.tokenTransfers||[],Object.keys(t).forEach(r=>{void 0!==t[r]&&"type"!==r&&"humanReadableType"!==r&&(e[r]=t[r])}),Object.keys(r).forEach(t=>{void 0===r[t]||t in e||"type"===t||"humanReadableType"===t||(e[t]=r[t])})}static applySchedulableTransactionParsing(e,t){e.cryptoTransfer&&ga.parseCryptoTransfers(e.cryptoTransfer,t),e.cryptoDelete&&(t.cryptoDelete=ga.parseCryptoDelete(e.cryptoDelete)),e.cryptoCreateAccount&&(t.cryptoCreateAccount=ga.parseCryptoCreateAccount(e.cryptoCreateAccount)),e.cryptoUpdateAccount&&(t.cryptoUpdateAccount=ga.parseCryptoUpdateAccount(e.cryptoUpdateAccount)),e.cryptoApproveAllowance&&(t.cryptoApproveAllowance=ga.parseCryptoApproveAllowance(e.cryptoApproveAllowance)),e.cryptoDeleteAllowance&&(t.cryptoDeleteAllowance=ga.parseCryptoDeleteAllowance(e.cryptoDeleteAllowance)),e.contractCall&&(t.contractCall=ma.parseContractCall(e.contractCall)),e.contractCreateInstance&&(t.contractCreate=ma.parseContractCreate(e.contractCreateInstance)),e.contractUpdateInstance&&(t.contractUpdate=ma.parseContractUpdate(e.contractUpdateInstance)),e.contractDeleteInstance&&(t.contractDelete=ma.parseContractDelete(e.contractDeleteInstance)),e.tokenCreation&&(t.tokenCreation=ua.parseTokenCreate(e.tokenCreation)),e.tokenMint&&(t.tokenMint=ua.parseTokenMint(e.tokenMint)),e.tokenBurn&&(t.tokenBurn=ua.parseTokenBurn(e.tokenBurn)),e.tokenUpdate&&(t.tokenUpdate=ua.parseTokenUpdate(e.tokenUpdate)),e.tokenFeeScheduleUpdate&&(t.tokenFeeScheduleUpdate=ua.parseTokenFeeScheduleUpdate(e.tokenFeeScheduleUpdate)),e.tokenFreeze&&(t.tokenFreeze=ua.parseTokenFreeze(e.tokenFreeze)),e.tokenUnfreeze&&(t.tokenUnfreeze=ua.parseTokenUnfreeze(e.tokenUnfreeze)),e.tokenGrantKyc&&(t.tokenGrantKyc=ua.parseTokenGrantKyc(e.tokenGrantKyc)),e.tokenRevokeKyc&&(t.tokenRevokeKyc=ua.parseTokenRevokeKyc(e.tokenRevokeKyc)),e.tokenPause&&(t.tokenPause=ua.parseTokenPause(e.tokenPause)),e.tokenUnpause&&(t.tokenUnpause=ua.parseTokenUnpause(e.tokenUnpause)),e.tokenWipe&&(t.tokenWipeAccount=ua.parseTokenWipeAccount(e.tokenWipe)),e.tokenDeletion&&(t.tokenDelete=ua.parseTokenDelete(e.tokenDeletion)),e.tokenAssociate&&(t.tokenAssociate=ua.parseTokenAssociate(e.tokenAssociate)),e.tokenDissociate&&(t.tokenDissociate=ua.parseTokenDissociate(e.tokenDissociate)),e.tokenAirdrop&&(t.tokenAirdrop=ua.parseTokenAirdropFromProto(e.tokenAirdrop)),e.consensusCreateTopic&&(t.consensusCreateTopic=pa.parseConsensusCreateTopic(e.consensusCreateTopic)),e.consensusSubmitMessage&&(t.consensusSubmitMessage=pa.parseConsensusSubmitMessage(e.consensusSubmitMessage)),e.consensusUpdateTopic&&(t.consensusUpdateTopic=pa.parseConsensusUpdateTopic(e.consensusUpdateTopic)),e.consensusDeleteTopic&&(t.consensusDeleteTopic=pa.parseConsensusDeleteTopic(e.consensusDeleteTopic)),e.fileCreate&&(t.fileCreate=ha.parseFileCreate(e.fileCreate)),e.fileAppend&&(t.fileAppend=ha.parseFileAppend(e.fileAppend)),e.fileUpdate&&(t.fileUpdate=ha.parseFileUpdate(e.fileUpdate)),e.fileDelete&&(t.fileDelete=ha.parseFileDelete(e.fileDelete)),e.utilPrng&&(t.utilPrng=fa.parseUtilPrng(e.utilPrng))}static parseTransactionBodyDetails(e,t){const r={},i=ba[t];if(i){const t=e[i.bodyField];if(t){const e=i.parser(t);i.spreadResult?Object.assign(r,e):r[i.resultField]=e}}return r}static mergeProtoParsingResults(e,t,r,i,o){const n=Object.values(ba).map(e=>e.resultField);for(const s of n){const o=t[s],n=r[s];void 0!==o?e[s]=o:void 0!==n?e[s]=n:this.handleSpecialFieldExtraction(e,s,i)}}static handleSpecialFieldExtraction(e,t,r){if("tokenCreation"===t&&"TOKENCREATE"===e.type){const i=ua.extractTokenCreationFromTransaction(r);i&&(e[t]=i)}else if("tokenAirdrop"===t&&"TOKENAIRDROP"===e.type){const i=ua.extractTokenAirdropFromTransaction(r);i&&(e[t]=i)}}static createFallbackResult(e,t,r){const i=this.validateTransactionBytes(e);return{type:"UNKNOWN",humanReadableType:"Unknown Transaction",transfers:[],tokenTransfers:[],details:{rawBytes:e.length>100?e.substring(0,100)+"...":e,primaryError:t?.message,secondaryError:r?.message,parseAttempts:r?2:1,validation:i},formatDetection:{originalFormat:i.format||"base64",wasConverted:!1,length:e.length},raw:{}}}}const va="undefined"!=typeof window&&void 0!==window.document;const Aa=new class{constructor(){this.cache=new Map,this.maxSize=100,this.defaultTtlMs=3e5}generateKey(e){return`${e.inputHash}-${e.clientConfigHash}-${e.optionsHash}`}hashObject(e){return globalThis.Buffer.from(JSON.stringify(e)).toString("base64").slice(0,16)}createCacheKey(e,t,r){return{inputHash:this.hashObject(e),clientConfigHash:this.hashObject({accountId:t.accountId,network:t.network}),optionsHash:this.hashObject({mode:r.mode,apiKey:r.apiKey?"present":"absent",network:r.network,metadata:r.metadata})}}get(e){const t=this.generateKey(e),r=this.cache.get(t);if(!r)return null;return Date.now()-r.timestamp>r.ttlMs?(this.cache.delete(t),null):(this.cache.delete(t),this.cache.set(t,r),r.quote)}set(e,t,r=this.defaultTtlMs){const i=this.generateKey(e);if(this.cache.size>=this.maxSize){const e=this.cache.keys().next().value;e&&this.cache.delete(e)}this.cache.set(i,{quote:t,timestamp:Date.now(),ttlMs:r})}clear(){this.cache.clear()}},Ca=new class{constructor(){this.cache=new Map,this.maxSize=10,this.defaultTtlMs=18e5}generateConfigKey(e){return globalThis.Buffer.from(JSON.stringify(e)).toString("base64")}get(e){const t=this.generateConfigKey(e),r=this.cache.get(t);if(!r)return null;return Date.now()-r.timestamp>this.defaultTtlMs?(this.cache.delete(t),null):r.sdk}set(e,t){const r=this.generateConfigKey(e);if(this.cache.size>=this.maxSize){const e=this.cache.keys().next().value;e&&this.cache.delete(e)}this.cache.set(r,{sdk:t,timestamp:Date.now(),config:r})}clear(){this.cache.clear()}};async function xa(e,t,r){if(r)return r;const i=t.connectionMode??"auto",o={apiKey:t.apiKey,accountId:e.accountId,network:e.network||"mainnet",authType:t.apiKey?"api":"server",connectionMode:i},n=Ca.get(o);if(n)return n;let s;return s=t.apiKey?new ds({apiKey:t.apiKey,network:e.network||"mainnet",connectionMode:i}):await ds.createWithAuth({type:"server",accountId:e.accountId,privateKey:"string"==typeof e.privateKey?e.privateKey:e.privateKey.toString(),network:e.network||"mainnet",connectionMode:i}),Ca.set(o,s),s}let Ra={};const Na=e=>{if(!e.includes("@"))return e;const t=e?.split("@");return`${t[0]}-${t[1].replace(".","-")}`};const _a=1e3;async function Pa(e){if(va)throw new Error("File path operations are not supported in browser environment. Use buffer input type instead.");if(await async function(){if(!va&&!Ra.readFileSync)try{const e="undefined"!=typeof global?global:globalThis,t=e.process?.mainModule?.require||e.require;if("function"!=typeof t)throw new Error("require function not available");{const e=t("fs"),r=t("path");Ra.readFileSync=e.readFileSync,Ra.basename=r.basename,Ra.extname=r.extname}}catch(e){console.warn("Node.js modules not available, file path operations will be disabled")}}(),!Ra.readFileSync||!Ra.basename||!Ra.extname)throw new Error("Node.js file system modules are not available. Cannot read file from path.");try{const r=Ra.readFileSync(e),i=r.toString("base64"),o=Ra.basename(e);let n="application/octet-stream";try{const e=await l.fileTypeFromBuffer(r);e&&(n=e.mime)}catch(t){const r=Ra.extname(e).toLowerCase();n={".txt":"text/plain",".json":"application/json",".html":"text/html",".css":"text/css",".js":"application/javascript",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".pdf":"application/pdf"}[r]||"application/octet-stream"}return{base64:i,fileName:o,mimeType:n}}catch(t){throw new Error(`Failed to read file ${e}: ${t.message}`)}}function Fa(e){return{accountId:e.accountId,privateKey:"string"==typeof e.privateKey?e.privateKey:e.privateKey.toString(),network:e.network}}async function za(e,t,r,i){const o=O.getInstance({module:"Inscriber",...r.logging});o.info("Starting inscription process",{type:e.type,mode:r.mode||"file",quoteOnly:r.quoteOnly||!1,..."url"===e.type?{url:e.url}:{},..."file"===e.type?{path:e.path}:{},..."buffer"===e.type?{fileName:e.fileName,bufferSize:e.buffer.byteLength}:{}});try{if(r.quoteOnly)return o.debug("Quote-only mode requested, generating quote"),await Ka(e,t,r,i);let n;if("hashinal"===r.mode&&r.metadata&&Ba(r.metadata,o),i)o.debug("Using existing InscriptionSDK instance"),n=i;else if(r.apiKey)o.debug("Initializing InscriptionSDK with API key"),n=new ds({apiKey:r.apiKey,network:t.network||"mainnet",connectionMode:"auto"});else{o.debug("Initializing InscriptionSDK with server auth");const e=Fa(t);n=await ds.createWithAuth({type:"server",accountId:e.accountId,privateKey:e.privateKey,network:e.network||"mainnet",connectionMode:"auto"})}const s={holderId:t.accountId,metadata:r.metadata||{},tags:r.tags||[],mode:r.mode||"file",fileStandard:r.fileStandard,chunkSize:r.chunkSize};let a;switch(e.type){case"url":a={...s,file:{type:"url",url:e.url}};break;case"file":{const t=await Pa(e.path);a={...s,file:{type:"base64",base64:t.base64,fileName:t.fileName,mimeType:t.mimeType}};break}case"buffer":a={...s,file:{type:"base64",base64:globalThis.Buffer.from(e.buffer instanceof ArrayBuffer?new Uint8Array(e.buffer):e.buffer).toString("base64"),fileName:e.fileName,mimeType:e.mimeType}}}"hashinal"===r.mode&&(a.metadataObject=r.metadata,a.creator=r.metadata?.creator||t.accountId,a.description=r.metadata?.description,r.jsonFileURL&&(a.jsonFileURL=r.jsonFileURL)),o.debug("Preparing to inscribe content",{type:e.type,mode:r.mode||"file",holderId:t.accountId});const c=Fa(t),l=await n.inscribeAndExecute(a,c),d=l.jobId||l.tx_id||l.transactionId||"",u=l.transactionId||d||"",p=Na(d),h=Na(u),g=Na(p||h||d||l.jobId||"");if(o.info("Starting to inscribe.",{type:e.type,mode:r.mode||"file",transactionId:l.jobId}),r.waitForConfirmation){o.debug("Waiting for inscription confirmation",{transactionId:g,maxAttempts:r.waitMaxAttempts,intervalMs:r.waitIntervalMs});const e=await Ua(n,g,r.waitMaxAttempts,r.waitIntervalMs,r.progressCallback);return o.info("Inscription confirmation received",{transactionId:l.jobId}),{confirmed:!0,result:{...l,jobId:g,transactionId:h},inscription:e,sdk:n,costSummary:await Oa(h,t.network||"mainnet",r.logging?.level)}}return{confirmed:!1,result:{...l,jobId:g,transactionId:h},sdk:n,costSummary:await Oa(h,t.network||"mainnet",r.logging?.level)}}catch(n){throw o.error("Error during inscription process",n),n}}async function Oa(e,t,r){const i=O.getInstance({module:"InscriberCost",level:r??"info"}),o=new V(t,i),n=Na(e),s=n.split("-")[0];for(let c=0;c<3;c++)try{const e=await o.getTransaction(n);if(!e){c<2&&await D(_a);continue}const t=e.transfers?.find(e=>e.account===s&&"number"==typeof e.amount&&e.amount<0);let r=null;if(t)r=Math.abs(t.amount);else if(e.transfers&&e.transfers.length>0){const t=e.transfers.filter(e=>"number"==typeof e.amount&&e.amount<0).reduce((e,t)=>e+Math.abs(t.amount),0);r=t>0?t:null}else"number"==typeof e.charged_tx_fee&&(r=e.charged_tx_fee);if(!r||r<=0){c<2&&await D(_a);continue}const i=new d(r).dividedBy(1e8).toFixed();return{totalCostHbar:i,breakdown:{transfers:[{to:"Hedera network (payer)",amount:i,description:`Transaction fee debited from ${s}`}]}}}catch(a){i.warn("Unable to resolve inscription cost",{transactionId:n,attempt:c+1,error:a instanceof Error?a.message:String(a)}),c<2&&await D(_a)}}async function Da(e,t,r,i){const o=O.getInstance({module:"Inscriber",...r.logging});o.info("Starting inscription process with signer",{type:e.type,mode:r.mode||"file",quoteOnly:r.quoteOnly||!1,..."url"===e.type?{url:e.url}:{},..."file"===e.type?{path:e.path}:{},..."buffer"===e.type?{fileName:e.fileName,bufferSize:e.buffer.byteLength}:{}});try{if(r.quoteOnly){o.debug("Quote-only mode requested with signer, generating quote");const n={accountId:t.getAccountId().toString(),privateKey:"",network:r.network||"mainnet"};return await Ka(e,n,r,i)}"hashinal"===r.mode&&r.metadata&&Ba(r.metadata,o);const n=t.getAccountId().toString();let s;o.debug("Using account ID from signer",{accountId:n}),i?(o.debug("Using existing InscriptionSDK instance"),s=i):r.apiKey?(o.debug("Initializing InscriptionSDK with API key"),s=new ds({apiKey:r.apiKey,network:r.network||"mainnet",connectionMode:"websocket"})):(o.debug("Initializing InscriptionSDK with client auth (websocket)"),s=await ds.createWithAuth({type:"client",accountId:n,signer:t,network:r.network||"mainnet",connectionMode:"websocket"}));const a={holderId:n,metadata:r.metadata||{},tags:r.tags||[],mode:r.mode||"file",fileStandard:r.fileStandard,chunkSize:r.chunkSize};let c;switch(e.type){case"url":c={...a,file:{type:"url",url:e.url}};break;case"file":{const t=await Pa(e.path);c={...a,file:{type:"base64",base64:t.base64,fileName:t.fileName,mimeType:t.mimeType}};break}case"buffer":c={...a,file:{type:"base64",base64:globalThis.Buffer.from(e.buffer instanceof ArrayBuffer?new Uint8Array(e.buffer):e.buffer).toString("base64"),fileName:e.fileName,mimeType:e.mimeType}}}"hashinal"===r.mode&&(c.metadataObject=r.metadata,c.creator=r.metadata?.creator||n,c.description=r.metadata?.description,r.jsonFileURL&&(c.jsonFileURL=r.jsonFileURL)),o.debug("Starting inscription via startInscription (websocket)",{type:e.type,mode:r.mode||"file",holderId:n,usesStartInscription:!0});const l=await s.startInscription({...c,holderId:n,network:r.network||"mainnet"});o.info("about to start inscription",{type:e.type,mode:r.mode||"file",jobId:l.id||l.tx_id,...l}),"string"==typeof l?.transactionBytes?(o.debug("Executing inscription transaction with signer from bytes"),await s.executeTransactionWithSigner(l.transactionBytes,t)):"Buffer"===l?.transactionBytes?.type&&(o.debug("Executing inscription transaction with signer from buffer"),await s.executeTransactionWithSigner(globalThis.Buffer.from(l.transactionBytes.data).toString("base64"),t));const d=Na(l.tx_id||l.id||""),u=Na(d||l.id||l.tx_id||"");if(r.waitForConfirmation){o.debug("Waiting for inscription confirmation (websocket)",{jobId:l.id||l.tx_id,maxAttempts:r.waitMaxAttempts,intervalMs:r.waitIntervalMs});const e=await Ua(s,u,r.waitMaxAttempts,r.waitIntervalMs,r.progressCallback);return o.info("Inscription confirmation received",{jobId:u}),{confirmed:!0,result:{jobId:u,transactionId:u,topic_id:l.topic_id,status:l.status,completed:l.completed},inscription:e,sdk:s,costSummary:await Oa(u,r.network||"mainnet",r.logging?.level)}}return{confirmed:!1,result:{jobId:u,transactionId:u,topic_id:l.topic_id,status:l.status,completed:l.completed},sdk:s,costSummary:await Oa(u,r.network||"mainnet",r.logging?.level)}}catch(n){throw o.error("Error during inscription process",n),n}}async function Ma(e,t){const r=O.getInstance({module:"Inscriber",...t?.logging||{}}),i=e.includes("@")?`${e.split("@")[0]}-${e.split("@")[1].replace(/\./g,"-")}`:e;r.info("Retrieving inscription",{originalTransactionId:e,formattedTransactionId:i});try{let e;if(t?.apiKey)r.debug("Initializing InscriptionSDK with API key"),e=new ds({apiKey:t.apiKey,network:t.network||"mainnet"});else{if(!t?.accountId||!t?.privateKey){const e=new Error("Either API key or account ID and private key are required for retrieving inscriptions");throw r.error("Missing authentication credentials",{hasApiKey:Boolean(t?.apiKey),hasAccountId:Boolean(t?.accountId),hasPrivateKey:Boolean(t?.privateKey)}),e}r.debug("Initializing InscriptionSDK with server auth"),e=await ds.createWithAuth({type:"server",accountId:t.accountId,privateKey:t.privateKey,network:t.network||"mainnet"})}r.debug("Initialized SDK for inscription retrieval",{formattedTransactionId:i,network:t.network||"mainnet"});const o=await e.retrieveInscription(i);return r.info("Successfully retrieved inscription",{formattedTransactionId:i}),o}catch(o){throw r.error("Error retrieving inscription",{formattedTransactionId:i,error:o}),o}}function Ba(e,t){const r=["name","creator","description","type"].filter(t=>!e[t]);if(r.length>0){const e=new Error(`Missing required Hashinal metadata fields: ${r.join(", ")}`);throw t.error("Hashinal metadata validation failed",{missingFields:r}),e}t.debug("Hashinal metadata validation passed",{name:e.name,creator:e.creator,description:e.description,type:e.type,hasAttributes:!!e.attributes,hasProperties:!!e.properties})}async function Ka(e,t,r,i){const o=O.getInstance({module:"Inscriber",...r.logging});o.info("Generating inscription quote",{type:e.type,mode:r.mode||"file",..."url"===e.type?{url:e.url}:{},..."file"===e.type?{path:e.path}:{},..."buffer"===e.type?{fileName:e.fileName,bufferSize:e.buffer.byteLength}:{}});try{!function(e,t,r){if(!e||"object"!=typeof e||!("type"in e))throw new Error("Invalid inscription input: type is required");if(!t||!t.accountId)throw new Error("Invalid client config: accountId is required");if(!r)throw new Error("Options are required");if("hashinal"===r.mode){if(!r.metadata)throw new Error("Hashinal mode requires metadata");const e=["name","creator","description","type"].filter(e=>!r.metadata||!r.metadata[e]);if(e.length>0)throw new Error(`Missing required Hashinal metadata fields: ${e.join(", ")}`)}}(e,t,r);const n=function(e,t,r){const i=Aa.createCacheKey(e,t,r);return Aa.get(i)}(e,t,r);if(n)return o.debug("Returning cached quote"),{confirmed:!1,quote:!0,result:n};"hashinal"===r.mode&&r.metadata&&Ba(r.metadata,o);const s=await xa(t,r,i),a={holderId:t.accountId,metadata:r.metadata||{},tags:r.tags||[],mode:r.mode||"file",fileStandard:r.fileStandard,chunkSize:r.chunkSize};let c;switch(e.type){case"url":c={...a,file:{type:"url",url:e.url}};break;case"file":{const t=await Pa(e.path);c={...a,file:{type:"base64",base64:t.base64,fileName:t.fileName,mimeType:t.mimeType}};break}case"buffer":c={...a,file:{type:"base64",base64:globalThis.Buffer.from(e.buffer instanceof ArrayBuffer?new Uint8Array(e.buffer):e.buffer).toString("base64"),fileName:e.fileName,mimeType:e.mimeType}}}"hashinal"===r.mode&&(c.metadataObject=r.metadata,c.creator=r.metadata?.creator||t.accountId,c.description=r.metadata?.description,r.jsonFileURL&&(c.jsonFileURL=r.jsonFileURL)),o.debug("Calling inscription SDK startInscription for quote",{type:e.type,mode:r.mode||"file",holderId:t.accountId});const l=await s.startInscription(c);o.debug("Received inscription response for quote parsing",{hasTransactionBytes:!!l.transactionBytes,bytesLength:l.transactionBytes?.length||0,transactionBytesType:typeof l.transactionBytes,totalCost:l.totalCost});const d=await async function(e,t){try{let i="0.001";if(e.totalCost&&"number"==typeof e.totalCost){i=(e.totalCost/1e8).toString(),t.debug("Using totalCost from inscription response",{totalCostTinybars:e.totalCost,totalCostHbar:i})}else if(e.transactionBytes){t.debug("Parsing transaction bytes for cost information");try{let r;if("string"==typeof e.transactionBytes)r=e.transactionBytes;else{if(!e.transactionBytes||"object"!=typeof e.transactionBytes||!("data"in e.transactionBytes))throw new Error("Invalid transactionBytes format");r=globalThis.Buffer.from(e.transactionBytes.data).toString("base64")}t.debug("About to parse transaction bytes",{bytesLength:r.length,bytesPreview:r.slice(0,100)});const o=await Ea.parseTransactionBytes(r,{includeRaw:!1});t.debug("Parsed transaction for quote",{type:o.type,hasTransfers:!!o.transfers,transferCount:o.transfers?.length||0,transfers:o.transfers});let n=0;if(o.transfers&&o.transfers.length>0)for(const e of o.transfers){const r="string"==typeof e.amount?parseFloat(e.amount):e.amount;if(r<0){const i=Math.abs(r);n+=i,t.debug("Found HBAR transfer",{from:e.accountId,to:"service",amount:i})}}n>0&&(i=n.toString(),t.debug("Using parsed transaction transfer amount",{totalTransferAmount:n,totalCostHbar:i}))}catch(r){t.warn("Could not parse transaction bytes, using totalCost fallback",{error:r,errorMessage:r instanceof Error?r.message:String(r)})}}const o=[{to:"Inscription Service",amount:i,description:`Inscription fee (${i} HBAR)`}],n={totalCostHbar:i,validUntil:new Date(Date.now()+9e5).toISOString(),breakdown:{transfers:o}};return t.debug("Successfully parsed transaction for quote",{totalCostHbar:n.totalCostHbar,transferCount:o.length,hasTransactionBytes:!!e.transactionBytes,hasTotalCost:!!e.totalCost}),n}catch(i){throw t.error("Error parsing transaction for quote",i),i}}(l,o);return function(e,t,r,i){const o=Aa.createCacheKey(e,t,r);Aa.set(o,i,6e5)}(e,t,r,d),o.info("Successfully generated inscription quote",{totalCostHbar:d.totalCostHbar}),{confirmed:!1,quote:!0,result:d}}catch(n){throw o.error("Error generating inscription quote",n),n}}async function Ua(e,t,r=30,i=4e3,o){const n=O.getInstance({module:"Inscriber"}),s=Na(t),a=new us({module:"Inscriber",logger:n,callback:o});try{n.debug("Waiting for inscription confirmation",{transactionId:s,maxAttempts:r,intervalMs:i}),a.preparing("Preparing for inscription confirmation",5,{transactionId:s,maxAttempts:r,intervalMs:i});try{const t=e.waitForInscription.bind(e),o=e=>{const t=e.stage||"confirming",r=["preparing","submitting","confirming","verifying","completed","failed"].includes(t)?t:"confirming",i=e.message||"Processing inscription",o=e.progressPercent||50;a.report({stage:r,message:i,progressPercent:o,details:e.details})};return await t(s,r,i,!0,o)}catch($g){return n.debug("Falling back to standard waitForInscription method",{error:$g}),a.verifying("Verifying inscription status",50,{error:$g}),await e.waitForInscription(s,r,i,!0)}}catch(c){throw n.error("Error waiting for inscription confirmation",{transactionId:t,maxAttempts:r,intervalMs:i,error:c}),a.failed("Inscription confirmation failed",{transactionId:t,error:c}),c}}function La(e){if(!e||"object"!=typeof e)return;const t=e,r=t.topicId||t.topic_id;if("string"==typeof r&&r.trim())return r;const i=t,o=i.topicId;if("string"==typeof o&&o.trim())return o;const n=i.topic_id;return"string"==typeof n&&n.trim()?n:void 0}var $a=(e=>(e.REGISTER_CONFIG="register-config",e.REGISTER="register",e))($a||{}),Ha=(e=>(e.EVM="evm",e.WASM="wasm",e))(Ha||{});const qa=r.z.object({name:r.z.string().optional(),type:r.z.string()}),ja=r.z.object({name:r.z.string(),inputs:r.z.array(qa),outputs:r.z.array(qa),stateMutability:r.z.enum(["view","pure"]),type:r.z.literal("function")}),Wa=r.z.enum(["number","string","bool"]),Va=r.z.object({p:r.z.literal("hcs-7"),m:r.z.string().optional()}),Ga=Va.extend({op:r.z.literal("register-config"),t:r.z.literal("evm"),c:r.z.object({contractAddress:r.z.string().regex(/^0x[a-fA-F0-9]{40}$/,"Invalid contract address"),abi:ja})}),Ja=Va.extend({op:r.z.literal("register-config"),t:r.z.literal("wasm"),c:r.z.object({wasmTopicId:r.z.string(),inputType:r.z.object({stateData:r.z.record(Wa)}),outputType:r.z.object({type:r.z.literal("string"),format:r.z.literal("topic-id")})})}),Ya=Va.extend({op:r.z.literal("register"),t_id:r.z.string(),d:r.z.object({weight:r.z.number(),tags:r.z.array(r.z.string()).nonempty()}).catchall(r.z.unknown())}),Xa=r.z.union([Ga,Ja,Ya]);class Za{constructor(e){this.network=e.network,this.logger=e.logger||O.getInstance({level:e.logLevel||"info",module:"HCS7Client",silent:e.silent}),this.mirrorNode=new V(this.network,this.logger,e.mirrorNodeUrl?{customUrl:e.mirrorNodeUrl}:void 0)}generateRegistryMemo(e){return`hcs-7:indexed:${e}`}createConfigMessage(e){return e.config.type===Ha.EVM?{p:"hcs-7",op:$a.REGISTER_CONFIG,t:Ha.EVM,c:{contractAddress:e.config.contractAddress,abi:e.config.abi},m:e.memo}:{p:"hcs-7",op:$a.REGISTER_CONFIG,t:Ha.WASM,c:{wasmTopicId:e.config.wasmTopicId,inputType:e.config.inputType,outputType:e.config.outputType},m:e.memo}}createMetadataMessage(e){return{p:"hcs-7",op:$a.REGISTER,t_id:e.metadataTopicId,m:e.memo,d:{weight:e.weight,tags:e.tags,...e.data||{}}}}validateMessage(e){const t=Xa.safeParse(e);if(t.success)return{valid:!0,errors:[]};const r=t.error.errors.map(e=>{const t=e.path.join(".");return t?`${t}: ${e.message}`:e.message});return this.logger.debug(`HCS-7 message validation failed: ${r.join(", ")}`),{valid:!1,errors:r}}async getRegistry(e,t){const r=[];try{const i=await this.mirrorNode.getTopicMessages(e,{limit:t?.limit,order:t?.order,sequenceNumber:t?.next});for(const e of i){if("hcs-7"!==e.p)continue;const t=Xa.safeParse(e);if(!t.success)continue;const i=t.data;r.push({sequenceNumber:Number(e.sequence_number),timestamp:e.consensus_timestamp||"",payer:e.payer||"",message:i})}}catch(i){this.logger.error("Failed to query HCS-7 registry",i)}return{topicId:e,entries:r}}}function Qa(e){const t=e.topicSequenceNumber;return"number"==typeof t?t:"function"==typeof t?.toNumber?t.toNumber():"number"==typeof t?.low?t.low:void 0}function ec(e){return J({memo:`hcs-7:indexed:${e.ttl}`,submitKey:e.submitKey,adminKey:e.adminKey,operatorPublicKey:e.operatorPublicKey})}function tc(e){const t={p:"hcs-7",...e.message};return Y({topicId:e.topicId,message:JSON.stringify(t),transactionMemo:e.transactionMemo})}class rc{constructor(){this.cache=new Map}get(e){return this.cache.get(e)}set(e,t){this.cache.set(e,t)}delete(e){this.cache.delete(e)}clear(){this.cache.clear()}}function ic(e,t){return null==e?"0":e._isBigNumber?e.toString():t.startsWith("uint")||t.startsWith("int")?String(e):"bool"===t?e?"true":"false":"string"===t?e:"address"===t?String(e).toLowerCase():t.endsWith("[]")?Array.isArray(e)?e.map(e=>String(e)).join(","):"":String(e)}function oc(e){const t=Object.create(O.prototype);return t.debug=(...t)=>e.debug(...t),t.info=(...t)=>e.info(...t),t.warn=(...t)=>e.warn(...t),t.error=(...t)=>e.error(...t),t.trace=(...t)=>e.trace(...t),t.setLogLevel=t=>e.setLogLevel(t),t.getLevel=()=>e.getLevel(),t.setSilent=t=>e.setSilent(t),t.setModule=t=>e.setModule(t),t.logger={level:e.getLevel()},t.moduleContext="",t.formatArgs=()=>({msg:""}),t}function nc(e){return e instanceof O}async function sc(e,t,r){const i=new V(t,r),o=[];for(const s of e)try{const e=await i.getPublicKey(s);o.push(e)}catch(n){r&&r.warn(`Could not get public key for account ${s}: ${n}`)}return o}const ac="hcs-21",cc=1024,lc=1e3,dc=/^(?:hcs:\/\/1\/0\.0\.\d+|ipfs:\/\/\S+|ar:\/\/\S+|oci:\/\/\S+|https?:\/\/\S+)$/,uc=/^(?:0\.0\.\d+|hcs:\/\/1\/0\.0\.\d+(?:\/\d+)?|ipfs:\/\/\S+|ar:\/\/\S+|oci:\/\/\S+|https?:\/\/\S+)$/;var pc=(e=>(e[e.ADAPTER_REGISTRY=0]="ADAPTER_REGISTRY",e[e.REGISTRY_OF_REGISTRIES=1]="REGISTRY_OF_REGISTRIES",e[e.ADAPTER_CATEGORY=2]="ADAPTER_CATEGORY",e))(pc||{});const hc=r.z.object({registry:r.z.string().min(1),name:r.z.string().min(1),version:r.z.string().min(1),integrity:r.z.string().min(1)}),gc=r.z.object({type:r.z.string().min(1),account:r.z.string().min(1).optional(),threshold:r.z.string().min(1).optional(),ctopic:r.z.string().min(1).optional(),ttopic:r.z.string().min(1).optional(),stopic:r.z.string().min(1).optional()}).catchall(r.z.unknown()),mc=r.z.object({p:r.z.literal(ac),op:r.z.enum(["register","update","delete"]),adapter_id:r.z.string().min(1),entity:r.z.string().min(1),package:hc,manifest:r.z.string().regex(dc,"manifest must be an immutable pointer (hcs://1/<topicId>, ipfs://cid/path, ar://txid, oci://repo@digest, https://...#sha384-..)"),manifest_sequence:r.z.number().int().positive().optional(),config:gc,state_model:r.z.string().min(1).optional(),signature:r.z.string().min(1).optional()}),fc=r.z.object({meta:r.z.object({spec_version:r.z.string().min(1),adapter_version:r.z.string().min(1),minimum_version:r.z.string().min(1).optional(),generated:r.z.string().min(1)}),adapter:r.z.object({name:r.z.string().min(1),id:r.z.string().min(1),maintainers:r.z.array(r.z.object({name:r.z.string().min(1),contact:r.z.string().min(1)})).min(1),license:r.z.string().min(1)}),package:r.z.object({registry:r.z.string().min(1),dist_tag:r.z.string().min(1).optional(),artifacts:r.z.array(r.z.object({url:r.z.string().min(1),digest:r.z.string().min(1),signature:r.z.string().min(1).optional()})).min(1)}),runtime:r.z.object({platforms:r.z.array(r.z.string().min(1)).min(1),primary:r.z.string().min(1),entry:r.z.string().min(1),dependencies:r.z.array(r.z.string().min(1)).optional(),env:r.z.array(r.z.string().min(1)).optional()}),capabilities:r.z.object({discovery:r.z.boolean(),communication:r.z.boolean(),protocols:r.z.array(r.z.string().min(1)),discovery_tags:r.z.array(r.z.string().min(1)).optional(),communication_channels:r.z.array(r.z.string().min(1)).optional(),extras:r.z.record(r.z.string(),r.z.unknown()).optional()}),consensus:r.z.object({state_model:r.z.string().min(1).optional(),profile_uri:r.z.string().min(1).optional(),entity_schema:r.z.string().min(1).optional(),required_fields:r.z.array(r.z.string().min(1)),hashing:r.z.literal("sha384")})}),yc=r.z.object({version:r.z.string().min(1),name:r.z.string().min(1),description:r.z.string().min(1),operator:r.z.object({account:r.z.string().min(1),name:r.z.string().optional(),contact:r.z.string().optional()}),entityTypes:r.z.array(r.z.string().min(1)),categories:r.z.array(r.z.string().min(1)).optional(),tags:r.z.array(r.z.string().min(1)).optional(),links:r.z.record(r.z.string().min(1)).optional()}),bc=r.z.union([fc,yc]);var wc=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTONOMOUS=1]="AUTONOMOUS",e))(wc||{}),Ic=(e=>(e[e.TEXT_GENERATION=0]="TEXT_GENERATION",e[e.IMAGE_GENERATION=1]="IMAGE_GENERATION",e[e.AUDIO_GENERATION=2]="AUDIO_GENERATION",e[e.VIDEO_GENERATION=3]="VIDEO_GENERATION",e[e.CODE_GENERATION=4]="CODE_GENERATION",e[e.LANGUAGE_TRANSLATION=5]="LANGUAGE_TRANSLATION",e[e.SUMMARIZATION_EXTRACTION=6]="SUMMARIZATION_EXTRACTION",e[e.KNOWLEDGE_RETRIEVAL=7]="KNOWLEDGE_RETRIEVAL",e[e.DATA_INTEGRATION=8]="DATA_INTEGRATION",e[e.MARKET_INTELLIGENCE=9]="MARKET_INTELLIGENCE",e[e.TRANSACTION_ANALYTICS=10]="TRANSACTION_ANALYTICS",e[e.SMART_CONTRACT_AUDIT=11]="SMART_CONTRACT_AUDIT",e[e.GOVERNANCE_FACILITATION=12]="GOVERNANCE_FACILITATION",e[e.SECURITY_MONITORING=13]="SECURITY_MONITORING",e[e.COMPLIANCE_ANALYSIS=14]="COMPLIANCE_ANALYSIS",e[e.FRAUD_DETECTION=15]="FRAUD_DETECTION",e[e.MULTI_AGENT_COORDINATION=16]="MULTI_AGENT_COORDINATION",e[e.API_INTEGRATION=17]="API_INTEGRATION",e[e.WORKFLOW_AUTOMATION=18]="WORKFLOW_AUTOMATION",e))(Ic||{});const Tc=r.z.nativeEnum(Ic),Sc=r.z.union([Tc,r.z.string()]),kc=r.z.union([r.z.string(),r.z.number(),r.z.boolean(),r.z.null()]),Ec=r.z.lazy(()=>r.z.union([kc,r.z.array(Ec),r.z.record(Ec)])),vc=r.z.object({version:r.z.string(),type:r.z.number(),display_name:r.z.string(),alias:r.z.string().optional(),bio:r.z.string().optional(),socials:r.z.array(Ec).optional(),aiAgent:r.z.object({type:r.z.nativeEnum(wc),creator:r.z.string().optional(),model:r.z.string().optional(),capabilities:r.z.array(Tc).optional()}).optional(),uaid:r.z.string().optional()}).catchall(Ec),Ac=r.z.object({uaid:r.z.string().optional(),ledgerAccountId:r.z.string().optional(),userId:r.z.string().optional(),email:r.z.string().optional(),encryptedShare:r.z.string()}),Cc=r.z.object({algorithm:r.z.string(),ciphertext:r.z.string(),nonce:r.z.string(),associatedData:r.z.string().optional(),keyLocator:r.z.object({sessionId:r.z.string().optional(),revision:r.z.number().optional()}).optional(),recipients:r.z.array(Ac)}),xc=r.z.object({keyType:r.z.string(),publicKey:r.z.string(),uaid:r.z.string().optional(),ledgerAccountId:r.z.string().optional(),userId:r.z.string().optional(),email:r.z.string().optional()}),Rc=r.z.object({role:r.z.enum(["requester","responder"]),uaid:r.z.string().optional(),userId:r.z.string().optional(),ledgerAccountId:r.z.string().optional(),keyType:r.z.string(),longTermPublicKey:r.z.string().optional(),ephemeralPublicKey:r.z.string(),signature:r.z.string().optional(),metadata:r.z.record(Ec).optional(),submittedAt:r.z.string()}),Nc=r.z.object({sessionId:r.z.string(),algorithm:r.z.string(),createdAt:r.z.string(),expiresAt:r.z.number(),status:r.z.enum(["pending","complete"]),requester:Rc.optional(),responder:Rc.optional()}),_c=r.z.object({enabled:r.z.boolean(),algorithm:r.z.string(),requireCiphertext:r.z.boolean(),requester:xc.nullable().optional(),responder:xc.nullable().optional(),handshake:Nc.nullable().optional()}),Pc=r.z.object({messageId:r.z.string(),role:r.z.enum(["user","agent"]),content:r.z.string(),timestamp:r.z.string(),cipherEnvelope:Cc.optional(),metadata:r.z.record(Ec).optional()}),Fc=r.z.record(r.z.union([r.z.array(Ec),r.z.record(Ec),Ec])).optional(),zc=r.z.object({id:r.z.string(),uaid:r.z.string(),registry:r.z.string(),name:r.z.string(),description:r.z.string().optional(),capabilities:r.z.array(Sc),endpoints:r.z.union([r.z.record(Ec),r.z.array(r.z.string())]).optional(),metadata:r.z.record(Ec).optional(),metadataFacet:Fc,profile:vc.optional(),protocols:r.z.array(r.z.string()).optional(),adapter:r.z.string().optional(),originalId:r.z.string().optional(),communicationSupported:r.z.boolean().optional(),routingSupported:r.z.boolean().optional(),available:r.z.boolean().optional(),availabilityStatus:r.z.string().optional(),availabilityCheckedAt:r.z.string().optional(),availabilitySource:r.z.string().optional(),availabilityLatencyMs:r.z.number().optional(),availabilityScore:r.z.number().optional(),capabilityLabels:r.z.array(r.z.string()).optional(),capabilityTokens:r.z.array(r.z.string()).optional(),image:r.z.string().optional(),createdAt:r.z.string().optional(),updatedAt:r.z.string().optional(),lastSeen:r.z.string().optional(),lastIndexed:r.z.string().optional()}).passthrough(),Oc=r.z.object({hits:r.z.array(zc),total:r.z.number(),page:r.z.number(),limit:r.z.number()}),Dc=r.z.object({totalAgents:r.z.number(),registries:r.z.record(r.z.number()),capabilities:r.z.record(r.z.number()),lastUpdate:r.z.string(),status:r.z.string()}),Mc=r.z.object({registries:r.z.array(r.z.string())}),Bc=r.z.object({searches:r.z.array(r.z.string())}),Kc=r.z.object({agent:zc}),Uc=r.z.object({sessionId:r.z.string(),uaid:r.z.string().nullable().optional(),agent:r.z.object({name:r.z.string(),description:r.z.string().optional(),capabilities:r.z.record(Ec).nullable().optional(),skills:r.z.array(r.z.string()).optional()}),history:r.z.array(Pc).optional().default([]),historyTtlSeconds:r.z.number().nullable().optional(),encryption:_c.nullable().optional()}),Lc=r.z.object({sessionId:r.z.string(),uaid:r.z.string().nullable().optional(),message:r.z.string(),timestamp:r.z.string(),rawResponse:Ec.optional(),content:r.z.string().optional(),history:r.z.array(Pc).optional(),historyTtlSeconds:r.z.number().nullable().optional(),encrypted:r.z.boolean().optional()}),$c=r.z.object({sessionId:r.z.string(),history:r.z.array(Pc),historyTtlSeconds:r.z.number()});r.z.object({preserveEntries:r.z.number().int().min(0).optional()}).strict();const Hc=r.z.object({sessionId:r.z.string(),history:r.z.array(Pc),summaryEntry:Pc,preservedEntries:r.z.array(Pc),historyTtlSeconds:r.z.number(),creditsDebited:r.z.number(),metadata:r.z.record(Ec).optional()}),qc=r.z.object({sessionId:r.z.string(),encryption:_c.nullable()}),jc=r.z.object({sessionId:r.z.string(),handshake:Nc}),Wc=r.z.object({id:r.z.string(),keyType:r.z.string(),publicKey:r.z.string(),uaid:r.z.string().nullable(),ledgerAccountId:r.z.string().nullable(),ledgerNetwork:r.z.string().nullable().optional(),userId:r.z.string().nullable().optional(),email:r.z.string().nullable().optional(),createdAt:r.z.string(),updatedAt:r.z.string()}),Vc=r.z.object({challengeId:r.z.string(),message:r.z.string(),expiresAt:r.z.string()}),Gc=r.z.object({id:r.z.string(),label:r.z.string().optional(),prefix:r.z.string(),lastFour:r.z.string(),createdAt:r.z.string(),lastUsedAt:r.z.string().nullable().optional(),ownerType:r.z.literal("ledger"),ledgerAccountId:r.z.string().optional(),ledgerNetwork:r.z.string().optional(),ledgerNetworkCanonical:r.z.string().optional()}),Jc=r.z.object({key:r.z.string(),apiKey:Gc,accountId:r.z.string(),network:r.z.string(),networkCanonical:r.z.string().optional()}),Yc=r.z.object({protocols:r.z.array(r.z.string())}),Xc=r.z.object({protocol:r.z.string().nullable()}),Zc=r.z.object({hits:r.z.array(zc),total:r.z.number(),page:r.z.number().optional(),limit:r.z.number().optional()}),Qc=r.z.union([r.z.string(),r.z.number()]),el=r.z.object({capabilities:r.z.array(Qc).optional(),type:r.z.enum(["ai-agents","mcp-servers"]).optional(),registry:r.z.string().optional(),protocols:r.z.array(r.z.string()).optional(),adapter:r.z.array(r.z.string()).optional()}).strict();r.z.object({query:r.z.string(),filter:el.optional(),limit:r.z.number().int().min(1).max(100).optional(),offset:r.z.number().int().min(0).optional()}).strict();const tl=r.z.object({agent:zc,score:r.z.number().optional(),highlights:r.z.record(r.z.array(r.z.string())).optional()}),rl=r.z.object({hits:r.z.array(tl),total:r.z.number(),took:r.z.number(),totalAvailable:r.z.number().optional(),visible:r.z.number().optional(),limited:r.z.boolean().optional(),credits_used:r.z.number().optional()}),il=r.z.object({enabled:r.z.boolean(),healthy:r.z.boolean(),mode:r.z.enum(["disabled","initializing","healthy","degraded","error"]),lastUpdated:r.z.string(),details:r.z.record(r.z.any()).optional(),lastError:r.z.object({message:r.z.string(),stack:r.z.string().optional(),timestamp:r.z.string().optional()}).optional()}),ol=r.z.object({storageMode:r.z.string(),vectorStatus:il}),nl=r.z.object({clients:r.z.number(),stats:r.z.object({totalClients:r.z.number().optional(),clientsByRegistry:r.z.record(r.z.number()).optional(),clientsByEventType:r.z.record(r.z.number()).optional()}).passthrough()}),sl=r.z.object({p50:r.z.number(),p90:r.z.number(),p95:r.z.number(),p99:r.z.number()}),al=r.z.object({http:r.z.object({requestsTotal:r.z.number(),activeConnections:r.z.number(),requestDuration:sl}),search:r.z.object({queriesTotal:r.z.number(),queryDuration:sl}),indexing:r.z.object({agentsTotal:r.z.number(),crawlErrors:r.z.number()}),registration:r.z.object({total:r.z.number(),failures:r.z.number(),duration:sl}),cache:r.z.object({hits:r.z.number(),misses:r.z.number(),hitRate:r.z.number()}),websocket:r.z.object({connections:r.z.number()})}),cl=r.z.object({uaid:r.z.string(),valid:r.z.boolean(),formats:r.z.array(r.z.string())}),ll=r.z.object({id:r.z.string(),agentId:r.z.string(),protocol:r.z.string(),endpoint:r.z.string(),status:r.z.enum(["connected","disconnected","error"]),metadata:r.z.record(kc).optional(),createdAt:r.z.string()}),dl=r.z.object({connected:r.z.boolean(),connection:ll.optional(),adapter:r.z.string().optional(),agentId:r.z.string().optional()}),ul=r.z.object({operatorId:r.z.string().optional(),adapters:r.z.array(r.z.object({name:r.z.string(),version:r.z.string(),status:r.z.string(),agentCount:r.z.number(),lastDiscovery:r.z.string(),registryType:r.z.string(),health:r.z.string()})).optional(),totalAgents:r.z.number().optional(),elasticsearchDocumentCount:r.z.number().optional(),agentsByAdapter:r.z.record(r.z.number()).optional(),agentsByRegistry:r.z.record(r.z.number()).optional(),systemInfo:r.z.object({uptime:r.z.number().optional(),version:r.z.string().optional(),network:r.z.string().optional()}).optional()}),pl=r.z.object({id:r.z.string(),name:r.z.string(),type:r.z.string(),endpoint:r.z.string().optional(),capabilities:r.z.array(Sc),registry:r.z.string().optional(),protocol:r.z.string().optional(),profile:vc.optional(),nativeId:r.z.string().optional(),metadata:r.z.record(Ec).optional()}),hl=r.z.object({tId:r.z.string().nullable(),sizeBytes:r.z.number().optional()}),gl=r.z.object({topicId:r.z.string().optional(),sequenceNumber:r.z.number().optional(),profileReference:r.z.string().optional(),profileTopicId:r.z.string().optional()}).passthrough().nullable().optional(),ml=r.z.object({registry:r.z.string(),status:r.z.enum(["created","duplicate","skipped","error","updated","pending"]),agentId:r.z.string().nullable().optional(),agentUri:r.z.string().nullable().optional(),error:r.z.string().optional(),metadata:r.z.record(Ec).optional(),registryKey:r.z.string().optional(),networkId:r.z.string().optional(),networkName:r.z.string().optional(),chainId:r.z.number().optional(),estimatedCredits:r.z.number().nullable().optional(),gasEstimateCredits:r.z.number().nullable().optional(),gasEstimateUsd:r.z.number().nullable().optional(),gasPriceGwei:r.z.number().nullable().optional(),gasLimit:r.z.number().nullable().optional(),creditMode:r.z.enum(["fixed","gas"]).nullable().optional(),minCredits:r.z.number().nullable().optional(),consumedCredits:r.z.number().nullable().optional(),cost:r.z.object({credits:r.z.number(),usd:r.z.number(),eth:r.z.number(),gasUsedWei:r.z.string(),effectiveGasPriceWei:r.z.string().nullable().optional(),transactions:r.z.array(r.z.object({hash:r.z.string(),gasUsedWei:r.z.string(),effectiveGasPriceWei:r.z.string().nullable().optional(),costWei:r.z.string()})).optional()}).optional()}),fl=r.z.object({base:r.z.number(),additional:r.z.number(),total:r.z.number()}),yl=r.z.object({status:r.z.string(),uaid:r.z.string().optional(),transactionId:r.z.string().optional(),consensusTimestamp:r.z.string().optional(),registryTopicId:r.z.string().optional(),topicSequenceNumber:r.z.number().optional(),payloadHash:r.z.string().optional(),profileReference:r.z.string().optional(),tId:r.z.string().optional(),profileSizeBytes:r.z.number().optional(),error:r.z.string().optional()}).passthrough(),bl=r.z.object({key:r.z.string(),registryId:r.z.string().optional(),networkId:r.z.string().optional(),name:r.z.string().optional(),chainId:r.z.number().optional(),label:r.z.string().optional(),estimatedCredits:r.z.number().nullable().optional(),baseCredits:r.z.number().nullable().optional(),gasPortionCredits:r.z.number().nullable().optional(),gasPortionUsd:r.z.number().nullable().optional(),gasEstimateCredits:r.z.number().nullable().optional(),gasEstimateUsd:r.z.number().nullable().optional(),gasPriceGwei:r.z.number().nullable().optional(),gasLimit:r.z.number().nullable().optional(),minCredits:r.z.number().nullable().optional(),creditMode:r.z.string().nullable().optional()}).passthrough(),wl=r.z.object({id:r.z.string(),label:r.z.string(),networks:r.z.array(bl)}),Il=r.z.object({registries:r.z.array(wl)}),Tl=r.z.object({success:r.z.literal(!0),status:r.z.enum(["created","duplicate","updated"]).optional(),uaid:r.z.string(),agentId:r.z.string(),message:r.z.string().optional(),registry:r.z.string().optional(),attemptId:r.z.string().nullable().optional(),agent:pl,openConvAI:r.z.object({compatible:r.z.boolean(),hcs11Profile:vc.optional(),bridgeEndpoint:r.z.string().optional()}).optional(),profile:hl.optional(),profileRegistry:gl.nullable().optional(),hcs10Registry:yl.nullable().optional(),credits:fl.optional(),additionalRegistries:r.z.array(ml).optional(),additionalRegistryCredits:r.z.array(ml).optional(),additionalRegistryCostPerRegistry:r.z.number().optional()}),Sl=r.z.object({success:r.z.literal(!0),status:r.z.literal("pending"),message:r.z.string(),uaid:r.z.string(),agentId:r.z.string(),registry:r.z.string().optional(),attemptId:r.z.string().nullable(),agent:pl,openConvAI:r.z.object({compatible:r.z.boolean(),hcs11Profile:vc.optional(),bridgeEndpoint:r.z.string().optional()}).optional(),profile:hl.optional(),profileRegistry:gl.nullable().optional(),hcs10Registry:yl.nullable().optional(),credits:fl,additionalRegistries:r.z.array(ml),additionalRegistryCredits:r.z.array(ml).optional(),additionalRegistryCostPerRegistry:r.z.number().optional()}),kl=r.z.object({success:r.z.literal(!1),status:r.z.literal("partial"),message:r.z.string(),uaid:r.z.string(),agentId:r.z.string(),registry:r.z.string().optional(),attemptId:r.z.string().nullable().optional(),agent:pl,openConvAI:r.z.object({compatible:r.z.boolean(),hcs11Profile:vc.optional(),bridgeEndpoint:r.z.string().optional()}).optional(),profile:hl.optional(),profileRegistry:gl.nullable().optional(),hcs10Registry:yl.nullable().optional(),credits:fl.optional(),additionalRegistries:r.z.array(ml).optional(),additionalRegistryCredits:r.z.array(ml).optional(),additionalRegistryCostPerRegistry:r.z.number().optional(),errors:r.z.array(r.z.object({registry:r.z.string(),registryKey:r.z.string().nullable().optional(),error:r.z.string()})).min(1)}),El=r.z.union([Tl,Sl,kl]),vl=r.z.object({registryId:r.z.string(),registryKey:r.z.string(),networkId:r.z.string().optional(),networkName:r.z.string().optional(),chainId:r.z.number().optional(),label:r.z.string().optional(),status:r.z.enum(["pending","in_progress","completed","failed"]),error:r.z.string().optional(),credits:r.z.number().nullable().optional(),agentId:r.z.string().nullable().optional(),agentUri:r.z.string().nullable().optional(),metadata:r.z.record(Ec).optional(),lastUpdated:r.z.string()}),Al=r.z.object({attemptId:r.z.string(),mode:r.z.enum(["register","update"]),status:r.z.enum(["pending","partial","completed","failed"]),uaid:r.z.string().optional(),agentId:r.z.string().optional(),registryNamespace:r.z.string(),accountId:r.z.string().optional(),startedAt:r.z.string(),completedAt:r.z.string().optional(),primary:r.z.object({status:r.z.enum(["pending","completed","failed"]),finishedAt:r.z.string().optional(),error:r.z.string().optional()}),additionalRegistries:r.z.record(r.z.string(),vl),errors:r.z.array(r.z.string()).optional()}),Cl=r.z.object({progress:Al}),xl=r.z.object({accountId:r.z.string().nullable().optional(),registry:r.z.string().optional(),protocol:r.z.string().optional(),requiredCredits:r.z.number(),availableCredits:r.z.number().nullable().optional(),shortfallCredits:r.z.number().nullable().optional(),creditsPerHbar:r.z.number().nullable().optional(),estimatedHbar:r.z.number().nullable().optional()}),Rl=r.z.object({success:r.z.boolean().optional(),purchaser:r.z.string(),credits:r.z.number(),hbarAmount:r.z.number(),transactionId:r.z.string(),consensusTimestamp:r.z.string().nullable().optional()}),Nl=r.z.object({success:r.z.boolean().optional(),transaction:r.z.string().optional(),network:r.z.string().optional(),payer:r.z.string().optional(),errorReason:r.z.string().optional()}).strict(),_l=r.z.object({success:r.z.boolean(),accountId:r.z.string(),creditedCredits:r.z.number(),usdAmount:r.z.number(),balance:r.z.number(),payment:r.z.object({payer:r.z.string().optional(),requirement:r.z.record(Ec).optional(),settlement:Nl.optional()}).optional()}),Pl=r.z.object({minimums:r.z.record(r.z.object({network:r.z.string().optional(),gasLimit:r.z.number().optional(),gasPriceWei:r.z.string().optional(),gasUsd:r.z.number().optional(),minUsd:r.z.number().optional(),ethUsd:r.z.number().optional(),fetchedAt:r.z.string().optional(),source:r.z.string().optional()})).optional(),creditUnitUsd:r.z.number().optional()}),Fl=r.z.object({adapters:r.z.array(r.z.string())}),zl=r.z.object({id:r.z.number().int(),network:r.z.string(),type:r.z.string(),slug:r.z.string(),name:r.z.string(),description:r.z.string().nullable().optional(),topicId:r.z.string(),versionTopicId:r.z.string(),registryTransactionId:r.z.string().nullable().optional(),versionTransactionId:r.z.string().nullable().optional(),metadataPointer:r.z.string().nullable().optional(),metadataSequence:r.z.number().int().nullable().optional(),createdAt:r.z.string(),updatedAt:r.z.string(),metadata:Ec.optional().nullable()}),Ol=r.z.object({categories:r.z.array(zl)}),Dl=r.z.object({id:r.z.union([r.z.string(),r.z.number()]).optional(),network:r.z.string().optional(),categoryId:r.z.union([r.z.string(),r.z.number()]).nullable().optional(),operation:r.z.string().optional(),adapterId:r.z.string(),adapterName:r.z.string(),entity:r.z.string(),manifestPointer:r.z.string().nullable().optional(),manifestSequence:r.z.number().int().nullable().optional(),packageRegistry:r.z.string().nullable().optional(),packageName:r.z.string().nullable().optional(),packageVersion:r.z.string().nullable().optional(),packageIntegrity:r.z.string().nullable().optional(),stateModel:r.z.string().nullable().optional(),config:Ec.nullable().optional(),signature:r.z.string().nullable().optional(),manifest:Ec.nullable().optional(),keywords:r.z.array(r.z.string()).optional(),searchText:r.z.string().nullable().optional(),creditAccountId:r.z.string().nullable().optional(),registeredByUserId:r.z.string().nullable().optional(),registeredByEmail:r.z.string().nullable().optional(),totalCostHbar:r.z.number().nullable().optional(),totalCostCredits:r.z.number().nullable().optional(),consensusTimestamp:r.z.string().nullable().optional(),sequenceNumber:r.z.number().int().nullable().optional(),payerAccountId:r.z.string().nullable().optional(),mirrorNodePayload:Ec.nullable().optional(),versionTopicId:r.z.string().nullable().optional(),declarationTopicId:r.z.string().nullable().optional(),categoryEntrySequence:r.z.number().int().nullable().optional(),categoryEntryTransactionId:r.z.string().nullable().optional(),versionPointerSequence:r.z.number().int().nullable().optional(),versionPointerTransactionId:r.z.string().nullable().optional(),transactionId:r.z.string().nullable().optional(),createdAt:r.z.string().optional(),category:zl.optional()}).passthrough(),Ml=r.z.object({network:r.z.string(),adapters:r.z.array(Dl)}),Bl=r.z.object({category:zl});r.z.object({adapter:r.z.record(Ec),declaration:mc,transactionId:r.z.string().optional().nullable(),category:zl});const Kl=r.z.object({submissionId:r.z.string(),status:r.z.string().optional(),network:r.z.string().optional(),message:r.z.string().optional()}).passthrough(),Ul=r.z.object({submission:r.z.object({id:r.z.string(),network:r.z.string(),status:r.z.enum(["pending","running","completed","failed"]),adapterId:r.z.string(),categorySlug:r.z.string().nullable().optional(),creditAccountId:r.z.string().nullable().optional(),registeredByUserId:r.z.string().nullable().optional(),registeredByEmail:r.z.string().nullable().optional(),requestPayload:Ec.optional(),resultPayload:Ec.nullable().optional(),error:r.z.string().nullable().optional(),createdAt:r.z.string().optional(),updatedAt:r.z.string().optional(),startedAt:r.z.string().nullable().optional(),completedAt:r.z.string().nullable().optional()}).passthrough()}),Ll=r.z.object({supportsChat:r.z.boolean(),delivery:r.z.string().optional(),transport:r.z.string().optional(),streaming:r.z.boolean().optional(),requiresAuth:r.z.array(r.z.string()).optional(),notes:r.z.string().optional()}),$l=r.z.object({discovery:r.z.boolean(),routing:r.z.boolean(),communication:r.z.boolean(),translation:r.z.boolean(),protocols:r.z.array(r.z.string())}),Hl=r.z.object({id:r.z.string(),name:r.z.string(),version:r.z.string(),author:r.z.string(),description:r.z.string(),supportedProtocols:r.z.array(r.z.string()),registryType:r.z.enum(["web2","web3","hybrid"]),chatProfile:Ll.optional(),capabilities:$l,enabled:r.z.boolean(),priority:r.z.number(),status:r.z.enum(["running","stopped"])}),ql=r.z.object({adapters:r.z.array(Hl)}),jl=r.z.object({value:r.z.union([r.z.string(),r.z.number(),r.z.boolean()]),label:r.z.string()}),Wl=r.z.object({key:r.z.string(),label:r.z.string(),description:r.z.string().optional(),type:r.z.enum(["string","boolean","number"]),adapters:r.z.array(r.z.string()).optional(),options:r.z.array(jl).optional()}),Vl=r.z.object({facets:r.z.array(Wl)});let Gl;function Jl(e,t){if(!t||"object"!=typeof t)return!1;const r=Reflect.get(t,"code"),i=Reflect.get(t,"message"),o="string"==typeof i?i:"";if("string"==typeof r&&r.includes("MODULE_NOT_FOUND"))return o.includes(e);if(o){const t=o.toLowerCase();if(t.includes("cannot find module")||t.includes("module not found")||t.includes("cannot find package"))return t.includes(e.toLowerCase())}return!1}async function Yl(e){try{return await import(e)}catch(t){if(Jl(e,t))return null;throw t}}async function Xl(e){if(va)return Yl(e);const t=await async function(){if(void 0!==Gl)return Gl;if(va)return Gl=null,Gl;try{const e="undefined"!=typeof global?global:globalThis,t=e.process?.mainModule?.require??e.require;Gl="function"==typeof t&&"function"==typeof t.resolve?t:null}catch{Gl=null}return Gl}();if(t)try{return t(e)}catch(r){if(!Jl(e,r))throw r}return Yl(e)}const Zl="https://hol.org/registry/api/v1",Ql=/application\/json/i,ed=e=>{let t=e.length;for(;t>0&&47===e.charCodeAt(t-1);)t-=1;return t===e.length?e:e.slice(0,t)},td=()=>"function"==typeof DOMException?new DOMException("Aborted","AbortError"):new Error("The operation was aborted"),rd=e=>e.trim().toLowerCase(),id=e=>{if(null===e)return null;if(e instanceof Date)return e.toISOString();if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(Array.isArray(e))return e.map(e=>void 0===e?null:id(e));if("object"==typeof e){const t={};return Object.entries(e).forEach(([e,r])=>{void 0!==r&&(t[e]=id(r))}),t}throw new TypeError("Only JSON-compatible values are supported")},od=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),nd=e=>{const t=id(e);if(od(t))return t;throw new TypeError("Expected JSON object value")},sd=e=>{const t={};return e.type&&(t.type=e.type),e.token&&(t.token=e.token),e.username&&(t.username=e.username),e.password&&(t.password=e.password),e.headerName&&(t.headerName=e.headerName),e.headerValue&&(t.headerValue=e.headerValue),e.headers&&(t.headers={...e.headers}),t},ad=e=>{const t={profile:nd(e.profile)};return void 0!==e.endpoint&&(t.endpoint=e.endpoint),void 0!==e.protocol&&(t.protocol=e.protocol),void 0!==e.communicationProtocol&&(t.communicationProtocol=e.communicationProtocol),void 0!==e.registry&&(t.registry=e.registry),void 0!==e.additionalRegistries&&(t.additionalRegistries=e.additionalRegistries),void 0!==e.metadata&&(t.metadata=nd(e.metadata)),t};class cd extends Error{constructor(e,t){super(e),this.status=t.status,this.statusText=t.statusText,this.body=t.body}}class ld extends Error{constructor(e,t,r){super(e),this.cause=t,this.rawValue=r}}class dd{constructor(e={}){this.encryptionBootstrapPromise=null;const{baseUrl:t=Zl,fetchImplementation:r,defaultHeaders:i,apiKey:o,ledgerApiKey:n,registrationAutoTopUp:s,historyAutoTopUp:a,encryption:c}=e;this.baseUrl=function(e){const t=e?.trim();let r=t&&t.length>0?t:Zl;try{const e=new URL(ed(r)),t=e.hostname.toLowerCase(),i=()=>{e.pathname.startsWith("/registry")||(e.pathname="/"===e.pathname?"/registry":`/registry${e.pathname}`)};"hol.org"===t?(i(),r=e.toString()):"registry.hashgraphonline.com"!==t&&"hashgraphonline.com"!==t||(i(),e.hostname="hol.org",r=e.toString())}catch{}const i=ed(r);return/\/api\/v\d+$/i.test(i)?i:/\/api$/i.test(i)?`${i}/v1`:`${i}/api/v1`}(t),this.fetchImpl=r??fetch,this.defaultHeaders={...i??{}},Object.entries(this.defaultHeaders).forEach(([e,t])=>{const r=rd(e);r!==e&&(delete this.defaultHeaders[e],this.defaultHeaders[r]=t)}),o&&(this.defaultHeaders["x-api-key"]=o),n&&(this.defaultHeaders["x-ledger-api-key"]=n),this.registrationAutoTopUp=s,this.historyAutoTopUp=a,this.encryptionOptions=c,this.encryptionOptions&&(this.encryptionBootstrapPromise=this.initializeEncryptionBootstrap(this.encryptionOptions))}static async initializeAgent(e){const{uaid:t,ensureEncryptionKey:r=!0,...i}=e,o=new dd(i);let n=null;if(r){const e="object"==typeof r?r:{generateIfMissing:!0};n=await o.encryption.ensureAgentKey({uaid:t,...e})}return{client:o,encryption:n}}setApiKey(e){this.setDefaultHeader("x-api-key",e)}setLedgerApiKey(e){this.setDefaultHeader("x-ledger-api-key",e)}setDefaultHeader(e,t){if(!e||0===e.trim().length)return;const r=rd(e);t&&0!==t.trim().length?this.defaultHeaders[r]=t.trim():delete this.defaultHeaders[r]}getDefaultHeaders(){return{...this.defaultHeaders}}async encryptionReady(){this.encryptionBootstrapPromise&&await this.encryptionBootstrapPromise}buildUrl(e){const t=e.startsWith("/")?e:`/${e}`;return`${this.baseUrl}${t}`}async request(e,t){const r=new Headers;Object.entries(this.defaultHeaders).forEach(([e,t])=>{r.set(e,t)}),t.headers&&Object.entries(t.headers).forEach(([e,t])=>{r.set(e,t)}),r.has("accept")||r.set("accept","application/json"),r.has("user-agent")||"undefined"!=typeof window&&"function"==typeof window.fetch||r.set("user-agent","@hol-org/rb-client");const i={method:t.method??"GET",headers:r};void 0!==t.body&&(i.body=JSON.stringify(t.body),r.has("content-type")||r.set("content-type","application/json"));const o=await this.fetchImpl(this.buildUrl(e),i);if(o.ok)return o;const n=await this.extractErrorBody(o);throw new cd("Registry broker request failed",{status:o.status,statusText:o.statusText,body:n})}async requestJson(e,t){const r=await this.request(e,t),i=r.headers?.get("content-type")??"";if(!Ql.test(i)){const e=await r.text();throw new ld("Expected JSON response from registry broker",e)}return await r.json()}async extractErrorBody(e){const t=e.headers?.get("content-type")??"";if(Ql.test(t))try{return await e.json()}catch(r){return{parseError:String(r)}}try{return await e.text()}catch(r){return{parseError:String(r)}}}parseWithSchema(e,t,i){try{return t.parse(e)}catch(o){throw new ld(`Failed to parse ${i}`,o instanceof r.ZodError||o instanceof Error?o:String(o),e)}}async delay(e,t){if(e<=0){if(t?.aborted)throw td()}else await new Promise((r,i)=>{const o=setTimeout(()=>{t&&t.removeEventListener("abort",n),r()},e),n=()=>{clearTimeout(o),t?.removeEventListener("abort",n),i(td())};if(t){if(t.aborted)return clearTimeout(o),void i(td());t.addEventListener("abort",n,{once:!0})}})}assertNodeRuntime(e){if("undefined"==typeof process||!process.versions?.node)throw new Error(`${e} is only available in Node.js environments`)}createEphemeralKeyPair(){this.assertNodeRuntime("generateEphemeralKeyPair");const e=h.randomBytes(32),t=g.secp256k1.getPublicKey(e,!0);return{privateKey:p.Buffer.from(e).toString("hex"),publicKey:p.Buffer.from(t).toString("hex")}}deriveSharedSecret(e){this.assertNodeRuntime("deriveSharedSecret");const t=this.hexToBuffer(e.privateKey),r=this.hexToBuffer(e.peerPublicKey),i=g.secp256k1.getSharedSecret(t,r,!0);return h.createHash("sha256").update(p.Buffer.from(i)).digest()}buildCipherEnvelope(e){this.assertNodeRuntime("encryptCipherEnvelope");const t=this.normalizeSharedSecret(e.sharedSecret),r=h.randomBytes(12),i=h.createCipheriv("aes-256-gcm",t,r),o=e.associatedData??e.sessionId,n=o?p.Buffer.from(o,"utf8").toString("base64"):void 0;o&&i.setAAD(p.Buffer.from(o,"utf8"));const s=p.Buffer.concat([i.update(p.Buffer.from(e.plaintext,"utf8")),i.final()]),a=i.getAuthTag();return{algorithm:"aes-256-gcm",ciphertext:p.Buffer.concat([s,a]).toString("base64"),nonce:r.toString("base64"),associatedData:n,keyLocator:{sessionId:e.sessionId,revision:e.revision??1},recipients:e.recipients.map(e=>({...e,encryptedShare:""}))}}openCipherEnvelope(e){this.assertNodeRuntime("decryptCipherEnvelope");const t=this.normalizeSharedSecret(e.sharedSecret),r=p.Buffer.from(e.envelope.ciphertext,"base64"),i=p.Buffer.from(e.envelope.nonce,"base64"),o=r.slice(0,r.length-16),n=r.slice(r.length-16),s=h.createDecipheriv("aes-256-gcm",t,i);e.envelope.associatedData&&s.setAAD(p.Buffer.from(e.envelope.associatedData,"base64")),s.setAuthTag(n);return p.Buffer.concat([s.update(o),s.final()]).toString(e.encoding??"utf8")}normalizeSharedSecret(e){if(p.Buffer.isBuffer(e))return p.Buffer.from(e);if(e instanceof Uint8Array)return p.Buffer.from(e);if("string"==typeof e)return this.bufferFromString(e);throw new Error("Unsupported shared secret input")}bufferFromString(e){const t=e.trim();if(!t)throw new Error("sharedSecret string cannot be empty");const r=t.startsWith("0x")?t.slice(2):t;return/^[0-9a-fA-F]+$/.test(r)&&r.length%2==0?p.Buffer.from(r,"hex"):p.Buffer.from(t,"base64")}hexToBuffer(e){const t=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(t)||t.length%2!=0)throw new Error("Expected hex-encoded value");return p.Buffer.from(t,"hex")}extractInsufficientCreditsDetails(e){if(!(e instanceof cd)||402!==e.status)return null;const t=e.body;if(!t||"object"!=typeof t||Array.isArray(t))return null;const r=t.shortfallCredits;return"number"!=typeof r||r<=0?null:{shortfallCredits:r}}extractErrorMessage(e){return"string"==typeof e?e:od(e)&&"string"==typeof e.error?e.error:od(e)&&"string"==typeof e.message?e.message:void 0}shouldAutoTopUpHistory(e,t){if(!this.historyAutoTopUp||void 0===e.historyTtlSeconds)return!1;if(!(t instanceof cd))return!1;if(402!==t.status)return!1;const r=this.extractErrorMessage(t.body);if(!r)return!0;const i=r.toLowerCase();return i.includes("history")||i.includes("chat history")}async executeHistoryAutoTopUp(e){if(!this.historyAutoTopUp)return;const t=this.historyAutoTopUp.hbarAmount&&this.historyAutoTopUp.hbarAmount>0?this.historyAutoTopUp.hbarAmount:.25;await this.purchaseCreditsWithHbar({accountId:this.historyAutoTopUp.accountId,privateKey:this.historyAutoTopUp.privateKey,hbarAmount:t,memo:this.historyAutoTopUp.memo??"registry-broker-client:chat-history-topup",metadata:{purpose:"chat-history",reason:e}})}initializeEncryptionBootstrap(e){return this.bootstrapEncryptionOptions(e).then(()=>{})}bootstrapEncryptionOptions(e){return Promise.resolve(null)}}async function ud(e,t){const r=await e.requestJson("/encryption/keys",{method:"POST",headers:{"content-type":"application/json"},body:t});return e.parseWithSchema(r,Wc,"register encryption key response")}async function pd(e,t){if(t.publicKey?.trim())return{publicKey:t.publicKey.trim()};let r=t.privateKey?.trim();const i=t.envVar??"RB_ENCRYPTION_PRIVATE_KEY";if(!r&&i&&process?.env?.[i]?.trim()&&(r=process.env[i]?.trim()),!r&&t.generateIfMissing){const r=await e.generateEncryptionKeyPair({keyType:t.keyType??"secp256k1",envVar:i,envPath:t.envPath,overwrite:t.overwriteEnv});return i&&(process.env[i]=r.privateKey),{publicKey:r.publicKey,privateKey:r.privateKey}}if(r){const t=function(e,t){const r=e.hexToBuffer(t),i=g.secp256k1.getPublicKey(r,!0);return p.Buffer.from(i).toString("hex")}(e,r);return{publicKey:t,privateKey:r}}return null}async function hd(e,t){const r=function(e){const t={};return e.uaid&&(t.uaid=e.uaid),e.ledgerAccountId&&(t.ledgerAccountId=e.ledgerAccountId,e.ledgerNetwork&&(t.ledgerNetwork=e.ledgerNetwork)),e.email&&(t.email=e.email),t.uaid||t.ledgerAccountId||t.email?t:null}(t);if(!r)throw new Error("Auto-registration requires uaid, ledgerAccountId, or email");const i=await pd(e,t);if(!i)throw new Error("Unable to resolve encryption public key for auto-registration");return await ud(e,{keyType:t.keyType??"secp256k1",publicKey:i.publicKey,...r}),i}const gd=new WeakMap;async function md(e){const[{default:t},r,i]=await Promise.all([import("axios"),Xl("x402-axios"),Xl("x402/types")]);if(!r||!i)throw new Error("x402-axios and x402/types are required for X402 flows. Install them to enable ledger payments.");const o=r.withPaymentInterceptor;return{createPaymentClient:r=>{const i=t.create({baseURL:e.baseUrl,headers:{...e.getDefaultHeaders(),"content-type":"application/json"}});return o(i,r)},decodePaymentResponse:r.decodeXPaymentResponse,createX402Signer:i.createSigner}}function fd(e){const t=Math.ceil(1e8*e);if(t<=0)throw new Error("Calculated purchase amount must be positive");return t/1e8}async function yd(e,t){const r=await e.requestJson("/register",{method:"POST",body:ad(t),headers:{"content-type":"application/json"}});return e.parseWithSchema(r,El,"register agent response")}function bd(e,t){if(t<=0)throw new Error("creditsPerHbar must be positive");if(e<=0)throw new Error("creditsToPurchase must be positive");const r=e/t;return Math.ceil(1e8*r)/1e8}function wd(e){return!Number.isFinite(e)||e<=0?0:Math.max(Math.ceil(e),1)}async function Id(e,t,r){const i=r??null;if(!i)return;if(!i.accountId||!i.accountId.trim())throw new Error("autoTopUp.accountId is required");if(!i.privateKey||!i.privateKey.trim())throw new Error("autoTopUp.privateKey is required");for(let o=0;o<3;o+=1){const r=await e.getRegistrationQuote(t),o=r.shortfallCredits??0;if(o<=0)return;const n=wd(o);if(n<=0)return;const s=r.creditsPerHbar??null;if(!s||s<=0)throw new Error("Unable to determine credits per HBAR for auto top-up");const a=bd(n,s);await e.purchaseCreditsWithHbar({accountId:i.accountId.trim(),privateKey:i.privateKey.trim(),hbarAmount:a,memo:i.memo??"Registry Broker auto top-up",metadata:{shortfallCredits:o,requiredCredits:r.requiredCredits,purchasedCredits:n}})}if(((await e.getRegistrationQuote(t)).shortfallCredits??0)>0)throw new Error("Unable to purchase sufficient credits for registration")}Object.defineProperty(dd.prototype,"encryption",{get(){const e=gd.get(this);if(e)return e;const t={registerKey:e=>ud(this,e),generateEphemeralKeyPair:()=>this.createEphemeralKeyPair(),deriveSharedSecret:e=>this.deriveSharedSecret(e),encryptCipherEnvelope:e=>this.buildCipherEnvelope(e),decryptCipherEnvelope:e=>this.openCipherEnvelope(e),ensureAgentKey:e=>async function(e,t){return hd(e,{...t,uaid:t.uaid})}(this,e)};return gd.set(this,t),t}}),dd.prototype.bootstrapEncryptionOptions=async function(e){return e?.autoRegister&&!1!==e.autoRegister.enabled?hd(this,e.autoRegister):null},dd.prototype.generateEncryptionKeyPair=async function(e={}){this.assertNodeRuntime("generateEncryptionKeyPair");if("secp256k1"!==(e.keyType??"secp256k1"))throw new Error("Only secp256k1 key generation is supported currently");const t=h.randomBytes(32),r=p.Buffer.from(t).toString("hex"),i=g.secp256k1.getPublicKey(t,!0),o=p.Buffer.from(i).toString("hex"),n=e.envVar??"RB_ENCRYPTION_PRIVATE_KEY",s=e.envPath?T.resolve(e.envPath):void 0;if(s){const t=await(async()=>{const e=await Xl("node:fs");return e&&"function"==typeof e.existsSync&&"function"==typeof e.readFileSync&&"function"==typeof e.writeFileSync&&"function"==typeof e.appendFileSync?e:null})();if(!t)throw new Error("File system module is not available; cannot write encryption key env file");const i=`${n}=${r}`;if(t.existsSync(s)){const r=t.readFileSync(s,"utf-8"),o=new RegExp(`^${n}=.*$`,"m");if(o.test(r)){if(!e.overwrite)throw new Error(`${n} already exists in ${s}; set overwrite=true to replace it`);const a=r.replace(o,i);t.writeFileSync(s,a)}else{const e=!r.endsWith("\n");t.appendFileSync(s,`${e?"\n":""}${i}\n`)}}else t.writeFileSync(s,`${i}\n`)}return{privateKey:r,publicKey:o,envPath:s,envVar:n}},dd.prototype.search=async function(e={}){const t=function(e){const t=new URLSearchParams,r=(e,r)=>{r&&r.forEach(r=>{if("string"==typeof r){const i=r.trim();i.length>0&&t.append(e,i)}})};if(e.q){const r=e.q.trim();r.length>0&&t.set("q",r)}if("number"==typeof e.page&&t.set("page",e.page.toString()),"number"==typeof e.limit&&t.set("limit",e.limit.toString()),e.registry){const r=e.registry.trim();r.length>0&&t.set("registry",r)}if(r("registries",e.registries),"number"==typeof e.minTrust&&t.set("minTrust",e.minTrust.toString()),r("capabilities",e.capabilities),r("protocols",e.protocols),r("adapters",e.adapters),e.metadata&&Object.entries(e.metadata).forEach(([e,r])=>{if(!e||!Array.isArray(r)||0===r.length)return;const i=e.trim();0!==i.length&&r.forEach(e=>{null!=e&&t.append(`metadata.${i}`,String(e))})}),e.type){const r=e.type.trim();r.length>0&&"all"!==r.toLowerCase()&&t.set("type",r)}if(!0===e.verified&&t.set("verified","true"),!0===e.online&&t.set("online","true"),e.sortBy){const r=e.sortBy.trim();r.length>0&&t.set("sortBy",r)}if(e.sortOrder){const r=e.sortOrder.toLowerCase();"asc"!==r&&"desc"!==r||t.set("sortOrder",r)}const i=t.toString();return i.length>0?`?${i}`:""}(e),r=await this.requestJson(`/search${t}`,{method:"GET"});return this.parseWithSchema(r,Oc,"search response")},dd.prototype.stats=async function(){const e=await this.requestJson("/stats",{method:"GET"});return this.parseWithSchema(e,Dc,"stats response")},dd.prototype.registries=async function(){const e=await this.requestJson("/registries",{method:"GET"});return this.parseWithSchema(e,Mc,"registries response")},dd.prototype.getAdditionalRegistries=async function(){const e=await this.requestJson("/register/additional-registries",{method:"GET"});return this.parseWithSchema(e,Il,"additional registry catalog response")},dd.prototype.popularSearches=async function(){const e=await this.requestJson("/popular",{method:"GET"});return this.parseWithSchema(e,Bc,"popular searches response")},dd.prototype.listProtocols=async function(){const e=await this.requestJson("/protocols",{method:"GET"});return this.parseWithSchema(e,Yc,"protocols response")},dd.prototype.detectProtocol=async function(e){const t=await this.requestJson("/detect-protocol",{method:"POST",body:{message:e},headers:{"content-type":"application/json"}});return this.parseWithSchema(t,Xc,"detect protocol response")},dd.prototype.registrySearchByNamespace=async function(e,t){const r=new URLSearchParams;t&&r.set("q",t);const i=r.size>0?`?${r.toString()}`:"",o=await this.requestJson(`/registries/${encodeURIComponent(e)}/search${i}`,{method:"GET"});return this.parseWithSchema(o,Zc,"registry search response")},dd.prototype.vectorSearch=async function(e){try{const t=await this.requestJson("/search",{method:"POST",body:e,headers:{"content-type":"application/json"}});return this.parseWithSchema(t,rl,"vector search response")}catch(t){if(t instanceof cd&&501===t.status){const t=await this.search(function(e){const t={q:e.query};let r;if("number"==typeof e.limit&&Number.isFinite(e.limit)&&(r=e.limit,t.limit=e.limit),"number"==typeof e.offset&&Number.isFinite(e.offset)&&e.offset>0){const i=r&&r>0?r:20;t.limit=i,t.page=Math.floor(e.offset/i)+1}return e.filter?.registry&&(t.registry=e.filter.registry),e.filter?.protocols?.length&&(t.protocols=[...e.filter.protocols]),e.filter?.adapter?.length&&(t.adapters=[...e.filter.adapter]),e.filter?.capabilities?.length&&(t.capabilities=e.filter.capabilities.map(e=>"number"==typeof e?e.toString(10):e)),e.filter?.type&&(t.type=e.filter.type),t}(e));return function(e){const t=e.hits.map(e=>({agent:e,score:0,highlights:{}})),r=e.total,i=e.limit,o=e.page,n=r>o*i||o>1;return{hits:t,total:r,took:0,totalAvailable:r,visible:t.length,limited:n,credits_used:0}}(t)}throw t}},dd.prototype.searchStatus=async function(){const e=await this.requestJson("/search/status",{method:"GET"});return this.parseWithSchema(e,ol,"search status response")},dd.prototype.websocketStats=async function(){const e=await this.requestJson("/websocket/stats",{method:"GET"});return this.parseWithSchema(e,nl,"websocket stats response")},dd.prototype.metricsSummary=async function(){const e=await this.requestJson("/metrics",{method:"GET"});return this.parseWithSchema(e,al,"metrics summary response")},dd.prototype.facets=async function(e){const t=new URLSearchParams;e&&t.set("adapter",e);const r=t.size>0?`?${t.toString()}`:"",i=await this.requestJson(`/search/facets${r}`,{method:"GET"});return this.parseWithSchema(i,Vl,"search facets response")},dd.prototype.adapters=async function(){const e=await this.requestJson("/adapters",{method:"GET"});return this.parseWithSchema(e,Fl,"adapters response")},dd.prototype.adaptersDetailed=async function(){const e=await this.requestJson("/adapters/details",{method:"GET"});return this.parseWithSchema(e,ql,"adapter details response")},dd.prototype.adapterRegistryCategories=async function(){const e=await this.requestJson("/adapters/registry/categories",{method:"GET"});return this.parseWithSchema(e,Ol,"adapter registry categories response")},dd.prototype.adapterRegistryAdapters=async function(e={}){const t=new URLSearchParams;e.category&&t.set("category",e.category),e.entity&&t.set("entity",e.entity),e.keywords?.length&&t.set("keywords",e.keywords.join(",")),e.query&&t.set("query",e.query),"number"==typeof e.limit&&t.set("limit",String(e.limit)),"number"==typeof e.offset&&t.set("offset",String(e.offset));const r=t.size>0?`?${t.toString()}`:"",i=await this.requestJson(`/adapters/registry/adapters${r}`,{method:"GET"});return this.parseWithSchema(i,Ml,"adapter registry adapters response")},dd.prototype.createAdapterRegistryCategory=async function(e){const t=await this.requestJson("/adapters/registry/categories",{method:"POST",headers:{"content-type":"application/json"},body:nd(e)});return this.parseWithSchema(t,Bl,"adapter registry create category response").category},dd.prototype.submitAdapterRegistryAdapter=async function(e){const t=await this.requestJson("/adapters/registry/adapters",{method:"POST",headers:{"content-type":"application/json"},body:nd(e)});return this.parseWithSchema(t,Kl,"adapter registry submit adapter response")},dd.prototype.adapterRegistrySubmissionStatus=async function(e){const t=await this.requestJson(`/adapters/registry/submissions/${encodeURIComponent(e)}`,{method:"GET"});return this.parseWithSchema(t,Ul,"adapter registry submission status response")},dd.prototype.purchaseCreditsWithHbar=async function(e){const t={accountId:e.accountId,payerKey:e.privateKey,hbarAmount:fd(e.hbarAmount)};e.memo&&(t.memo=e.memo),e.metadata&&(t.metadata=e.metadata);const r=await this.requestJson("/credits/purchase",{method:"POST",headers:{"content-type":"application/json"},body:t});return this.parseWithSchema(r,Rl,"credit purchase response")},dd.prototype.getX402Minimums=async function(){const e=await this.requestJson("/credits/purchase/x402/minimums",{method:"GET"});return this.parseWithSchema(e,Pl,"x402 minimums response")},dd.prototype.purchaseCreditsWithX402=async function(e){const{createPaymentClient:t,decodePaymentResponse:r}=await md(this);if(!Number.isFinite(e.credits)||e.credits<=0)throw new Error("credits must be a positive number");if(void 0!==e.usdAmount&&(!Number.isFinite(e.usdAmount)||e.usdAmount<=0))throw new Error("usdAmount must be a positive number when provided");const i={accountId:e.accountId,credits:e.credits};void 0!==e.usdAmount&&(i.usdAmount=e.usdAmount),e.description&&(i.description=e.description),e.metadata&&(i.metadata=e.metadata);const o=t(e.walletClient),n=await o.post("/credits/purchase/x402",i),s=this.parseWithSchema(n.data,_l,"x402 credit purchase response"),a=n.headers??{},c="string"==typeof a["x-payment-response"]?a["x-payment-response"]:void 0;return{...s,paymentResponseHeader:c,paymentResponse:void 0!==c?r(c):void 0}},dd.prototype.buyCreditsWithX402=async function(e){const t=e.network??"base",{createX402Signer:r}=await md(this),i=(e=>{const t=e.trim();if(!t)throw new Error("evmPrivateKey is required");return t.startsWith("0x")?t:`0x${t}`})(e.evmPrivateKey),o=await r(t,i);return this.purchaseCreditsWithX402({accountId:e.accountId,credits:e.credits,usdAmount:e.usdAmount,description:e.description,metadata:e.metadata,walletClient:o})},dd.prototype.resolveUaid=async function(e){const t=await this.requestJson(`/resolve/${encodeURIComponent(e)}`,{method:"GET"});return this.parseWithSchema(t,Kc,"resolve UAID response")},dd.prototype.registerAgent=async function(e,t){const r=t?.autoTopUp??this.registrationAutoTopUp;if(!r)return yd(this,e);await Id(this,e,r);let i=!1;for(;;)try{return await yd(this,e)}catch(o){if(this.extractInsufficientCreditsDetails(o)&&!i){await Id(this,e,r),i=!0;continue}throw o}},dd.prototype.getRegistrationQuote=async function(e){const t=await this.requestJson("/register/quote",{method:"POST",body:ad(e),headers:{"content-type":"application/json"}});return this.parseWithSchema(t,xl,"registration quote response")},dd.prototype.updateAgent=async function(e,t){const r=await this.requestJson(`/register/${encodeURIComponent(e)}`,{method:"PUT",body:ad(t),headers:{"content-type":"application/json"}});return this.parseWithSchema(r,El,"update agent response")},dd.prototype.getRegistrationProgress=async function(e){const t=e.trim();if(!t)throw new Error("attemptId is required");try{const e=await this.requestJson(`/register/progress/${encodeURIComponent(t)}`,{method:"GET"});return this.parseWithSchema(e,Cl,"registration progress response").progress}catch(r){if(r instanceof cd&&404===r.status)return null;throw r}},dd.prototype.waitForRegistrationCompletion=async function(e,t={}){const r=e.trim();if(!r)throw new Error("attemptId is required");const i=Math.max(250,t.intervalMs??1500),o=t.timeoutMs??3e5,n=t.throwOnFailure??!0,s=t.signal,a=Date.now();for(;;){if(s?.aborted)throw td();const e=await this.getRegistrationProgress(r);if(e){if(t.onProgress?.(e),"completed"===e.status)return e;if("partial"===e.status||"failed"===e.status){if(n)throw new cd("Registration did not complete successfully",{status:409,statusText:e.status,body:e});return e}}if(Date.now()-a>=o)throw new Error(`Registration progress polling timed out after ${o}ms`);await this.delay(i,s)}},dd.prototype.validateUaid=async function(e){const t=await this.requestJson(`/uaids/validate/${encodeURIComponent(e)}`,{method:"GET"});return this.parseWithSchema(t,cl,"UAID validation response")},dd.prototype.getUaidConnectionStatus=async function(e){const t=await this.requestJson(`/uaids/connections/${encodeURIComponent(e)}/status`,{method:"GET"});return this.parseWithSchema(t,dl,"UAID connection status")},dd.prototype.closeUaidConnection=async function(e){await this.request(`/uaids/connections/${encodeURIComponent(e)}`,{method:"DELETE"})},dd.prototype.dashboardStats=async function(){const e=await this.requestJson("/dashboard/stats",{method:"GET"});return this.parseWithSchema(e,ul,"dashboard stats response")};const Td=e=>e.trim().toLowerCase(),Sd=new Map([["hedera:mainnet",{canonical:"hedera:mainnet",hederaNetwork:"mainnet"}],["mainnet",{canonical:"hedera:mainnet",hederaNetwork:"mainnet"}],["hedera-mainnet",{canonical:"hedera:mainnet",hederaNetwork:"mainnet"}],["hedera_mainnet",{canonical:"hedera:mainnet",hederaNetwork:"mainnet"}],["hedera:testnet",{canonical:"hedera:testnet",hederaNetwork:"testnet"}],["testnet",{canonical:"hedera:testnet",hederaNetwork:"testnet"}],["hedera-testnet",{canonical:"hedera:testnet",hederaNetwork:"testnet"}],["hedera_testnet",{canonical:"hedera:testnet",hederaNetwork:"testnet"}]]),kd={abstract:2741,"abstract-testnet":11124,base:8453,"base-sepolia":84532,avalanche:43114,"avalanche-fuji":43113,iotex:4689,sei:1329,"sei-testnet":1328,polygon:137,"polygon-amoy":80002,peaq:3338},Ed=new Map(Object.entries(kd).map(([e,t])=>[t,e])),vd=e=>{const t=Td(e);let r,i=(e=>/^eip155:\d+$/i.test(e)?Number.parseInt(e.split(":")[1],10):/^\d+$/.test(e)?Number.parseInt(e,10):void 0)(t);if(void 0===i){const e=kd[t];void 0!==e&&(i=e,r=t)}else Ed.has(i)&&(r=Ed.get(i));if(void 0===i)throw new Error('Unsupported EVM ledger network. Provide an alias like "base-sepolia" or a canonical eip155:<chainId> string.');return{canonical:`eip155:${i}`,kind:"evm",chainId:i,legacyName:r}},Ad=e=>{if("string"!=typeof e||0===e.trim().length)throw new Error("Ledger network is required.");const t=Td(e);return t.startsWith("hedera:")||t.includes("hedera-")||t.includes("hedera_")||"mainnet"===t||"testnet"===t?(e=>{const t=Td(e),r=Sd.get(t);if(!r)throw new Error('Unsupported Hedera network. Use hedera:mainnet or hedera:testnet (legacy "mainnet"/"testnet" also accepted).');return{canonical:r.canonical,kind:"hedera",hederaNetwork:r.hederaNetwork}})(t):vd(t)},Cd=e=>new Error(`${e} is not supported by the in-memory signer`),xd=e=>{const t=Nd(),{AccountId:r,LedgerId:i,PrivateKey:o,SignerSignature:n}=t;if(!e.privateKey)throw new Error("privateKey is required to create a ledger signer.");if(!e.accountId)throw new Error("accountId is required to create a ledger signer.");const s=r.fromString(e.accountId),a=o.fromString(e.privateKey),c=i.fromString(e.network);return{getLedgerId:()=>c,getAccountId:()=>s,getAccountKey:()=>a.publicKey,getNetwork:()=>({}),getMirrorNetwork:()=>[],sign:async e=>Promise.all(e.map(async e=>{const t=await a.sign(e);return new n({publicKey:a.publicKey,signature:t,accountId:s})})),getAccountBalance:async()=>{throw Cd("getAccountBalance")},getAccountInfo:async()=>{throw Cd("getAccountInfo")},getAccountRecords:async()=>{throw Cd("getAccountRecords")},signTransaction:async e=>{throw Cd("signTransaction")},checkTransaction:async e=>{throw Cd("checkTransaction")},populateTransaction:async e=>{throw Cd("populateTransaction")},call:async e=>{throw Cd("call")}}};let Rd=null;const Nd=()=>{if(Rd)return Rd;const e=function(e){if(va)return null;try{const t="undefined"!=typeof global?global:globalThis,r=t.process?.mainModule?.require??t.require;if("function"==typeof r&&"function"==typeof r.resolve)return r(e)}catch(t){if(!Jl(e,t))throw t}return null}("@hashgraph/sdk");if(e)return Rd=e,e;try{const e=m.createRequire("undefined"==typeof document?require("url").pathToFileURL(__filename).href:w&&"SCRIPT"===w.tagName.toUpperCase()&&w.src||new URL("standards-sdk.cjs",document.baseURI).href)("@hashgraph/sdk");return Rd=e,e}catch{throw new Error("@hashgraph/sdk is required for ledger signing. Install it as a dependency to enable createPrivateKeySigner.")}};dd.prototype.createLedgerChallenge=async function(e){const t=Ad(e.network),r="hedera"===t.kind?t.hederaNetwork??t.canonical:t.canonical,i=await this.requestJson("/auth/ledger/challenge",{method:"POST",headers:{"content-type":"application/json"},body:{accountId:e.accountId,network:r}});return this.parseWithSchema(i,Vc,"ledger challenge response")},dd.prototype.verifyLedgerChallenge=async function(e){const t=Ad(e.network),r="hedera"===t.kind?t.hederaNetwork??t.canonical:t.canonical,i={challengeId:e.challengeId,accountId:e.accountId,network:r,signature:e.signature};e.signatureKind&&(i.signatureKind=e.signatureKind),e.publicKey&&(i.publicKey=e.publicKey),"number"==typeof e.expiresInMinutes&&(i.expiresInMinutes=e.expiresInMinutes);const o=await this.requestJson("/auth/ledger/verify",{method:"POST",headers:{"content-type":"application/json"},body:i}),n=this.parseWithSchema(o,Jc,"ledger verification response");return this.setLedgerApiKey(n.key),n},dd.prototype.authenticateWithLedger=async function(e){const t=await this.createLedgerChallenge({accountId:e.accountId,network:e.network}),r=await async function(e,t){if("function"==typeof t.sign){const r=await t.sign(e);if(!r||"string"!=typeof r.signature||0===r.signature.length)throw new Error("Custom ledger signer failed to produce a signature.");return r}if(!t.signer||"function"!=typeof t.signer.sign)throw new Error("Ledger authentication requires a Hedera Signer or custom sign function.");const r=p.Buffer.from(e,"utf8"),i=await t.signer.sign([r]),o=i?.[0];if(!o)throw new Error("Signer did not return any signatures.");let n;if(o.publicKey)n=o.publicKey.toString();else if("function"==typeof t.signer.getAccountKey){const e=await t.signer.getAccountKey();e&&"function"==typeof e.toString&&(n=e.toString())}return{signature:p.Buffer.from(o.signature).toString("base64"),signatureKind:"raw",publicKey:n}}(t.message,e);return await this.verifyLedgerChallenge({challengeId:t.challengeId,accountId:e.accountId,network:e.network,signature:r.signature,signatureKind:r.signatureKind,publicKey:r.publicKey,expiresInMinutes:e.expiresInMinutes})},dd.prototype.authenticateWithLedgerCredentials=async function(e){const{accountId:t,network:r,signer:i,sign:o,hederaPrivateKey:n,evmPrivateKey:s,expiresInMinutes:a,setAccountHeader:c=!0,label:l,logger:d}=e,u=Ad(r),p=l?` for ${l}`:"",h={accountId:t,network:u.canonical,expiresInMinutes:a};if(o)h.sign=o;else if(i)h.signer=i;else if(n){if("hedera"!==u.kind||!u.hederaNetwork)throw new Error("hederaPrivateKey can only be used with hedera:mainnet or hedera:testnet networks.");h.signer=xd({accountId:t,privateKey:n,network:u.hederaNetwork})}else{if(!s)throw new Error("Provide a signer, sign function, hederaPrivateKey, or evmPrivateKey to authenticate with the ledger.");{if("evm"!==u.kind)throw new Error("evmPrivateKey can only be used with CAIP-2 EVM networks (eip155:<chainId>).");const e=s.startsWith("0x")?s:`0x${s}`,t=await async function(e){try{return(await import("viem/accounts")).privateKeyToAccount(e)}catch(t){const e=new Error('EVM ledger authentication requires the optional dependency "viem". Install it to use evmPrivateKey flows.');throw e.cause=t,e}}(e);h.sign=async e=>({signature:await t.signMessage({message:e}),signatureKind:"evm",publicKey:t.publicKey})}}d?.info?.(`Authenticating ledger account ${t} (${u.canonical})${p}...`);const g=await this.authenticateWithLedger(h);return c&&this.setDefaultHeader("x-account-id",g.accountId),d?.info?.(`Ledger authentication complete${p}. Issued key prefix: ${g.apiKey.prefix}…${g.apiKey.lastFour}`),g};const _d=new WeakMap;function Pd(e){const t=_d.get(e);if(t)return t;const r=new Map;return _d.set(e,r),r}function Fd(e,t){return!e&&!t||!(!e||!t)&&(!(!e.uaid||!t.uaid||e.uaid.toLowerCase()!==t.uaid.toLowerCase())||(!(!e.ledgerAccountId||!t.ledgerAccountId||e.ledgerAccountId.toLowerCase()!==t.ledgerAccountId.toLowerCase())||(!(!e.userId||!t.userId||e.userId!==t.userId)||!(!e.email||!t.email||e.email.toLowerCase()!==t.email.toLowerCase()))))}dd.prototype.fetchHistorySnapshot=async function(e,t){if(!e||0===e.trim().length)throw new Error("sessionId is required to fetch chat history");const r=await this.requestJson(`/chat/session/${encodeURIComponent(e)}/history`,{method:"GET"}),i=this.parseWithSchema(r,$c,"chat history snapshot response");return this.attachDecryptedHistory(e,i,t)},dd.prototype.attachDecryptedHistory=function(e,t,r){if(!(void 0!==r?.decrypt?r.decrypt:!0===this.encryptionOptions?.autoDecryptHistory))return t;const i=this.resolveDecryptionContext(e,r);if(!i)throw new Error("Unable to decrypt chat history: encryption context unavailable");const o=t.history.map(t=>({entry:t,plaintext:this.decryptHistoryEntryFromContext(e,t,i)}));return{...t,decryptedHistory:o}},dd.prototype.registerConversationContextForEncryption=function(e){const t={sessionId:e.sessionId,sharedSecret:p.Buffer.from(e.sharedSecret),identity:e.identity?{...e.identity}:void 0},r=Pd(this),i=r.get(e.sessionId)??[],o=i.findIndex(e=>Fd(e.identity,t.identity));o>=0?i[o]=t:i.push(t),r.set(e.sessionId,i)},dd.prototype.resolveDecryptionContext=function(e,t){if(t?.sharedSecret)return{sessionId:e,sharedSecret:this.normalizeSharedSecret(t.sharedSecret),identity:t.identity};const r=Pd(this).get(e);if(!r||0===r.length)return null;if(t?.identity){const e=r.find(e=>Fd(e.identity,t.identity));if(e)return e}return r[0]},dd.prototype.decryptHistoryEntryFromContext=function(e,t,r){const i=t.cipherEnvelope;if(!i)return t.content;const o=p.Buffer.from(r.sharedSecret);try{return this.encryption.decryptCipherEnvelope({envelope:i,sharedSecret:o})}catch(n){return null}};class zd extends Error{constructor(e,t){super("Encryption is not enabled for this session"),this.sessionId=e,this.summary=t}}class Od{constructor(e){this.client=e}registerConversationContext(e){this.client.registerConversationContextForEncryption(e)}async startSession(e){await this.client.encryptionReady();const t=await this.client.chat.createSession({uaid:e.uaid,senderUaid:e.senderUaid,encryptionRequested:!0,historyTtlSeconds:e.historyTtlSeconds,auth:e.auth});e.onSessionCreated?.(t.sessionId);const r=t.encryption;if(!r?.enabled)throw new zd(t.sessionId,t.encryption??null);return await this.establishRequesterContext({sessionId:t.sessionId,summary:r,senderUaid:e.senderUaid,handshakeTimeoutMs:e.handshakeTimeoutMs,pollIntervalMs:e.pollIntervalMs})}async acceptSession(e){await this.client.encryptionReady();const t=await this.waitForEncryptionSummary(e.sessionId,e.handshakeTimeoutMs,e.pollIntervalMs);return await this.establishResponderContext({sessionId:e.sessionId,summary:t,responderUaid:e.responderUaid,handshakeTimeoutMs:e.handshakeTimeoutMs,pollIntervalMs:e.pollIntervalMs})}async establishRequesterContext(e){const t=this.client.encryption.generateEphemeralKeyPair();await this.client.chat.submitEncryptionHandshake(e.sessionId,{role:"requester",keyType:"secp256k1",ephemeralPublicKey:t.publicKey,uaid:e.senderUaid??e.summary.requester?.uaid??void 0});const{summary:r,record:i}=await this.waitForHandshakeCompletion(e.sessionId,e.handshakeTimeoutMs,e.pollIntervalMs),o=i.responder?.ephemeralPublicKey;if(!o)throw new Error("Responder handshake was not completed in time");const n=this.client.encryption.deriveSharedSecret({privateKey:t.privateKey,peerPublicKey:o}).subarray(),s=this.buildRecipients(r);return this.createHandle({sessionId:e.sessionId,sharedSecret:n,summary:r,recipients:s,identity:r.requester??void 0})}async establishResponderContext(e){const t=this.client.encryption.generateEphemeralKeyPair();await this.client.chat.submitEncryptionHandshake(e.sessionId,{role:"responder",keyType:"secp256k1",ephemeralPublicKey:t.publicKey,uaid:e.responderUaid??e.summary.responder?.uaid??void 0});const{summary:r,record:i}=await this.waitForHandshakeCompletion(e.sessionId,e.handshakeTimeoutMs,e.pollIntervalMs),o=i.requester?.ephemeralPublicKey;if(!o)throw new Error("Requester handshake was not detected in time");const n=this.client.encryption.deriveSharedSecret({privateKey:t.privateKey,peerPublicKey:o}).subarray(),s=this.buildRecipients(r);return this.createHandle({sessionId:e.sessionId,sharedSecret:n,summary:r,recipients:s,identity:r.responder??void 0})}async waitForHandshakeCompletion(e,t=3e4,r=1e3){const i=Date.now()+t;for(;;){const t=(await this.client.chat.getEncryptionStatus(e)).encryption,o=t?.handshake;if(t&&o&&"complete"===o.status)return{summary:t,record:o};if(Date.now()>=i)throw new Error("Timed out waiting for encrypted handshake completion");await this.delay(r)}}async waitForEncryptionSummary(e,t=3e4,r=1e3){const i=await this.client.chat.getEncryptionStatus(e);if(!i.encryption?.enabled)throw new zd(e,i.encryption??null);return i.encryption}buildRecipients(e){const t=[e.requester,e.responder].filter(Boolean).map(e=>{if(!e)return null;const t={};return e.uaid&&(t.uaid=e.uaid),e.ledgerAccountId&&(t.ledgerAccountId=e.ledgerAccountId),e.userId&&(t.userId=e.userId),e.email&&(t.email=e.email),t}).filter(e=>Boolean(e?.uaid||e?.ledgerAccountId||e?.userId||e?.email));return t.length>0?t:e.responder?.uaid?[{uaid:e.responder.uaid}]:[]}createHandle(e){const t=e.sharedSecret,r=e.summary.requester?.uaid??e.summary.responder?.uaid??e.identity?.uaid,i={sessionId:e.sessionId,mode:"encrypted",summary:e.summary,send:async i=>{const o=i.recipients??e.recipients;return this.client.chat.sendMessage({sessionId:e.sessionId,message:i.message??"[ciphertext omitted]",streaming:i.streaming,auth:i.auth,uaid:r,encryption:{plaintext:i.plaintext,sharedSecret:globalThis.Buffer.from(t),recipients:o}})},decryptHistoryEntry:r=>this.decryptEntry(r,e.identity,t)};return this.registerConversationContext({sessionId:e.sessionId,sharedSecret:t,identity:e.identity}),i}decryptEntry(e,t,r){const i=e.cipherEnvelope;if(!i)return null;const o=globalThis.Buffer.from(r);try{return this.client.encryption.decryptCipherEnvelope({envelope:i,sharedSecret:o})}catch(n){return null}}recipientMatches(e,t){return!(!t.uaid||e.uaid?.toLowerCase()!==t.uaid.toLowerCase())||(!(!t.ledgerAccountId||e.ledgerAccountId?.toLowerCase()!==t.ledgerAccountId.toLowerCase())||(!(!t.userId||e.userId!==t.userId)||!(!t.email||e.email?.toLowerCase()!==t.email.toLowerCase())))}async delay(e){e<=0||await new Promise(t=>setTimeout(t,e))}}const Dd=new WeakMap,Md=new WeakMap;function Bd(e){const t=Dd.get(e);if(t)return t;const r=new Od(e);return Dd.set(e,r),r}Object.defineProperty(dd.prototype,"chat",{get(){const e=Md.get(this);if(e)return e;const t=Bd(this),r={start:e=>this.startChat(e),createSession:e=>this.createSession(e),sendMessage:e=>this.sendMessage(e),endSession:e=>this.endSession(e),getHistory:(e,t)=>this.fetchHistorySnapshot(e,t),compactHistory:e=>this.compactHistory(e),getEncryptionStatus:e=>this.fetchEncryptionStatus(e),submitEncryptionHandshake:(e,t)=>this.postEncryptionHandshake(e,t),startConversation:e=>this.startConversation(e),acceptConversation:e=>this.acceptConversation(e),createEncryptedSession:e=>t.startSession(e),acceptEncryptedSession:e=>t.acceptSession(e)};return Md.set(this,r),r}}),dd.prototype.createSession=async function(e,t=!0){const r={};"uaid"in e&&e.uaid&&(r.uaid=e.uaid),"agentUrl"in e&&e.agentUrl&&(r.agentUrl=e.agentUrl),e.auth&&(r.auth=sd(e.auth)),void 0!==e.historyTtlSeconds&&(r.historyTtlSeconds=e.historyTtlSeconds),void 0!==e.encryptionRequested&&(r.encryptionRequested=e.encryptionRequested),e.senderUaid&&(r.senderUaid=e.senderUaid);try{const e=await this.requestJson("/chat/session",{method:"POST",body:r,headers:{"content-type":"application/json"}});return this.parseWithSchema(e,Uc,"chat session response")}catch(i){const r=i instanceof Error?i:null;if(t&&this.shouldAutoTopUpHistory(e,r))return await this.executeHistoryAutoTopUp("chat.session"),this.createSession(e,!1);throw i}},dd.prototype.startChat=async function(e){if("uaid"in e&&e.uaid)return this.startConversation({uaid:e.uaid,senderUaid:e.senderUaid,historyTtlSeconds:e.historyTtlSeconds,auth:e.auth,encryption:e.encryption,onSessionCreated:e.onSessionCreated});if("agentUrl"in e&&e.agentUrl){const t=await this.createSession({agentUrl:e.agentUrl,auth:e.auth,historyTtlSeconds:e.historyTtlSeconds,senderUaid:e.senderUaid});return e.onSessionCreated?.(t.sessionId),this.createPlaintextConversationHandle(t.sessionId,t.encryption??null,e.auth,{agentUrl:e.agentUrl,uaid:e.uaid})}throw new Error("startChat requires either uaid or agentUrl")},dd.prototype.startConversation=async function(e){const t=e.encryption?.preference??"preferred";if(!("disabled"!==t)){const t=await this.createSession({uaid:e.uaid,auth:e.auth,historyTtlSeconds:e.historyTtlSeconds,senderUaid:e.senderUaid,encryptionRequested:!1});return e.onSessionCreated?.(t.sessionId),this.createPlaintextConversationHandle(t.sessionId,t.encryption??null,e.auth,{uaid:e.uaid})}try{const t=Bd(this);return await t.startSession({uaid:e.uaid,senderUaid:e.senderUaid,historyTtlSeconds:e.historyTtlSeconds,handshakeTimeoutMs:e.encryption?.handshakeTimeoutMs,pollIntervalMs:e.encryption?.pollIntervalMs,onSessionCreated:t=>{e.onSessionCreated?.(t)},auth:e.auth})}catch(r){if(r instanceof zd){if("required"===t)throw r;return this.createPlaintextConversationHandle(r.sessionId,r.summary??null,e.auth,{uaid:e.uaid})}throw r}},dd.prototype.acceptConversation=async function(e){const t=e.encryption?.preference??"preferred";if("disabled"===t)return this.createPlaintextConversationHandle(e.sessionId,null);try{const t=Bd(this);return await t.acceptSession({sessionId:e.sessionId,responderUaid:e.responderUaid,handshakeTimeoutMs:e.encryption?.handshakeTimeoutMs,pollIntervalMs:e.encryption?.pollIntervalMs})}catch(r){if(r instanceof zd&&"required"!==t)return this.createPlaintextConversationHandle(e.sessionId,null,void 0,{uaid:e.responderUaid});throw r}},dd.prototype.createPlaintextConversationHandle=function(e,t,r,i){const o=i?.uaid?.trim(),n=i?.agentUrl?.trim();return{sessionId:e,mode:"plaintext",summary:t??null,send:async t=>{const i=t.plaintext;if(!i||0===i.trim().length)throw new Error("plaintext is required for chat messages");const s=t.message??i;return this.sendMessage({sessionId:e,message:s,streaming:t.streaming,auth:t.auth??r,uaid:o,agentUrl:n})},decryptHistoryEntry:e=>e.content}},dd.prototype.compactHistory=async function(e){if(!e.sessionId||0===e.sessionId.trim().length)throw new Error("sessionId is required to compact chat history");const t={};"number"==typeof e.preserveEntries&&Number.isFinite(e.preserveEntries)&&e.preserveEntries>=0&&(t.preserveEntries=Math.floor(e.preserveEntries));const r=await this.requestJson(`/chat/session/${encodeURIComponent(e.sessionId)}/compact`,{method:"POST",headers:{"content-type":"application/json"},body:t});return this.parseWithSchema(r,Hc,"chat history compaction response")},dd.prototype.fetchEncryptionStatus=async function(e){if(!e||0===e.trim().length)throw new Error("sessionId is required for encryption status");const t=await this.requestJson(`/chat/session/${encodeURIComponent(e)}/encryption`,{method:"GET"});return this.parseWithSchema(t,qc,"session encryption status response")},dd.prototype.postEncryptionHandshake=async function(e,t){if(!e||0===e.trim().length)throw new Error("sessionId is required for encryption handshake");const r=await this.requestJson(`/chat/session/${encodeURIComponent(e)}/encryption-handshake`,{method:"POST",headers:{"content-type":"application/json"},body:{role:t.role,keyType:t.keyType,ephemeralPublicKey:t.ephemeralPublicKey,longTermPublicKey:t.longTermPublicKey,signature:t.signature,uaid:t.uaid,userId:t.userId,ledgerAccountId:t.ledgerAccountId,metadata:t.metadata}});return this.parseWithSchema(r,jc,"encryption handshake response").handshake},dd.prototype.sendMessage=async function(e){const t={message:e.message};void 0!==e.streaming&&(t.streaming=e.streaming),e.auth&&(t.auth=sd(e.auth)),"uaid"in e&&(t.uaid=e.uaid),"sessionId"in e&&e.sessionId&&(t.sessionId=e.sessionId),"agentUrl"in e&&e.agentUrl&&(t.agentUrl=e.agentUrl);let r=e.cipherEnvelope??null;if(e.encryption){const i=e.encryption.sessionId??("string"==typeof t.sessionId?t.sessionId:void 0);if(!i)throw new Error("sessionId is required when using encrypted chat payloads");if(!e.encryption.recipients?.length)throw new Error("recipients are required for encrypted chat payloads");r=this.encryption.encryptCipherEnvelope({...e.encryption,sessionId:i})}r&&(t.cipherEnvelope=nd(r));const i=await this.requestJson("/chat/message",{method:"POST",body:t,headers:{"content-type":"application/json"}});return this.parseWithSchema(i,Lc,"chat message response")},dd.prototype.endSession=async function(e){await this.request(`/chat/session/${encodeURIComponent(e)}`,{method:"DELETE"})};class Kd{constructor(e="info"){this.defaultEndpoint="https://kiloscribe.com/api/inscription-cdn",this.logger=O.getInstance({level:e,module:"HRLResolver"})}isBinaryContentType(e){return["image/","audio/","video/","application/octet-stream","application/pdf","application/zip","application/gzip","application/x-binary","application/vnd.ms-","application/x-msdownload","application/x-shockwave-flash","font/","application/wasm"].some(t=>e.startsWith(t))}parseHRL(e){if(!e)return null;const t=e.match(/^hcs:\/\/(\d+)\/([0-9]+\.[0-9]+\.[0-9]+)$/);return t?{standard:t[1],topicId:t[2]}:null}isValidHRL(e){if(!e||"string"!=typeof e)return!1;const t=this.parseHRL(e);if(!t)return!1;return!!/^[0-9]+\.[0-9]+\.[0-9]+$/.test(t.topicId)}isValidTopicId(e){return/^[0-9]+\.[0-9]+\.[0-9]+$/.test(e)}async resolve(e,t){if(this.isValidHRL(e))return this.resolveHRL(e,t);if(!this.isValidTopicId(e))throw new Error(`Invalid HRL or topic ID format: ${e}`);try{const r=new V(t.network,this.logger),i=await r.getTopicInfo(e),o=i?.memo||"";let n="1";if(o){const e=o.match(/^hcs-(\d+)/);e&&e[1]&&(n=e[1])}const s=`hcs://${n}/${e}`;return this.resolveHRL(s,t)}catch(r){this.logger.error(`Failed to get topic info for ${e}: ${r.message}`);const i=`hcs://1/${e}`;return this.resolveHRL(i,t)}}async getContentWithType(e,t){if(!this.isValidHRL(e))return{content:e,contentType:"text/plain",isBinary:!1};try{const r=await this.resolveHRL(e,t);return{content:r.content,contentType:r.contentType,isBinary:r.isBinary}}catch($g){const t=`Error resolving HRL for content and type: ${$g.message}`;throw this.logger.error(t),new Error(t)}}async resolveHRL(e,t){const r=this.parseHRL(e);if(!r)throw new Error(`Invalid HRL format: ${e}`);const{standard:i,topicId:n}=r;this.logger.debug(`Resolving HRL reference: standard=${i}, topicId=${n}`);try{const e=`${t.cdnEndpoint||this.defaultEndpoint}/${n}?network=${t.network}`;this.logger.debug(`Fetching content from CDN: ${e}`);const r=(await o.head(e)).headers["content-type"]||"";if(this.isBinaryContentType(r)||t.returnRaw){return{content:(await o.get(e,{responseType:"arraybuffer"})).data,contentType:r,topicId:n,isBinary:!0}}if("application/json"===r){const t=await o.get(e,{responseType:"json"});if(!t.data)throw new Error(`Failed to fetch content from topic: ${n}`);return{content:t.data,contentType:r,topicId:n,isBinary:!1}}const i=await o.get(e);if(!i.data)throw new Error(`Failed to fetch content from topic: ${n}`);let s;return s="object"==typeof i.data?i.data.content||i.data.text||JSON.stringify(i.data):i.data,{content:s,contentType:r,topicId:n,isBinary:!1}}catch($g){const t=`Error resolving HRL reference: ${$g.message}`;throw this.logger.error(t),new Error(t)}}}class Ud{constructor(e){this.nodeHash=e}update(e){return this.nodeHash.update(e),this}digest(e){return this.nodeHash.digest(e)}}class Ld{constructor(e){this.algorithm=e,this.data=[]}update(e){const t="string"==typeof e?(new TextEncoder).encode(e):new Uint8Array(e);return this.data.push(t),this}async digest(e){const t=this.concatenateArrays(this.data),r=new Uint8Array(t).buffer,i=await crypto.subtle.digest(this.mapAlgorithm(this.algorithm),r);return"hex"===e?Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,"0")).join(""):globalThis.Buffer.from(i)}concatenateArrays(e){const t=e.reduce((e,t)=>e+t.length,0),r=new Uint8Array(t);let i=0;for(const o of e)r.set(o,i),i+=o.length;return r}mapAlgorithm(e){return{sha256:"SHA-256",sha384:"SHA-384",sha1:"SHA-1",sha512:"SHA-512"}[e.toLowerCase()]||"SHA-256"}}class $d{constructor(e){this.algorithm=e,this.data=[]}update(e){const t="string"==typeof e?globalThis.Buffer.from(e):e;return this.data.push(t),this}digest(e){const t=globalThis.Buffer.concat(this.data),r=this.simpleHash(t);return"hex"===e?r.toString(16).padStart(8,"0"):r.toString()}simpleHash(e){let t=0;for(let r=0;r<e.length;r++)t=(t<<5)-t+e[r]&4294967295;return Math.abs(t)}}function Hd(){const e="undefined"==typeof window;let t,r=!1,i=!1;try{r="undefined"!=typeof require&&"undefined"!=typeof process&&!!process.versions?.node}catch{r=!1}try{i="undefined"!=typeof crypto&&void 0!==crypto.subtle&&!e}catch{i=!1}return t=r&&e?"node":i&&!e?"web":"none",{hasNodeCrypto:r,hasWebCrypto:i,isSSR:e,preferredAPI:t}}function qd(){return"undefined"==typeof window}class jd{constructor(e){this.nodeHmac=e}update(e){return this.nodeHmac.update(e),this}digest(e){return this.nodeHmac.digest(e)}}class Wd{constructor(e,t="sha256"){this.key=e,this.algorithm=t,this.data=[]}update(e){return this.data.push(e),this}async digest(e){const t=globalThis.Buffer.concat(this.data),r=new Uint8Array(this.key),i=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:this.mapAlgorithm(this.algorithm)},!1,["sign"]),o=await crypto.subtle.sign("HMAC",i,new Uint8Array(t));return"hex"===e?Array.from(new Uint8Array(o)).map(e=>e.toString(16).padStart(2,"0")).join(""):globalThis.Buffer.from(o)}mapAlgorithm(e){return{sha256:"SHA-256",sha1:"SHA-1",sha512:"SHA-512"}[e.toLowerCase()]||"SHA-256"}}class Vd{constructor(e,t="sha256"){this.key=e,this.algorithm=t,this.data=[]}update(e){return this.data.push(e),this}digest(e){const t=globalThis.Buffer.concat(this.data),r=this.simpleHmac(t,this.key);return"hex"===e?r.toString(16).padStart(8,"0"):r.toString()}simpleHmac(e,t){let r=0;for(let i=0;i<e.length;i++){const o=t[i%t.length];r=(r<<5)-r+e[i]+o&4294967295}return Math.abs(r)}}class Gd{constructor(){try{const e="crypto";this.crypto=require(e)}catch(e){throw new Error("Node.js crypto module not available")}}createHash(e){return new Ud(this.crypto.createHash(e))}createHmac(e,t){return new jd(this.crypto.createHmac(e,t))}async pbkdf2(e,t,r,i,o){return new Promise((n,s)=>{this.crypto.pbkdf2(e,t,r,i,o,(e,t)=>{e?s(e):n(t)})})}timingSafeEqual(e,t){return this.crypto.timingSafeEqual(e,t)}}class Jd{createHash(e){return new Ld(e)}createHmac(e,t){return new Wd(t,e)}async pbkdf2(e,t,r,i,o){const n=new TextEncoder,s=await crypto.subtle.importKey("raw",n.encode(e),{name:"PBKDF2"},!1,["deriveBits"]),a=await crypto.subtle.deriveBits({name:"PBKDF2",salt:new Uint8Array(t),iterations:r,hash:this.mapDigest(o)},s,8*i);return globalThis.Buffer.from(a)}timingSafeEqual(e,t){if(e.length!==t.length)return!1;let r=0;for(let i=0;i<e.length;i++)r|=e[i]^t[i];return 0===r}mapDigest(e){return{sha256:"SHA-256",sha1:"SHA-1",sha512:"SHA-512"}[e.toLowerCase()]||"SHA-256"}}class Yd{createHash(e){return new $d(e)}createHmac(e,t){return new Vd(t,e)}async pbkdf2(e,t,r,i,o){const n=new TextEncoder,s=globalThis.Buffer.from(n.encode(e));let a=globalThis.Buffer.alloc(i);for(let c=0;c<r;c++){const e=globalThis.Buffer.concat([s,t,globalThis.Buffer.from([c])]);let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e[t]&4294967295;a[c%i]^=255&r}return a}timingSafeEqual(e,t){if(e.length!==t.length)return!1;let r=0;for(let i=0;i<e.length;i++)r|=e[i]^t[i];return 0===r}}function Xd(){switch(Hd().preferredAPI){case"node":try{return new Gd}catch{return new Yd}case"web":return new Jd;default:return new Yd}}const Zd=["mainnet","testnet","previewnet","devnet"];function Qd(e){return Zd.includes(e)}const eu=/^hedera:(mainnet|testnet|previewnet|devnet):\d+\.\d+\.\d+(?:-[a-zA-Z0-9]{5})?$/;function tu(e){return eu.test(e)}function ru(e,t){if(!Qd(e))throw new Error("Invalid Hedera network");if(t.startsWith("hedera:")){if(tu(t))return t;throw new Error("Invalid Hedera CAIP-10 account")}if(!/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9]{5})?$/.test(t))throw new Error("Invalid Hedera accountId format");return`hedera:${e}:${t}`}function iu(e){if(!tu(e))throw new Error("Invalid Hedera CAIP-10");const[,t,r]=e.match(/^hedera:([^:]+):(.+)$/);return{network:t,accountId:r}}const ou=/^eip155:(\d+):(0x[0-9a-fA-F]{39,40})$/;function nu(e){return ou.test(e)}function su(e,t){const r=`eip155:${"number"==typeof e?String(e):e}:${t.startsWith("0x")?t:`0x${t}`}`;if(!nu(r))throw new Error("Invalid EIP-155 CAIP-10");return r}var au=(e=>(e[e.PERSONAL=0]="PERSONAL",e[e.AI_AGENT=1]="AI_AGENT",e[e.MCP_SERVER=2]="MCP_SERVER",e[e.FLORA=3]="FLORA",e))(au||{}),cu=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTONOMOUS=1]="AUTONOMOUS",e))(cu||{}),lu=(e=>(e[e.REST=0]="REST",e[e.WEBSOCKET=1]="WEBSOCKET",e[e.GRPC=2]="GRPC",e))(lu||{}),du=(e=>(e[e.TEXT_GENERATION=0]="TEXT_GENERATION",e[e.IMAGE_GENERATION=1]="IMAGE_GENERATION",e[e.AUDIO_GENERATION=2]="AUDIO_GENERATION",e[e.VIDEO_GENERATION=3]="VIDEO_GENERATION",e[e.CODE_GENERATION=4]="CODE_GENERATION",e[e.LANGUAGE_TRANSLATION=5]="LANGUAGE_TRANSLATION",e[e.SUMMARIZATION_EXTRACTION=6]="SUMMARIZATION_EXTRACTION",e[e.KNOWLEDGE_RETRIEVAL=7]="KNOWLEDGE_RETRIEVAL",e[e.DATA_INTEGRATION=8]="DATA_INTEGRATION",e[e.MARKET_INTELLIGENCE=9]="MARKET_INTELLIGENCE",e[e.TRANSACTION_ANALYTICS=10]="TRANSACTION_ANALYTICS",e[e.SMART_CONTRACT_AUDIT=11]="SMART_CONTRACT_AUDIT",e[e.GOVERNANCE_FACILITATION=12]="GOVERNANCE_FACILITATION",e[e.SECURITY_MONITORING=13]="SECURITY_MONITORING",e[e.COMPLIANCE_ANALYSIS=14]="COMPLIANCE_ANALYSIS",e[e.FRAUD_DETECTION=15]="FRAUD_DETECTION",e[e.MULTI_AGENT_COORDINATION=16]="MULTI_AGENT_COORDINATION",e[e.API_INTEGRATION=17]="API_INTEGRATION",e[e.WORKFLOW_AUTOMATION=18]="WORKFLOW_AUTOMATION",e))(du||{}),uu=(e=>(e[e.RESOURCE_PROVIDER=0]="RESOURCE_PROVIDER",e[e.TOOL_PROVIDER=1]="TOOL_PROVIDER",e[e.PROMPT_TEMPLATE_PROVIDER=2]="PROMPT_TEMPLATE_PROVIDER",e[e.LOCAL_FILE_ACCESS=3]="LOCAL_FILE_ACCESS",e[e.DATABASE_INTEGRATION=4]="DATABASE_INTEGRATION",e[e.API_INTEGRATION=5]="API_INTEGRATION",e[e.WEB_ACCESS=6]="WEB_ACCESS",e[e.KNOWLEDGE_BASE=7]="KNOWLEDGE_BASE",e[e.MEMORY_PERSISTENCE=8]="MEMORY_PERSISTENCE",e[e.CODE_ANALYSIS=9]="CODE_ANALYSIS",e[e.CONTENT_GENERATION=10]="CONTENT_GENERATION",e[e.COMMUNICATION=11]="COMMUNICATION",e[e.DOCUMENT_PROCESSING=12]="DOCUMENT_PROCESSING",e[e.CALENDAR_SCHEDULE=13]="CALENDAR_SCHEDULE",e[e.SEARCH=14]="SEARCH",e[e.ASSISTANT_ORCHESTRATION=15]="ASSISTANT_ORCHESTRATION",e))(uu||{}),pu=(e=>(e.DNS="dns",e.SIGNATURE="signature",e.CHALLENGE="challenge",e))(pu||{}),hu=(e=>(e.PUBLIC="PUBLIC",e.CONTROLLED="CONTROLLED",e.FEE_BASED="FEE_BASED",e))(hu||{});const gu={text_generation:0,image_generation:1,audio_generation:2,video_generation:3,code_generation:4,language_translation:5,summarization:6,extraction:6,knowledge_retrieval:7,data_integration:8,data_visualization:8,market_intelligence:9,transaction_analytics:10,smart_contract_audit:11,governance:12,security_monitoring:13,compliance_analysis:14,fraud_detection:15,multi_agent:16,api_integration:17,workflow_automation:18},mu=r.z.object({platform:r.z.string().min(1),handle:r.z.string().min(1)}),fu=r.z.object({type:r.z.nativeEnum(cu),capabilities:r.z.array(r.z.nativeEnum(du)).min(1),model:r.z.string().min(1),creator:r.z.string().optional()}),yu=r.z.object({url:r.z.string().min(1),transport:r.z.enum(["stdio","sse"])}),bu=r.z.object({type:r.z.nativeEnum(pu),value:r.z.string(),dns_field:r.z.string().optional(),challenge_path:r.z.string().optional()}),wu=r.z.object({minVersion:r.z.string().optional()}),Iu=r.z.object({name:r.z.string().min(1),description:r.z.string().min(1)}),Tu=r.z.object({name:r.z.string().min(1),description:r.z.string().min(1)}),Su=r.z.object({version:r.z.string().min(1),connectionInfo:yu,services:r.z.array(r.z.nativeEnum(uu)).min(1),description:r.z.string().min(1),verification:bu.optional(),host:wu.optional(),capabilities:r.z.array(r.z.string()).optional(),resources:r.z.array(Iu).optional(),tools:r.z.array(Tu).optional(),maintainer:r.z.string().optional(),repository:r.z.string().optional(),docs:r.z.string().optional()}),ku=r.z.object({version:r.z.string().min(1),type:r.z.nativeEnum(au),display_name:r.z.string().min(1),alias:r.z.string().optional(),bio:r.z.string().optional(),socials:r.z.array(mu).optional(),profileImage:r.z.string().optional(),uaid:r.z.string().optional(),properties:r.z.record(r.z.any()).optional(),inboundTopicId:r.z.string().optional(),outboundTopicId:r.z.string().optional(),base_account:r.z.string().optional()}),Eu=ku.extend({type:r.z.literal(au.PERSONAL),language:r.z.string().optional(),timezone:r.z.string().optional()}),vu=ku.extend({type:r.z.literal(au.AI_AGENT),aiAgent:fu}),Au=ku.extend({type:r.z.literal(au.MCP_SERVER),mcpServer:Su}),Cu=r.z.object({version:r.z.string(),type:r.z.literal(au.FLORA),display_name:r.z.string().min(1),members:r.z.array(r.z.object({accountId:r.z.string(),publicKey:r.z.string().optional(),weight:r.z.number().optional()})),threshold:r.z.number().min(1),topics:r.z.object({communication:r.z.string(),transaction:r.z.string(),state:r.z.string()}),inboundTopicId:r.z.string(),outboundTopicId:r.z.string(),bio:r.z.string().optional(),metadata:r.z.record(r.z.any()).optional(),policies:r.z.record(r.z.any()).optional()}),xu=r.z.union([Eu,vu,Au,Cu]);class Ru{constructor(e){this.client="mainnet"===e.network?i.Client.forMainnet():i.Client.forTestnet(),this.auth=e.auth,this.network=e.network,this.operatorId=e.auth.operatorId,this.logger=O.getInstance({level:e.logLevel||"info",module:"HCS-11",silent:e.silent}),this.mirrorNode=new V(this.network,this.logger),this.auth.privateKey?(this.operatorCtx=ie({network:this.network,operatorId:this.operatorId,operatorKey:this.auth.privateKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:this.client}),this.client=this.operatorCtx.client,this.keyType=this.operatorCtx.keyType,this.operatorCtx.ensureInitialized(),this.client.setOperator(this.operatorId.toString(),this.operatorCtx.operatorKey)):this.keyType=e.keyType||"ed25519"}getClient(){return this.client}getOperatorId(){return this.auth.operatorId}async initializeOperator(){if(this.operatorCtx)try{await this.operatorCtx.ensureInitialized(),this.keyType=this.operatorCtx.keyType,this.client.setOperator(this.operatorId,this.operatorCtx.operatorKey)}catch(e){this.logger.warn(`Failed to verify operator key with mirror node: ${e.message}`)}}createPersonalProfile(e,t){return{version:"1.0",type:au.PERSONAL,display_name:e,alias:t?.alias,bio:t?.bio,socials:t?.socials,profileImage:t?.profileImage,properties:t?.properties,inboundTopicId:t?.inboundTopicId,outboundTopicId:t?.outboundTopicId,base_account:t?.baseAccount}}createAIAgentProfile(e,t,r,i,o){const n=this.validateProfile({version:"1.0",type:au.AI_AGENT,display_name:e,alias:o?.alias,bio:o?.bio,socials:o?.socials,profileImage:o?.profileImage,properties:o?.properties,inboundTopicId:o?.inboundTopicId,outboundTopicId:o?.outboundTopicId,base_account:o?.baseAccount,aiAgent:{type:t,capabilities:r,model:i,creator:o?.creator}});if(!n.valid)throw new Error(`Invalid AI Agent Profile: ${n.errors.join(", ")}`);return{version:"1.0",type:au.AI_AGENT,display_name:e,alias:o?.alias,bio:o?.bio,socials:o?.socials,profileImage:o?.profileImage,properties:o?.properties,inboundTopicId:o?.inboundTopicId,outboundTopicId:o?.outboundTopicId,base_account:o?.baseAccount,aiAgent:{type:t,capabilities:r,model:i,creator:o?.creator}}}createMCPServerProfile(e,t,r){const i=this.validateProfile({version:"1.0",type:au.MCP_SERVER,display_name:e,alias:r?.alias,bio:r?.bio,socials:r?.socials,profileImage:r?.profileImage,properties:r?.properties,inboundTopicId:r?.inboundTopicId,outboundTopicId:r?.outboundTopicId,mcpServer:t});if(!i.valid)throw new Error(`Invalid MCP Server Profile: ${i.errors.join(", ")}`);return{version:"1.0",type:au.MCP_SERVER,display_name:e,alias:r?.alias,bio:r?.bio,socials:r?.socials,profileImage:r?.profileImage,properties:r?.properties,inboundTopicId:r?.inboundTopicId,outboundTopicId:r?.outboundTopicId,mcpServer:t}}validateProfile(e){const t=xu.safeParse(e);if(t.success)return{valid:!0,errors:[]};return{valid:!1,errors:t.error.errors.map(e=>{const t=e.path.join(".");let r=e.message;if("invalid_type"===e.code)r=`Expected ${e.expected}, got ${e.received}`;else if("invalid_enum_value"===e.code){const t=e.options?.join(", ");r=`Invalid value. Valid options are: ${t}`}else"too_small"===e.code&&"string"===e.type&&(r="Cannot be empty");return`${t}: ${r}`})}}profileToJSONString(e){return JSON.stringify(e)}parseProfileFromString(e){try{const t=JSON.parse(e),r=this.validateProfile(t);return r.valid?t:(this.logger.error("Invalid profile format:",r.errors),null)}catch(t){return this.logger.error("Error parsing profile:"),null}}setProfileForAccountMemo(e,t=1){return`hcs-11:hcs://${t}/${e}`}async executeTransaction(e){try{if(this.auth.privateKey){const t=await e.signWithOperator(this.client),r=await t.execute(this.client),o=await r.getReceipt(this.client);return o.status.toString()!==i.Status.Success.toString()?{success:!1,error:`Transaction failed: ${o.status.toString()}`}:{success:!0,result:o}}if(!this.auth.signer)throw new Error("No valid authentication method provided");const t=this.auth.signer,r=await e.freezeWithSigner(t),o=await r.executeWithSigner(t),n=await o.getReceiptWithSigner(t);return n.status.toString()!==i.Status.Success.toString()?{success:!1,error:`Transaction failed: ${n.status.toString()}: ${i.Status.Success.toString()}`}:{success:!0,result:n}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Unknown error during transaction execution"}}}async inscribeImage(e,t,r){try{const o=r?.progressCallback,n=new us({module:"HCS11-Image",logger:this.logger,callback:o});n.preparing("Preparing to inscribe image",0);const s=S.lookup(t)||"application/octet-stream",a=r?.waitForConfirmation??!0;let c;if(this.auth.signer){if(!("accountId"in this.auth.signer))throw n.failed("Signer must be a DAppSigner for inscription"),new Error("Signer must be a DAppSigner for inscription");n.preparing("Using signer for inscription",10),c=await Da({type:"buffer",buffer:e,fileName:t,mimeType:s},this.auth.signer,{network:this.network,waitForConfirmation:a,waitMaxAttempts:150,waitIntervalMs:4e3,logging:{level:"debug"},progressCallback:e=>{const t=10+.8*(e.progressPercent||0);n.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}})}else{if(!this.auth.privateKey)throw n.failed("Private key is required for inscription"),this.logger.error("Private key is required for inscription"),new Error("Private key is required for inscription");n.preparing("Using private key for inscription",10);const r="ecdsa"===this.keyType?i.PrivateKey.fromStringECDSA(this.auth.privateKey):i.PrivateKey.fromStringED25519(this.auth.privateKey);c=await za({type:"buffer",buffer:e,fileName:t,mimeType:s},{accountId:this.auth.operatorId,privateKey:r,network:this.network},{waitForConfirmation:a,waitMaxAttempts:150,waitIntervalMs:2e3,logging:{level:"debug"},progressCallback:e=>{const t=10+.8*(e.progressPercent||0);n.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}})}if(c.confirmed)return n.completed("Image inscription completed",{topicId:La(c.inscription)}),{imageTopicId:La(c.inscription)||"",transactionId:c.result.jobId,success:!0};{const e=c.quote?"quote-only":c.result.jobId;return n.verifying("Waiting for inscription confirmation",50,{jobId:e}),{imageTopicId:"",transactionId:e,success:!1,error:"Inscription not confirmed"}}}catch(o){return this.logger.error("Error inscribing image:",o),{imageTopicId:"",transactionId:"",success:!1,error:o instanceof Error?o.message:"Error inscribing image"}}}async inscribeProfile(e,t){this.logger.info("Inscribing HCS-11 profile");const r=t?.progressCallback,o=new us({module:"HCS11-Profile",logger:this.logger,callback:r});await this.attachUaidIfMissing(e),o.preparing("Validating profile data",5);const n=this.validateProfile(e);if(!n.valid)return o.failed(`Invalid profile: ${n.errors.join(", ")}`),{profileTopicId:"",transactionId:"",success:!1,error:`Invalid profile: ${n.errors.join(", ")}`};o.preparing("Formatting profile for inscription",15);const s=this.profileToJSONString(e),a=`profile-${e.display_name.toLowerCase().replace(/\s+/g,"-")}.json`;try{const e=globalThis.Buffer.from(s,"utf-8"),t="application/json";o.preparing("Preparing profile for inscription",20);const r={type:"buffer",buffer:e,fileName:a,mimeType:t},n={waitForConfirmation:!0,mode:"file",network:this.network,waitMaxAttempts:100,waitIntervalMs:2e3,progressCallback:e=>{const t=20+.75*Number(e?.progressPercent||0);o?.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}};let c;if(o.submitting("Submitting profile to Hedera network",30),this.auth.privateKey){const e="ecdsa"===this.keyType?i.PrivateKey.fromStringECDSA(this.auth.privateKey):i.PrivateKey.fromStringED25519(this.auth.privateKey);c=await za(r,{accountId:this.auth.operatorId,privateKey:e,network:this.network},n)}else{if(!this.auth.signer)throw new Error("No authentication method available - neither private key nor signer");c=await Da(r,this.auth.signer,n)}if(!c.confirmed||!La(c.inscription))return o.failed("Failed to inscribe profile content"),{profileTopicId:"",transactionId:"",success:!1,error:"Failed to inscribe profile content"};const l=La(c.inscription);return o.completed("Profile inscription completed",{topicId:l,transactionId:c.result.transactionId}),{profileTopicId:l,transactionId:c.result.transactionId,success:!0,totalCostHbar:c.costSummary?.totalCostHbar}}catch(c){return o.failed(`Error inscribing profile: ${c.message||"Unknown error"}`),{profileTopicId:"",transactionId:"",success:!1,error:c.message||"Unknown error during inscription"}}}async attachUaidIfMissing(e){if(!e.uaid&&Qd(this.network))try{const{HCS14Client:t}=await Promise.resolve().then(()=>eh),r=new t({client:this.client}),i=await r.createDid({method:"hedera",client:this.client}),o=ru(this.network,this.auth.operatorId);let n=this.auth.operatorId;const s=e.inboundTopicId;if(s&&s.trim().length>0)n=`${s}@${this.auth.operatorId}`;else try{const e=await this.fetchProfileByAccountId(this.auth.operatorId,this.network),t=e?.topicInfo?.inboundTopic;t&&t.trim().length>0&&(n=`${t}@${this.auth.operatorId}`)}catch{}const a=r.createUaid(i,{proto:"hcs-10",nativeId:o,uid:n});e.uaid=a}catch($g){this.logger.warn("Hiero registrar not available; skipping UAID generation for profile",$g)}}async updateAccountMemoWithProfile(e,t){try{this.logger.info(`Updating account memo for ${e} with profile ${t}`);const r=this.setProfileForAccountMemo(t),o=(new i.AccountUpdateTransaction).setAccountMemo(r).setAccountId(e);return this.executeTransaction(o)}catch(r){return this.logger.error(`Error updating account memo: ${r instanceof Error?r.message:"Unknown error"}`),{success:!1,error:r instanceof Error?r.message:"Unknown error updating account memo"}}}async createAndInscribeProfile(e,t=!0,r){const i=r?.progressCallback,o=new us({module:"HCS11-ProfileCreation",logger:this.logger,callback:i});o.preparing("Starting profile creation process",0);const n=o.createSubProgress({minPercent:0,maxPercent:80,logPrefix:"Inscription"}),s=await this.inscribeProfile(e,{...r,progressCallback:e=>{n.report({stage:e.stage,message:e.message,progressPercent:e.progressPercent,details:e.details})}});if(!s?.success)return o.failed("Profile inscription failed",{error:s?.error}),s;if(o.confirming("Profile inscribed, updating account memo",85),t){const e=await this.updateAccountMemoWithProfile(this.auth.operatorId,s.profileTopicId);if(!e.success)return o.failed("Failed to update account memo",{error:e?.error}),{...s,success:!1,error:e?.error}}return o.completed("Profile creation completed successfully",{profileTopicId:s.profileTopicId,transactionId:s.transactionId,totalCostHbar:s.totalCostHbar}),s}async getCapabilitiesFromTags(e){const t=[];if(0===e.length)return[du.TEXT_GENERATION];for(const r of e){const e=gu[r.toLowerCase()];void 0===e||t.includes(e)||t.push(e)}return 0===t.length&&t.push(du.TEXT_GENERATION),t}getAgentTypeFromMetadata(e){return"autonomous"===e.type?cu.AUTONOMOUS:cu.MANUAL}async fetchProfileByAccountId(e,t){try{this.logger.debug(`Fetching profile for account ${e.toString()} on ${this.network}`);const i=await this.mirrorNode.getAccountMemo(e.toString());if(this.logger.debug(`Got account memo: ${i}`),!i?.startsWith("hcs-11:"))return{success:!1,error:`Account ${e.toString()} does not have a valid HCS-11 memo. Current memo: ${i||"empty"}`};this.logger.debug(`Found HCS-11 memo: ${i}`);const o=i.substring(7);if(!o?.startsWith("hcs://")){if(o.startsWith("ipfs://")){this.logger.warn("IPFS protocol references are not fully supported");const e=await fetch(`https://ipfs.io/ipfs/${o.replace("ipfs://","")}`),t=await e.json(),r=xu.safeParse(t);return r.success?{success:!0,profile:r.data,topicInfo:{inboundTopic:r.data.inboundTopicId||"",outboundTopic:r.data.outboundTopicId||"",profileTopicId:""}}:{success:!1,error:`Invalid HCS-11 profile data from IPFS reference ${o}`}}if(o.startsWith("ar://")){const e=o.replace("ar://",""),t=await fetch(`https://arweave.net/${e}`);if(!t.ok)return{success:!1,error:`Failed to fetch profile from Arweave ${e}: ${t.statusText}`};const r=await t.json(),i=xu.safeParse(r);return i.success?{success:!0,profile:i.data,topicInfo:{inboundTopic:i.data.inboundTopicId||"",outboundTopic:i.data.outboundTopicId||"",profileTopicId:""}}:{success:!1,error:`Invalid HCS-11 profile data from Arweave reference ${e}`}}return{success:!1,error:`Invalid protocol reference format: ${o}`}}{const e=o.match(/hcs:\/\/(\d+)\/(.+)/);if(!e)return{success:!1,error:`Invalid HCS protocol reference format: ${o}`};const[i,n,s]=e,a=t||this.network||"mainnet";this.logger.debug(`Retrieving profile from Kiloscribe CDN: ${s}`);const c=`https://kiloscribe.com/api/inscription-cdn/${s}?network=${a}`;try{const e=await fetch(c);if(!e.ok)return{success:!1,error:`Failed to fetch profile from Kiloscribe CDN: ${e.statusText}`};const t=await e.json();if(!t)return{success:!1,error:`No profile data found for topic ${s}`};const r=xu.safeParse(t);return r.success?{success:!0,profile:r.data,topicInfo:{inboundTopic:r.data.inboundTopicId||"",outboundTopic:r.data.outboundTopicId||"",profileTopicId:s}}:{success:!1,error:`Invalid HCS-11 profile data for topic ${s}`}}catch(r){return this.logger.error(`Error retrieving from Kiloscribe CDN: ${r.message}`),{success:!1,error:`Error retrieving from Kiloscribe CDN: ${r.message}`}}}}catch(i){return this.logger.error(`Error fetching profile: ${i.message}`),{success:!1,error:`Error fetching profile: ${i.message}`}}}}class Nu{async checkRegistrationStatus(e,t,r,i){try{const o=await fetch(`${r}/api/request-confirm`,{method:"POST",headers:{"Content-Type":"application/json","X-Network":t},body:JSON.stringify({transaction_id:e})});if(!o.ok){const e=`Failed to confirm registration: ${o.statusText}`;throw i&&i.error(e),new Error(e)}return await o.json()}catch(o){throw i&&i.error(`Error checking registration status: ${o.message}`),o}}async waitForRegistrationConfirmation(e,t,r,i=60,o=2e3,n){let s=0;for(;s<i;){n&&n.info(`Checking registration status. Attempt ${s+1}/${i}`);const a=await this.checkRegistrationStatus(e,t,r,n);if("success"===a.status)return n&&n.info("Registration confirmed successfully"),!0;if("failed"===a.status)throw n&&n.error("Registration confirmation failed"),new Error("Registration confirmation failed");n&&n.info(`Registration still pending. Waiting ${o}ms before next attempt`),await new Promise(e=>setTimeout(e,o)),s++}return n&&n.warn(`Registration not confirmed after ${i} attempts`),!1}async executeRegistration(e,t="mainnet",r="https://moonscape.tech",i){try{i&&i.info("Registering agent with guarded registry");try{const r=new Ru({network:t,auth:{operatorId:"0.0.0"}});i?.info(`Fetching profile by account ID ${e} on ${t}`),await D(5e3);const o=await r.fetchProfileByAccountId(e,t);if(i?.info("Profile fetched",o),o?.error)return i?.error("Error fetching profile",o.error),{error:o.error,success:!1};if(!o?.success||!o?.profile)return i&&i.error("Profile not found for agent registration"),{error:"Profile not found for the provided account ID",success:!1};if(!o.profile.inboundTopicId)return i&&i.error("Missing inbound topic ID in profile"),{error:"Profile is missing required inbound topic ID",success:!1};if(!o.profile.outboundTopicId)return i&&i.error("Missing outbound topic ID in profile"),{error:"Profile is missing required outbound topic ID",success:!1};i&&i.info(`Profile validation successful. Inbound topic: ${o.profile.inboundTopicId}, Outbound topic: ${o.profile.outboundTopicId}`)}catch(o){return i&&i.error(`Error validating profile: ${o.message}`),{error:`Error validating profile: ${o.message}`,success:!1}}const n=await fetch(`${r}/api/request-register`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"*/*","Accept-Language":"en;q=0.5",Origin:r,Referer:`${r}/`,"X-Network":t},body:JSON.stringify({accountId:e})}),s=await n.json();return n.ok?(i&&i.info(`Created new registration request. Transaction ID: ${s.transaction_id}`),{transactionId:s.transaction_id,transaction:s.transaction,success:!0}):s.details?.length>0?{validationErrors:s.details,error:s.error||"Validation failed",success:!1}:{error:s.error||"Failed to register agent",success:!1}}catch(n){return{error:`Error during registration request: ${n.message}`,success:!1}}}async findRegistrations(e={},t="https://moonscape.tech"){try{const r=new URLSearchParams;e.tags?.forEach(e=>r.append("tags",e.toString())),e.accountId&&r.append("accountId",e.accountId),e.network&&r.append("network",e.network);const i=await fetch(`${t}/api/registrations?${r}`,{headers:{Accept:"*/*","Accept-Language":"en;q=0.5",Origin:t,Referer:`${t}/`}});if(!i.ok){return{registrations:[],error:await i.text()||"Failed to fetch registrations",success:!1}}const o=await i.json();return o.error?{registrations:[],error:o.error,success:!1}:{registrations:o.registrations||[],success:!0}}catch($g){return{registrations:[],error:`Error fetching registrations: ${$g.message}`,success:!1}}}}function _u(e,t){return`hcs-10:op:${e}:${t}`}function Pu(e){var t,r;return J({memo:e.memoOverride??(t=e.ttl,r=e.accountId,`hcs-10:0:${t}:0:${r}`),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function Fu(e){return J({memo:e.memoOverride??`hcs-10:0:${e.ttl}:1`,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function zu(e){var t,r,i;return J({memo:e.memoOverride??(t=e.ttl,r=e.inboundTopicId,i=e.connectionId,`hcs-10:1:${t}:2:${r}:${i}`),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function Ou(e){var t,r;return J({memo:e.memoOverride??(t=e.ttl,(r=e.metadataTopicId)?`hcs-10:0:${t}:3:${r}`:`hcs-10:0:${t}:3`),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function Du(e){const t={p:"hcs-10",op:"connection_request",operator_id:e.operatorId,m:e.memo};return Y({topicId:e.inboundTopicId,message:JSON.stringify(t),transactionMemo:_u(3,1)})}function Mu(e){const t={p:"hcs-10",op:"connection_created",connection_topic_id:e.connectionTopicId,connected_account_id:e.connectedAccountId,operator_id:e.operatorId,connection_id:e.connectionId,m:e.memo};return Y({topicId:e.inboundTopicId,message:JSON.stringify(t),transactionMemo:_u(4,1)})}function Bu(e){const t={p:"hcs-10",op:"connection_request",operator_id:e.operatorId,outbound_topic_id:e.outboundTopicId,connection_request_id:e.connectionRequestId,m:e.memo};return Y({topicId:e.outboundTopicId,message:JSON.stringify(t),transactionMemo:_u(3,2)})}function Ku(e){const t={p:"hcs-10",op:"connection_created",connection_topic_id:e.connectionTopicId,outbound_topic_id:e.outboundTopicId,requestor_outbound_topic_id:e.requestorOutboundTopicId,confirmed_request_id:e.confirmedRequestId,connection_request_id:e.connectionRequestId,operator_id:e.operatorId,m:e.memo};return Y({topicId:e.outboundTopicId,message:JSON.stringify(t),transactionMemo:_u(4,2)})}function Uu(e){const t={p:"hcs-10",op:"message",operator_id:e.operatorId,data:e.data,m:e.memo};return Y({topicId:e.connectionTopicId,message:JSON.stringify(t),transactionMemo:_u(6,3)})}function Lu(e){const t={p:"hcs-10",op:"register",account_id:e.accountId,...e.inboundTopicId?{inbound_topic_id:e.inboundTopicId}:{},m:e.memo};return Y({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:_u(0,0)})}var $u=(e=>(e.INBOUND="inbound",e.OUTBOUND="outbound",e.CONNECTION="connection",e.REGISTRY="registry",e))($u||{});class Hu extends Nu{constructor(e){super(),this.network=e.network,this.logger=O.getInstance({level:e.logLevel||"info",module:"HCS10-BaseClient",prettyPrint:e.prettyPrint,silent:e.silent}),this.mirrorNode=new V(e.network,this.logger,e.mirrorNode),this.feeAmount=e.feeAmount||.001}configureMirrorNode(e){this.mirrorNode.configureMirrorNode(e),this.logger.info("Mirror node configuration updated")}extractTopicFromOperatorId(e){if(!e)return"";const t=e.split("@");return t.length>0?t[0]:""}extractAccountFromOperatorId(e){if(!e)return"";const t=e.split("@");return t.length>1?t[1]:""}async getMessageStream(e,t){try{const r=await this.mirrorNode.getTopicMessages(e,t),i=["message","close_connection","transaction"];return{messages:r.filter(e=>{if("hcs-10"!==e.p||!i.includes(e.op))return!1;if("message"===e.op||"close_connection"===e.op){if(!e.operator_id)return!1;if(!this.isValidOperatorId(e.operator_id))return!1;if("message"===e.op&&!e.data)return!1}if("transaction"===e.op){if(!e.operator_id||!e.schedule_id)return!1;if(!this.isValidOperatorId(e.operator_id))return!1}return!0})}}catch(r){return this.logger&&this.logger.error(`Error fetching messages: ${r.message}`),{messages:[]}}}async getPublicTopicInfo(e){try{return await this.mirrorNode.getTopicInfo(e)}catch(t){return this.logger.error(`Error getting public topic info for ${e}:`,t),null}}async canSubmitToTopic(e,t){try{const o=await this.mirrorNode.getTopicInfo(e);if(!o)return{canSubmit:!1,requiresFee:!1,reason:"Topic does not exist"};if(!o.submit_key?.key)return{canSubmit:!0,requiresFee:!1};try{const e=await this.mirrorNode.getPublicKey(t);if("ProtobufEncoded"===o.submit_key._type){const t=globalThis.Buffer.from(o.submit_key.key,"hex");if(await this.mirrorNode.checkKeyListAccess(t,e))return{canSubmit:!0,requiresFee:!1}}else{const t=i.PublicKey.fromString(o.submit_key.key);if(e.toString()===t.toString())return{canSubmit:!0,requiresFee:!1}}}catch(r){this.logger.error(`Key validation error: ${r instanceof Error?r.message:String(r)}`)}return o.fee_schedule_key?.key&&o.custom_fees?.fixed_fees?.length>0?{canSubmit:!0,requiresFee:!0,reason:"Requires fee payment via HIP-991"}:{canSubmit:!1,requiresFee:!1,reason:"User does not have submit permission for this topic"}}catch(r){const e=r instanceof Error?r.message:String(r);return this.logger.error(`Topic submission validation error: ${e}`),{canSubmit:!1,requiresFee:!1,reason:`Error: ${e}`}}}async getMessages(e,t){try{const r=await this.mirrorNode.getTopicMessages(e,t);return{messages:r.filter(e=>{if("hcs-10"!==e.p)return!1;if("message"===e.op){if(!e.data)return!1;if(e.operator_id&&!this.isValidOperatorId(e.operator_id))return!1}return!0})}}catch(r){return this.logger&&this.logger.error(`Error fetching messages: ${r.message}`),{messages:[]}}}async requestAccount(e){try{if(!e)throw new Error("Account ID is required");return await this.mirrorNode.requestAccount(e)}catch($g){throw this.logger.error("Failed to fetch account",$g),$g}}async getAccountMemo(e){return await this.mirrorNode.getAccountMemo(e)}async retrieveProfile(e,t,r){const i=r?.maxRetries??0,o=r?.retryDelay??3e3;let n=0;for(;n<=i;){this.logger.debug(`Retrieving profile for account: ${e}${n>0?` (attempt ${n+1}/${i+1})`:""}`);const r=`${e}-${this.network}`;if(!t&&0===n){const t=qu.getInstance().get(r);if(t)return this.logger.debug(`Cache hit for profile: ${e}`),t}try{const t=new Ru({network:this.network,auth:{operatorId:"0.0.0"},logLevel:this.logger.getLevel()}),s=await t.fetchProfileByAccountId(e,this.network);if(!s?.success){if(n<i){this.logger.info(`Profile not found for account ${e}, retrying in ${o}ms... (${s?.error})`),n++,await new Promise(e=>setTimeout(e,o));continue}return this.logger.error(`Failed to retrieve profile for account ID: ${e}`,s?.error),{profile:null,success:!1,error:s?.error||`Failed to retrieve profile for account ID: ${e}`}}const a=s?.profile;let c=null;s?.topicInfo?.inboundTopic&&s?.topicInfo?.outboundTopic&&s?.topicInfo?.profileTopicId&&(c={inboundTopic:s.topicInfo.inboundTopic,outboundTopic:s.topicInfo.outboundTopic,profileTopicId:s.topicInfo.profileTopicId});const l={profile:a,topicInfo:c,success:!0};return qu.getInstance().set(r,l),l}catch($g){if(n<i){this.logger.info(`Error retrieving profile for account ${e}, retrying in ${o}ms... (${$g.message})`),n++,await new Promise(e=>setTimeout(e,o));continue}const r=`Failed to retrieve profile: ${$g.message}`;return this.logger.error(r),{profile:null,success:!1,error:r}}}return{profile:null,success:!1,error:"Unexpected error in profile retrieval"}}async retrieveOutboundConnectTopic(e){return await this.retrieveCommunicationTopics(e,!0)}async retrieveCommunicationTopics(e,t,r){try{const i=await this.retrieveProfile(e,t,r);if(!i?.success)throw new Error(i.error||"Failed to retrieve profile");const o=i.profile;if(!o)throw new Error(`Profile is null or undefined for account ${e}`);if(!o.inboundTopicId||!o.outboundTopicId)throw new Error("Invalid HCS-11 profile for HCS-10 agent: missing inboundTopicId or outboundTopicId");if(!i.topicInfo)throw new Error(`TopicInfo is missing in the profile for account ${e}`);return i.topicInfo}catch($g){const t=$g,r=`Failed to retrieve topic info: ${t.message}`;throw this.logger.error(r),t}}async retrieveOutboundMessages(e,t){try{const r=await this.retrieveCommunicationTopics(e);if(!r)return this.logger.warn(`No outbound connect topic found for agentAccountId: ${e}`),[];return(await this.getMessages(r.outboundTopic,t)).messages.filter(e=>"hcs-10"===e.p&&("connection_request"===e.op||"connection_created"===e.op||"message"===e.op))}catch($g){const t=`Failed to retrieve outbound messages: ${$g.message}`;return this.logger.error(t),[]}}async hasConnectionCreated(e,t){try{const r=await this.retrieveCommunicationTopics(e);return(await this.retrieveOutboundMessages(r.outboundTopic)).some(e=>"connection_created"===e.op&&e.connection_id===t)}catch($g){const t=`Failed to check connection created: ${$g.message}`;return this.logger.error(t),!1}}async getMessageContent(e,t=!1){if(!e.match(/^hcs:\/\/(\d+)\/([0-9]+\.[0-9]+\.[0-9]+)$/))return e;try{const r=new Kd(this.logger.getLevel());if(!r.isValidHRL(e))return e;return(await r.resolveHRL(e,{network:this.network,returnRaw:t})).content}catch($g){const t=`Error resolving HRL reference: ${$g.message}`;throw this.logger.error(t),new Error(t)}}async getMessageContentWithType(e,t=!1){if(!e.match(/^hcs:\/\/(\d+)\/([0-9]+\.[0-9]+\.[0-9]+)$/))return{content:e,contentType:"text/plain",isBinary:!1};try{const r=new Kd(this.logger.getLevel());return await r.getContentWithType(e,{network:this.network,returnRaw:t})}catch($g){const t=`Error resolving HRL reference with type: ${$g.message}`;throw this.logger.error(t),new Error(t)}}async submitConnectionRequest(e,t){const r=this.getAccountAndSigner();if(!r?.accountId)throw new Error("Operator account ID is not set");const i=await this.getOperatorId(),o=r.accountId,n=await this.canSubmitToTopic(e,o);if(!n?.canSubmit)throw new Error(`Cannot submit to topic: ${n.reason}`);const s=await this.retrieveInboundAccountId(e);if(!s)throw new Error("Failed to retrieve topic info account ID");const a=n.requiresFee,c=Du({inboundTopicId:e,operatorId:i,memo:t}),l=await this.submitPayload(c,void 0,void 0,a);this.logger.info(`Submitted connection request to topic ID: ${e}`);const d=await this.retrieveCommunicationTopics(o);if(!d)throw new Error("Failed to retrieve outbound topic");const u=l.topicSequenceNumber?.toNumber();if(!u)throw new Error("Failed to get response sequence number");const p=`${e}@${s}`,h=Bu({outboundTopicId:d.outboundTopic,operatorId:p,connectionRequestId:u,memo:t});return await this.submitPayload(h),l}async recordOutboundConnectionConfirmation({outboundTopicId:e,requestorOutboundTopicId:t,connectionRequestId:r,confirmedRequestId:i,connectionTopicId:o,operatorId:n,memo:s}){const a=Ku({outboundTopicId:e,requestorOutboundTopicId:t,connectionTopicId:o,confirmedRequestId:i,connectionRequestId:r,operatorId:n,memo:s});return await this.submitPayload(a)}async waitForConnectionConfirmation(e,t,r=60,i=2e3,o=!0){this.logger.info(`Waiting for connection confirmation on inbound topic ${e} for request ID ${t}`);for(let n=0;n<r;n++){this.logger.info(`Attempt ${n+1}/${r} to find connection confirmation`);const s=(await this.mirrorNode.getTopicMessages(e,{order:"desc",limit:100})).filter(e=>"connection_created"===e.op);if(this.logger.info(`Found ${s.length} connection_created messages`),s.length>0)for(const e of s)if(Number(e.connection_id)===Number(t)){const r={connectionTopicId:e.connection_topic_id,sequence_number:Number(e.sequence_number),confirmedBy:e.operator_id,memo:e.m},i=this.extractAccountFromOperatorId(r.confirmedBy),n=this.getAccountAndSigner(),s=await this.retrieveCommunicationTopics(i),a=await this.retrieveCommunicationTopics(n.accountId);return this.logger.info("Connection confirmation found",r),o&&await this.recordOutboundConnectionConfirmation({requestorOutboundTopicId:s.outboundTopic,outboundTopicId:a.outboundTopic,connectionRequestId:t,confirmedRequestId:r.sequence_number,connectionTopicId:r.connectionTopicId,operatorId:r.confirmedBy,memo:r.memo||"Connection confirmed"}),r}n<r-1&&(this.logger.info(`No matching confirmation found, waiting ${i}ms before retrying...`),await new Promise(e=>setTimeout(e,i)))}throw new Error(`Connection confirmation not found after ${r} attempts for request ID ${t}`)}async getOperatorId(e){if(this.operatorId&&!e)return this.operatorId;const t=this.getAccountAndSigner();if(!t?.accountId)throw new Error("Operator ID not found");const r=await this.retrieveProfile(t.accountId);if(!r?.success)throw new Error("Failed to retrieve profile");if(!r?.topicInfo?.inboundTopic)throw new Error("Failed to retrieve inbound topic");const i=`${r.topicInfo?.inboundTopic}@${t.accountId}`;return this.operatorId=i,i}async retrieveInboundAccountId(e){const t=await this.mirrorNode.getTopicInfo(e);if(!t?.memo)throw new Error("Failed to retrieve topic info");const r=t.memo.toString().split(":"),i=r?.[4];if(!i)throw new Error("Failed to retrieve topic info account ID");return i}clearCache(){qu.getInstance().clear()}_generateHcs10Memo(e,t){const r=t.ttl??60;switch(e){case"inbound":if(!t.accountId)throw new Error("accountId is required for inbound memo");return`hcs-10:0:${r}:0:${t.accountId}`;case"outbound":return`hcs-10:0:${r}:1`;case"connection":if(!t.inboundTopicId||void 0===t.connectionId)throw new Error("inboundTopicId and connectionId are required for connection memo");return`hcs-10:1:${r}:2:${t.inboundTopicId}:${t.connectionId}`;default:throw new Error(`Invalid HCS-10 memo type: ${e}`)}}async getTopicMemoType(e){try{const t=await this.mirrorNode.getTopicInfo(e);if(!t?.memo)return this.logger.debug(`No memo found for topic ${e}`),null;const r=t.memo.toString();if(!r.startsWith("hcs-10:"))return this.logger.debug(`Topic ${e} is not an HCS-10 topic`),null;const i=r.split(":");if(i.length<4)return this.logger.warn(`Invalid HCS-10 memo format for topic ${e}: ${r}`),null;const o=i[3];switch(o){case"0":return"inbound";case"1":return"outbound";case"2":return"connection";case"3":return"registry";default:return this.logger.warn(`Unknown HCS-10 type enum: ${o} for topic ${e}`),null}}catch(t){return this.logger.error(`Error getting topic memo type for ${e}:`,t),null}}async checkRegistrationStatus(e,t,r){try{const i=await fetch(`${r}/api/request-confirm`,{method:"POST",headers:{"Content-Type":"application/json","X-Network":t},body:JSON.stringify({transaction_id:e})});if(!i.ok)throw new Error(`Failed to confirm registration: ${i.statusText}`);return await i.json()}catch($g){const t=$g,r=`Error checking registration status: ${t.message}`;throw this.logger.error(r),t}}isValidOperatorId(e){if(!e)return!1;const t=e.split("@");if(2!==t.length)return!1;const r=t[0],i=t[1];if(!r)return!1;if(!i)return!1;const o=/^[0-9]+\.[0-9]+\.[0-9]+$/;return!!o.test(i)&&!!o.test(r)}async getTransactionRequests(e,t){this.logger.debug(`Retrieving transaction requests from topic ${e}`);const{messages:r}=await this.getMessageStream(e,{limit:t?.limit,sequenceNumber:t?.sequenceNumber,order:t?.order||"desc"}),i=r.filter(e=>"transaction"===e.op&&e.schedule_id).map(e=>({operator_id:e.operator_id||"",schedule_id:e.schedule_id||"",data:e.data||"",memo:e.m,sequence_number:Number(e.sequence_number)})).sort((e,t)=>e.sequence_number&&t.sequence_number?t.sequence_number-e.sequence_number:0);return t?.limit?i.slice(0,t.limit):i}getHcs10TransactionMemo(e){if("object"!=typeof e||!("op"in e))return null;const t=e;let r,i;switch(t.op){case"register":r="0",i="0";break;case"delete":r="1",i="0";break;case"migrate":r="2",i="0";break;case"connection_request":r="3",i=t.outbound_topic_id?"2":"1";break;case"connection_created":r="4",i=t.outbound_topic_id?"2":"1";break;case"connection_closed":r="5",i=t.outbound_topic_id?"2":"3";break;case"message":case"transaction":default:r="6",i="3";break;case"close_connection":r="5",i="3"}return`hcs-10:op:${r}:${i}`}}class qu{constructor(){this.CACHE_TTL=36e5,this.cache=new Map,this.cacheExpiry=new Map}static getInstance(){return qu.instance||(qu.instance=new qu),qu.instance}set(e,t){this.cache.set(e,t),this.cacheExpiry.set(e,Date.now()+this.CACHE_TTL)}get(e){const t=this.cacheExpiry.get(e);if(t&&t>Date.now())return this.cache.get(e);t&&(this.cache.delete(e),this.cacheExpiry.delete(e))}clear(){this.cache.clear(),this.cacheExpiry.clear()}}class ju extends Error{constructor(e,t){super(e),this.payloadSize=t,this.name="PayloadSizeError"}}class Wu extends Error{constructor(e){super(e),this.name="AccountCreationError"}}class Vu extends Error{constructor(e){super(e),this.name="TopicCreationError"}}class Gu extends Error{constructor(e){super(e),this.name="ConnectionConfirmationError"}}class Ju{constructor(){this.config={},this.logger=O.getInstance({module:"AgentBuilder"})}setName(e){return this.config.name=e,this}setAlias(e){return this.config.alias=e,this}setBio(e){return this.config.bio=e,this}setDescription(e){return this.config.bio=e,this}setCapabilities(e){return this.config.capabilities=e,this}setAgentType(e){return this.config.metadata?this.config.metadata.type=e:this.config.metadata={type:e},this}setType(e){return this.config.metadata?this.config.metadata.type=e:this.config.metadata={type:e},this}setModel(e){return this.config.metadata||(this.config.metadata={type:"manual"}),this.config.metadata.model=e,this}setCreator(e){return this.config.metadata||(this.config.metadata={type:"manual"}),this.config.metadata.creator=e,this}addSocial(e,t){return this.config.metadata||(this.config.metadata={type:"manual"}),this.config.metadata.socials||(this.config.metadata.socials={}),this.config.metadata.socials[e]=t,this}addProperty(e,t){return this.config.metadata||(this.config.metadata={type:"manual"}),this.config.metadata.properties||(this.config.metadata.properties={}),this.config.metadata.properties[e]=t,this}setMetadata(e){return this.config.metadata=e,this}setProfilePicture(e,t){return this.config.pfpBuffer=e,this.config.pfpFileName=t,this}setExistingProfilePicture(e){return this.config.existingPfpTopicId=e,this}setNetwork(e){return this.config.network=e,this}setInboundTopicType(e){return this.config.inboundTopicType=e,this}setFeeConfig(e){return this.config.feeConfig=e,this}setConnectionFeeConfig(e){return this.config.connectionFeeConfig=e,this}setExistingAccount(e,t){return this.config.existingAccount={accountId:e,privateKey:t},this}setInboundTopicId(e){return this.config.inboundTopicId=e,this}setOutboundTopicId(e){return this.config.outboundTopicId=e,this}setBaseAccount(e){return this.baseAccount=e,this}build(){if(!this.config.name)throw new Error("Agent display name is required");if(this.config.bio||this.logger?.warn("Agent description is not set"),this.config.pfpBuffer||this.config.existingPfpTopicId||this.logger.warn("No profile picture provided or referenced."),!this.config.network)throw new Error("Network is required");if(this.config.inboundTopicType||(this.config.inboundTopicType=hu.PUBLIC),this.config.capabilities||(this.config.capabilities=[]),this.config.metadata?this.config.metadata.type||(this.config.metadata.type="manual"):this.config.metadata={type:"manual"},this.config.inboundTopicType===hu.FEE_BASED&&!this.config.feeConfig)throw new Error("Fee configuration is required for fee-based topics");const e=this.config;return this.baseAccount&&(e.baseAccount=this.baseAccount),e}}class Yu extends Hu{constructor(e){super({network:e.network,logLevel:e.logLevel,prettyPrint:e.prettyPrint,feeAmount:e.feeAmount,mirrorNode:e.mirrorNode,silent:e.silent,keyType:e.keyType}),this.logger=O.getInstance({level:e.logLevel||"info",module:"HCS-SDK",silent:e.silent}),this.operatorAccountId=e.operatorId,this.operatorCtx=ie({network:this.network,operatorId:this.operatorAccountId,operatorKey:e.operatorPrivateKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:"mainnet"===e.network?i.Client.forMainnet():i.Client.forTestnet()}),this.client=this.operatorCtx.client,this.network=e.network,this.guardedRegistryBaseUrl=e.guardedRegistryBaseUrl||"https://moonscape.tech",this.hcs11Client=new Ru({network:e.network,auth:{operatorId:e.operatorId,privateKey:this.operatorCtx.operatorKey.toString()},logLevel:e.logLevel,silent:e.silent,keyType:e.keyType})}async ensureInitialized(){await this.operatorCtx.ensureInitialized()}getClient(){return this.client}async createAccount(e=50){await this.ensureInitialized(),this.logger.info(`Creating new account with ${e} HBAR initial balance`);const t=i.PrivateKey.generateED25519(),r=(new i.AccountCreateTransaction).setKeyWithoutAlias(t.publicKey).setInitialBalance(new i.Hbar(e)),o=await r.execute(this.client),n=(await o.getReceipt(this.client)).accountId;if(!n)throw this.logger.error("Account creation failed: accountId is null"),new Wu("Failed to create account: accountId is null");return this.logger.info(`Account created successfully: ${n.toString()}`),{accountId:n.toString(),privateKey:t.toString()}}async createInboundTopic(e,t,r=60,i){let o,n;switch(await this.ensureInitialized(),this._generateHcs10Memo($u.INBOUND,{accountId:e,ttl:r}),t){case hu.PUBLIC:o=!1;break;case hu.CONTROLLED:o=!0;break;case hu.FEE_BASED:if(o=!1,!i)throw new Error("Fee configuration builder is required for fee-based topics");i.customFees.forEach(t=>{t.feeCollectorAccountId||(t.feeCollectorAccountId=e)}),n=i.build(),n.customFees=n.customFees.map(t=>({...t,feeCollectorAccountId:t.feeCollectorAccountId||e}));break;default:throw new Error(`Unsupported inbound topic type: ${t}`)}const s=this.client.operatorPublicKey||this.operatorCtx.operatorKey.publicKey,a=Pu({accountId:e,ttl:r,adminKey:!0,submitKey:o,operatorPublicKey:s});this.logger.info("Creating inbound topic");const{topicId:c}=await this.executeTopicCreateTransaction({transaction:a,feeConfig:n});return c}async createAgent(e,t=60,r,i){await this.ensureInitialized();const o=e.build(),n=this.client.operatorAccountId?.toString();if(!n)throw new Error("Failed to retrieve operator account ID");const s=await this._createEntityTopics(t,{outboundTopicId:r?.outboundTopicId||"",inboundTopicId:r?.inboundTopicId||"",pfpTopicId:r?.pfpTopicId||o.existingPfpTopicId||"",profileTopicId:r?.profileTopicId||""},n,o.inboundTopicType,o.feeConfig,o.pfpBuffer,o.pfpFileName,i);if(s.profileTopicId)this.logger.info(`Using existing profile topic ID: ${s.profileTopicId}`);else{i&&i({stage:"preparing",message:"Creating agent profile",progressPercent:60,details:{outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,state:{currentStage:"profile",completedPercentage:60}}});const e=await this.storeHCS11Profile(o.name,o.bio,s.inboundTopicId,s.outboundTopicId,o.capabilities,o.metadata,o.pfpBuffer&&o.pfpBuffer.length>0&&!s.pfpTopicId?o.pfpBuffer:void 0,o.pfpFileName,s.pfpTopicId);s.profileTopicId=e.profileTopicId,this.logger.info(`Profile stored with topic ID: ${s.profileTopicId}`),i&&i({stage:"preparing",message:"Agent profile created",progressPercent:70,details:{outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,profileTopicId:s.profileTopicId,state:{currentStage:"profile",completedPercentage:70}}})}return s}async create(e,t){const r=t?.progressCallback,i=new us({module:"ProfileCreate",logger:this.logger,callback:r?e=>r({stage:e.stage,message:e.message,progressPercent:e.progressPercent,details:e.details}):void 0});try{const r=e instanceof Ju;let o;if(o=t?.existingState?t.existingState:{currentStage:"init",completedPercentage:0,createdResources:[]},r){this.logger.info("Creating Agent Profile and HCS-10 Topics");const t=e.build();o.agentMetadata=t.metadata}else this.logger.info("Creating Person HCS-11 Profile");i.preparing(`Starting ${r?"agent":"person"} resource creation`,0,{state:o});const n=this.client.operatorAccountId?.toString();if(!n)throw new Error("Failed to retrieve operator account ID");const{inboundTopicId:s,outboundTopicId:a,state:c}=await this.createCommunicationTopics(n,t,i);let l,d,u;if(o=c,e.setInboundTopicId(s),e.setOutboundTopicId(a),r){const t=e.build();l=t.existingPfpTopicId||o.pfpTopicId,d=t.pfpBuffer,u=t.pfpFileName||"pfp.png"}else{const t=e.build();l=o.pfpTopicId,d=t.pfpBuffer,u=t.pfpFileName}!l&&d&&u?l=await this.handleProfilePictureCreation(d,u,o,i):l&&(i.preparing(`Using existing profile picture: ${l}`,50,{state:o}),o.pfpTopicId=l),await this.createAndInscribeProfile(r,e,l,o,s,a,t,i),o.currentStage="complete",o.completedPercentage=100,i.completed((r?"Agent":"Person")+" profile created successfully",{profileTopicId:o.profileTopicId,inboundTopicId:s,outboundTopicId:a,pfpTopicId:l,state:o});let p="";o.outboundTopicId&&(p=o.outboundTopicId);let h="";o.inboundTopicId&&(h=o.inboundTopicId);let g="";o.pfpTopicId&&(g=o.pfpTopicId);let m="";return o.profileTopicId&&(m=o.profileTopicId),{outboundTopicId:p,inboundTopicId:h,pfpTopicId:g,profileTopicId:m,success:!0,state:o}}catch(o){return i.failed("Error during profile creation",{error:o.message}),{outboundTopicId:"",inboundTopicId:"",pfpTopicId:"",profileTopicId:"",success:!1,error:o.message,state:{currentStage:"init",completedPercentage:0,error:o.message}}}}async inscribePfp(e,t){try{this.logger.info("Inscribing profile picture using HCS-11 client");const r=await this.hcs11Client.inscribeImage(e,t);if(!r.success)throw this.logger.error(`Failed to inscribe profile picture: ${r.error}`),new Error(r?.error||"Failed to inscribe profile picture");return this.logger.info(`Successfully inscribed profile picture with topic ID: ${r.imageTopicId}`),{pfpTopicId:r.imageTopicId,transactionId:r.transactionId,success:!0}}catch($g){const t=$g,r=`Error inscribing profile picture: ${t.message}`;return this.logger.error(r),{pfpTopicId:"",transactionId:"",success:!1,error:t.message}}}async storeHCS11Profile(e,t,r,i,o=[],n,s,a,c){try{let l=c||"";if(!l&&s&&a){this.logger.info("Inscribing profile picture for HCS-11 profile");const e=await this.inscribePfp(s,a);e.success?l=e.pfpTopicId:this.logger.warn(`Failed to inscribe profile picture: ${e.error}, proceeding without pfp`)}else c&&(this.logger.info(`Using existing profile picture with topic ID: ${c} for HCS-11 profile`),l=c);const d=this.hcs11Client.getAgentTypeFromMetadata({type:n.type||"autonomous"}),u=n.socials?Object.entries(n.socials).filter(([e,t])=>t).map(([e,t])=>({platform:e,handle:t})):void 0,p=this.hcs11Client.createAIAgentProfile(e,d,o,n.model||"unknown",{alias:e.toLowerCase().replace(/\s+/g,"_"),bio:t,profileImage:l?`hcs://1/${l}`:void 0,socials:u,properties:n.properties,inboundTopicId:r,outboundTopicId:i,creator:n.creator}),h=await this.hcs11Client.createAndInscribeProfile(p,!0);if(!h.success)throw this.logger.error(`Failed to inscribe profile: ${h.error}`),new Error(h.error||"Failed to inscribe profile");return this.logger.info(`Profile inscribed with topic ID: ${h.profileTopicId}, transaction ID: ${h.transactionId}`),{profileTopicId:h.profileTopicId,pfpTopicId:l,transactionId:h.transactionId,success:!0}}catch($g){const t=$g,r=`Error storing HCS-11 profile: ${t.message}`;return this.logger.error(r),{profileTopicId:"",pfpTopicId:"",transactionId:"",success:!1,error:t.message}}}async setupFees(e,t,r=[]){let o=e;if(!this.client.operatorPublicKey)return o;if(!t.customFees||0===t.customFees.length)return this.logger.warn("No custom fees provided in fee config for setupFees"),o;t.customFees.length>10&&(this.logger.warn("More than 10 custom fees provided, only the first 10 will be used"),t.customFees=t.customFees.slice(0,10));const n=t.customFees.map(e=>{if(!e.feeCollectorAccountId)return this.logger.error("Internal Error: Fee collector ID missing in setupFees"),null;if("FIXED_FEE"===e.type){const t=(new i.CustomFixedFee).setAmount(Number(e.feeAmount.amount)).setFeeCollectorAccountId(i.AccountId.fromString(e.feeCollectorAccountId));return e.feeTokenId&&t.setDenominatingTokenId(i.TokenId.fromString(e.feeTokenId)),t}return null}).filter(Boolean);if(0===n.length)return this.logger.warn("No valid custom fees to apply in setupFees"),o;const s=[...t.exemptAccounts||[],...r];return s.length>0&&(o=await this.setupExemptKeys(e,s)),o.setFeeScheduleKey(this.client.operatorPublicKey).setCustomFees(n)}async setupExemptKeys(e,t){let r=e;const i=Array.from(new Set(t)).filter(e=>e!==this.client.operatorAccountId?.toString());let o=[];if(i.length>0)try{o=await sc(i,this.network,this.logger)}catch($g){const t=`Error getting exempt keys: ${$g.message}, continuing without exempt keys`;this.logger.warn(t)}return o.length>0&&(r=r.setFeeExemptKeys(o)),r}async handleConnectionRequest(e,t,r,o,n=60){this.logger.info(`Handling connection request ${r} from ${t}`);const s=this.getClient().operatorAccountId?.toString();if(!s)throw new Error("Failed to retrieve operator account ID");let a=await this.mirrorNode.getPublicKey(t);const c=await this.mirrorNode.getPublicKey(s);if(!c)throw new Error("Failed to retrieve public key");const l=new i.KeyList([c,a],1);let d;try{const t=zu({ttl:n,inboundTopicId:e,connectionId:r,adminKey:l,submitKey:l});if(o){const e=o.build(),r={...e,exemptAccounts:[...e.exemptAccounts||[]]},{topicId:i}=await this.executeTopicCreateTransaction({transaction:t,feeConfig:r});d=i}else{const{topicId:e}=await this.executeTopicCreateTransaction({transaction:t});d=e}this.logger.info(`Created new connection topic ID: ${d}`)}catch(f){const e=`Failed to create connection topic: ${f}`;throw this.logger.error(e),new Vu(e)}const u=`${e}@${s}`,p=await this.confirmConnection(e,d,t,r,"Connection accepted. Looking forward to collaborating!"),h=await this.retrieveCommunicationTopics(s),g=await this.retrieveCommunicationTopics(t),m=`${g.inboundTopic}@${t}`;return await this.recordOutboundConnectionConfirmation({outboundTopicId:h.outboundTopic,requestorOutboundTopicId:g.outboundTopic,connectionRequestId:r,confirmedRequestId:p,connectionTopicId:d,operatorId:m,memo:`Connection established with ${t}`}),{connectionTopicId:d,confirmedConnectionSequenceNumber:p,operatorId:u}}async confirmConnection(e,t,r,i,o,n){const s=await this.getOperatorId();this.logger.info(`Confirming connection with ID ${i}`);const a=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),c=Mu({inboundTopicId:e,connectionTopicId:t,connectedAccountId:r,operatorId:s,connectionId:i,memo:o}),l=await this.submitPayload(c,void 0,n,a.requiresFee),d=l.topicSequenceNumber?.toNumber();if(!d)throw new Gu("Failed to confirm connection: sequence number is null");return d}async sendMessage(e,t,r,i,o){const n=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),s=await this.getOperatorId(),a={p:"hcs-10",op:"message",operator_id:s,data:t,m:r},c=JSON.stringify(a);if(globalThis.Buffer.from(c).length>1e3){this.logger.info("Message payload exceeds 1000 bytes, storing via inscription");try{const e=globalThis.Buffer.from(t),r=`message-${Date.now()}.json`,i=await this.inscribeFile(e,r,{progressCallback:o?.progressCallback,waitMaxAttempts:o?.waitMaxAttempts,waitIntervalMs:o?.waitIntervalMs});if(!La(i))throw new Error("Failed to inscribe large message content");a.data=`hcs://1/${La(i)}`,this.logger.info(`Large message inscribed with topic ID: ${La(i)}`)}catch(d){const e=`Error inscribing large message: ${d.message}`;throw this.logger.error(e),new Error(e)}}this.logger.info("Submitting message to connection topic",a);const l=Uu({connectionTopicId:e,operatorId:s,data:a.data,memo:r});return await this.submitPayload(l,void 0,i,n.requiresFee)}async executeTopicCreateTransaction(e){let t=e.transaction;e.feeConfig&&(t=await this.setupFees(t,e.feeConfig,e.additionalExemptAccounts||[]));try{const e=await t.execute(this.client),r=await e.getReceipt(this.client);if(!r.topicId)throw this.logger.error("Failed to create topic: topicId is null"),new Error("Failed to create topic: topicId is null");return{topicId:r.topicId.toString(),receipt:r,response:e}}catch(r){throw this.logger.error("Topic creation failed",{error:r.message,transactionId:r.transactionId?.toString(),operatorId:this.client.operatorAccountId?.toString()}),r}}async createTopic(e,t,r,i){this.logger.info("Creating topic");const o=J({memo:e,adminKey:t,submitKey:r,operatorPublicKey:this.client.operatorPublicKey||this.operatorCtx.operatorKey?.publicKey}),{topicId:n}=await this.executeTopicCreateTransaction({transaction:o,feeConfig:i});return n}async submitPayload(e,t,r,o=!1){if(e instanceof i.TopicMessageSubmitTransaction||"string"!=typeof e&&"function"==typeof e.getMessage){const t=(i.TopicMessageSubmitTransaction,e),n=t.getMessage();if(!n)throw new Error("Message payload is missing");const s=globalThis.Buffer.from(n).length;if(s>1e3)throw new ju("Payload size exceeds 1000 bytes limit",s);let a;if(o&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),t.setMaxTransactionFee(new i.Hbar(this.feeAmount))),r){const e=t.freezeWith(this.client),i=await e.sign(r);a=await i.execute(this.client)}else a=await t.execute(this.client);const c=await a.getReceipt(this.client);if(!c)throw this.logger.error("Failed to submit message: receipt is null"),new Error("Failed to submit message: receipt is null");return this.logger.info("Message submitted successfully"),c}const n="string"==typeof t?t:JSON.stringify(t),s=globalThis.Buffer.byteLength(n,"utf8");if(s>1e3)throw new ju("Payload size exceeds 1000 bytes limit",s);const a=Y({topicId:e,message:n,transactionMemo:this.getHcs10TransactionMemo(t)||void 0});let c;if(o&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),a.setMaxTransactionFee(new i.Hbar(this.feeAmount))),r){const e=a.freezeWith(this.client),t=await e.sign(r);c=await t.execute(this.client)}else c=await a.execute(this.client);const l=await c.getReceipt(this.client);if(!l)throw this.logger.error("Failed to submit message: receipt is null"),new Error("Failed to submit message: receipt is null");return this.logger.info("Message submitted successfully"),l}async inscribeFile(e,t,r){if(this.logger.info("Inscribing file"),!this.client.operatorAccountId)throw this.logger.error("Operator account ID is not set"),new Error("Operator account ID is not set");if(!this.operatorCtx.operatorKey)throw this.logger.error("Operator private key is not set"),new Error("Operator private key is not set");const i=S.lookup(t)||"application/octet-stream",o=this.operatorCtx.operatorKey,n=await ds.createWithAuth({type:"server",accountId:this.client.operatorAccountId.toString(),privateKey:o,network:this.network}),s={mode:"file",waitForConfirmation:!0,waitMaxAttempts:r?.waitMaxAttempts||30,waitIntervalMs:r?.waitIntervalMs||4e3,progressCallback:r?.progressCallback,logging:{level:this.logger.getLevel?this.logger.getLevel():"info"}},a=await za({type:"buffer",buffer:e,fileName:t,mimeType:i},{accountId:this.client.operatorAccountId.toString(),privateKey:o,network:this.network},s,n);if(!a.confirmed||!a.inscription)throw new Error("Inscription was not confirmed");return a.inscription}async waitForConnectionConfirmation(e,t,r=60,i=2e3,o=!0){this.logger.info(`Waiting for connection confirmation on inbound topic ${e} for request ID ${t}`);for(let n=0;n<r;n++){this.logger.info(`Attempt ${n+1}/${r} to find connection confirmation`);const s=(await this.mirrorNode.getTopicMessages(e)).filter(e=>"connection_created"===e.op);if(this.logger.info(`Found ${s.length} connection_created messages`),s.length>0)for(const e of s)if(Number(e.connection_id)===Number(t)){const r={connectionTopicId:e.connection_topic_id,sequence_number:Number(e.sequence_number),confirmedBy:e.operator_id,memo:e.m},i=this.extractAccountFromOperatorId(r.confirmedBy),n=this.getAccountAndSigner(),s=await this.retrieveCommunicationTopics(i),a=await this.retrieveCommunicationTopics(n.accountId);return this.logger.info("Connection confirmation found",r),o&&await this.recordOutboundConnectionConfirmation({requestorOutboundTopicId:s.outboundTopic,outboundTopicId:a.outboundTopic,connectionRequestId:t,confirmedRequestId:r.sequence_number,connectionTopicId:r.connectionTopicId,operatorId:r.confirmedBy,memo:r.memo||"Connection confirmed"}),r}n<r-1&&(this.logger.info(`No matching confirmation found, waiting ${i}ms before retrying...`),await new Promise(e=>setTimeout(e,i)))}throw new Error(`Connection confirmation not found after ${r} attempts for request ID ${t}`)}getAccountAndSigner(){const e=this.operatorCtx.operatorKey;return{accountId:this.client.operatorAccountId.toString(),signer:e}}async createAndRegisterAgent(e,t){try{const r=e.build(),o=t?.progressCallback,n=t?.baseUrl||this.guardedRegistryBaseUrl;let s=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};s.agentMetadata=r.metadata,o&&o({stage:"preparing",message:"Starting agent creation process",progressPercent:0,details:{state:s}});let a,c=r.existingAccount;if(s.inboundTopicId&&s.outboundTopicId&&s.profileTopicId){if(c=c||r.existingAccount,!c)throw new Error("Cannot resume registration without account information");const e="ecdsa"===this.operatorCtx.keyType?i.PrivateKey.fromStringECDSA(c.privateKey).publicKey.toString():i.PrivateKey.fromStringED25519(c.privateKey).publicKey.toString();a=new Yu({network:r.network,operatorId:c.accountId,operatorPrivateKey:c.privateKey,operatorPublicKey:e,logLevel:"info",guardedRegistryBaseUrl:n}),this.logger.info("Resuming registration with existing state",{inboundTopicId:s.inboundTopicId,outboundTopicId:s.outboundTopicId,profileTopicId:s.profileTopicId,pfpTopicId:s.pfpTopicId})}else{if(!c)if(s.createdResources&&s.createdResources.some(e=>e.startsWith("account:"))){const e=s.createdResources.find(e=>e.startsWith("account:")),i=e?.split(":")[1];i&&r.existingAccount?(c=r.existingAccount,this.logger.info(`Resuming with existing account: ${i}`)):(c=await this.createAccount(t?.initialBalance),s.createdResources=s.createdResources||[],s.createdResources.push(`account:${c.accountId}`))}else c=await this.createAccount(t?.initialBalance),s.createdResources=s.createdResources||[],s.createdResources.push(`account:${c.accountId}`);o&&o({stage:"preparing",message:"Created account or using existing account",progressPercent:20,details:{state:s,account:c}});const i=new re({mirrorNode:this.mirrorNode,logger:this.logger}),l=await i.resolveOperatorKey(c.accountId,c.privateKey),d=l.privateKey.publicKey.toString();a=new Yu({network:r.network,operatorId:c.accountId,operatorPrivateKey:l.privateKey.toString(),operatorPublicKey:d,keyType:l.keyType,logLevel:"info",guardedRegistryBaseUrl:n}),o&&o({stage:"preparing",message:"Initialized agent client",progressPercent:25,details:{state:s}});let u=s.outboundTopicId,p=s.inboundTopicId,h=s.pfpTopicId,g=s.profileTopicId;if(!u||!p||!g){h&&e.setExistingProfilePicture(h);const t=await a.createAgent(e,60,s,e=>{o&&o({stage:e.stage,message:e.message,progressPercent:e.progressPercent||0,details:{...e.details,state:{...s,...e.details?.state}}})});u=t.outboundTopicId,p=t.inboundTopicId,h=t.pfpTopicId,g=t.profileTopicId,s.outboundTopicId=u,s.inboundTopicId=p,s.pfpTopicId=h,s.profileTopicId=g,s.createdResources||(s.createdResources=[]),h&&!s.createdResources.includes(`pfp:${h}`)&&s.createdResources.push(`pfp:${h}`),s.createdResources.includes(`inbound:${p}`)||s.createdResources.push(`inbound:${p}`),s.createdResources.includes(`outbound:${u}`)||s.createdResources.push(`outbound:${u}`),s.createdResources.includes(`profile:${g}`)||s.createdResources.push(`profile:${g}`)}s.currentStage="profile",s.completedPercentage=60,o&&o({stage:"submitting",message:"Created agent with topics and profile",progressPercent:60,details:{state:s,outboundTopicId:u,inboundTopicId:p,pfpTopicId:h,profileTopicId:g}})}const l=`${s.inboundTopicId}@${c.accountId}`;if("complete"!==s.currentStage||!s.createdResources?.includes(`registration:${s.inboundTopicId}`)){const e=await a.registerAgentWithGuardedRegistry(c.accountId,r.network,{progressCallback:e=>{const t=60+.4*(e.progressPercent||0);o&&o({stage:e.stage,message:e.message,progressPercent:t,details:{...e.details,outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,profileTopicId:s.profileTopicId,operatorId:l,state:e.details?.state||s}})},existingState:s});if(!e.success)return{...e,state:s};s=e.state||s}return o&&o({stage:"completed",message:"Agent creation and registration complete",progressPercent:100,details:{outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,profileTopicId:s.profileTopicId,operatorId:l,state:s}}),{success:!0,state:s,metadata:{accountId:c.accountId,privateKey:c.privateKey,operatorId:l,inboundTopicId:s.inboundTopicId,outboundTopicId:s.outboundTopicId,profileTopicId:s.profileTopicId,pfpTopicId:s.pfpTopicId}}}catch($g){const r=$g,i=`Failed to create and register agent: ${r.message}`;return this.logger.error(i),{error:r.message,success:!1,state:t?.existingState||{currentStage:"init",completedPercentage:0,error:r.message}}}}async registerAgentWithGuardedRegistry(e,t=this.network,r){try{this.logger.info("Registering agent with guarded registry");const o=r?.maxAttempts??60,n=r?.delayMs??2e3,s=r?.progressCallback;let a=r?.existingState||{currentStage:"registration",completedPercentage:0,createdResources:[]};s&&s({stage:"preparing",message:"Preparing agent registration",progressPercent:10,details:{state:a}});const c=await this.executeRegistration(e,t,this.guardedRegistryBaseUrl,this.logger);if(!c.success)return{...c,state:a};if(s&&s({stage:"submitting",message:"Submitting registration to registry",progressPercent:30,details:{transactionId:c.transactionId,state:a}}),c.transaction){const e=i.Transaction.fromBytes(globalThis.Buffer.from(c.transaction,"base64"));this.logger.info("Processing registration transaction"),await e.execute(this.client),this.logger.info("Successfully processed registration transaction")}s&&s({stage:"confirming",message:"Confirming registration transaction",progressPercent:60,details:{accountId:e,transactionId:c.transactionId,state:a}});const l=await this.waitForRegistrationConfirmation(c.transactionId,t,this.guardedRegistryBaseUrl,o,n,this.logger);return a.currentStage="complete",a.completedPercentage=100,a.createdResources||(a.createdResources=[]),c.transactionId&&a.createdResources.push(`registration:${c.transactionId}`),s&&s({stage:"completed",message:"Agent registration complete",progressPercent:100,details:{confirmed:l,transactionId:c.transactionId,state:a}}),{...c,confirmed:l,state:a}}catch($g){const t=$g,r=`Failed to register agent: ${t.message}`;return this.logger.error(r),{error:t.message,success:!1}}}async registerAgent(e,t,r,i,o){this.logger.info("Registering agent");const n=Lu({registryTopicId:e,accountId:t,inboundTopicId:r,memo:i});await this.submitPayload(n,void 0,o)}async getInboundTopicType(e){try{const t=await this.mirrorNode.getTopicInfo(e);if(!t)throw new Error("Topic does not exist");if(!(t.submit_key&&t.submit_key.key))return hu.PUBLIC;if(t.fee_schedule_key&&t.fee_schedule_key.key&&t.custom_fees){const r=t.custom_fees;if(r&&r.fixed_fees&&r.fixed_fees.length>0)return this.logger.info(`Topic ${e} is fee-based with ${r.fixed_fees.length} custom fees`),hu.FEE_BASED}return hu.CONTROLLED}catch($g){const t=`Error determining topic type: ${$g.message}`;throw this.logger.error(t),new Error(t)}}getNetwork(){return this.network}getLogger(){return this.logger}getOperatorAccountId(){return this.client.operatorAccountId?.toString()??null}async createScheduledTransaction(e,t,r,o){this.logger.info("Creating scheduled transaction");const n=(new i.ScheduleCreateTransaction).setScheduledTransaction(e).setPayerAccountId(o?i.AccountId.fromString(o):this.client.operatorAccountId);if(t&&n.setScheduleMemo(t),r){const e=y.addSeconds(new Date,r),t=i.Timestamp.fromDate(e);n.setExpirationTime(t)}const s=await n.execute(this.client),a=await s.getReceipt(this.client);if(!a.scheduleId)throw this.logger.error("Failed to create scheduled transaction: scheduleId is null"),new Error("Failed to create scheduled transaction: scheduleId is null");const c=a.scheduleId.toString(),l=s.transactionId.toString();return this.logger.info(`Scheduled transaction created successfully: ${c}`),{scheduleId:c,transactionId:l}}async sendTransactionOperation(e,t,r,i,o){const n=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),s={p:"hcs-10",op:"transaction",operator_id:await this.getOperatorId(),schedule_id:t,data:r,m:o?.memo};return this.logger.info("Submitting transaction operation to connection topic",s),await this.submitPayload(e,s,i,n.requiresFee)}async sendTransaction(e,t,r,i){this.logger.info("Creating scheduled transaction and sending transaction operation");const{scheduleId:o,transactionId:n}=await this.createScheduledTransaction(t,i?.scheduleMemo,i?.expirationTime,i?.schedulePayerAccountId);return{scheduleId:o,transactionId:n,receipt:await this.sendTransactionOperation(e,o,r,i?.submitKey,{memo:i?.operationMemo})}}async createCommunicationTopics(e,t,r){let i=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};if(r&&r.preparing("Starting communication topic creation",0,{state:i}),!i.outboundTopicId){i.currentStage="topics",r&&r.preparing("Creating outbound topic",5,{state:i});const e=this.client.operatorPublicKey||this.operatorCtx.operatorKey.publicKey,o=Fu({ttl:t?.ttl??60,adminKey:!0,submitKey:!0,operatorPublicKey:e}),{topicId:n}=await this.executeTopicCreateTransaction({transaction:o});i.outboundTopicId=n,i.createdResources&&i.createdResources.push(`outbound:${i.outboundTopicId}`)}if(!i.inboundTopicId){i.currentStage="topics",r&&r.preparing("Creating inbound topic",10,{state:i});const o=this.client.operatorPublicKey||this.operatorCtx.operatorKey.publicKey,n=Pu({accountId:e,ttl:t?.ttl??60,adminKey:!0,submitKey:!1,operatorPublicKey:o}),{topicId:s}=await this.executeTopicCreateTransaction({transaction:n});i.inboundTopicId=s,i.createdResources&&i.createdResources.push(`inbound:${i.inboundTopicId}`)}return{inboundTopicId:i.inboundTopicId,outboundTopicId:i.outboundTopicId,state:i}}async handleProfilePictureCreation(e,t,r,i){r.currentStage="pfp",i.preparing("Creating profile picture",30,{state:r}),i.createSubProgress({minPercent:30,maxPercent:50,logPrefix:"PFP"});const o=await this.inscribePfp(e,t);if(!o.success){let e="Failed to inscribe profile picture";throw o.error&&(e=o.error),new Error(e)}const n=o.pfpTopicId;return r.pfpTopicId=n,r.createdResources&&r.createdResources.push(`pfp:${r.pfpTopicId}`),i.preparing("Profile picture created",50,{state:r}),n}async createAndInscribeProfile(e,t,r,i,o,n,s,a){if(this.logger.info("Creating and inscribing profile"),i.profileTopicId)a&&a.preparing(`Using existing ${e?"agent":"person"} profile`,95,{state:i});else{let c;if(a&&a.preparing(`Storing HCS-11 ${e?"agent":"person"} profile`,80),a?.createSubProgress({minPercent:80,maxPercent:95,logPrefix:"StoreProfile"}),e){const e=t.build(),i=e.metadata?.socials?Object.entries(e.metadata.socials).map(([e,t])=>({platform:e,handle:t})):[];c=this.hcs11Client.createAIAgentProfile(e.name,"manual"===e.metadata?.type?0:1,e.capabilities||[],e.metadata?.model||"unknown",{alias:e.name.toLowerCase().replace(/\s+/g,"_"),bio:e.bio,profileImage:r?`hcs://1/${r}`:void 0,socials:i,properties:e.metadata?.properties||{},inboundTopicId:o,outboundTopicId:n,creator:e.metadata?.creator})}else{const e=t.build(),{pfpBuffer:i,pfpFileName:s,...a}=e;c=this.hcs11Client.createPersonalProfile(e.display_name,{alias:e.alias,bio:e.bio,socials:e.socials,profileImage:r?`hcs://1/${r}`:e.profileImage,properties:e.properties,inboundTopicId:o,outboundTopicId:n})}const l=await this.hcs11Client.createAndInscribeProfile(c,s?.updateAccountMemo??!0);if(!l.success){a&&a.failed(`Failed to inscribe ${e?"agent":"person"} profile`,{error:l.error});let t=`Failed to inscribe ${e?"agent":"person"} profile`;throw l.error&&(t=l.error),new Error(t)}i.profileTopicId=l.profileTopicId,i.createdResources&&i.createdResources.push(`profile:${l.profileTopicId}`),a&&a.preparing("HCS-11 Profile stored",95,{state:i})}}async createMCPServer(e,t=60,r,i){await this.ensureInitialized();const o=e.build(),n=this.client.operatorAccountId?.toString();if(!n)throw new Error("Failed to retrieve operator account ID");const s=await this._createEntityTopics(t,{outboundTopicId:r?.outboundTopicId||"",inboundTopicId:r?.inboundTopicId||"",pfpTopicId:r?.pfpTopicId||o.existingPfpTopicId||"",profileTopicId:r?.profileTopicId||""},n,hu.PUBLIC,void 0,o.pfpBuffer,o.pfpFileName,i);if(s.profileTopicId)this.logger.info(`Using existing profile topic ID: ${s.profileTopicId}`);else{this.logger.info("Creating and storing HCS-11 MCP server profile"),i&&i({stage:"preparing",message:"Creating MCP server profile",progressPercent:60,details:{outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,state:{currentStage:"profile",completedPercentage:60}}}),await this.hcs11Client.initializeOperator();const e=this.hcs11Client.createMCPServerProfile(o.name,o.mcpServer,{alias:o.alias,bio:o.bio,socials:o.socials||[],inboundTopicId:s.inboundTopicId,outboundTopicId:s.outboundTopicId,profileImage:s.pfpTopicId?`hcs://1/${s.pfpTopicId}`:void 0}),t=await this.hcs11Client.inscribeProfile(e);if(!t.success)throw this.logger.error(`Failed to inscribe MCP server profile: ${t.error}`),new Error(t.error||"Failed to inscribe MCP server profile");s.profileTopicId=t.profileTopicId,this.logger.info(`MCP server profile stored with topic ID: ${s.profileTopicId}`);const r=await this.hcs11Client.updateAccountMemoWithProfile(n,s.profileTopicId);r.success?this.logger.info("Updated account memo with profile reference"):this.logger.warn(`Failed to update account memo: ${r.error}, but continuing with MCP server creation`),i&&i({stage:"preparing",message:"MCP server profile created",progressPercent:70,details:{outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,profileTopicId:s.profileTopicId,state:{currentStage:"profile",completedPercentage:70}}})}return s}async _createEntityTopics(e,t,r,i,o,n,s,a){let{outboundTopicId:c,inboundTopicId:l,pfpTopicId:d,profileTopicId:u}=t;if(c)this.logger.info(`Using existing outbound topic ID: ${c}`);else{const t=Fu({ttl:e,adminKey:!0,submitKey:!0,operatorPublicKey:this.client.operatorPublicKey||this.operatorCtx.operatorKey.publicKey}),{topicId:r}=await this.executeTopicCreateTransaction({transaction:t});c=r,this.logger.info(`Created new outbound topic ID: ${c}`),a&&a({stage:"preparing",message:"Created outbound topic",progressPercent:30,details:{outboundTopicId:c,state:{currentStage:"topics",completedPercentage:30}}})}if(l?this.logger.info(`Using existing inbound topic ID: ${l}`):(l=await this.createInboundTopic(r,i,e,i===hu.FEE_BASED?o:void 0),this.logger.info(`Created new inbound topic ID: ${l}`),a&&a({stage:"preparing",message:"Created inbound topic",progressPercent:40,details:{outboundTopicId:c,inboundTopicId:l,state:{currentStage:"topics",completedPercentage:40}}})),!d&&n&&n.length>0&&s){this.logger.info("Inscribing new profile picture"),a&&a({stage:"preparing",message:"Inscribing profile picture",progressPercent:50,details:{outboundTopicId:c,inboundTopicId:l,state:{currentStage:"pfp",completedPercentage:50}}});d=(await this.inscribePfp(n,s)).pfpTopicId,this.logger.info(`Profile picture inscribed with topic ID: ${d}`),a&&a({stage:"preparing",message:"Profile picture inscribed",progressPercent:55,details:{outboundTopicId:c,inboundTopicId:l,pfpTopicId:d,state:{currentStage:"pfp",completedPercentage:55}}})}else d&&this.logger.info(`Using existing profile picture with topic ID: ${d}`);return{inboundTopicId:l,outboundTopicId:c,pfpTopicId:d,profileTopicId:u}}async createAndRegisterMCPServer(e,t){try{const r=e.build(),o=t?.progressCallback,n=t?.baseUrl||this.guardedRegistryBaseUrl;let s=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};s.serverMetadata={name:r.name,description:r.mcpServer.description,services:r.mcpServer.services},o&&o({stage:"preparing",message:"Starting MCP server creation process",progressPercent:0,details:{state:s}});let a,c=r.existingAccount;if(s.inboundTopicId&&s.outboundTopicId&&s.profileTopicId){if(c=c||r.existingAccount,!c)throw new Error("Cannot resume registration without account information");const e=te(c.privateKey),t=("ed25519"===e.detectedType?i.PrivateKey.fromStringED25519(c.privateKey):i.PrivateKey.fromStringECDSA(c.privateKey)).publicKey.toString();a=new Yu({network:r.network,operatorId:c.accountId,operatorPrivateKey:c.privateKey,operatorPublicKey:t,keyType:e.detectedType,logLevel:"info",guardedRegistryBaseUrl:n}),this.logger.info("Resuming registration with existing state",{inboundTopicId:s.inboundTopicId,outboundTopicId:s.outboundTopicId,profileTopicId:s.profileTopicId,pfpTopicId:s.pfpTopicId})}else{if(!c)if(s.createdResources&&s.createdResources.some(e=>e.startsWith("account:"))){const e=s.createdResources.find(e=>e.startsWith("account:")),i=e?.split(":")[1];i&&r.existingAccount?(c=r.existingAccount,this.logger.info(`Resuming with existing account: ${i}`)):(c=await this.createAccount(t?.initialBalance),s.createdResources=s.createdResources||[],s.createdResources.push(`account:${c.accountId}`))}else c=await this.createAccount(t?.initialBalance),s.createdResources=s.createdResources||[],s.createdResources.push(`account:${c.accountId}`);o&&o({stage:"preparing",message:"Created account or using existing account",progressPercent:20,details:{state:s,account:c}});const l=new re({mirrorNode:this.mirrorNode,logger:this.logger}),d=await l.resolveOperatorKey(c.accountId,c.privateKey);e.setExistingAccount(c.accountId,c.privateKey);const u=("ed25519"===d.keyType?i.PrivateKey.fromStringED25519(c.privateKey):i.PrivateKey.fromStringECDSA(c.privateKey)).publicKey.toString();a=new Yu({network:r.network,operatorId:c.accountId,operatorPrivateKey:c.privateKey,operatorPublicKey:u,logLevel:"info",guardedRegistryBaseUrl:n}),o&&o({stage:"preparing",message:"Initialized MCP server client",progressPercent:25,details:{state:s}});let p=s.outboundTopicId,h=s.inboundTopicId,g=s.pfpTopicId,m=s.profileTopicId;if(!p||!h||!m){g&&e.setExistingProfilePicture(g);const t=await a.createMCPServer(e,60,s,e=>{o&&o({stage:e.stage,message:e.message,progressPercent:e.progressPercent||0,details:{...e.details,state:{...s,...e.details?.state}}})});p=t.outboundTopicId,h=t.inboundTopicId,g=t.pfpTopicId,m=t.profileTopicId,s.outboundTopicId=p,s.inboundTopicId=h,s.pfpTopicId=g,s.profileTopicId=m,s.createdResources||(s.createdResources=[]),g&&!s.createdResources.includes(`pfp:${g}`)&&s.createdResources.push(`pfp:${g}`),s.createdResources.includes(`inbound:${h}`)||s.createdResources.push(`inbound:${h}`),s.createdResources.includes(`outbound:${p}`)||s.createdResources.push(`outbound:${p}`),s.createdResources.includes(`profile:${m}`)||s.createdResources.push(`profile:${m}`)}s.currentStage="profile",s.completedPercentage=60,o&&o({stage:"submitting",message:"Created MCP server with topics and profile",progressPercent:60,details:{state:s,outboundTopicId:p,inboundTopicId:h,pfpTopicId:g,profileTopicId:m}})}const l=`${s.inboundTopicId}@${c.accountId}`;if("complete"!==s.currentStage||!s.createdResources?.includes(`registration:${s.inboundTopicId}`)){const e=await a.registerAgentWithGuardedRegistry(c.accountId,r.network,{progressCallback:e=>{const t=60+.4*(e.progressPercent||0);o&&o({stage:e.stage,message:e.message,progressPercent:t,details:{...e.details,outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,profileTopicId:s.profileTopicId,operatorId:l,state:e.details?.state||s}})},existingState:s});if(!e.success)return{...e,state:s};s=e.state||s}return o&&o({stage:"completed",message:"MCP server creation and registration complete",progressPercent:100,details:{outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,profileTopicId:s.profileTopicId,operatorId:l,state:s}}),{success:!0,state:s,metadata:{accountId:c.accountId,privateKey:c.privateKey,operatorId:l,inboundTopicId:s.inboundTopicId,outboundTopicId:s.outboundTopicId,profileTopicId:s.profileTopicId,pfpTopicId:s.pfpTopicId}}}catch($g){const r=$g,i=`Failed to create and register MCP server: ${r.message}`;return this.logger.error(i),{error:r.message,success:!1,state:t?.existingState||{currentStage:"init",completedPercentage:0,error:r.message}}}}async createRegistryTopic(e={}){const{ttl:t=86400,metadata:r,adminKey:i=!1,submitKey:o=!1,waitForConfirmation:n=!0,waitMaxAttempts:s=30,waitIntervalMs:a=4e3,progressCallback:c}=e;try{let e;if(await this.ensureInitialized(),c&&c({stage:"preparing",message:"Preparing registry topic creation",progressPercent:10,details:{metadata:!!r}}),r){this.logger.info("Creating metadata inscription for registry"),c&&c({stage:"submitting",message:"Creating registry metadata inscription",progressPercent:30,details:{metadataName:r.name}});const t=globalThis.Buffer.from(JSON.stringify(r,null,2)),i={mode:"file",waitForConfirmation:n,waitMaxAttempts:s,waitIntervalMs:a,logging:{level:this.logger.getLevel?this.logger.getLevel():"info"}},o=await za({type:"buffer",buffer:t,fileName:`registry-metadata-${Date.now()}.json`,mimeType:"application/json"},{accountId:this.client.operatorAccountId.toString(),privateKey:this.operatorCtx.operatorKey,network:this.network},i);if(!o.confirmed||!o.inscription)throw new Error("Metadata inscription was not confirmed");e=La(o.inscription),this.logger.info(`Metadata inscribed to topic: ${e}`)}c&&c({stage:"submitting",message:"Creating registry topic",progressPercent:60,details:{metadataTopicId:e}});const l=this.operatorCtx.operatorKey,d=Ou({ttl:t,metadataTopicId:e,adminKey:i,submitKey:o,operatorPublicKey:this.client.operatorPublicKey||l.publicKey}),{topicId:u,response:p}=await this.executeTopicCreateTransaction({transaction:d});return c&&c({stage:"completed",message:"Registry topic created successfully",progressPercent:100,details:{topicId:u,metadataTopicId:e,transactionId:p.transactionId.toString()}}),this.logger.info(`Registry topic created successfully: ${u}`),{success:!0,topicId:u,transactionId:p.transactionId.toString(),metadataTopicId:e}}catch(l){const e=l instanceof Error?l.message:"Unknown error";return c&&c({stage:"failed",message:`Registry creation failed: ${e}`,progressPercent:0,details:{error:e}}),this.logger.error("Failed to create registry topic",{error:e}),{success:!1,error:e}}}}const Xu="undefined"!=typeof window;var Zu=(e=>(e[e.ACTION=0]="ACTION",e[e.ASSEMBLY=2]="ASSEMBLY",e[e.HASHLINKS=3]="HASHLINKS",e))(Zu||{});class Qu{constructor(e,t,r,i,o){this.entries=new Map,this.networkType=e,this.logger=t,this.registryType=r,this.topicId=i,this.client=o}async getEntry(e){const t=this.entries.get(e);return t||(this.topicId&&this.client?(await this.sync(),this.entries.get(e)||null):null)}async getLatestEntry(e){if(!this.client)return null;try{const t=await this.client.mirrorNode.getTopicMessagesByFilter(e,{order:"desc",limit:1});if(!t||0===t.length)return null;const r=t[0];let i;if(r.raw_content)i=JSON.parse(r.raw_content);else{const e=r;if("hcs-12"!==e.p||!e.op)return null;i={p:e.p,op:e.op,name:e.name,version:e.version,description:e.description,permissions:e.permissions,metadata:e.metadata,data:e.data,category:e.category,source:e.source,inputs:e.inputs,outputs:e.outputs,tags:e.tags,fields:e.fields,styles:e.styles,actions:e.actions,blocks:e.blocks,refs:e.refs},Object.keys(i).forEach(e=>{void 0===i[e]&&delete i[e]})}return{id:r.sequence_number.toString(),sequenceNumber:r.sequence_number,timestamp:r.consensus_timestamp||(new Date).toISOString(),submitter:r.payer||"unknown",data:i}}catch(t){return this.logger.error("Failed to get latest entry",{topicId:e,error:t}),null}}async listEntries(e){this.topicId&&this.client&&await this.sync();const t=Array.from(this.entries.values());return e?t.filter(t=>(!e.submitter||t.submitter===e.submitter)&&(!(e.afterTimestamp&&t.timestamp<e.afterTimestamp)&&!(e.beforeTimestamp&&t.timestamp>e.beforeTimestamp))):t}async sync(){if(this.topicId&&this.client){this.logger.info("Syncing registry entries",{topicId:this.topicId,registryType:Zu[this.registryType],lastSync:this.lastSyncTimestamp});try{const t=await this.client.mirrorNode.getTopicMessagesByFilter(this.topicId,{startTime:this.lastSyncTimestamp,order:"asc",limit:100});for(const r of t)try{let e;if(r.raw_content)e=JSON.parse(r.raw_content);else{const t=r;if("hcs-12"!==t.p||!t.op)continue;e={p:t.p,op:t.op,name:t.name,version:t.version,description:t.description,permissions:t.permissions,metadata:t.metadata,data:t.data,category:t.category,source:t.source,inputs:t.inputs,outputs:t.outputs,tags:t.tags,fields:t.fields,styles:t.styles,actions:t.actions,blocks:t.blocks,refs:t.refs,t_id:t.t_id,hash:t.hash,wasm_hash:t.wasm_hash,info_t_id:t.info_t_id,validation_rules:t.validation_rules,js_t_id:t.js_t_id,js_hash:t.js_hash,interface_version:t.interface_version,title:t.title,template:t.template,author:t.author,m:t.m},Object.keys(e).forEach(t=>{void 0===e[t]&&delete e[t]})}if("hcs-12"!==e.p)continue;const t={id:r.sequence_number.toString(),sequenceNumber:r.sequence_number,timestamp:r.consensus_timestamp||(new Date).toISOString(),submitter:r.payer||"unknown",data:e};this.entries.set(t.id,t)}catch(e){this.logger.warn("Failed to parse registry message",{sequenceNumber:r.sequence_number,error:e})}t.length>0?this.lastSyncTimestamp=t[t.length-1].consensus_timestamp||(new Date).toISOString():this.lastSyncTimestamp=(new Date).toISOString(),this.logger.info("Registry sync completed",{topicId:this.topicId,messageCount:t.length,lastSync:this.lastSyncTimestamp})}catch(e){throw this.logger.error("Failed to sync registry",{error:e}),e}}else this.logger.warn("Cannot sync without topic ID and client")}getTopicMemo(){return`hcs-12:1:60:${this.registryType}`}async createRegistryTopic(){if(!this.client)throw new Error("Client required to create topic");const e=await this.client.createRegistryTopic(this.registryType);return this.topicId=e,e}getConfig(){return{type:this.registryType,indexed:!1,ttl:60,topicId:this.topicId,memo:this.getTopicMemo()}}async inscribeContent(e,t,r){if(!this.client)throw new Error("Client required for inscription");const i="string"==typeof e?globalThis.Buffer.from(e):e;let o;if(this.logger.info("Inscribing content via HCS-1",{size:i.length,mimeType:t,registryType:Zu[this.registryType]}),"getOperatorAccountId"in this.client)o=await za({type:"buffer",buffer:i,fileName:"application/octet-stream"===t&&"wasm"===r?.fileType?`${r?.name||"content"}.wasm`:r?.name||"content",mimeType:t},{accountId:this.client.getOperatorAccountId(),privateKey:this.client.getOperatorPrivateKey(),network:this.networkType},{mode:"file",metadata:r,waitForConfirmation:!0});else{const{accountId:e,signer:n}=await this.client.getAccountAndSigner();o=await Da({type:"buffer",buffer:i,fileName:"application/octet-stream"===t&&"wasm"===r?.fileType?`${r?.name||"content"}.wasm`:r?.name||"content",mimeType:t},n,{mode:"file",metadata:r,waitForConfirmation:!0})}if(!o.confirmed)throw new Error("Failed to inscribe content");const n=o.inscription.topic_id;if(!n)throw new Error("No topic ID in inscription response");return this.logger.info("Content inscribed successfully",{topicId:n}),n}validateBaseRegistration(e){if(!e.p||"hcs-12"!==e.p)throw new Error("Invalid protocol identifier");if(!e.op||"register"!==e.op)throw new Error("Invalid operation")}clearCache(){this.entries.clear(),this.lastSyncTimestamp=void 0,this.logger.info("Registry cache cleared",{registryType:Zu[this.registryType]})}getStats(){return{entryCount:this.entries.size,lastSync:this.lastSyncTimestamp,topicId:this.topicId,registryType:Zu[this.registryType]}}}const ep=r.z.object({p:r.z.literal("hcs-12")}),tp=r.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid Hedera address format"),rp=r.z.string().regex(/^[a-f0-9]{64}$/,"Invalid SHA-256 hash format"),ip=r.z.object({format:r.z.enum(["tar.gz","zip","car"]),root_manifest:r.z.string(),includes_lockfile:r.z.boolean(),workspace_members:r.z.array(r.z.string()).optional()}),op=r.z.object({source_t_id:tp,source_hash:rp,compiler_version:r.z.string(),cargo_version:r.z.string(),target:r.z.literal("wasm32-unknown-unknown"),profile:r.z.string(),build_flags:r.z.array(r.z.string()),lockfile_hash:rp,source_structure:ip}),np=r.z.lazy(()=>r.z.object({type:r.z.string().optional(),required:r.z.array(r.z.string()).optional(),properties:r.z.record(np).optional(),pattern:r.z.string().optional(),minimum:r.z.number().optional(),maximum:r.z.number().optional(),regex:r.z.string().optional(),min:r.z.number().optional(),max:r.z.number().optional(),length:r.z.number().optional(),email:r.z.boolean().optional(),url:r.z.boolean().optional(),uuid:r.z.boolean().optional(),cuid:r.z.boolean().optional(),cuid2:r.z.boolean().optional(),ulid:r.z.boolean().optional(),datetime:r.z.boolean().optional(),ip:r.z.boolean().optional(),startsWith:r.z.string().optional(),endsWith:r.z.string().optional(),includes:r.z.string().optional(),gt:r.z.number().optional(),gte:r.z.number().optional(),lt:r.z.number().optional(),lte:r.z.number().optional(),int:r.z.boolean().optional(),positive:r.z.boolean().optional(),nonnegative:r.z.boolean().optional(),negative:r.z.boolean().optional(),nonpositive:r.z.boolean().optional(),multipleOf:r.z.number().optional(),finite:r.z.boolean().optional(),safe:r.z.boolean().optional(),nonempty:r.z.boolean().optional(),literal:r.z.union([r.z.string(),r.z.number(),r.z.boolean()]).optional(),enum:r.z.array(r.z.string()).optional(),nullable:r.z.boolean().optional(),nullish:r.z.boolean().optional(),optional:r.z.boolean().optional(),element:r.z.any().optional(),shape:r.z.record(r.z.any()).optional(),strict:r.z.boolean().optional(),passthrough:r.z.boolean().optional(),catchall:r.z.any().optional()})),sp=r.z.object({p:r.z.literal("hcs-12"),op:r.z.literal("register"),t_id:tp,hash:rp,wasm_hash:rp,js_t_id:tp.optional(),js_hash:rp.optional(),interface_version:r.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid version format").optional(),info_t_id:tp.optional(),source_verification:op.optional(),previous_version:r.z.string().optional(),migration_notes:r.z.string().optional(),validation_rules:r.z.record(np).optional(),m:r.z.string().optional()}),ap=r.z.object({p:r.z.literal("hcs-12"),op:r.z.enum(["register","template"]),name:r.z.string(),version:r.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid semver format"),data:r.z.union([r.z.any(),r.z.string()]).optional(),t_id:tp.optional()});r.z.enum(["register","add-action","add-block","update"]);const cp=ep.extend({op:r.z.literal("register"),name:r.z.string(),version:r.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid semver format"),description:r.z.string().optional(),tags:r.z.array(r.z.string()).optional(),author:r.z.string().optional()}),lp=ep.extend({op:r.z.literal("add-action"),t_id:tp,alias:r.z.string(),config:r.z.any().optional(),data:tp.optional()}),dp=ep.extend({op:r.z.literal("add-block"),block_t_id:tp,actions:r.z.record(r.z.string(),tp).optional(),attributes:r.z.record(r.z.any()).optional(),children:r.z.array(r.z.string()).optional(),data:tp.optional()}),up=ep.extend({op:r.z.literal("update"),description:r.z.string().optional(),tags:r.z.array(r.z.string()).optional()});r.z.object({type:r.z.enum(["vertical","horizontal","grid"]),responsive:r.z.boolean().optional(),containerClass:r.z.string().optional()}),r.z.object({source_t_id:tp,source_hash:rp,description:r.z.string().optional()});const pp=r.z.discriminatedUnion("op",[cp,lp,dp,up]),hp=cp,gp=ep.extend({op:r.z.literal("register"),t_id:tp,name:r.z.string().max(100,"Name must be 100 characters or less"),description:r.z.string().max(500,"Description must be 500 characters or less").optional(),tags:r.z.array(r.z.string()).max(10,"Maximum 10 tags allowed").optional(),category:r.z.string().optional(),featured:r.z.boolean().optional(),icon:r.z.string().optional(),author:r.z.string().optional(),website:r.z.string().url().optional()});function mp(e){return sp.parse(e)}function fp(e){return pp.parse(e)}function yp(e,t){const r=t.safeParse(e);return r.success?{isValid:!0,errors:[],data:r.data}:{isValid:!1,errors:r.error.errors.map(e=>`${e.path.join(".")}: ${e.message}`)}}class bp extends Qu{constructor(e,t,r,i){super(e,t,Zu.ACTION,r,i),this.actionsByHash=new Map,this.cryptoAdapter=Xd()}async registerWithWasm(e,t,r){let i,o;if(qd()){i=this.createSSRSafeHash(e,"wasm");const r=JSON.stringify(t);o=this.createSSRSafeHash(globalThis.Buffer.from(r),"info")}else{const r=this.cryptoAdapter.createHash("sha256").update(e).digest("hex"),n=r instanceof Promise?await r:r;i="string"==typeof n?n:n.toString("hex");const s=JSON.stringify(t),a=this.cryptoAdapter.createHash("sha256").update(globalThis.Buffer.from(s)).digest("hex"),c=a instanceof Promise?await a:a;o="string"==typeof c?c:c.toString("hex")}const n=await this.inscribeContent(e,"application/octet-stream",{name:t.name,version:t.version,hash:i,fileType:"wasm"});let s;const a=JSON.stringify(t);globalThis.Buffer.byteLength(a,"utf8")>1024&&(s=await this.inscribeContent(a,"application/json",{name:`${t.name}-info`,version:t.version}));const c={p:"hcs-12",op:"register",t_id:n,hash:o,wasm_hash:i,info_t_id:s,source_verification:r,m:`${t.name} v${t.version}`};return await this.register(c),c}async register(e){if(this.validateRegistration(e),this.topicId&&this.client){this.logger.info("Submitting action registration to HCS",{topicId:this.topicId,hash:e.hash,wasmHash:e.wasm_hash});const t=(await this.client.submitMessage(this.topicId,JSON.stringify(e))).sequenceNumber;if(!t)throw new Error("No sequence number returned from submission");const r={id:t.toString(),sequenceNumber:t,timestamp:(new Date).toISOString(),submitter:"getHashConnect"in this.client?(await this.client.getAccountAndSigner()).accountId:this.client.getOperatorAccountId(),data:e};return this.entries.set(r.id,r),this.actionsByHash.set(e.hash,e),this.logger.info("Action registered",{hash:e.hash,sequenceNumber:t,hasSourceVerification:!!e.source_verification}),t.toString()}{const t=this.entries.size+1,r={id:t.toString(),sequenceNumber:t,timestamp:(new Date).toISOString(),submitter:"local",data:e};return this.entries.set(r.id,r),this.actionsByHash.set(e.hash,e),t.toString()}}async getAction(e){const t=this.actionsByHash.get(e);return t||(this.topicId&&this.client?(await this.sync(),this.actionsByHash.get(e)||null):null)}async getActionByTopicId(e){this.logger.debug("getActionByTopicId called",{topicId:e}),console.log("DEBUG: getActionByTopicId called",{topicId:e,cacheSize:this.actionsByHash.size,cachedTopicIds:Array.from(this.actionsByHash.values()).map(e=>e.t_id)});for(const t of this.actionsByHash.values())if(t.t_id===e)return this.logger.debug("Action found in cache",{topicId:e,action:t}),console.log("DEBUG: Action found in cache",{topicId:e,action:t}),t;if(this.topicId&&this.client){this.logger.debug("Action not in cache, syncing...",{topicId:e}),console.log("DEBUG: Action not in cache, syncing..."),await this.sync(),console.log("DEBUG: After sync",{cacheSize:this.actionsByHash.size,cachedTopicIds:Array.from(this.actionsByHash.values()).map(e=>e.t_id)});for(const t of this.actionsByHash.values())if(t.t_id===e)return this.logger.debug("Action found after sync",{topicId:e,action:t}),console.log("DEBUG: Action found after sync",{topicId:e,action:t}),t}return this.logger.warn("Action not found",{topicId:e}),console.log("DEBUG: Action not found",{topicId:e}),null}async getActionInfo(e){const t=await this.getAction(e);if(!t)return null;try{let e;if(!t.info_t_id)return this.logger.warn("Inline INFO storage not yet implemented"),null;{if(!this.client)return this.logger.error("Client not initialized - cannot fetch INFO"),null;let r;if("getOperatorAccountId"in this.client)r=await Ma(t.info_t_id,{accountId:this.client.getOperatorAccountId(),privateKey:this.client.getOperatorPrivateKey(),network:this.networkType});else{const{accountId:e}=await this.client.getAccountAndSigner();r=await Ma(t.info_t_id,{accountId:e,network:this.networkType})}if(!r.content)return this.logger.error("No content in inscription response"),null;e="string"==typeof r.content?r.content:globalThis.Buffer.from(r.content).toString("utf8")}const r=JSON.parse(e);let i;if(qd())i=this.createSSRSafeHash(globalThis.Buffer.from(e),"info");else{const t=this.cryptoAdapter.createHash("sha256").update(globalThis.Buffer.from(e)).digest("hex"),r=t instanceof Promise?await t:t;i="string"==typeof r?r:r.toString("hex")}if(i!==t.hash)throw this.logger.error("INFO hash mismatch",{expected:t.hash,computed:i}),new Error("Module info verification failed");return r}catch(r){return this.logger.error("Failed to fetch action INFO",{hash:e,error:r}),null}}async getActionWasm(e){const t=await this.getAction(e);if(!t)return null;if(!this.client)return this.logger.error("Client not initialized - cannot fetch WASM"),null;try{let e;if("getOperatorAccountId"in this.client)e=await Ma(t.t_id,{accountId:this.client.getOperatorAccountId(),privateKey:this.client.getOperatorPrivateKey(),network:this.networkType});else{const{accountId:r}=await this.client.getAccountAndSigner();e=await Ma(t.t_id,{accountId:r,network:this.networkType})}if(!e.content)return this.logger.error("No content in inscription response"),null;const r="string"==typeof e.content?globalThis.Buffer.from(e.content,"base64"):globalThis.Buffer.from(e.content);let i;if(qd())i=this.createSSRSafeHash(r,"wasm");else{const e=this.cryptoAdapter.createHash("sha256").update(r).digest("hex"),t=e instanceof Promise?await e:e;i="string"==typeof t?t:t.toString("hex")}if(i!==t.wasm_hash)throw this.logger.error("WASM hash mismatch",{expected:t.wasm_hash,computed:i}),new Error("WASM binary verification failed");return new Uint8Array(r)}catch(r){return this.logger.error("Failed to fetch WASM from HCS-1",{topicId:t.t_id,error:r}),null}}async searchActions(e){return(await this.listEntries({submitter:e.creator,afterTimestamp:e.afterTimestamp,beforeTimestamp:e.beforeTimestamp})).map(e=>e.data).filter(t=>{if(void 0!==e.hasSourceVerification){if(!!t.source_verification!==e.hasSourceVerification)return!1}return!0})}async getVersionChain(e){const t=[];let r=e;for(;r;){const e=await this.getAction(r);if(!e)break;t.push(e),r=void 0}return t}validateRegistration(e){try{mp(e)}catch(t){if(t instanceof r.ZodError){const e=t.errors[0];throw new Error(`Validation failed: ${e.path.join(".")} - ${e.message}`)}throw t}}async sync(){await super.sync(),this.actionsByHash.clear();for(const e of this.entries.values()){const t=e.data;this.actionsByHash.set(t.hash,t)}}clearCache(){super.clearCache(),this.actionsByHash.clear()}createSSRSafeHash(e,t){let r=0;for(let i=0;i<Math.min(e.length,256);i++)r=(r<<5)-r+e[i]&4294967295;return`ssr-${t}-${e.length}-${Math.abs(r).toString(16).padStart(8,"0")}`}}class wp{constructor(e,t,r){this.blockCache=new Map,this.templateCache=new Map,this.networkType=e,this.logger=t,this.client=r}async loadBlockDefinition(e){const t=this.blockCache.get(e);if(t)return t;try{const t=new Kd,r=await t.resolve(e,{network:this.networkType});if(!r.content)throw new Error(`Block definition not found: ${e}`);let i;return i="object"!=typeof r.content||null===r.content||r.content instanceof ArrayBuffer?JSON.parse("string"==typeof r.content?r.content:r.content.toString()):r.content,this.blockCache.set(e,i),i}catch(r){throw this.logger.error("Failed to load block definition",{blockTopicId:e,error:r.message}),new Error(`Failed to load block definition: ${r.message}`)}}async loadBlockTemplate(e){const t=this.templateCache.get(e);if(t)return t;try{const t=new Kd,r=await t.resolve(e,{network:this.networkType});if(!r.content)throw new Error(`Block template not found: ${e}`);let i;return i="string"==typeof r.content?r.content:"object"==typeof r.content&&null!==r.content?r.content.text||JSON.stringify(r.content):r.content.toString(),this.templateCache.set(e,i),i}catch(r){throw this.logger.error("Failed to load block template",{templateTopicId:e,error:r.message}),new Error(`Failed to load block template: ${r.message}`)}}async loadBlock(e){const t=await this.loadBlockDefinition(e);return{definition:t,template:await this.loadBlockTemplate(t.template_t_id)}}async storeBlock(e,t){if(!this.client||!("inscribeFile"in this.client))throw new Error("Client does not support inscription");try{const r=globalThis.Buffer.from(e),i=await this.client.inscribeFile(r,`block-${t.name}-template.html`);if(!i?.topic_id)throw new Error("Failed to inscribe block template");const o={...t,template_t_id:i.topic_id},n=globalThis.Buffer.from(JSON.stringify(o)),s=await this.client.inscribeFile(n,`block-${t.name}-definition.json`);if(!s?.topic_id)throw new Error("Failed to inscribe block definition");return this.blockCache.set(s.topic_id,o),this.templateCache.set(i.topic_id,e),{definitionTopicId:s.topic_id,templateTopicId:i.topic_id}}catch(r){throw this.logger.error("Failed to store block",{error:r.message}),new Error(`Failed to store block: ${r.message}`)}}clearCache(){this.blockCache.clear(),this.templateCache.clear()}}class Ip extends Qu{constructor(e,t,r,i){super(e,t,Zu.ASSEMBLY,r,i),this.assemblyStates=new Map}getTopicMemo(){return`hcs-12:0:60:${this.registryType}`}async register(e){return this.submitMessage(e)}async createAssemblyTopic(){const e=await this.createRegistryTopic();return this.topicId=e,e}async addAction(e){return this.submitMessage(e)}async addBlock(e){return this.submitMessage(e)}async update(e){return this.submitMessage(e)}async submitMessage(e){if(this.validateMessage(e),!this.topicId)throw new Error("Assembly topic ID not found");if(!this.client)throw new Error("Client not found");this.logger.info("Submitting assembly message to HCS",{topicId:this.topicId,op:e.op});const t=(await this.client.submitMessage(this.topicId,JSON.stringify(e))).sequenceNumber;if(!t)throw new Error("No sequence number returned from submission");const r={id:t.toString(),sequenceNumber:t,timestamp:(new Date).toISOString(),submitter:"getHashConnect"in this.client?(await this.client.getAccountAndSigner()).accountId:this.client.getOperatorAccountId(),data:e};return this.entries.set(r.id,r),await this.processMessage(r),this.logger.info("Assembly message processed",{op:e.op,sequenceNumber:t}),t.toString()}async processMessage(e){const t=e.data;if(!this.topicId)return;let r=this.assemblyStates.get(this.topicId);switch(t.op){case"register":const i=t;r={topicId:this.topicId,name:i.name,version:i.version,description:i.description,tags:i.tags,author:i.author,actions:[],blocks:[],created:e.timestamp,updated:e.timestamp},this.assemblyStates.set(this.topicId,r);break;case"add-action":if(!r)return void this.logger.warn("Cannot add action without assembly registration");const o=t,n={t_id:o.t_id,alias:o.alias,config:o.config,data:o.data};r.actions.push(n),r.updated=e.timestamp;break;case"add-block":if(!r)return void this.logger.warn("Cannot add block without assembly registration");const s=t,a={block_t_id:s.block_t_id,actions:s.actions,attributes:s.attributes,children:s.children,data:s.data};r.blocks.push(a),r.updated=e.timestamp;break;case"update":if(!r)return void this.logger.warn("Cannot update without assembly registration");const c=t;void 0!==c.description&&(r.description=c.description),void 0!==c.tags&&(r.tags=c.tags),r.updated=e.timestamp}}async getAssemblyState(e){const t=e||this.topicId;if(!t||!this.client)return null;let r=this.assemblyStates.get(t);if(r)return r;if(t===this.topicId&&this.entries.size>0){this.logger.debug("Building state from existing entries",{topicId:t,entriesCount:this.entries.size}),this.assemblyStates.clear();for(const r of this.entries.values())this.processAssemblyMessage(t,r);const e=this.assemblyStates.get(t)||null;return this.logger.debug("Built state from entries",{topicId:t,hasState:!!e,name:e?.name}),e}this.logger.info("Syncing assembly state from topic",{topicId:t});try{const e=await this.client.mirrorNode.getTopicMessagesByFilter(t,{order:"asc",limit:1e3}),r=Array.isArray(e)?e:[];this.logger.info("Processing assembly messages",{topicId:t,messageCount:r.length});for(const n of r)try{let e;if(!n.message)continue;try{let t;t="undefined"==typeof window?globalThis.Buffer.from(n.message,"base64").toString("utf-8"):(new TextDecoder).decode(Uint8Array.from(atob(n.message),e=>e.charCodeAt(0))),e=JSON.parse(t),this.logger.debug("Successfully parsed message",{sequenceNumber:n.sequence_number,op:e.op,p:e.p})}catch(i){this.logger.debug("Failed to decode/parse message",{sequenceNumber:n.sequence_number,error:i});continue}if("hcs-12"!==e.p){this.logger.debug("Skipping non-HCS-12 message",{sequenceNumber:n.sequence_number,protocol:e.p});continue}const r={id:n.sequence_number.toString(),sequenceNumber:n.sequence_number,timestamp:n.consensus_timestamp||(new Date).toISOString(),submitter:n.payer_account_id||"unknown",data:e};this.processAssemblyMessage(t,r),this.logger.debug("Processed message for assembly",{topicId:t,sequenceNumber:r.sequenceNumber,op:r.data.op})}catch(i){this.logger.warn("Failed to parse assembly message",{sequenceNumber:n.sequence_number,error:i})}const o=this.assemblyStates.get(t)||null;return this.logger.info("Assembly state after sync",{topicId:t,hasState:!!o,name:o?.name,version:o?.version,actionsCount:o?.actions?.length||0,blocksCount:o?.blocks?.length||0}),o}catch(i){return this.logger.error("Failed to sync assembly state",{topicId:t,error:i}),null}}processAssemblyMessage(e,t){const r=t.data;let i=this.assemblyStates.get(e);switch(this.logger.debug("Processing assembly message",{topicId:e,op:r.op,hasState:!!i}),r.op){case"register":const o=r;i={topicId:e,name:o.name,version:o.version,description:o.description,tags:o.tags,author:o.author,actions:[],blocks:[],created:t.timestamp,updated:t.timestamp},this.assemblyStates.set(e,i),this.logger.debug("Assembly registered",{topicId:e,name:o.name,version:o.version});break;case"add-action":if(!i)return void this.logger.warn("Cannot add action without assembly registration");const n=r,s={t_id:n.t_id,alias:n.alias,config:n.config,data:n.data};i.actions.push(s),i.updated=t.timestamp;break;case"add-block":if(!i)return void this.logger.warn("Cannot add block without assembly registration");const a=r,c={block_t_id:a.block_t_id,actions:a.actions,attributes:a.attributes,children:a.children,data:a.data};i.blocks.push(c),i.updated=t.timestamp;break;case"update":if(!i)return void this.logger.warn("Cannot update without assembly registration");const l=r;void 0!==l.description&&(i.description=l.description),void 0!==l.tags&&(i.tags=l.tags),i.updated=t.timestamp}}async sync(){if(this.topicId&&this.client){this.entries.clear(),this.assemblyStates.delete(this.topicId),this.logger.info("Syncing assembly messages",{topicId:this.topicId});try{const t=await this.client.mirrorNode.getTopicMessagesByFilter(this.topicId,{order:"asc",limit:1e3}),r=Array.isArray(t)?t:[];this.logger.info("Processing assembly messages",{topicId:this.topicId,messageCount:r.length});for(const i of r)try{let t;if(i.message)try{let e;e="undefined"==typeof window?globalThis.Buffer.from(i.message,"base64").toString("utf-8"):(new TextDecoder).decode(Uint8Array.from(atob(i.message),e=>e.charCodeAt(0))),t=JSON.parse(e)}catch(e){this.logger.debug("Failed to decode/parse message in sync",{sequenceNumber:i.sequence_number,error:e});continue}else if(i.raw_content)try{t=JSON.parse(i.raw_content)}catch{continue}else{const e=i;if(!e.p||!e.op)continue;t={...e},delete t.consensus_timestamp,delete t.sequence_number,delete t.payer_account_id,delete t.topic_id,delete t.running_hash,delete t.running_hash_version,delete t.chunk_info,delete t.created,delete t.payer}if("hcs-12"!==t.p)continue;const r={id:i.sequence_number.toString(),sequenceNumber:i.sequence_number,timestamp:i.consensus_timestamp||(new Date).toISOString(),submitter:i.payer_account_id||"unknown",data:t};this.entries.set(r.id,r),await this.processMessage(r),this.logger.debug("Processed sync message",{sequenceNumber:r.sequenceNumber,op:r.data.op})}catch(e){this.logger.warn("Failed to parse assembly message",{sequenceNumber:i.sequence_number,error:e})}this.logger.info("Assembly sync completed",{topicId:this.topicId,messageCount:r.length})}catch(e){throw this.logger.error("Failed to sync assembly",{error:e}),e}}else this.logger.warn("Cannot sync without topic ID and client")}validateMessage(e){try{fp(e)}catch(t){if(t instanceof r.ZodError){const e=t.errors.map(e=>`${e.path.join(".")}: ${e.message}`);throw new Error(`Assembly validation failed: ${e.join("; ")}`)}throw t}}}class Tp extends Qu{constructor(e,t,r,i){super(e,t,Zu.HASHLINKS,r,i)}async register(e){this.validateRegistration(e);const t=`${this.topicId||"local"}_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,r={id:t,sequenceNumber:0,timestamp:(new Date).toISOString(),submitter:this.client&&"getHashConnect"in this.client?"browser":this.client?.getOperatorAccountId()||"local",data:e};if(this.entries.set(t,r),this.client&&this.topicId)try{const i=JSON.stringify(e),o=await this.client.submitMessage(this.topicId,i);return o.sequenceNumber&&(r.sequenceNumber=o.sequenceNumber,r.id=o.sequenceNumber.toString(),this.entries.delete(t),this.entries.set(r.id,r)),this.logger.info("HashLink submitted to HCS",{transactionId:o.transactionId,sequenceNumber:o.sequenceNumber,topicId:this.topicId}),r.id}catch(i){throw this.logger.error("Failed to submit HashLink to HCS",{error:i}),this.entries.delete(t),i}return this.logger.info("HashLink registered in directory",{id:t,name:e.name,assemblyTopicId:e.t_id,tags:e.tags}),t}async searchByTags(e){return(await this.listEntries()).map(e=>e.data).filter(t=>!(!t.tags||0===t.tags.length)&&e.some(e=>t.tags?.includes(e)))}async searchByName(e){const t=await this.listEntries(),r=e.toLowerCase();return t.map(e=>e.data).filter(e=>e.name.toLowerCase().includes(r)||(e.description?.toLowerCase().includes(r)??!1))}async getFeatured(){return(await this.listEntries()).map(e=>e.data).filter(e=>!0===e.featured)}async getByCategory(e){return(await this.listEntries()).map(e=>e.data).filter(t=>t.category===e)}async getCategories(){const e=await this.listEntries(),t=new Set;return e.forEach(e=>{const r=e.data;r.category&&t.add(r.category)}),Array.from(t).sort()}async getAllTags(){const e=await this.listEntries(),t=new Set;return e.forEach(e=>{const r=e.data;r.tags&&r.tags.forEach(e=>t.add(e))}),Array.from(t).sort()}validateRegistration(e){this.validateBaseRegistration(e);const t=yp(e,gp);if(!t.isValid)throw new Error(`HashLinks validation failed: ${t.errors.join(", ")}`);if(!e.t_id||!e.t_id.match(/^\d+\.\d+\.\d+$/))throw new Error("Valid assembly topic ID (t_id) is required");if(e.tags&&e.tags.length>10)throw new Error("Maximum 10 tags allowed");if(e.name.length>100)throw new Error("Name must be 100 characters or less");if(e.description&&e.description.length>500)throw new Error("Description must be 500 characters or less")}getStats(){const e=super.getStats(),t=Array.from(this.entries.values()),r=new Set,i=new Set;let o=0;return t.forEach(e=>{const t=e.data;t.category&&r.add(t.category),t.tags&&t.tags.forEach(e=>i.add(e)),t.featured&&o++}),{...e,categories:r.size,totalTags:i.size,featuredCount:o}}}class Sp{constructor(e,t,r,i){this.cache=new Map,this.logger=e,this.assemblyRegistry=t,this.actionRegistry=r,this.blockLoader=i}async loadAssembly(e){this.logger.debug("Loading assembly",{topicId:e});const t=this.cache.get(e);if(t)return this.logger.debug("Assembly loaded from cache",{topicId:e}),t;try{const t=await this.assemblyRegistry.getAssemblyState(e);if(!t)throw new Error(`Assembly not found: ${e}`);const r={topicId:e,state:t,actions:[],blocks:[]};return this.cache.set(e,r),this.logger.debug("Assembly loaded successfully",{topicId:e,name:t.name,version:t.version,actionsCount:t.actions?.length||0,blocksCount:t.blocks?.length||0}),r}catch(r){throw this.logger.error("Failed to load assembly",{topicId:e,error:r}),new Error(`Failed to load assembly: ${r instanceof Error?r.message:"Unknown error"}`)}}async resolveReferences(e){this.logger.debug("Resolving assembly references",{name:e.name});const t={topicId:e.topicId,state:e,actions:[],blocks:[]};if(e.actions)for(const i of e.actions)try{const e=await this.resolveActionReference(i);t.actions.push({alias:i.alias,t_id:i.t_id,definition:e,config:i.config})}catch(r){this.logger.warn("Failed to resolve action reference",{t_id:i.t_id,alias:i.alias,error:r}),t.actions.push({alias:i.alias,t_id:i.t_id,definition:null,config:i.config,error:r instanceof Error?r.message:"Unknown error"})}if(e.blocks)for(const i of e.blocks)try{const{definition:e,template:r}=await this.resolveBlockReference(i);t.blocks.push({block_t_id:i.block_t_id,definition:e,template:r,attributes:i.attributes,actions:i.actions,children:i.children})}catch(r){this.logger.warn("Failed to resolve block reference",{block_t_id:i.block_t_id,error:r}),t.blocks.push({block_t_id:i.block_t_id,definition:null,attributes:i.attributes,actions:i.actions,children:i.children,error:r instanceof Error?r.message:"Unknown error"})}return t}validateComposition(e){const t=[];if(this.logger.debug("Validating assembly composition",{topicId:e.topicId}),e.state.name||t.push("Assembly must have a name"),e.state.version||t.push("Assembly must have a version"),e.state.blocks)for(const r of e.state.blocks){if(r.actions)for(const[i,o]of Object.entries(r.actions)){const n=e.state.actions?.some(e=>e.t_id===o);n||t.push(`Block ${r.block_t_id} references non-existent action: ${o} for key ${i}`)}if(r.children)for(const i of r.children){const o=e.state.blocks?.some(e=>e.block_t_id===i);o||t.push(`Block ${r.block_t_id} references non-existent child block: ${i}`)}}for(const r of e.actions)r.error&&t.push(`Action ${r.alias} has resolution error: ${r.error}`);for(const r of e.blocks)r.error&&t.push(`Block ${r.block_t_id} has resolution error: ${r.error}`);return{valid:0===t.length,errors:t}}async loadAndResolveAssembly(e){this.logger.debug("Loading and resolving assembly",{topicId:e});try{const t=await this.loadAssembly(e),r=await this.resolveReferences(t.state),i=this.validateComposition(r);return i.valid||this.logger.warn("Assembly validation failed",{topicId:e,errors:i.errors}),r}catch(t){throw this.logger.error("Failed to load and resolve assembly",{topicId:e,error:t}),new Error(`Failed to load and resolve assembly: ${t instanceof Error?t.message:"Unknown error"}`)}}async resolveActionReference(e){const t=await this.actionRegistry.getActionByTopicId(e.t_id);if(!t)throw new Error(`Action not found at topic: ${e.t_id}`);return t}async resolveBlockReference(e){return await this.blockLoader.loadBlock(e.block_t_id)}clearCache(){this.cache.clear(),this.logger.debug("Assembly cache cleared")}getCachedAssembly(e){return this.cache.get(e)}isAssemblyCached(e){return this.cache.has(e)}}class kp{constructor(e){this.network=e.network,this.logger=e.logger||O.getInstance({level:e.logLevel||"info",module:"HCS12-BaseClient",prettyPrint:e.prettyPrint,silent:e.silent}),this.mirrorNode=new V(e.network,this.logger,e.mirrorNode)}initializeRegistries(e){this.actionRegistryTopicId=e?.action,this._assemblyRegistryTopicId=e?.assembly,this._hashLinksRegistryTopicId=e?.hashlinks}async registerAssembly(e){if(!this._assemblyRegistry)throw new Error("Assembly registry not initialized");return{id:await this._assemblyRegistry.register(e)}}async getAction(e){if(!this._actionRegistry)throw new Error("Action registry not initialized");return this._actionRegistry.getAction(e)}async loadBlock(e){return this._blockLoader||(this._blockLoader=new wp(this.network,this.logger,this)),this._blockLoader.loadBlock(e)}async getAssembly(e,t){if(!this._assemblyRegistry)throw new Error("Assembly registry not initialized");const r=await this._assemblyRegistry.listEntries();for(const i of r){const r=await this._assemblyRegistry.getAssemblyState(i.id);if(r&&r.name===e&&r.version===t)return r}return null}async loadAssembly(e){this._actionRegistry&&(this.logger.info("Syncing action registry before loading assembly"),await this._actionRegistry.sync());const t=new Ip(this.network,this.logger,e,this);await t.sync();return new Sp(this.logger,t,this._actionRegistry,this._blockLoader).loadAndResolveAssembly(e)}async getAssemblyState(e){if(!this._assemblyRegistry)throw new Error("Assembly registry not initialized");return this._assemblyRegistry.getAssemblyState(e)}ensureAssemblyEngine(){if(!this._assemblyEngine){if(!this._actionRegistry||!this._blockLoader||!this._assemblyRegistry)throw new Error("Registries must be initialized before assembly engine");this._assemblyEngine=new Sp(this.logger,this._assemblyRegistry,this._actionRegistry,this._blockLoader)}}async registerHashLink(e){if(!this._hashLinksRegistry)throw new Error("HashLinks registry not initialized");return{id:await this._hashLinksRegistry.register(e)}}async searchHashLinksByTags(e){if(!this._hashLinksRegistry)throw new Error("HashLinks registry not initialized");return this._hashLinksRegistry.searchByTags(e)}async searchHashLinksByName(e){if(!this._hashLinksRegistry)throw new Error("HashLinks registry not initialized");return this._hashLinksRegistry.searchByName(e)}async getFeaturedHashLinks(){if(!this._hashLinksRegistry)throw new Error("HashLinks registry not initialized");return this._hashLinksRegistry.getFeatured()}async getHashLinksByCategory(e){if(!this._hashLinksRegistry)throw new Error("HashLinks registry not initialized");return this._hashLinksRegistry.getByCategory(e)}async syncRegistries(){const e=[];this._actionRegistry&&e.push(this._actionRegistry.sync()),this._assemblyRegistry&&e.push(this._assemblyRegistry.sync()),this._hashLinksRegistry&&e.push(this._hashLinksRegistry.sync()),await Promise.all(e)}getRegistryTopicIds(){return{action:this.actionRegistryTopicId,assembly:this._assemblyRegistryTopicId,hashlinks:this._hashLinksRegistryTopicId}}clearCaches(){this._actionRegistry?.clearCache(),this._blockLoader?.clearCache(),this._assemblyRegistry?.clearCache(),this._hashLinksRegistry?.clearCache()}get actionRegistry(){return this._actionRegistry}get blockLoader(){return this._blockLoader}get assemblyRegistry(){return this._assemblyRegistry}get hashLinksRegistry(){return this._hashLinksRegistry}}class Ep{constructor(){this.block={apiVersion:3},this.attributes={},this.supports={},this.actions={},this.logger=new O({module:"BlockBuilder"})}setName(e){return this.block.name=e,this}setTitle(e){return this.block.title=e,this}setDescription(e){return this.block.description=e,this}setCategory(e){return this.block.category=e,this}setIcon(e){return this.block.icon=e,this}setKeywords(e){return this.block.keywords=e,this}setApiVersion(e){return this.block.apiVersion=e,this}addAttribute(e,t,r,i){const o={type:t,default:r};return i?.enum&&(o.enum=i.enum),i?.source&&(o.source=i.source),i?.selector&&(o.selector=i.selector),i?.attribute&&(o.attribute=i.attribute),this.attributes[e]=o,this}setTemplateTopicId(e){return this.block.template_t_id=e,this}setTemplate(e){return this.templateBuffer=e,this}setActions(e){return this.actions=e,this}addAction(e,t){return this.actions[e]=t,this}addSupport(e,t=!0){return this.supports[e]=t,this}enableCommonSupports(){return this.supports={...this.supports,align:!0,anchor:!0,className:!0,spacing:{margin:!0,padding:!0}},this}build(){if(!this.block.name)throw new Error("Block name is required");if(!this.block.title)throw new Error("Block title is required");if(!this.block.category)throw new Error("Block category is required");if(!this.block.template_t_id)throw new Error("Block template_t_id is required");return{apiVersion:this.block.apiVersion||3,name:this.block.name,title:this.block.title,category:this.block.category,template_t_id:this.block.template_t_id,icon:this.block.icon,description:this.block.description,keywords:this.block.keywords,attributes:this.attributes,supports:this.supports}}static createDisplayBlock(e,t){return(new Ep).setName(e).setTitle(t).setCategory("formatting").enableCommonSupports()}static createInteractiveBlock(e,t){return(new Ep).setName(e).setTitle(t).setCategory("widgets").enableCommonSupports()}static createWidgetBlock(e,t){return this.createInteractiveBlock(e,t)}static createContainerBlock(e,t){return(new Ep).setName(e).setTitle(t).setCategory("design").enableCommonSupports().addSupport("html",!1)}getTemplate(){return this.templateBuffer}getActions(){return this.actions}setTopicId(e){return this.blockTopicId=e,this}getTopicId(){if(!this.blockTopicId)throw new Error("Block topic ID not set");return this.blockTopicId}getName(){return this.block.name}}class vp{constructor(e,t){this.wasmCache=new Map,this.logger=e,this.network=t,this.hrlResolver=new Kd}async execute(e,t){try{if(this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Executing WASM action",{actionId:e.t_id,method:t.method,hasJavaScript:!!e.js_t_id}),e.js_t_id)return await this.executeJavaScript(e,t);throw new Error("Raw WASM execution is not supported for wasm-bindgen modules. JavaScript wrapper is required.")}catch(r){return this.logger&&"function"==typeof this.logger.error?this.logger.error("WASM execution failed",{actionId:e.t_id,error:r.message}):console.error("WASM execution failed",{actionId:e.t_id,error:r.message}),{success:!1,error:r.message}}}readWasmString(e,t){const r=new Uint8Array(e.buffer);let i=0;for(;0!==r[t+i];)i++;return(new TextDecoder).decode(r.slice(t,t+i))}async executeJavaScript(e,t){try{if(this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Loading JavaScript wrapper",{jsTopicId:e.js_t_id}),"undefined"==typeof window){this.logger&&"function"==typeof this.logger.info&&this.logger.info("Executing JavaScript wrapper in Node.js environment");const t=await this.hrlResolver.resolve(e.js_t_id,{network:this.network,returnRaw:!1});if(!t.content||"string"!=typeof t.content)throw new Error("Failed to load JavaScript module: invalid content");await this.hrlResolver.resolve(e.t_id,{network:this.network,returnRaw:!0}),global,globalThis,WebAssembly,console,queueMicrotask,TextDecoder,TextEncoder,void 0!==globalThis.FinalizationRegistry&&globalThis.FinalizationRegistry,URL;throw new Error("WASM execution in Node.js/SSR environment is not supported. This functionality is browser-only.")}{const r=await this.hrlResolver.resolve(e.js_t_id,{network:this.network,returnRaw:!1});if(!r.content||"string"!=typeof r.content)throw new Error("Failed to load JavaScript module: invalid content");const i=new Blob([r.content],{type:"application/javascript"}),o=URL.createObjectURL(i);try{this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Importing JavaScript module from blob URL");const r=new Function("url","return import(url)"),i=await r(o);if(this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Module imported, exports:",Object.keys(i)),!i.default&&!i.init)throw new Error("No init function found in JavaScript module");{const t=i.default||i.init;this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Loading WASM bytes from topic:",e.t_id);const r=await this.hrlResolver.resolve(e.t_id,{network:this.network,returnRaw:!0});if(this.logger&&"function"==typeof this.logger.debug){const e=r.content instanceof ArrayBuffer?r.content.byteLength:r.content.length;this.logger.debug("WASM bytes loaded, size:",e)}await t({module_or_path:r.content}),this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("WASM module initialized successfully")}const n=i.WasmInterface;if(!n)throw new Error("WasmInterface not found in module exports. Available exports: "+Object.keys(i).join(", "));this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Creating WasmInterface instance");const s=new n;let a,c;if("POST"===t.method&&s.POST){const e=t.params.operation||"default",r={...t.params,...t.state},i=JSON.stringify(r);this.logger&&"function"==typeof this.logger.debug?this.logger.debug("Calling POST method",{actionName:e,paramsJson:i,allParams:r}):console.log("WASM POST params:",{actionName:e,paramsJson:i,allParams:r}),a=await s.POST(e,i,this.network.toString(),"")}else if("GET"===t.method&&s.GET){const e=t.params.operation||"default",r=JSON.stringify(t.params);this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Calling GET method",{actionName:e,paramsJson:r}),a=await s.GET(e,r,this.network.toString())}else{if("INFO"!==t.method||!s.INFO)throw new Error(`Method ${t.method} not supported by WASM module`);this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Calling INFO method"),a=s.INFO()}try{c=JSON.parse(a)}catch{c={value:a}}return s.free&&s.free(),URL.revokeObjectURL(o),{success:!0,data:c}}catch($g){throw URL.revokeObjectURL(o),$g}}}catch(r){const t=r instanceof Error?r.message:String(r),i=r instanceof Error?r.stack:void 0;return this.logger&&"function"==typeof this.logger.error?this.logger.error("JavaScript execution failed",{jsTopicId:e.js_t_id,error:t,stack:i,fullError:r}):console.error("JavaScript execution failed",{jsTopicId:e.js_t_id,error:t,stack:i,fullError:r}),{success:!1,error:t||"Unknown error"}}}clearCache(){this.wasmCache.clear()}}class Ap{constructor(e){this.logger=e}async scanTemplate(e){const t=[],r=/<([^>]+)\s+data-hashlink=["']([^"']+)["']([^>]*)>/gs;let i;for(;null!==(i=r.exec(e));){const e=i[0],r=i[1].split(/\s+/)[0],n=i[2],s=i[3];try{const i=this.parseHashLinkURI(n),o=s.match(/data-attributes=(['"])((?:(?!\1).)*)\1/s);let a;if(o)try{const e=o[2];a=JSON.parse(e)}catch($g){this.logger.warn("Failed to parse data-attributes",{uri:n,attributes:o[2],error:$g.message})}const c=s.match(/data-actions=(['"])((?:(?!\1).)*)\1/s);let l;if(c)try{const e=c[2];l=JSON.parse(e)}catch($g){this.logger.warn("Failed to parse data-actions",{uri:n,actions:c[2],error:$g.message})}const d=s.match(/data-loading=['"]([^'"]+)['"]/),u=d?.[1]||"eager";t.push({element:r,uri:n,...i,attributes:a,actions:l,loading:u,placeholder:e}),this.logger.debug("Found HashLink reference",{uri:n,parsed:i})}catch(o){this.logger.error("Failed to parse HashLink URI",{uri:n,error:o.message})}}return t}parseHashLinkURI(e){const t=e.match(/^hcs:\/\/(\d+)\/(.+)$/);if(!t)throw new Error(`Invalid HashLink URI format: ${e}`);const r=t[1],i=t[2];if("2"===r){const e=i.split("/");if(2!==e.length)throw new Error(`Invalid HCS-2 reference format: ${i}`);return{protocol:r,reference:i,registryId:e[0],entryName:e[1]}}return{protocol:r,reference:i}}createPlaceholder(e,t){return`\x3c!-- HASHLINK_PLACEHOLDER_${t}_${e.uri.replace(/[^a-zA-Z0-9]/g,"_")} --\x3e`}}class Cp{constructor(e,t,r,i){this.logger=e,this.blockLoader=t,this.hrlResolver=r,this.network=i,this.cache=new Map,this.renderStack=new Set}async resolveReference(e,t){this.logger.debug("Resolving HashLink reference",{uri:e.uri,protocol:e.protocol});try{switch(e.protocol){case"12":return await this.resolveHCS12Block(e,t);case"1":return await this.resolveHCS1Block(e,t);case"2":return await this.resolveHCS2Block(e,t);default:throw new Error(`Unsupported HashLink protocol: ${e.protocol}`)}}catch(r){return this.logger.error("Failed to resolve HashLink",{uri:e.uri,error:r.message}),{blockId:e.reference,definition:null,template:null,attributes:{},actions:{},error:r.message}}}async resolveHCS12Block(e,t){const r=e.reference;if(this.renderStack.has(r))return{blockId:r,definition:null,template:null,attributes:{},actions:{},error:"Circular reference detected"};const i=this.getCacheKey(r,e.attributes,e.actions);if(this.cache.has(i))return this.cache.get(i);try{const o=await this.blockLoader.loadBlock(r);if(!o||!o.definition)throw new Error(`Block not found: ${r}`);const n={...this.extractDefaults(o.definition),...t.attributes,...e.attributes},s={...t.actions,...e.actions},a={blockId:r,definition:o.definition,template:o.template,attributes:n,actions:s};return this.cache.set(i,a),a}catch(o){throw this.renderStack.delete(r),new Error(`Failed to load HCS-12 block ${r}: ${o.message}`)}}async resolveHCS1Block(e,t){const r=e.reference;try{const t=await this.blockLoader.loadBlock(r);if(t&&t.definition)return{blockId:r,definition:t.definition,template:t.template,attributes:{...this.extractDefaults(t.definition),...e.attributes},actions:e.actions||{}};return{blockId:r,definition:null,template:(await this.hrlResolver.resolve(r,{network:this.network})).content,attributes:e.attributes||{},actions:e.actions||{}}}catch(i){throw new Error(`Failed to load HCS-1 content ${r}: ${i.message}`)}}async resolveHCS2Block(e,t){if(!e.registryId||!e.entryName)throw new Error("Invalid HCS-2 reference: missing registry ID or entry name");try{const t=`hcs://2/${e.registryId}`;await this.hrlResolver.resolve(t,{network:this.network});return this.logger.warn("HCS-2 registry lookup not fully implemented",{registryId:e.registryId,entryName:e.entryName}),{blockId:`${e.registryId}/${e.entryName}`,definition:null,template:`\x3c!-- HCS-2 lookup not implemented: ${e.uri} --\x3e`,attributes:e.attributes||{},actions:e.actions||{}}}catch(r){throw new Error(`Failed to resolve HCS-2 entry: ${r.message}`)}}extractDefaults(e){const t={};return e.attributes&&Object.entries(e.attributes).forEach(([e,r])=>{r&&"object"==typeof r&&"default"in r&&(t[e]=r.default)}),t}getCacheKey(e,t,r){return`${e}:${t?JSON.stringify(t):""}:${r?JSON.stringify(r):""}`}pushRenderStack(e){this.renderStack.add(e)}popRenderStack(e){this.renderStack.delete(e)}clearCache(){this.cache.clear()}}const xp={ACTIONS:{CALCULATOR:"0.0.TBD1",NFT_MINT:"0.0.TBD2",TOKEN_TRANSFER:"0.0.TBD3"},BLOCKS:{BUTTON:"0.0.TBD4",NFT_GALLERY:"0.0.TBD5",FORM:"0.0.TBD6"},ASSEMBLIES:{NFT_MARKETPLACE:"0.0.TBD7",TOKEN_DASHBOARD:"0.0.TBD8"}},Rp={ACTIONS:{},BLOCKS:{},ASSEMBLIES:{}};const Np=/^[a-z0-9][a-z0-9-]*$/,_p=r.z.object({registry:r.z.string().min(1),name:r.z.string().min(1),version:r.z.string().min(1),protocol:r.z.string().min(1),nativeId:r.z.string().min(1),skills:r.z.array(r.z.number().int().nonnegative())});function Pp(e){return e.trim()}function Fp(e){return e.trim().toLowerCase()}function zp(e){const t=_p.parse(e);if("hcs-10"===t.protocol.trim().toLowerCase()&&!tu(t.nativeId.trim()))throw new Error("HCS-14: For protocol hcs-10, nativeId must be CAIP-10 (hedera:<network>:<account>)");if("acp-virtuals"===t.protocol.trim().toLowerCase()&&!nu(t.nativeId.trim()))throw new Error("HCS-14: For protocol acp-virtuals, nativeId must be EIP-155 CAIP-10 (eip155:<chainId>:<address>)");const r={registry:Fp(t.registry),name:Pp(t.name),version:Pp(t.version),protocol:Fp(t.protocol),nativeId:Pp(t.nativeId),skills:[...t.skills].sort((e,t)=>e-t)},i=["skills","name","nativeId","protocol","registry","version"],o={};for(const n of i)o[n]=r[n];return{normalized:r,canonicalJson:JSON.stringify(o)}}const Op="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function Dp(e){if(0===e.length)return"";let t=0;for(;t<e.length&&0===e[t];)t++;if(t===e.length)return"1".repeat(t);const r=[0];for(let o=t;o<e.length;o++){let t=e[o];for(let e=0;e<r.length;e++){const i=(r[e]<<8)+t;r[e]=i%58,t=i/58|0}for(;t>0;)r.push(t%58),t=t/58|0}let i="";for(let o=0;o<t;o++)i+="1";for(let o=r.length-1;o>=0;o--)i+=Op[r[o]];return i}function Mp(e){if(!e.startsWith("z"))throw new Error("Invalid multibase base58btc");return function(e){if(0===e.length)return new Uint8Array(0);let t=0;for(;t<e.length&&"1"===e[t];)t++;const r=[];for(let i=t;i<e.length;i++){const t=e[i],o=Op.indexOf(t);if(-1===o)throw new Error("Invalid Base58 character");let n=o;for(let e=0;e<r.length;e++){const t=58*r[e]+n;r[e]=255&t,n=t>>8}for(;n>0;)r.push(255&n),n>>=8}for(let i=0;i<t;i++)r.push(0);return r.reverse(),Uint8Array.from(r)}(e.slice(1))}function Bp(e){const t=[];return e.uid&&t.push(["uid",e.uid]),e.registry&&t.push(["registry",e.registry]),e.proto&&t.push(["proto",e.proto]),e.nativeId&&t.push(["nativeId",e.nativeId]),e.domain&&t.push(["domain",e.domain]),e.src&&t.push(["src",e.src]),0===t.length?"":t.map(([e,t])=>`${e}=${t}`).join(";")}function Kp(e,t){let r,i;if(e.startsWith("uaid:aid:"))r="aid",i=e.slice(9);else{if(!e.startsWith("did:"))throw new Error("Invalid DID format");{const t=e.indexOf(":"),o=e.indexOf(":",t+1);if(o<0)throw new Error("Invalid DID format");r=e.slice(t+1,o),i=e.slice(o+1)}}const{sanitized:o,hadSuffix:n}=function(e){const t=e.search(/[;?#]/);return-1===t?{sanitized:e,hadSuffix:!1}:{sanitized:e.slice(0,t),hadSuffix:!0}}(i);let s=o;if("hedera"===r){const e=o.match(/^(mainnet|testnet|previewnet|devnet):(.+)$/);e&&(s=e[2])}const a={...t||{}};var c;n&&!a.src&&(a.src=(c=e,"z"+Dp(globalThis.Buffer.from(c,"utf8"))));const l=Bp(a);return l?`uaid:did:${s};${l}`:`uaid:did:${s}`}function Up(e,t,r){return"string"==typeof e?Kp(e,t):async function(e,t,r){const{normalized:i,canonicalJson:o}=zp(e),n=Xd().createHash("sha384").update(globalThis.Buffer.from(o,"utf8")).digest(),s=await Promise.resolve(n),a=Dp(globalThis.Buffer.isBuffer(s)?s:globalThis.Buffer.from(s)),c=!1!==r?.includeParams,l=c?function(e,t){const r={...t};return r.registry||(r.registry=e.registry),r.nativeId||(r.nativeId=e.nativeId),r.uid||(r.uid="0"),r}(i,t||{}):{},d=c?Bp(l):"";return d?`uaid:aid:${a};${d}`:`uaid:aid:${a}`}(e,t,r)}function Lp(e){if(e.startsWith("uaid:")){const t=e.slice(5);let r,i;if(t.startsWith("did:"))r="did",i=t.slice(4);else{if(!t.startsWith("aid:"))throw new Error("Invalid UAID");r="aid",i=t.slice(4)}const o=i.indexOf(";"),n=o>=0?i.slice(0,o):i,s=(e=>{const t={};if(!e)return t;const r=e.split(";");for(const i of r){const e=i.indexOf("=");if(e>0){const r=i.slice(0,e),o=i.slice(e+1);t[r]=o}}return t})(o>=0?i.slice(o+1):"");return{method:"did"===r?"uaid":"aid",id:n,params:s}}throw new Error("Invalid DID")}const $p=["@hiero-did-sdk","resolver"].join("/");let Hp=null;class qp{constructor(){this.meta={id:"hedera/hiero-resolver",didMethods:["hedera"],caip2Networks:["hedera:mainnet","hedera:testnet","hedera:previewnet","hedera:devnet"],caip10Namespaces:["hedera"],displayName:"Hedera (Hiero Resolver)",description:"Resolves did:hedera identifiers via Hiero DID resolver.",homepage:"https://github.com/hiero-ledger/hiero-did-sdk-js"}}supports(e){return e.startsWith("did:hedera:")}async resolve(e){const t=await async function(){return Hp||(Hp=Xl($p).then(e=>e?.resolveDID??null)),Hp}();if(!t)throw new Error("Hiero resolver unavailable. Ensure @hiero-did-sdk/resolver is installed.");const r=await t(e);return r&&"string"==typeof r.id?{id:r.id}:null}}class jp{constructor(){this.resolvers=[]}register(e){this.resolvers.push(e)}list(){return[...this.resolvers]}filterByDidMethod(e){return this.resolvers.filter(t=>t.meta?.didMethods?.includes(e))}async resolveDid(e){for(const t of this.resolvers)if(t.supports(e))return t.resolve(e);return null}async resolveUaid(e){const t=Lp(e);if("uaid"!==t.method)return null;const r=t.params.src;if(r){const e=globalThis.Buffer.from(Mp(r)).toString("utf8");return this.resolveDid(e)}const i=t.id;if(i.startsWith("testnet:")||i.startsWith("mainnet:")||i.startsWith("previewnet:")||i.startsWith("devnet:")){const e=`did:hedera:${i}`;return this.resolveDid(e)}const o=t.params.proto,n=t.params.nativeId;if("hcs-10"===o&&n){const e=n.match(/^hedera:(mainnet|testnet|previewnet|devnet):/);if(e){const t=`did:hedera:${e[1]}:${i}`;return this.resolveDid(t)}}return null}}const Wp=new jp;function Vp(){Wp.register(new qp)}class Gp{constructor(){this.issuers=[]}register(e){this.issuers.push(e)}list(){return[...this.issuers]}filterByDidMethod(e){return this.issuers.filter(t=>t.meta.didMethods.includes(e))}filterByCaip2(e){return this.issuers.filter(t=>t.meta.caip2Networks?.includes(e))}filter(e){return this.issuers.filter(e)}async issue(e){for(const t of this.issuers)if(t.supports(e.method))return t.issue(e);throw new Error(`No issuer registered for method: ${e.method}`)}}const Jp=new Gp,Yp=["@hiero-did-sdk","registrar"].join("/");let Xp=null;class Zp{constructor(){this.meta={id:"hedera/hiero",didMethods:["hedera"],caip2Networks:["hedera:mainnet","hedera:testnet","hedera:previewnet","hedera:devnet"],caip10Namespaces:["hedera"],displayName:"Hedera (Hiero Registrar)",description:"Issues did:hedera identifiers using the Hiero DID registrar.",homepage:"https://github.com/hiero-ledger/hiero-did-sdk-js"}}supports(e){return"hedera"===e}async issue(e){if("hedera"!==e.method)throw new Error('HederaHieroIssuer only handles method "hedera"');if(!("client"in e))throw new Error("Hedera client is required to issue did:hedera");const t=await async function(){return Xp||(Xp=Xl(Yp).then(e=>e?.createDID??null)),Xp}();if(!t)throw new Error("Hiero registrar unavailable. Ensure @hiero-did-sdk/registrar is installed.");return(await t({},{client:e.client})).did}}class Qp{constructor(e){this.registry=e?.registry??Wp,this.issuers=new Gp,this.registerHederaIssuer(),this.registerHederaResolver(),this.logger=O.getInstance({module:"HCS-14"}),this.client=e?.client,this.network=e?.network,this.operatorId=e?.operatorId,!this.client&&e?.network&&e?.operatorId&&e?.privateKey&&this.configureHederaClient(e.network,e.operatorId,e.privateKey),e?.privateKey&&(this.operatorPrivateKey=e.privateKey),e?.hcs10Client&&(this.hcs10Client=e.hcs10Client)}configureHederaClient(e,t,r){const o=ie({network:e,operatorId:t,operatorKey:r,mirrorNode:new V(e),logger:this.logger,client:i.Client.forName(e)});this.operatorCtx=o,this.client=o.client,this.network=e,this.operatorId=t,this.operatorPrivateKey=r}async ensureInitializedHedera(){this.operatorCtx&&(await this.operatorCtx.ensureInitialized(),this.operatorId||(this.operatorId=this.operatorCtx.operatorId.toString()),this.operatorPrivateKey||(this.operatorPrivateKey=this.operatorCtx.operatorKey.toString()),this.client||(this.client=this.operatorCtx.client))}getIssuerRegistry(){return this.issuers}listIssuers(){return this.issuers.list()}listResolvers(){return this.registry.list()}filterIssuersByMethod(e){return this.issuers.filterByDidMethod(e)}filterResolversByMethod(e){return this.registry.filterByDidMethod(e)}registerHederaIssuer(){this.issuers.register(new Zp)}async createDid(e){return this.issuers.issue(e)}canonicalizeAgentData(e){return zp(e)}createUaid(e,t,r){return"string"==typeof e?Up(e,t):Up(e,t,r)}parseHcs14Did(e){return Lp(e)}isHederaNetwork(e){return Qd(e)}isHederaCaip10(e){return tu(e)}toHederaCaip10(e,t){return ru(e,t)}parseHederaCaip10(e){return iu(e)}isEip155Caip10(e){return nu(e)}toEip155Caip10(e,t){return su(e,t)}getResolverRegistry(){return this.registry}registerHederaResolver(){this.registry.register(new qp)}async createDidWithUaid(e){const t=await this.createDid(e.issue);let r=e.uid;const i=e.proto;let o=e.nativeId;if("hedera"===e.issue.method){if(await this.ensureInitializedHedera(),!o){if(!this.network||!this.operatorId)throw new Error("nativeId not provided and network/operatorId are not configured");o=ru(this.network,this.operatorId)}if(!r&&"hcs-10"===i&&this.network&&this.operatorId)try{if(!this.hcs10Client&&this.operatorPrivateKey&&(this.hcs10Client=new Yu({network:this.network,operatorId:this.operatorId,operatorPrivateKey:this.operatorPrivateKey,silent:!0})),this.hcs10Client)r=await this.hcs10Client.getOperatorId();else{const e=new Ru({network:this.network,auth:{operatorId:this.operatorId},silent:!0}),t=await e.fetchProfileByAccountId(this.operatorId,this.network),i=t?.topicInfo?.inboundTopic;r=i?`${i}@${this.operatorId}`:this.operatorId}}catch{r=this.operatorId}}r=r??"0";const n=this.createUaid(t,{uid:r,proto:i,nativeId:o});return{did:t,uaid:n,parsed:Lp(n)}}}const eh=Object.freeze(Object.defineProperty({__proto__:null,CanonicalAgentDataSchema:_p,HCS14Client:Qp,HCS14_PROTOCOL_REGEX:Np,HederaHieroIssuer:Zp,HieroDidResolver:qp,IssuerRegistry:Gp,ResolverRegistry:jp,canonicalizeAgentData:zp,createUaid:Up,defaultIssuerRegistry:Jp,defaultResolverRegistry:Wp,isEip155Caip10:nu,isHederaCaip10:tu,isHederaNetwork:Qd,parseHcs14Did:Lp,parseHederaCaip10:iu,registerDefaultResolvers:Vp,toEip155Caip10:su,toHederaCaip10:ru},Symbol.toStringTag,{value:"Module"}));function th(e){return`hcs://1/${e}`}class rh{constructor(e){this.network=e.network,this.logger=e.logger||O.getInstance({level:e.logLevel||"info",module:"HCS5Client",silent:e.silent}),this.mirrorNode=new V(this.network,this.logger)}}function ih(e){const t=(new i.TokenMintTransaction).setTokenId(i.TokenId.fromString(e.tokenId)).setMetadata([globalThis.Buffer.from(e.metadata)]);return e.transactionMemo&&t.setTransactionMemo(e.transactionMemo),t}var oh=(e=>(e.REGISTER="register",e.UPDATE="update",e.DELETE="delete",e.MIGRATE="migrate",e))(oh||{}),nh=(e=>(e[e.INDEXED=0]="INDEXED",e[e.NON_INDEXED=1]="NON_INDEXED",e))(nh||{});const sh=r.z.string().regex(/^\d+\.\d+\.\d+$/,{message:"Topic ID must be in Hedera format (e.g., '0.0.123456')"}),ah=r.z.object({p:r.z.string().regex(/^hcs-\d+$/,{message:"Protocol must be in format 'hcs-N' where N is a number"}),op:r.z.enum(["register","update","delete","migrate"]),m:r.z.string().max(500,"Memo must not exceed 500 characters").optional(),ttl:r.z.number().int().positive().optional()}),ch=ah.extend({op:r.z.literal("register"),t_id:sh,metadata:r.z.string().optional()}),lh=ah.extend({op:r.z.literal("update"),uid:r.z.string(),t_id:sh,metadata:r.z.string().optional()}),dh=ah.extend({op:r.z.literal("delete"),uid:r.z.string()}),uh=ah.extend({op:r.z.literal("migrate"),t_id:sh,metadata:r.z.string().optional()}),ph=r.z.discriminatedUnion("op",[ch,lh,dh,uh]);class hh{constructor(e){this.network=e.network,this.logger=e.logger||O.getInstance({level:e.logLevel||"info",module:"HCS2Client",silent:e.silent}),this.mirrorNode=new V(this.network,this.logger,e.mirrorNodeUrl?{customUrl:e.mirrorNodeUrl}:void 0)}parseRegistryTypeFromMemo(e){try{const t=/hcs-2:(\d):(\d+)/,r=e.match(t);if(r&&3===r.length){const e=parseInt(r[1]),t=parseInt(r[2]);if(void 0!==e&&!isNaN(t))return{registryType:e,ttl:t}}return}catch(t){return void this.logger.error(`Error parsing registry type from memo: ${t}`)}}generateRegistryMemo(e,t){return`hcs-2:${e}:${t}`}validateMessage(e){try{return ph.parse(e),{valid:!0,errors:[]}}catch(t){const e=[];return t instanceof r.ZodError?t.errors.forEach(t=>{const r=t.path.join(".");e.push(`${r?r+": ":""}${t.message}`)}):e.push(`Unexpected error: ${t}`),this.logger.debug(`Message validation failed: ${e.join(", ")}`),{valid:!1,errors:e}}}createRegisterMessage(e,t,r,i="hcs-2"){return{p:i,op:oh.REGISTER,t_id:e,metadata:t,m:r}}createUpdateMessage(e,t,r,i,o="hcs-2"){return{p:o,op:oh.UPDATE,t_id:e,uid:t,metadata:r,m:i}}createDeleteMessage(e,t,r="hcs-2"){return{p:r,op:oh.DELETE,uid:e,m:t}}createMigrateMessage(e,t,r,i="hcs-2"){return{p:i,op:oh.MIGRATE,t_id:e,metadata:t,m:r}}parseRegistryEntries(e,t,r,i){const o=[];let n;this.logger.debug(`Parsing ${t.length} messages for topic ${e}`);for(const a of t)try{if(!a.message){this.logger.debug(`Message is missing 'message' property: ${JSON.stringify(a)}`);continue}const t=globalThis.Buffer.from(a.message,"base64").toString("utf-8"),i=JSON.parse(t);this.logger.debug(`Successfully parsed message: ${JSON.stringify(i)}`);const{valid:s,errors:c}=this.validateMessage(i);if(!s){this.logger.warn(`Invalid HCS-2 message: ${c.join(", ")}`);continue}const l={topicId:e,sequence:a.sequence_number,timestamp:a.consensus_timestamp,payer:a.payer_account_id,message:i,consensus_timestamp:a.consensus_timestamp,registry_type:r};o.push(l),(r===nh.NON_INDEXED||!n||l.timestamp>n.timestamp)&&(n=l)}catch(s){this.logger.warn(`Error parsing message: ${s}`)}return this.logger.debug(`Parsed ${o.length} valid entries for topic ${e}`),{topicId:e,registryType:r,ttl:i,entries:r===nh.INDEXED?o:n?[n]:[],latestEntry:n}}}function gh(e){var t,r;return J({memo:e.memoOverride??(t=e.registryType,r=e.ttl,`hcs-2:${t}:${r}`),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function mh(e){const t={p:"hcs-2",op:oh.REGISTER,t_id:e.targetTopicId,metadata:e.metadata,m:e.memo};return Y({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})}const fh=class e extends hh{constructor(e){super({network:e.network,logLevel:e.logLevel,silent:e.silent,mirrorNodeUrl:e.mirrorNodeUrl,logger:e.logger}),this.registryTypeCache=new Map,this.operatorId="string"==typeof e.operatorId?i.AccountId.fromString(e.operatorId):e.operatorId,this.operatorCtx=ie({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:this.createClient(e.network)}),this.client=this.operatorCtx.client}async ensureInitialized(){await this.operatorCtx.ensureInitialized()}createClient(e){return"mainnet"===e?i.Client.forMainnet():i.Client.forTestnet()}async createRegistry(e={}){try{await this.ensureInitialized();const t=e.registryType??nh.INDEXED,r=e.ttl??86400;this.generateRegistryMemo(t,r);let o,n,s,a;if(e.adminKey)if("string"==typeof e.adminKey)try{n=i.PublicKey.fromString(e.adminKey)}catch{const t=globalThis.Buffer.from(e.adminKey.replace(/^0x/i,""),"hex");n="ed25519"===this.operatorCtx.keyType?i.PublicKey.fromBytesED25519(t):i.PublicKey.fromBytesECDSA(t)}else"boolean"==typeof e.adminKey?n=this.operatorCtx.operatorKey.publicKey:(n=e.adminKey.publicKey,o=e.adminKey);if(e.submitKey)if("string"==typeof e.submitKey)try{a=i.PublicKey.fromString(e.submitKey)}catch{const t=globalThis.Buffer.from(e.submitKey.replace(/^0x/i,""),"hex");a="ed25519"===this.operatorCtx.keyType?i.PublicKey.fromBytesED25519(t):i.PublicKey.fromBytesECDSA(t)}else"boolean"==typeof e.submitKey?a=this.operatorCtx.operatorKey.publicKey:(a=e.submitKey.publicKey,s=e.submitKey);const c=gh({registryType:t,ttl:r,adminKey:n,submitKey:a,operatorPublicKey:this.operatorCtx.operatorKey.publicKey}),l=await c.freezeWith(this.client);o&&await l.sign(o),s&&await l.sign(s);const d=await l.execute(this.client),u=(await d.getReceipt(this.client)).topicId;if(!u)throw new Error("Failed to create registry: No topic ID in receipt");const p=u.toString();return this.registryTypeCache.set(p,t),this.logger.info(`Created registry topic: ${p} (${t===nh.INDEXED?"Indexed":"Non-indexed"}, TTL: ${r}s)`),{success:!0,topicId:p,transactionId:d.transactionId.toString()}}catch(t){return this.logger.error(`Failed to create registry: ${t}`),{success:!1,error:`Failed to create registry: ${t}`}}}async registerEntry(e,t,r="hcs-2"){try{await this.ensureInitialized();const i=this.createRegisterMessage(t.targetTopicId,t.metadata,t.memo,r),o=t.registryType??await this.resolveRegistryType(e);this.registryTypeCache.set(e,o);const n=t.analyticsMemo??this.buildAnalyticsMemo(oh.REGISTER,o),s=await this.submitMessage(e,i,n);return this.logger.info(`Registered entry in registry ${e} pointing to topic ${t.targetTopicId} using protocol ${r}`),{success:!0,receipt:s,sequenceNumber:s.topicSequenceNumber?.low??void 0}}catch(i){return this.logger.error(`Failed to register entry: ${i}`),{success:!1,error:`Failed to register entry: ${i}`}}}async updateEntry(e,t){try{await this.ensureInitialized();const r=await this.mirrorNode.getTopicInfo(e),i=this.parseRegistryTypeFromMemo(r.memo);if(!i||i.registryType!==nh.INDEXED)throw new Error("Update operation is only valid for indexed registries");const o=this.createUpdateMessage(t.targetTopicId,t.uid,t.metadata,t.memo),n=t.registryType??await this.resolveRegistryType(e);this.registryTypeCache.set(e,n);const s=t.analyticsMemo??this.buildAnalyticsMemo(oh.UPDATE,n),a=await this.submitMessage(e,o,s);return this.logger.info(`Updated entry with UID ${t.uid} in registry ${e}`),{success:!0,receipt:a,sequenceNumber:a.topicSequenceNumber?.low??void 0}}catch(r){throw this.logger.error(`Failed to update entry: ${r}`),r}}async deleteEntry(e,t){try{await this.ensureInitialized();const r=await this.mirrorNode.getTopicInfo(e),i=this.parseRegistryTypeFromMemo(r.memo);if(!i||i.registryType!==nh.INDEXED)throw new Error("Delete operation is only valid for indexed registries");const o=this.createDeleteMessage(t.uid,t.memo),n=t.registryType??await this.resolveRegistryType(e);this.registryTypeCache.set(e,n);const s=t.analyticsMemo??this.buildAnalyticsMemo(oh.DELETE,n),a=await this.submitMessage(e,o,s);return this.logger.info(`Deleted entry with UID ${t.uid} from registry ${e}`),{success:!0,receipt:a,sequenceNumber:a.topicSequenceNumber?.low??void 0}}catch(r){throw this.logger.error(`Failed to delete entry: ${r}`),r}}async migrateRegistry(e,t){try{await this.ensureInitialized();const r=this.createMigrateMessage(t.targetTopicId,t.metadata,t.memo),i=t.registryType??await this.resolveRegistryType(e);this.registryTypeCache.set(e,i);const o=t.analyticsMemo??this.buildAnalyticsMemo(oh.MIGRATE,i),n=await this.submitMessage(e,r,o);return this.logger.info(`Migrated registry ${e} to ${t.targetTopicId}`),{success:!0,receipt:n,sequenceNumber:n.topicSequenceNumber?.low??void 0}}catch(r){throw this.logger.error(`Failed to migrate registry: ${r}`),r}}async getRegistry(e,t={}){try{await this.ensureInitialized();const i=await this.mirrorNode.getTopicInfo(e);this.logger.debug(`Retrieved topic info for ${e}: ${JSON.stringify(i)}`);const o=this.parseRegistryTypeFromMemo(i.memo);if(!o)throw new Error(`Topic ${e} is not an HCS-2 registry (invalid memo format)`);this.logger.debug(`Retrieving messages for topic ${e} with limit ${t.limit??100}`);const n=await this.mirrorNode.getTopicMessages(e,{sequenceNumber:t.skip&&t.skip>0?`gt:${t.skip}`:void 0,limit:t.limit??100,order:t.order??"asc"}),s=t.limit?n.slice(0,t.limit):n;this.logger.debug(`Retrieved ${n.length} messages, using ${s.length} after applying limit.`);const a=[];let c;for(const t of s)try{const r={p:"hcs-2",op:t.op,t_id:t.t_id,uid:t.uid,metadata:t.metadata,m:t.m},{valid:i,errors:n}=this.validateMessage(r);if(!i){this.logger.warn(`Invalid HCS-2 message: ${n.join(", ")}`);continue}const s={topicId:e,sequence:t.sequence_number,timestamp:t.consensus_timestamp,payer:t.payer_account_id||t.payer||"",message:r,consensus_timestamp:t.consensus_timestamp,registry_type:o.registryType};a.push(s),(o.registryType===nh.NON_INDEXED||!c||s.timestamp>c.timestamp)&&(c=s)}catch(r){this.logger.warn(`Error processing message: ${r}`)}this.logger.debug(`Processed ${a.length} valid entries for registry ${e}`);return{topicId:e,registryType:o.registryType,ttl:o.ttl,entries:o.registryType===nh.INDEXED?a:c?[c]:[],latestEntry:c}}catch(r){throw this.logger.error(`Failed to get registry: ${r}`),r}}buildAnalyticsMemo(t,r){return`hcs-2:op:${e.operationAnalyticsCode[t]}:${r}`}async resolveRegistryType(e){const t=this.registryTypeCache.get(e);if(void 0!==t)return t;const r=await this.mirrorNode.getTopicInfo(e),i=this.parseRegistryTypeFromMemo(r.memo);if(!i)throw new Error(`Topic ${e} is not an HCS-2 registry (invalid memo format)`);return this.registryTypeCache.set(e,i.registryType),i.registryType}async submitMessage(e,t,r){try{await this.ensureInitialized();const{valid:i,errors:o}=this.validateMessage(t);if(!i)throw new Error(`Invalid HCS-2 message: ${o.join(", ")}`);const n=Y({topicId:e,message:JSON.stringify(t),transactionMemo:r}),s=await n.execute(this.client);return await s.getReceipt(this.client)}catch(i){throw this.logger.error(`Failed to submit message: ${i}`),i}}async getTopicInfo(e){return this.mirrorNode.getTopicInfo(e)}close(){this.logger.info("HCS-2 client closed.")}getKeyType(){return this.operatorCtx.keyType}getOperatorKey(){return this.operatorCtx.operatorKey}};fh.operationAnalyticsCode={[oh.REGISTER]:0,[oh.UPDATE]:1,[oh.DELETE]:2,[oh.MIGRATE]:3};let yh=fh;class bh extends hh{constructor(e){super({network:e.network,logLevel:e.logLevel,silent:e.silent,mirrorNodeUrl:e.mirrorNodeUrl,logger:e.logger}),this.hwc=e.hwc,va?this.logger.info("HCS-2 browser client initialized successfully"):this.logger.error("BrowserHCS2Client initialized in server environment - browser-specific features will not be available. Use HCS2Client instead.")}getOperatorId(){const e=this.hwc.getAccountInfo();if(!e||!e.accountId)throw new Error("No connected account found");return e.accountId}async createRegistry(e={}){try{const t=e.registryType??nh.INDEXED,r=e.ttl??86400,o=this.generateRegistryMemo(t,r);let n=(new i.TopicCreateTransaction).setTopicMemo(o);if(e.adminKey){let t;if("string"==typeof e.adminKey)try{t=i.PublicKey.fromString(e.adminKey)}catch{const r=ee.detect(e.adminKey);if(!r.rawBytes)throw new Error("Failed to parse admin public key");t="ed25519"===r.type?i.PublicKey.fromBytesED25519(r.rawBytes):i.PublicKey.fromBytesECDSA(r.rawBytes)}else t="boolean"==typeof e.adminKey?await this.mirrorNode.getPublicKey(this.getOperatorId()):e.adminKey.publicKey;n=n.setAdminKey(t)}if(e.submitKey){let t;if("string"==typeof e.submitKey)try{t=i.PublicKey.fromString(e.submitKey)}catch{const r=ee.detect(e.submitKey);if(!r.rawBytes)throw new Error("Failed to parse submit public key");t="ed25519"===r.type?i.PublicKey.fromBytesED25519(r.rawBytes):i.PublicKey.fromBytesECDSA(r.rawBytes)}else t="boolean"==typeof e.submitKey?await this.mirrorNode.getPublicKey(this.getOperatorId()):e.submitKey.publicKey;n=n.setSubmitKey(t)}const s=await this.executeWithWallet(n);if(s?.error)throw new Error(s.error);const a=s?.result;if(!a?.topicId)throw new Error("Failed to create registry: No topic ID in receipt");const c=a.topicId.toString();return this.logger.info(`Created registry topic: ${c} (${t===nh.INDEXED?"Indexed":"Non-indexed"}, TTL: ${r}s)`),{success:!0,topicId:c,transactionId:s.transactionId||"unknown"}}catch(t){return this.logger.error(`Failed to create registry: ${t}`),{success:!1,error:`Failed to create registry: ${t}`}}}async registerEntry(e,t){try{const r=this.createRegisterMessage(t.targetTopicId,t.metadata,t.memo);if(r.op!==oh.REGISTER)throw new Error(`Invalid operation type: ${r.op}, expected ${oh.REGISTER}`);const i=await this.submitMessage(e,r);return this.logger.info(`Registered entry in registry ${e} pointing to topic ${t.targetTopicId}`),{success:!0,receipt:i,sequenceNumber:i.topicSequenceNumber?.low??void 0}}catch(r){return this.logger.error(`Failed to register entry: ${r}`),{success:!1,error:`Failed to register entry: ${r}`}}}async updateEntry(e,t){try{const r=await this.mirrorNode.getTopicInfo(e),i=this.parseRegistryTypeFromMemo(r.memo);if(!i||i.registryType!==nh.INDEXED)throw new Error("Update operation is only valid for indexed registries");const o=this.createUpdateMessage(t.targetTopicId,t.uid,t.metadata,t.memo),n=await this.submitMessage(e,o);return this.logger.info(`Updated entry with UID ${t.uid} in registry ${e}`),{success:!0,receipt:n,sequenceNumber:n.topicSequenceNumber?.low??void 0}}catch(r){return this.logger.error(`Failed to update entry: ${r}`),{success:!1,error:`Failed to update entry: ${r}`}}}async deleteEntry(e,t){try{const r=await this.mirrorNode.getTopicInfo(e),i=this.parseRegistryTypeFromMemo(r.memo);if(!i||i.registryType!==nh.INDEXED)throw new Error("Delete operation is only valid for indexed registries");const o=this.createDeleteMessage(t.uid,t.memo),n=await this.submitMessage(e,o);return this.logger.info(`Deleted entry with UID ${t.uid} from registry ${e}`),{success:!0,receipt:n,sequenceNumber:n.topicSequenceNumber?.low??void 0}}catch(r){return this.logger.error(`Failed to delete entry: ${r}`),{success:!1,error:`Failed to delete entry: ${r}`}}}async migrateRegistry(e,t){try{const r=this.createMigrateMessage(t.targetTopicId,t.metadata,t.memo),i=await this.submitMessage(e,r);return this.logger.info(`Migrated registry ${e} to ${t.targetTopicId}`),{success:!0,receipt:i,sequenceNumber:i.topicSequenceNumber?.low??void 0}}catch(r){return this.logger.error(`Failed to migrate registry: ${r}`),{success:!1,error:`Failed to migrate registry: ${r}`}}}async getRegistry(e,t={}){try{const r=await this.mirrorNode.getTopicInfo(e),i=this.parseRegistryTypeFromMemo(r.memo);if(!i)throw new Error(`Topic ${e} is not an HCS-2 registry (invalid memo format)`);const o=await this.mirrorNode.getTopicMessages(e,{sequenceNumber:t.skip&&t.skip>0?`gt:${t.skip}`:void 0,limit:t.limit??100,order:t.order??"asc"}),n=t.limit?o.slice(0,t.limit):o;return this.parseRegistryEntries(e,n,i.registryType,i.ttl)}catch(r){throw this.logger.error(`Failed to get registry: ${r}`),r}}async submitMessage(e,t){try{const{valid:r,errors:i}=this.validateMessage(t);if(!r)throw new Error(`Invalid HCS-2 message: ${i.join(", ")}`);const o=Y({topicId:e,message:JSON.stringify(t)}),n=await this.executeWithWallet(o);if(n?.error)throw new Error(n.error);return n.result}catch(r){throw this.logger.error(`Failed to submit message: ${r}`),r}}async executeWithWallet(e){const t=this.hwc.executeTransactionWithErrorHandling;if(!t)throw new Error("Wallet SDK does not support executeTransactionWithErrorHandling");return await t.call(this.hwc,e,!1)}}const wh={PROTOCOL:"hcs-20",PUBLIC_TOPIC_ID:"0.0.4350190",REGISTRY_TOPIC_ID:"0.0.4362300",MAX_NUMBER_LENGTH:18,MAX_NAME_LENGTH:100,MAX_METADATA_LENGTH:100,HEDERA_ACCOUNT_REGEX:/^(0|(?:[1-9]\d*))\.(0|(?:[1-9]\d*))\.(0|(?:[1-9]\d*))$/},Ih=r.z.string().regex(wh.HEDERA_ACCOUNT_REGEX,"Invalid Hedera account ID format"),Th=r.z.string().regex(/^\d+$/,"Must be a valid number").max(wh.MAX_NUMBER_LENGTH,`Max ${wh.MAX_NUMBER_LENGTH} digits`),Sh=r.z.string().min(1,"Tick cannot be empty").transform(e=>e.toLowerCase().trim()),kh=r.z.object({p:r.z.literal("hcs-20"),m:r.z.string().optional()}),Eh=kh.extend({op:r.z.literal("deploy"),name:r.z.string().min(1).max(wh.MAX_NAME_LENGTH),tick:Sh,max:Th,lim:Th.optional(),metadata:r.z.string().max(wh.MAX_METADATA_LENGTH).optional()}),vh=kh.extend({op:r.z.literal("mint"),tick:Sh,amt:Th,to:Ih}),Ah=kh.extend({op:r.z.literal("burn"),tick:Sh,amt:Th,from:Ih}),Ch=kh.extend({op:r.z.literal("transfer"),tick:Sh,amt:Th,from:Ih,to:Ih}),xh=kh.extend({op:r.z.literal("register"),name:r.z.string().min(1).max(wh.MAX_NAME_LENGTH),metadata:r.z.string().max(wh.MAX_METADATA_LENGTH).optional(),private:r.z.boolean(),t_id:Ih}),Rh=r.z.discriminatedUnion("op",[Eh,vh,Ah,Ch,xh]);class Nh extends Error{constructor(e){super(e),this.name="HCS20Error"}}class _h extends Nh{constructor(e,t){super(e),this.tick=t,this.name="PointsDeploymentError"}}class Ph extends Nh{constructor(e,t,r,i,o,n){super(e),this.tick=t,this.from=r,this.to=i,this.amount=o,this.availableBalance=n,this.name="PointsTransferError"}}class Fh extends Nh{constructor(e,t,r,i,o){super(e),this.tick=t,this.from=r,this.amount=i,this.availableBalance=o,this.name="PointsBurnError"}}class zh extends Nh{constructor(e,t){super(e),this.validationErrors=t,this.name="PointsValidationError"}}class Oh extends Nh{constructor(e,t){super(e),this.topicId=t,this.name="TopicRegistrationError"}}class Dh extends Nh{constructor(e){super(`Invalid Hedera account format: ${e}`),this.account=e,this.name="InvalidAccountFormatError"}}class Mh{constructor(e){this.logger=e.logger||new O({module:"HCS20Client"}),this.network="mainnet"===e.network?"mainnet":"testnet",this.mirrorNode=new V(this.network,this.logger,e.mirrorNodeUrl?{customUrl:e.mirrorNodeUrl}:void 0),this.registryTopicId=e.registryTopicId||wh.REGISTRY_TOPIC_ID,this.publicTopicId=e.publicTopicId||wh.PUBLIC_TOPIC_ID}validateMessage(e){try{return Rh.parse(e),{valid:!0}}catch(t){if(t.errors){return{valid:!1,errors:t.errors.map(e=>`${e.path.join(".")}: ${e.message}`)}}return{valid:!1,errors:[t.message]}}}normalizeTick(e){return e.toLowerCase().trim()}accountToString(e){if("string"==typeof e){if(!wh.HEDERA_ACCOUNT_REGEX.test(e))throw new Dh(e);return e}return e.toString()}topicToString(e){if("string"==typeof e){if(!wh.HEDERA_ACCOUNT_REGEX.test(e))throw new Dh(e);return e}return e.toString()}}function Bh(e){const t={p:"hcs-20",op:"deploy",name:e.name,tick:e.tick.toLowerCase().trim(),max:e.max,lim:e.lim,metadata:e.metadata,m:e.memo};return Y({topicId:e.topicId,message:JSON.stringify(t)})}function Kh(e){const t={p:"hcs-20",op:"mint",tick:e.tick.toLowerCase().trim(),amt:e.amt,to:e.to,m:e.memo};return Y({topicId:e.topicId,message:JSON.stringify(t)})}function Uh(e){const t={p:"hcs-20",op:"transfer",tick:e.tick.toLowerCase().trim(),amt:e.amt,from:e.from,to:e.to,m:e.memo};return Y({topicId:e.topicId,message:JSON.stringify(t)})}function Lh(e){const t={p:"hcs-20",op:"burn",tick:e.tick.toLowerCase().trim(),amt:e.amt,from:e.from,m:e.memo};return Y({topicId:e.topicId,message:JSON.stringify(t)})}function $h(e){const t={p:"hcs-20",op:"register",name:e.name,metadata:e.metadata,private:e.isPrivate,t_id:e.topicId,m:e.memo};return Y({topicId:e.registryTopicId,message:JSON.stringify(t)})}class Hh extends Error{constructor(e,t){super(e),this.code=t,this.name="HCS21ValidationError"}}function qh(e){const t=e.indexed??0,r=e.type??pc.ADAPTER_REGISTRY;if(e.metaTopicId&&!uc.test(e.metaTopicId))throw new Hh("Meta value must be a short pointer (topic ID, HRL, IPFS, Arweave, OCI, or HTTPS)","invalid_payload");const i=e.metaTopicId?`:${e.metaTopicId}`:"";return`hcs-21:${t}:${e.ttl}:${r}${i}`}function jh(e){return J({memo:qh({ttl:e.ttl,indexed:e.indexed,type:e.type,metaTopicId:e.metaTopicId}),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function Wh(e){const t=JSON.stringify(e.declaration),r=globalThis.Buffer.byteLength(t,"utf8");if(r>lc)throw new Hh(`HCS-21 payload exceeds safe limit of 1000 bytes (${r}); Hedera cap is 1024`,"size_exceeded");return Y({topicId:e.topicId,message:JSON.stringify(e.declaration),transactionMemo:e.transactionMemo})}class Vh{constructor(e){this.network=e.network,this.logger=e.logger||new O({level:"info",module:"HCS-21"}),this.mirrorNode=new V(this.network,this.logger,{customUrl:e.mirrorNodeUrl})}buildDeclaration(e){const t={p:ac,op:e.op,adapter_id:e.adapterId,entity:e.entity,package:e.adapterPackage,manifest:e.manifest,...e.manifestSequence?{manifest_sequence:e.manifestSequence}:{},config:e.config,state_model:e.stateModel,signature:e.signature};return this.validateDeclaration(t)}validateDeclaration(e){try{const t="string"==typeof e?JSON.parse(e):e,r=mc.parse(t);return this.assertSizeLimit(r),r}catch(t){const e=t instanceof Error?t.message:"Invalid adapter declaration";throw new Hh(e,"invalid_payload")}}async fetchDeclarations(e,t){const r=await this.mirrorNode.getTopicMessages(e,{limit:t?.limit,order:t?.order}),i=[];for(const n of r)if(n.p===ac)try{const e=this.validateDeclaration(n);i.push({declaration:e,consensusTimestamp:n.consensus_timestamp,sequenceNumber:n.sequence_number,payer:n.payer})}catch(o){const e=o instanceof Error?o.message:"unknown error";this.logger.warn(`Skipping invalid HCS-21 message: ${e}`)}return i}async fetchCategoryEntries(e){const t=await this.mirrorNode.getTopicMessages(e),r=[];for(const i of t){if("hcs-2"!==i.p||"register"!==i.op)continue;if(!i.t_id||"string"!=typeof i.t_id)continue;const e="string"==typeof i.m?i.m:void 0,t=e?.startsWith("adapter:")?e.slice(8):e;r.push({adapterId:t??i.t_id,adapterTopicId:i.t_id,metadata:i.metadata,memo:e,payer:i.payer,sequenceNumber:Number(i.sequence_number??0),consensusTimestamp:i.consensus_timestamp})}return r}assertSizeLimit(e){const t=JSON.stringify(e),r=globalThis.Buffer.byteLength(t,"utf8");if(r>lc)throw new Hh(`HCS-21 payload exceeds safe limit of 1000 bytes (${r}); Hedera cap is 1024`,"size_exceeded")}}function Gh(e){if(Array.isArray(e))return e.map(Gh);if(e&&"object"==typeof e){const t=Object.entries(e).sort(([e],[t])=>e<t?-1:e>t?1:0),r={};for(const[e,i]of t)r[e]=Gh(i);return r}return e}function Jh(e){const t=Gh(e);return JSON.stringify(t)}function Yh(e){const t=(new i.AccountCreateTransaction).setECDSAKeyWithAlias(e.publicKey).setInitialBalance(e.initialBalance instanceof i.Hbar?e.initialBalance:new i.Hbar(e.initialBalance??1));return"number"==typeof e.maxAutomaticTokenAssociations&&t.setMaxAutomaticTokenAssociations(e.maxAutomaticTokenAssociations),e.accountMemo&&t.setAccountMemo(e.accountMemo),t}function Xh(e){const t=(new i.AccountCreateTransaction).setKeyWithoutAlias(e.publicKey).setInitialBalance(e.initialBalance instanceof i.Hbar?e.initialBalance:new i.Hbar(e.initialBalance??1));return"number"==typeof e.maxAutomaticTokenAssociations&&t.setMaxAutomaticTokenAssociations(e.maxAutomaticTokenAssociations),e.accountMemo&&t.setAccountMemo(e.accountMemo),t}class Zh{constructor(e){this.network=e.network,this.logger=e.logger||new O({module:"HCS-15",level:e.logLevel||"info"}),this.mirrorNode=new V(this.network,this.logger,{customUrl:e.mirrorNodeUrl})}async verifyPetalAccount(e,t){try{const r=await this.mirrorNode.requestAccount(e),i=await this.mirrorNode.requestAccount(t),o=r?.key?.key||"";return""!==o&&o===(i?.key?.key||"")}catch($g){return this.logger.warn("verifyPetalAccount failed",{error:String($g)}),!1}}}var Qh=(e=>(e[e.COMMUNICATION=0]="COMMUNICATION",e[e.TRANSACTION=1]="TRANSACTION",e[e.STATE=2]="STATE",e))(Qh||{}),eg=(e=>(e.FLORA_CREATED="flora_created",e.TRANSACTION="transaction",e.STATE_UPDATE="state_update",e.FLORA_JOIN_REQUEST="flora_join_request",e.FLORA_JOIN_VOTE="flora_join_vote",e.FLORA_JOIN_ACCEPTED="flora_join_accepted",e))(eg||{});class tg extends Error{constructor(e,t){super(e),this.code=t,this.name="FloraError"}}function rg(e){const t=function(e){return`hcs-16:${e.floraAccountId}:${e.topicType}`}({floraAccountId:e.floraAccountId,topicType:e.topicType}),r=J({memo:t,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey});return e.autoRenewAccountId&&r.setAutoRenewAccountId(i.AccountId.fromString(e.autoRenewAccountId)),r}function ig(e){const t=(new i.AccountCreateTransaction).setKey(e.keyList),r="number"==typeof e.initialBalanceHbar?e.initialBalanceHbar:1;t.setInitialBalance(new i.Hbar(r));const o="number"==typeof e.maxAutomaticTokenAssociations?e.maxAutomaticTokenAssociations:-1;return t.setMaxAutomaticTokenAssociations(o),t}function og(e){const t={p:"hcs-16",op:e.op,operator_id:e.operatorId,...e.body||{}};return Y({topicId:e.topicId,message:JSON.stringify(t)})}function ng(e){return og({topicId:e.topicId,operatorId:e.operatorId,op:eg.FLORA_CREATED,body:{flora_account_id:e.floraAccountId,topics:e.topics}})}function sg(e){return og({topicId:e.topicId,operatorId:e.operatorId,op:eg.TRANSACTION,body:{schedule_id:e.scheduleId,data:e.data,m:e.data}})}function ag(e){return og({topicId:e.topicId,operatorId:e.operatorId,op:eg.STATE_UPDATE,body:{hash:e.hash,epoch:e.epoch,timestamp:(new Date).toISOString()}})}function cg(e){return og({topicId:e.topicId,operatorId:e.operatorId,op:eg.FLORA_JOIN_REQUEST,body:{candidate_account_id:e.candidateAccountId}})}function lg(e){return og({topicId:e.topicId,operatorId:e.operatorId,op:eg.FLORA_JOIN_VOTE,body:{candidate_account_id:e.candidateAccountId,approve:e.approve}})}function dg(e){return og({topicId:e.topicId,operatorId:e.operatorId,op:eg.FLORA_JOIN_ACCEPTED,body:{members:e.members,epoch:e.epoch}})}class ug{constructor(e){this.network=e.network,this.logger=e.logger||new O({level:"info",module:"HCS-16"}),this.mirrorNode=new V(this.network,this.logger,{customUrl:e.mirrorNodeUrl})}async assembleKeyList(e){const t=[];for(const r of e.members){const e=await this.mirrorNode.getPublicKey(r);t.push(e)}return new i.KeyList(t,e.threshold)}async assembleSubmitKeyList(e){const t=[];for(const r of e){const e=await this.mirrorNode.getPublicKey(r);t.push(e)}return new i.KeyList(t,1)}buildFloraTopicCreateTxs(e){return{communication:rg({floraAccountId:e.floraAccountId,topicType:Qh.COMMUNICATION,adminKey:e.keyList,submitKey:e.submitList,autoRenewAccountId:e.autoRenewAccountId}),transaction:rg({floraAccountId:e.floraAccountId,topicType:Qh.TRANSACTION,adminKey:e.keyList,submitKey:e.submitList,autoRenewAccountId:e.autoRenewAccountId}),state:rg({floraAccountId:e.floraAccountId,topicType:Qh.STATE,adminKey:e.keyList,submitKey:e.submitList,autoRenewAccountId:e.autoRenewAccountId})}}parseTopicMemo(e){const t=e.match(/^hcs-16:([0-9.]+):(\d)$/);if(!t)return null;const r=t[1],i=Number(t[2]);return i!==Qh.COMMUNICATION&&i!==Qh.TRANSACTION&&i!==Qh.STATE?null:{protocol:"hcs-16",floraAccountId:r,topicType:i}}createFloraMessage(e,t,r){return{p:"hcs-16",op:e,operator_id:t,...r||{}}}async getRecentMessages(e,t){const r=t?.limit??25,i=t?.order??"desc",o=await this.mirrorNode.getTopicMessages(e,{limit:r,order:i}),n=[];for(const s of o){if("hcs-16"!==s.p)continue;const{consensus_timestamp:e,sequence_number:r,running_hash:i,running_hash_version:o,topic_id:a,payer:c,created:l,chunk_info:d,...u}=s,p=u.op,h=u.operator_id;if(t?.opFilter&&p!==t.opFilter)continue;if("string"!=typeof h)continue;const g=u;n.push({message:g,consensus_timestamp:e,sequence_number:Number(r),payer:c})}return n}async getLatestMessage(e,t){const r=await this.getRecentMessages(e,{limit:1,order:"desc",opFilter:t});if(0===r.length)return null;const i=r[0];return Object.assign({},i.message,{consensus_timestamp:i.consensus_timestamp,sequence_number:i.sequence_number})}}const pg=r.z.object({p:r.z.literal("hcs-17"),op:r.z.literal("state_hash"),state_hash:r.z.string().min(1),topics:r.z.array(r.z.string()),account_id:r.z.string().min(1),timestamp:r.z.string().optional(),m:r.z.string().optional()});class hg extends Error{constructor(e,t){super(e),this.code=t,this.name="StateHashError"}}var gg=(e=>(e[e.STATE=0]="STATE",e))(gg||{});function mg(e){return`hcs-17:0:${e}`}function fg(e){try{const t=e.match(/^hcs-17:(\d+):(\d+)$/);if(!t)return;const r=Number(t[1]),i=Number(t[2]);if(Number.isNaN(r)||Number.isNaN(i)||i<=0)return;if(0!==r)return;return{type:r,ttl:i}}catch{return}}class yg{constructor(e){this.network=e.network,this.logger=e.logger||new O({level:e.logLevel||"info",module:"HCS-17"}),this.mirrorNode=new V(this.network,this.logger,{customUrl:e.mirrorNodeUrl})}createMessage(e){return{p:"hcs-17",op:"state_hash",state_hash:e.stateHash,topics:e.topics,account_id:e.accountId,timestamp:(new Date).toISOString(),m:e.memo}}validateMessage(e){const t=pg.safeParse(e);if(t.success)return{valid:!0,errors:[]};const r=t.error.errors.map(e=>`${e.path.join(".")}: ${e.message}`);return this.logger.debug(`HCS-17 message validation failed: ${r.join(", ")}`),{valid:!1,errors:r}}generateTopicMemo(e){return mg(e)}async validateHCS17Topic(e){try{const t=fg((await this.mirrorNode.getTopicInfo(e)).memo);return t?t.type!==gg.STATE?{valid:!1,error:"Unsupported HCS-17 topic type"}:{valid:!0,type:t.type,ttl:t.ttl}:{valid:!1,error:"Invalid HCS-17 memo format"}}catch($g){return{valid:!1,error:String($g)}}}async getRecentMessages(e,t){const r=t?.limit??25,i=t?.order??"desc",o=await this.mirrorNode.getTopicMessages(e,{limit:r,order:i}),n=[];for(const s of o)try{if("hcs-17"!==s.p||"state_hash"!==s.op)continue;const e=s,{valid:t}=this.validateMessage(e);if(!t)continue;n.push({message:{p:"hcs-17",op:"state_hash",state_hash:e.state_hash,topics:e.topics,account_id:e.account_id,timestamp:e.timestamp,m:e.m},consensus_timestamp:e.consensus_timestamp,sequence_number:Number(e.sequence_number),payer:e.payer})}catch(Hg){this.logger.debug(`Failed to parse HCS-17 message: ${Hg}`)}return n}async getLatestMessage(e){const t=await this.getRecentMessages(e,{limit:1,order:"desc"});if(!t.length)return null;const{message:r,consensus_timestamp:i,sequence_number:o}=t[0];return Object.assign({},r,{consensus_timestamp:i,sequence_number:o})}calculateAccountStateHash(e){try{this.logger.debug("Calculating account state hash",{accountId:e.accountId,topicCount:e.topics.length});const t=[...e.topics].sort((e,t)=>e.topicId.localeCompare(t.topicId));let r="";for(const e of t)r+=e.topicId+e.latestRunningHash;let i="";i="string"==typeof e.publicKey?e.publicKey:e.publicKey.toString(),r+=i;const o=b.createHash("sha384");o.update(r);const n=o.digest("hex");return this.logger.debug("Account state hash calculated",{accountId:e.accountId,stateHash:n}),{stateHash:n,accountId:e.accountId,timestamp:new Date,topicCount:e.topics.length}}catch(t){throw this.logger.error("Failed to calculate account state hash",t),new Error("HCS-17 CALCULATION_FAILED")}}calculateCompositeStateHash(e){try{this.logger.debug("Calculating composite state hash",{compositeAccountId:e.compositeAccountId,memberCount:e.memberStates.length,topicCount:e.compositeTopics.length});const t=[...e.memberStates].sort((e,t)=>e.accountId.localeCompare(t.accountId)),r=[...e.compositeTopics].sort((e,t)=>e.topicId.localeCompare(t.topicId));let i="";for(const e of t)i+=e.accountId+e.stateHash;for(const e of r)i+=e.topicId+e.latestRunningHash;i+=e.compositePublicKeyFingerprint;const o=b.createHash("sha384");o.update(i);const n=o.digest("hex");return this.logger.debug("Composite state hash calculated",{compositeAccountId:e.compositeAccountId,stateHash:n}),{stateHash:n,accountId:e.compositeAccountId,timestamp:new Date,topicCount:e.compositeTopics.length,memberCount:e.memberStates.length,compositeTopicCount:e.compositeTopics.length}}catch(t){throw this.logger.error("Failed to calculate composite state hash",t),new Error("HCS-17 COMPOSITE_CALCULATION_FAILED")}}calculateKeyFingerprint(e,t){try{const r={threshold:t,keys:[...e].sort((e,t)=>e.toString().localeCompare(t.toString())).map(e=>e.toString())},i=b.createHash("sha384");return i.update(JSON.stringify(r)),i.digest("hex")}catch(r){throw this.logger.error("Failed to calculate key fingerprint",r),new Error("HCS-17 FINGERPRINT_FAILED")}}createStateHashMessage(e,t,r,i){return{p:"hcs-17",op:"state_hash",state_hash:e,topics:r,account_id:t,timestamp:(new Date).toISOString(),m:i}}async verifyStateHash(e,t){try{let r;r="publicKey"in e?this.calculateAccountStateHash(e).stateHash:this.calculateCompositeStateHash(e).stateHash;const i=r===t,o="accountId"in e?e.accountId:e.compositeAccountId;return this.logger.debug("State hash verification",{accountId:o,isValid:i,expected:t,calculated:r}),i}catch(r){return this.logger.error("Failed to verify state hash",r),!1}}}function bg(e){return J({memo:mg(e.ttl),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function wg(e){const t={p:"hcs-17",op:"state_hash",state_hash:e.stateHash,topics:e.topics,account_id:e.accountId,timestamp:(new Date).toISOString(),m:e.memo};return Y({topicId:e.topicId,message:JSON.stringify(t),transactionMemo:e.transactionMemo})}var Ig=(e=>(e.ANNOUNCE="announce",e.PROPOSE="propose",e.RESPOND="respond",e.COMPLETE="complete",e.WITHDRAW="withdraw",e))(Ig||{});function Tg(e){return"object"==typeof e&&null!==e}function Sg(e){return"string"==typeof e}function kg(e){return"number"==typeof e&&Number.isFinite(e)}function Eg(e){if(!Tg(e))return!1;if("hcs-18"!==e.p)return!1;if(!Sg(e.op))return!1;const t=e.op;return!!["announce","propose","respond","complete","withdraw"].includes(t)&&"data"in e}var vg=(e=>(e.IDLE="idle",e.ANNOUNCED="announced",e.PROPOSING="proposing",e.FORMING="forming",e.ACTIVE="active",e.WITHDRAWN="withdrawn",e))(vg||{});class Ag extends Error{constructor(e,t){super(e),this.code=t,this.name="DiscoveryError"}}function Cg(e,t){return t&&t.trim().length>0?t:e&&e>0?`hcs-18:0:${e}`:"hcs-18:0"}function xg(e){return J({memo:Cg(e.ttlSeconds,e.memoOverride),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function Rg(e){const t="string"==typeof e.transactionMemo&&e.transactionMemo.length>0?e.transactionMemo:`hcs-18:op:${function(e){switch(e){case Ig.ANNOUNCE:return 0;case Ig.PROPOSE:return 1;case Ig.RESPOND:return 2;case Ig.COMPLETE:return 3;case Ig.WITHDRAW:return 4;default:return 0}}(e.message.op)}`;return(new i.TopicMessageSubmitTransaction).setTopicId(e.topicId).setMessage(JSON.stringify(e.message)).setTransactionMemo(t)}function Ng(e){return{p:"hcs-18",op:Ig.ANNOUNCE,data:e}}function _g(e){return{p:"hcs-18",op:Ig.PROPOSE,data:e}}function Pg(e){return{p:"hcs-18",op:Ig.RESPOND,data:e}}function Fg(e){return{p:"hcs-18",op:Ig.COMPLETE,data:e}}function zg(e){return{p:"hcs-18",op:Ig.WITHDRAW,data:e}}class Og{constructor(e){this.network=e.network,this.logger=e.logger||O.getInstance({module:"HCS-18"}),this.mirrorNode=new V(this.network,this.logger)}async getDiscoveryMessages(e,t){const r=["announce","propose","respond","complete","withdraw"],i=await this.mirrorNode.getTopicMessages(e,t);return i?i.filter(e=>"hcs-18"===e.p&&r.includes(e.op)):[]}isProposalReady(e){const t=Array.from(e.responses.values()).filter(e=>"accept"===e.decision),r=e.data.members.length-1;return t.length>=r}}var Dg=(e=>(e.FIXED_FEE="FIXED_FEE",e.FRACTIONAL_FEE="FRACTIONAL_FEE",e.ROYALTY_FEE="ROYALTY_FEE",e))(Dg||{});class Mg{constructor(e){this.customFees=[],this.logger=e.logger,this.mirrorNode=new V(e.network,e.logger),this.defaultCollectorAccountId=e.defaultCollectorAccountId||""}static forHbar(e,t,r,i,o=[]){return new Mg({network:r,logger:i,defaultCollectorAccountId:t}).addHbarFee(e,t,o)}static async forToken(e,t,r,i,o,n=[],s){const a=new Mg({network:i,logger:o,defaultCollectorAccountId:r});return await a.addTokenFee(e,t,r,s,n),a}addHbarFee(e,t,r=[]){if(e<=0)throw new Error("HBAR amount must be greater than zero");return this.customFees.push({feeAmount:{amount:1e8*e,decimals:0},feeCollectorAccountId:t||this.defaultCollectorAccountId,feeTokenId:void 0,exemptAccounts:[...r],type:Dg.FIXED_FEE}),this}async addTokenFee(e,t,r,i,o=[]){if(e<=0)throw new Error("Token amount must be greater than zero");if(!t)throw new Error("Fee token ID is required when adding a token fee");let n=i;if(void 0===n)try{const e=await this.mirrorNode.getTokenInfo(t);e?.decimals?(n=parseInt(e.decimals,10),this.logger.info(`Fetched decimals for ${t}: ${n}`)):(this.logger.warn(`Could not fetch decimals for ${t}, defaulting to 0.`),n=0)}catch(s){this.logger.error(`Error fetching decimals for ${t}, defaulting to 0: ${s}`),n=0}return this.customFees.push({feeAmount:{amount:e*10**n,decimals:n},feeCollectorAccountId:r||this.defaultCollectorAccountId,feeTokenId:t,exemptAccounts:[...o],type:Dg.FIXED_FEE}),this}build(){if(0===this.customFees.length)throw new Error("At least one fee must be added using addHbarFee/addTokenFee or created using forHbar/forToken");if(this.customFees.length>10)throw new Error("Maximum of 10 custom fees per topic allowed");const e=new Set;this.customFees.forEach(t=>{t.exemptAccounts.forEach(t=>e.add(t))});return{customFees:this.customFees.map(e=>({...e,feeCollectorAccountId:e.feeCollectorAccountId||this.defaultCollectorAccountId})),exemptAccounts:Array.from(e)}}}class Bg{constructor(){this.resolver=null,this.onUnavailableCallbacks=[],this.logger=O.getInstance({module:"ContentResolverRegistry"})}static getInstance(){return Bg._instance||(Bg._instance=new Bg),Bg._instance}register(e){this.resolver&&this.logger.warn("Resolver already registered, replacing existing"),this.resolver=e,this.logger.info("Content resolver registered")}getResolver(){return this.resolver}isAvailable(){return null!==this.resolver}unregister(){this.resolver&&(this.resolver=null,this.logger.info("Content resolver unregistered"),this.onUnavailableCallbacks.forEach(e=>{try{e()}catch(t){this.logger.error("Error in unavailable callback:",t)}}))}onUnavailable(e){this.onUnavailableCallbacks.push(e)}offUnavailable(e){const t=this.onUnavailableCallbacks.indexOf(e);-1!==t&&this.onUnavailableCallbacks.splice(t,1)}async withResolver(e,t){if(!this.resolver)return this.logger.warn("No resolver available, using fallback"),await t();try{return await e(this.resolver)}catch(r){return this.logger.warn("Resolver operation failed, using fallback:",r),await t()}}}const Kg=Bg.getInstance();class Ug{constructor(){this.contentStore=null,this.logger=O.getInstance({module:"ContentStoreService"})}static getInstance(){return Ug._instance||(Ug._instance=new Ug),Ug._instance}async setInstance(e){this.contentStore&&this.logger.warn("Content store already set, replacing"),this.contentStore=e,this.logger.info("Content store instance set")}getInstance(){return this.contentStore}dispose(){this.contentStore=null,this.logger.info("Content store disposed")}isAvailable(){return null!==this.contentStore}}const Lg=Ug.getInstance();exports.AIAgentCapability=du,exports.AIAgentDetailsSchema=fu,exports.AIAgentProfileSchema=vu,exports.AIAgentType=cu,exports.AccountCreationError=Wu,exports.ActionBuilder=class{constructor(e){this.cryptoAdapter=Xd(),this.logger=e,this.registration={p:"hcs-12",op:"register"}}setTopicId(e){if(!this.isValidTopicId(e))throw new Error("Invalid topic ID format");return this.registration.t_id=e,this}setAlias(e){return this.alias=e,this}setHash(e){if(!this.isValidHash(e))throw new Error("Invalid hash format");return this.registration.hash=e,this}setWasmHash(e){if(!this.isValidHash(e))throw new Error("Invalid hash format");return this.registration.wasm_hash=e,this}setInfoTopicId(e){if(!this.isValidTopicId(e))throw new Error("Invalid topic ID format");return this.registration.info_t_id=e,this}setJsTopicId(e){if(!this.isValidTopicId(e))throw new Error("Invalid topic ID format");return this.registration.js_t_id=e,this}setJsHash(e){if(!this.isValidHash(e))throw new Error("Invalid hash format");return this.registration.js_hash=e,this}setInterfaceVersion(e){if(!this.isValidVersion(e))throw new Error("Invalid version format");return this.registration.interface_version=e,this}addValidationRule(e,t){return this.registration.validation_rules||(this.registration.validation_rules={}),this.registration.validation_rules[e]=t,this}setSourceVerification(e){if(!this.isValidTopicId(e.source_t_id))throw new Error("Invalid source topic ID");if(!this.isValidHash(e.source_hash))throw new Error("Invalid source hash");if("wasm32-unknown-unknown"!==e.target)throw new Error("Invalid compilation target");return this.registration.source_verification=e,this}build(e={validate:!0}){return!1!==e.validate&&this.validate(),{...this.registration}}reset(){return this.registration={p:"hcs-12",op:"register"},this.alias=void 0,this}getAlias(){if(!this.alias)throw new Error("Action alias not set");return this.alias}getTopicId(){if(!this.registration.t_id)throw new Error("Action topic ID not set");return this.registration.t_id}async generateWasmHash(e){if(qd())return this.createSSRSafeHash(e,"wasm");const t=this.cryptoAdapter.createHash("sha256").update(globalThis.Buffer.from(e)).digest("hex"),r=t instanceof Promise?await t:t;return"string"==typeof r?r:r.toString("hex")}async generateInfoHash(e){const t=JSON.stringify(e,Object.keys(e).sort());if(qd())return this.createSSRSafeHash(globalThis.Buffer.from(t),"info");const r=this.cryptoAdapter.createHash("sha256").update(globalThis.Buffer.from(t)).digest("hex"),i=r instanceof Promise?await r:r;return"string"==typeof i?i:i.toString("hex")}async calculateHash(e){const t="string"==typeof e||e instanceof Uint8Array?globalThis.Buffer.from(e):e;if(qd())return this.createSSRSafeHash(t,"data");const r=this.cryptoAdapter.createHash("sha256").update(t).digest("hex"),i=r instanceof Promise?await r:r;return"string"==typeof i?i:i.toString("hex")}createSSRSafeHash(e,t){const r=e instanceof Uint8Array?globalThis.Buffer.from(e):e;let i=0;for(let o=0;o<Math.min(r.length,256);o++)i=(i<<5)-i+r[o]&4294967295;return`ssr-${t}-${r.length}-${Math.abs(i).toString(16).padStart(8,"0")}`}async createFromWasmAndInfo(e,t,r){const i=await this.generateWasmHash(t),o=await this.generateInfoHash(r),n=this.registration.js_t_id,s=this.registration.js_hash,a=this.registration.interface_version;return this.reset().setTopicId(e).setHash(o).setWasmHash(i),n&&this.setJsTopicId(n),s&&this.setJsHash(s),a&&this.setInterfaceVersion(a),this.build()}isComplete(e){return!!("hcs-12"===e.p&&"register"===e.op&&e.t_id&&e.hash&&e.wasm_hash)}validate(){if(!this.registration.t_id)throw new Error("Topic ID is required");if(!this.registration.hash)throw new Error("INFO hash is required");if(!this.registration.wasm_hash)throw new Error("WASM hash is required")}isValidTopicId(e){return/^\d+\.\d+\.\d+$/.test(e)}isValidHash(e){return/^[a-f0-9]{64}$/.test(e)}isValidVersion(e){return/^\d+\.\d+\.\d+$/.test(e)}},exports.ActionRegistry=bp,exports.AgentBuilder=Ju,exports.AssemblyBuilder=class{constructor(e){this.registration={p:"hcs-12",op:"register"},this.operations=[],this.updateFields={p:"hcs-12",op:"update"},this.logger=e||new O({module:"AssemblyBuilder"})}setName(e){if(!this.isValidName(e))throw new Error("Invalid assembly name format");return this.registration.name=e,this}setVersion(e){if(!this.isValidSemver(e))throw new Error("Invalid semantic version");return this.registration.version=e,this}setDescription(e){return this.registration.description=e,this.updateFields&&(this.updateFields.description=e),this}setTags(e){return this.registration.tags=e,this.updateFields&&(this.updateFields.tags=e),this}addTag(e){return this.registration.tags||(this.registration.tags=[]),this.updateFields.tags||(this.updateFields.tags=[]),this.registration.tags.push(e),this.updateFields.tags.push(e),this}setAuthor(e){return this.registration.author=e,this}addAction(e){const t=e.getTopicId(),r=e.getAlias();if(!this.isValidAlias(r))throw new Error("Invalid alias format");const i={p:"hcs-12",op:"add-action",t_id:t,alias:r};return this.operations.push(i),this}addBlock(e){const t=e.getTopicId();if(!this.isValidTopicId(t))throw new Error(`Invalid block topic ID: ${t}`);const r=e.build(),i=e.getActions(),o=this.extractDefaultAttributes(r.attributes);if(i&&Object.keys(i).length>0)for(const[s,a]of Object.entries(i))if(!this.isValidTopicId(a))throw new Error(`Invalid action topic ID for "${s}": ${a}`);const n={p:"hcs-12",op:"add-block",block_t_id:t,...Object.keys(i).length>0&&{actions:i},attributes:o};return this.operations.push(n),this}updateMetadata(e,t){const r={p:"hcs-12",op:"update",description:e,tags:t};return this.operations.push(r),this}build(){if(!this.registration.name)throw new Error("Assembly name is required");if(!this.registration.version)throw new Error("Assembly version is required");return{...this.registration}}buildUpdate(){const e={p:"hcs-12",op:"update"};return void 0!==this.updateFields.description&&(e.description=this.updateFields.description),void 0!==this.updateFields.tags&&(e.tags=this.updateFields.tags),e}buildOperations(){return[...this.operations]}reset(){return this.registration={p:"hcs-12",op:"register"},this.operations=[],this.updateFields={p:"hcs-12",op:"update"},this}getRegistration(){return this.build()}getOperations(){return this.buildOperations()}buildPreview(){const e=[],t=[];for(const r of this.operations)switch(r.op){case"add-action":e.push({t_id:r.t_id,alias:r.alias,config:r.config,data:r.data});break;case"add-block":t.push({block_t_id:r.block_t_id,actions:r.actions,attributes:r.attributes,children:r.children,data:r.data});break;case"update":r.description&&(this.registration.description=r.description),r.tags&&(this.registration.tags=r.tags)}return{topicId:"",name:this.registration.name,version:this.registration.version,description:this.registration.description,tags:this.registration.tags,author:this.registration.author,actions:e,blocks:t,created:(new Date).toISOString(),updated:(new Date).toISOString()}}validate(){const e=[];this.registration.name||e.push("Assembly name is required"),this.registration.version||e.push("Assembly version is required"),this.registration.version&&!this.isValidSemver(this.registration.version)&&e.push("Invalid semantic version format");const t=new Set;for(const i of this.operations)"add-action"===i.op?(t.has(i.alias)?e.push(`Duplicate alias: ${i.alias}`):t.add(i.alias),this.isValidTopicId(i.t_id)||e.push(`Invalid topic ID for ${i.alias}: ${i.t_id}`),this.isValidAlias(i.alias)||e.push(`Invalid alias format: ${i.alias}`)):"add-block"===i.op&&(this.isValidTopicId(i.block_t_id)||e.push(`Invalid block topic ID: ${i.block_t_id}`));const r=new Set;this.operations.filter(e=>"add-action"===e.op).forEach(e=>r.add(e.alias));for(const i of this.operations)if("add-block"===i.op&&i.actions)for(const[t,r]of Object.entries(i.actions))this.isValidTopicId(r)||e.push(`Block ${i.block_t_id} has invalid action topic ID for key ${t}: ${r}`);return{valid:0===e.length,errors:e}}isValidSemver(e){return/^\d+\.\d+\.\d+(-[\w\.\+]+)?$/.test(e)}isValidTopicId(e){return/^\d+\.\d+\.\d+$/.test(e)}isValidAlias(e){return/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(e)&&e.length>=2&&e.length<=50}isValidName(e){return/^[a-z0-9-]+$/.test(e)&&e.length>=2&&e.length<=100}extractDefaultAttributes(e){if(!e)return{};const t={};for(const[r,i]of Object.entries(e))i&&"object"==typeof i&&"default"in i&&(t[r]=i.default);return t}},exports.AssemblyEngine=Sp,exports.AssemblyRegistry=Ip,exports.BaseProfileSchema=ku,exports.BaseRegistry=Qu,exports.BlockBuilder=Ep,exports.BlockLoader=wp,exports.BlockRenderer=class{constructor(e,t,r,i){this.MAX_DEPTH=10,this.logger=e,this.gutenbergBridge=t,this.templateEngine=r,this.stateManager=i,this.hashLinkScanner=new Ap(e)}async render(e,t={}){try{this.currentBlock=e,this.currentOptions=t,t.assembly&&(this.assembly=t.assembly),t.actionRegistry&&(this.actionRegistry=t.actionRegistry),t.network&&!this.wasmExecutor&&(this.wasmExecutor=new vp(this.logger,t.network)),t.initialState&&this.stateManager.setBlockState(e.id,t.initialState);let r=this.stateManager.getBlockState(e.id)||{attributes:{},actionResults:{}};r.attributes&&"object"==typeof r.attributes||(this.logger.warn("Invalid state structure, fixing...",{state:r}),r={attributes:r||{},actionResults:{}});let i={},o=e.attributes||{};if(this.assembly){const t=this.assembly.state?.blocks?.find(t=>t.block_t_id===e.id||t.block_t_id===e.t_id);t&&(i=t.actions||{},o={...t.attributes,...o})}const n={};e.attributes&&Object.entries(e.attributes).forEach(([e,t])=>{t&&"object"==typeof t&&"default"in t&&(n[e]=t.default)});const s={...n};o&&"object"==typeof o&&Object.entries(o).forEach(([e,t])=>{"object"==typeof t&&null!==t||(s[e]=t)}),r.attributes&&"object"==typeof r.attributes&&Object.entries(r.attributes).forEach(([e,t])=>{"object"==typeof t&&null!==t||(s[e]=t)}),r.attributes={...s},this.stateManager.setBlockState(e.id,r);const a={attributes:s,actions:i,blockId:e.id,actionResults:r.actionResults||{}};this.logger.debug("Template context",{blockId:e.id,attributes:a.attributes,hasActions:!!i,actionKeys:Object.keys(i),rawState:r,mergedAttributes:s});let c=await this.templateEngine.render(e.template||"",a);if(this.shouldProcessHashLinks(t)&&(c=await this.processHashLinks(c,e,t)),t.container&&"undefined"!=typeof window){const r="string"==typeof t.container?document.querySelector(t.container):t.container;if(r instanceof HTMLElement)return r.innerHTML=c,e.styles&&this.applyStyles(e.id,e.styles),this.setupEventHandlers(r,e.id),{element:r,html:c,cleanup:()=>this.cleanup(e.id)}}return{html:c}}catch(r){throw this.logger.error("Block render failed",{blockId:e.id,error:r}),r}}applyStyles(e,t){if("undefined"==typeof document)return;const r=`hashlink-styles-${e}`;let i=document.getElementById(r);i||(i=document.createElement("style"),i.id=r,document.head.appendChild(i)),i.textContent=t}setupEventHandlers(e,t){this.stateManager.onStateChange(t,t=>{this.updateBlockUI(e,t)}),e.querySelectorAll("[data-action]").forEach(e=>{e.addEventListener("click",async r=>{r.preventDefault();const i=e.dataset.action,o=e.dataset.params;this.logger.debug("Action button clicked",{actionTopicId:i,paramsStr:o,hasAction:!!i}),i&&await this.executeAction(t,i,o)})})}async updateBlockDisplay(e,t){try{this.logger.debug("updateBlockDisplay called",{blockId:e,newState:t});const r=document.querySelector(`[data-block-id="${e}"]`);if(!r||!r.parentElement)return void this.logger.warn("Block element not found for re-render",{blockId:e});const i=r.parentElement;if(this.currentBlock&&this.currentBlock.id===e&&this.currentOptions){const r={...this.currentOptions,container:i,initialState:t};await this.render(this.currentBlock,r);this.logger.debug("Block re-rendered with updated state",{blockId:e,newState:t})}}catch(r){this.logger.error("Failed to re-render block",{blockId:e,error:r.message})}}async executeAction(e,t,r){try{this.logger.debug("Executing action",{blockId:e,actionTopicId:t});let i={};if(r)try{i=JSON.parse(r)}catch($g){this.logger.warn("Failed to parse action params",{paramsStr:r})}const o=this.stateManager.getBlockState(e)||{attributes:{},actionResults:{}};if(this.wasmExecutor&&this.actionRegistry){this.logger.debug("Looking up action in registry",{actionTopicId:t});const r=await this.actionRegistry.getActionByTopicId(t);if(this.logger.debug("Action lookup result",{found:!!r,actionTopicId:t,actionData:r}),!r)throw new Error(`Action not found: ${t}`);this.logger.debug("Executing WASM",{actionData:r,params:i,state:o.attributes});const n=await this.wasmExecutor.execute(r,{method:"POST",params:i,state:o.attributes});if(this.logger.debug("WASM execution result",{result:n}),n.success&&n.data){const t=i.operation||"default";let r=n.data;r.success&&r.data&&(r=r.data);const s={...o,attributes:{...o.attributes,...r},actionResults:{...o.actionResults,[t]:r}};this.stateManager.updateBlockState(e,s),await this.updateBlockDisplay(e,s)}else this.logger.error("Action execution failed",{result:n})}else this.stateManager.sendMessage(e,"action",{action:t,params:i})}catch(i){this.logger.error("Failed to execute action",{blockId:e,actionTopicId:t,error:i.message}),this.stateManager.sendMessage(e,"action-error",{action:t,error:i.message})}}updateBlockUI(e,t){Object.entries(t).forEach(([t,r])=>{e.querySelectorAll(`[data-bind="${t}"]`).forEach(e=>{e instanceof HTMLElement&&(e.textContent=String(r))})})}cleanup(e){const t=document.getElementById(`hashlink-styles-${e}`);t&&t.remove(),this.stateManager.removeBlockState(e)}shouldProcessHashLinks(e){const t=e.depth||0,r=e.maxDepth||this.MAX_DEPTH;return t>=r?(this.logger.warn("Max render depth reached, skipping HashLink processing",{depth:t,maxDepth:r}),!1):!(!e.network||!e.blockLoader&&!this.blockLoader)}ensureHashLinkResolver(e){!this.hashLinkResolver&&e.network&&(this.blockLoader=e.blockLoader||this.blockLoader,this.hrlResolver=e.hrlResolver||this.hrlResolver,this.blockLoader&&this.hrlResolver&&(this.hashLinkResolver=new Cp(this.logger,this.blockLoader,this.hrlResolver,e.network)))}async processHashLinks(e,t,r){if(this.ensureHashLinkResolver(r),!this.hashLinkResolver)return this.logger.warn("HashLink resolver not available, skipping processing"),e;this.hashLinkResolver.pushRenderStack(t.id);try{const o=await this.hashLinkScanner.scanTemplate(e);if(0===o.length)return e;this.logger.debug("Processing HashLinks",{parentBlockId:t.id,referenceCount:o.length});const n={blockId:t.id,depth:(r.depth||0)+1,parentContext:r.parentContext,attributes:r.initialState?.attributes||{},actions:{},assembly:this.assembly,maxDepth:r.maxDepth||this.MAX_DEPTH};if(this.assembly){const e=this.assembly.state?.blocks?.find(e=>e.block_t_id===t.id||e.block_t_id===t.t_id);e?.actions&&(n.actions=e.actions)}let s=e;for(let e=0;e<o.length;e++){const t=o[e];try{const e=await this.hashLinkResolver.resolveReference(t,n);if(e.error){this.logger.error("Failed to resolve HashLink",{uri:t.uri,error:e.error});const r=`\x3c!-- HashLink Error: ${e.error} --\x3e`;s=s.replace(t.placeholder,r);continue}let i;if(e.definition){const t={id:e.blockId,template:e.template||"",attributes:e.definition.attributes,p:"hcs-12",op:"register",name:e.definition.name,version:"1.0.0",title:e.definition.title,description:e.definition.description},o={attributes:e.attributes,actionResults:{}},s={attributes:e.attributes,actions:e.actions,blockId:e.blockId,actionResults:{}};if(e.template){i=await this.templateEngine.render(e.template,s);const a={...r,depth:n.depth,parentContext:n,initialState:o};this.shouldProcessHashLinks(a)&&(i=await this.processHashLinks(i,t,a))}else i="\x3c!-- Block has no template --\x3e"}else i=e.template?e.template:"\x3c!-- Empty block --\x3e";"lazy"===t.loading&&(i=this.wrapLazyLoad(i,t)),s=s.replace(t.placeholder,i)}catch(i){this.logger.error("Error processing HashLink",{uri:t.uri,error:i.message});const e=`\x3c!-- HashLink Error: ${i.message} --\x3e`;s=s.replace(t.placeholder,e)}}return s}finally{this.hashLinkResolver.popRenderStack(t.id)}}wrapLazyLoad(e,t){return`\n <div id="${`lazy-${t.uri.replace(/[^a-zA-Z0-9]/g,"-")}`}" class="hashlink-lazy-container" data-hashlink-lazy="${t.uri}">\n <div class="hashlink-lazy-placeholder">Loading...</div>\n <template class="hashlink-lazy-content">${e}</template>\n </div>\n `}},exports.BlockStateManager=class{constructor(e){this.blockStates=new Map,this.stateListeners=new Map,this.messageHandlers=new Map,this.schemas=new Map,this.persistentBlocks=new Set,this.unusedBlocks=new Set,this.maxBlockStates=1e3,this.logger=e}createBlockState(e,t){for(this.logger.debug("Creating block state",{blockId:e}),this.schemas.has(e)&&this.validateState(e,t);this.blockStates.size>=this.maxBlockStates;)this.unusedBlocks.size>0?this.cleanupUnusedStates():this.evictOldestBlock();this.blockStates.set(e,{...t}),this.logger.debug("Block state created",{blockId:e,stateKeys:Object.keys(t)})}getBlockState(e){return this.blockStates.has(e)?{...this.blockStates.get(e)}:null}hasBlockState(e){return this.blockStates.has(e)}updateBlockState(e,t){if(!this.blockStates.has(e))throw new Error(`Block state not found: ${e}`);const r={...this.blockStates.get(e)},i={...r,...t};this.schemas.has(e)&&this.validateState(e,i),this.blockStates.set(e,i);const o=this.stateListeners.get(e)||[];for(const s of o)try{s(i,r,e)}catch(n){this.logger.error("State change listener error",{blockId:e,error:n})}this.logger.debug("Block state updated",{blockId:e,updates:t})}destroyBlockState(e){this.logger.debug("Destroying block state",{blockId:e}),this.blockStates.delete(e),this.stateListeners.delete(e),this.messageHandlers.delete(e),this.schemas.delete(e),this.persistentBlocks.delete(e),this.unusedBlocks.delete(e),this.logger.debug("Block state destroyed",{blockId:e})}onStateChange(e,t){this.stateListeners.has(e)||this.stateListeners.set(e,[]),this.stateListeners.get(e).push(t)}removeStateChangeListener(e,t){const r=this.stateListeners.get(e);if(r){const e=r.indexOf(t);e>-1&&r.splice(e,1)}}onBlockMessage(e,t){this.messageHandlers.has(e)||this.messageHandlers.set(e,[]),this.messageHandlers.get(e).push(t)}sendBlockMessage(e,t,r,i){const o={type:r,payload:i,fromBlock:e,toBlock:t},n=this.messageHandlers.get(t)||[];for(const a of n)try{a(o)}catch(s){this.logger.error("Block message handler error",{fromBlock:e,toBlock:t,type:r,error:s})}this.logger.debug("Block message sent",{fromBlock:e,toBlock:t,type:r})}broadcastMessage(e,t){for(const i of this.blockStates.keys()){const o=this.messageHandlers.get(i)||[],n={type:e,payload:t,fromBlock:"system",toBlock:i};for(const t of o)try{t(n)}catch(r){this.logger.error("Broadcast message handler error",{blockId:i,type:e,error:r})}}this.logger.debug("Message broadcasted",{type:e,blockCount:this.blockStates.size})}async bindActionResult(e,t,r,i){if(!this.blockStates.has(e))throw new Error(`Block state not found: ${e}`);const o=this.getBlockState(e);let n;try{if(r.success&&i.onSuccess)n=i.onSuccess(o,r);else{if(r.success||!i.onError)return;n=i.onError(o,r)}n&&this.updateBlockState(e,n),this.logger.debug("Action result bound to state",{blockId:e,actionName:t,success:r.success})}catch(s){throw this.logger.error("Action result binding failed",{blockId:e,actionName:t,error:s}),s}}async persistBlockState(e){if(!this.storageBackend)return this.logger.warn("No storage backend configured"),void this.persistentBlocks.add(e);if(!this.blockStates.has(e))throw new Error(`Block state not found: ${e}`);try{const t=this.blockStates.get(e);await this.storageBackend.setItem(e,JSON.stringify(t)),this.persistentBlocks.add(e),this.logger.debug("Block state persisted",{blockId:e})}catch(t){this.logger.error("Failed to persist block state",{blockId:e,error:t})}}async restoreBlockState(e){if(this.storageBackend)try{const t=await this.storageBackend.getItem(e);if(t){const r=JSON.parse(t);this.blockStates.set(e,r),this.persistentBlocks.add(e),this.logger.debug("Block state restored",{blockId:e})}}catch(t){this.logger.error("Failed to restore block state",{blockId:e,error:t})}else this.logger.warn("No storage backend configured")}isPersistent(e){return this.persistentBlocks.has(e)}setStorageBackend(e){this.storageBackend=e}setBlockStateSchema(e,t){this.schemas.set(e,t),this.logger.debug("Block state schema set",{blockId:e})}setMaxBlockStates(e){this.maxBlockStates=e}getActiveBlockCount(){return this.blockStates.size}markBlockUnused(e){this.unusedBlocks.add(e)}cleanupUnusedStates(){for(const e of this.unusedBlocks)this.destroyBlockState(e);this.unusedBlocks.clear(),this.logger.debug("Unused states cleaned up")}evictOldestBlock(){for(const e of this.blockStates.keys())if(!this.persistentBlocks.has(e))return this.destroyBlockState(e),void this.logger.debug("Evicted block to make room",{blockId:e});this.logger.warn("Cannot evict blocks - all are persistent")}getListenerCount(e){return(this.stateListeners.get(e)?.length||0)+(this.messageHandlers.get(e)?.length||0)}validateState(e,t){const r=this.schemas.get(e);if(r&&"object"===r.type){if("object"!=typeof t||null===t)throw new Error("State validation failed: expected object");if(r.required)for(const e of r.required)if(!(e in t))throw new Error(`State validation failed: missing required property '${e}'`);if(r.properties)for(const[e,i]of Object.entries(r.properties))if(e in t){const r=t[e],o=i.type;if("string"===o&&"string"!=typeof r)throw new Error(`State validation failed: property '${e}' must be string`);if("number"===o&&"number"!=typeof r)throw new Error(`State validation failed: property '${e}' must be number`);if("number"===o&&void 0!==i.minimum&&r<i.minimum)throw new Error(`State validation failed: property '${e}' below minimum`)}}}setBlockState(e,t){this.blockStates.has(e)?this.updateBlockState(e,t):this.createBlockState(e,t)}removeBlockState(e){this.blockStates.delete(e),this.stateListeners.delete(e),this.messageHandlers.delete(e),this.persistentBlocks.delete(e),this.schemas.delete(e),this.storageBackend&&this.storageBackend.removeItem(e).catch(t=>{this.logger.error("Failed to remove persisted state",{blockId:e,error:t})}),this.logger.debug("Block state removed",{blockId:e})}sendMessage(e,t,r,i="system"){const o=this.messageHandlers.get(e)||[],n={type:t,payload:r,fromBlock:i,toBlock:e};for(const a of o)try{a(n)}catch(s){this.logger.error("Message handler error",{blockId:e,type:t,error:s})}}},exports.BrowserHCS20Client=class extends Mh{constructor(e){super({network:e.network,logger:e.logger,mirrorNodeUrl:e.mirrorNodeUrl,registryTopicId:e.registryTopicId,publicTopicId:e.publicTopicId}),this.hwc=e.hwc,this.feeAmount=e.feeAmount||20}getOperatorId(){const e=this.hwc.getAccountInfo();if(!e?.accountId)throw new Error("Wallet not connected");return e.accountId}async createRegistryTopic(){const e=new bh({hwc:this.hwc,network:this.network}),t=await e.createRegistry();if(!t.success)throw new Error("Failed to create topic");return t.topicId}async deployPoints(e){const t=this.getOperatorId(),{progressCallback:r}=e;try{let i;if(r?.({stage:"creating-topic",percentage:20}),e.usePrivateTopic){const e=await this.mirrorNode.getPublicKey(t),r=new bh({hwc:this.hwc,network:this.network}),o=await r.createRegistry({submitKey:e.toString(),adminKey:e.toString()});if(!o.success)throw new Error("Failed to create topic");i=o.topicId,this.logger.info(`Created private topic: ${i}`)}else i=this.publicTopicId;r?.({stage:"submitting-deploy",percentage:50,topicId:i});const o={p:"hcs-20",op:"deploy",name:e.name,tick:this.normalizeTick(e.tick),max:e.maxSupply,lim:e.limitPerMint,metadata:e.metadata,m:e.topicMemo},n=this.validateMessage(o);if(!n.valid)throw new zh("Invalid deploy message",n.errors);const s=await this.submitPayload(i,o,e.usePrivateTopic),a=s.transactionHash?.toString()||"";return r?.({stage:"confirming",percentage:80,topicId:i,deployTxId:a}),await new Promise(e=>setTimeout(e,2e3)),r?.({stage:"complete",percentage:100,topicId:i,deployTxId:a}),{name:e.name,tick:this.normalizeTick(e.tick),maxSupply:e.maxSupply,limitPerMint:e.limitPerMint,metadata:e.metadata,topicId:i,deployerAccountId:t,currentSupply:"0",deploymentTimestamp:(new Date).toISOString(),isPrivate:e.usePrivateTopic||!1}}catch(i){throw r?.({stage:"complete",percentage:100,error:i instanceof Error?i.message:"Unknown error"}),i}}async mintPoints(e){const{progressCallback:t}=e;try{t?.({stage:"validating",percentage:20}),t?.({stage:"submitting",percentage:50});const r={p:"hcs-20",op:"mint",tick:this.normalizeTick(e.tick),amt:e.amount,to:this.accountToString(e.to),m:e.memo},i=e.topicId||this.publicTopicId,o=await this.submitPayload(i,r,!1),n=o.transactionHash?.toString()||"";return t?.({stage:"confirming",percentage:80,mintTxId:n}),await new Promise(e=>setTimeout(e,2e3)),t?.({stage:"complete",percentage:100,mintTxId:n}),{id:n,operation:"mint",tick:this.normalizeTick(e.tick),amount:e.amount,to:this.accountToString(e.to),timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:i,transactionId:n,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async transferPoints(e){const{progressCallback:t}=e;try{t?.({stage:"validating-balance",percentage:20}),t?.({stage:"submitting",percentage:50});const r={p:"hcs-20",op:"transfer",tick:this.normalizeTick(e.tick),amt:e.amount,from:this.accountToString(e.from),to:this.accountToString(e.to),m:e.memo},i=e.topicId||this.publicTopicId,o=await this.submitPayload(i,r,!1),n=o.transactionHash?.toString()||"";return t?.({stage:"confirming",percentage:80,transferTxId:n}),await new Promise(e=>setTimeout(e,2e3)),t?.({stage:"complete",percentage:100,transferTxId:n}),{id:n,operation:"transfer",tick:this.normalizeTick(e.tick),amount:e.amount,from:this.accountToString(e.from),to:this.accountToString(e.to),timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:i,transactionId:n,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async burnPoints(e){const{progressCallback:t}=e;try{t?.({stage:"validating-balance",percentage:20}),t?.({stage:"submitting",percentage:50});const r={p:"hcs-20",op:"burn",tick:this.normalizeTick(e.tick),amt:e.amount,from:this.accountToString(e.from),m:e.memo},i=e.topicId||this.publicTopicId,o=await this.submitPayload(i,r,!1),n=o.transactionHash?.toString()||"";return t?.({stage:"confirming",percentage:80,burnTxId:n}),await new Promise(e=>setTimeout(e,2e3)),t?.({stage:"complete",percentage:100,burnTxId:n}),{id:n,operation:"burn",tick:this.normalizeTick(e.tick),amount:e.amount,from:this.accountToString(e.from),timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:i,transactionId:n,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async registerTopic(e){const{progressCallback:t}=e;try{t?.({stage:"validating",percentage:20});const r={p:"hcs-20",op:"register",name:e.name,metadata:e.metadata,private:e.isPrivate,t_id:this.topicToString(e.topicId),m:e.memo},i=this.validateMessage(r);if(!i.valid)throw new zh("Invalid register message",i.errors);t?.({stage:"submitting",percentage:50});const o=await this.submitPayload(this.registryTopicId,r,!1),n=o.transactionHash?.toString()||"";t?.({stage:"confirming",percentage:80,registerTxId:n}),await new Promise(e=>setTimeout(e,2e3)),t?.({stage:"complete",percentage:100,registerTxId:n})}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),new Oh(r instanceof Error?r.message:"Unknown error",this.topicToString(e.topicId))}}async submitPayload(e,t,r){let o;this.logger.debug(`Submitting payload to topic ${e}`),o="string"==typeof t?t:JSON.stringify(t);const n=(new i.TopicMessageSubmitTransaction).setTopicId(i.TopicId.fromString(e)).setMessage(o);r&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),n.setMaxTransactionFee(new i.Hbar(this.feeAmount)));const s=await this.hwc.executeTransactionWithErrorHandling(n,!1);if(s?.error)throw this.logger.error(`Failed to submit payload: ${s.error}`),new Error(`Failed to submit payload: ${s.error}`);if(!s?.result)throw this.logger.error("Failed to submit message: receipt is null or undefined"),new Error("Failed to submit message: receipt is null or undefined");return this.logger.debug("Payload submitted successfully via HWC"),s.result}},exports.BrowserHCS2Client=bh,exports.BrowserHCSClient=class extends Hu{constructor(e){let t;if(super({network:e.network,logLevel:e.logLevel,prettyPrint:e.prettyPrint,feeAmount:e.feeAmount,mirrorNode:e.mirrorNode,silent:e.silent}),this.hcs11Client=null,this.hwc=e.hwc,e.guardedRegistryBaseUrl?this.guardedRegistryBaseUrl=e.guardedRegistryBaseUrl:this.guardedRegistryBaseUrl="https://moonscape.tech",t=e.logLevel?e.logLevel:"info",this.logger=O.getInstance({level:t,module:"HCS-Browser",prettyPrint:e.prettyPrint,silent:e.silent}),Xu)try{const{accountId:t,signer:r}=this.getAccountAndSigner();this.hcs11Client=new Ru({network:e.network,auth:{operatorId:t,signer:r},logLevel:e.logLevel,silent:e.silent})}catch(Hg){this.logger.warn(`Failed to initialize HCS11Client: ${Hg}`)}else this.logger.error("BrowserHCSClient initialized in server environment - browser-specific features will not be available. Use HCS10Client instead.")}async sendMessage(e,t,r,i,o){this.logger.info("Sending message");const n={p:"hcs-10",op:"message",operator_id:await this.getOperatorId(),data:t,m:r},s=await this.canSubmitToTopic(e,this.hwc.getAccountInfo().accountId),a=JSON.stringify(n);if(globalThis.Buffer.from(a).length>1e3){this.logger.info("Message payload exceeds 1000 bytes, storing via inscription");try{const e=globalThis.Buffer.from(t),r=`message-${Date.now()}.json`,i=await this.inscribeFile(e,r,{progressCallback:o?.progressCallback,waitMaxAttempts:o?.waitMaxAttempts,waitIntervalMs:o?.waitIntervalMs});if(!La(i))throw new Error("Failed to inscribe large message content");n.data=`hcs://1/${La(i)}`,this.logger.info(`Large message inscribed with topic ID: ${La(i)}`)}catch(c){throw this.logger.error("Error inscribing large message:",c),new Error(`Failed to handle large message: ${c instanceof Error?c.message:"Unknown error"}`)}}return await this.submitPayload(e,n,i,s.requiresFee)}async getPublicKey(e){return await this.mirrorNode.getPublicKey(e)}async handleConnectionRequest(e,t,r,o="Connection accepted. Looking forward to collaborating!",n=60){this.logger.info("Handling connection request");const s=this.hwc.getAccountInfo().accountId;if(!s)throw new Error("Failed to retrieve user account ID");const a=await this.mirrorNode.getPublicKey(t),c=await this.mirrorNode.getPublicKey(s);if(!c)throw new Error("Failed to retrieve public key");const l=new i.KeyList([c,a],1),d=this._generateHcs10Memo($u.CONNECTION,{ttl:n,inboundTopicId:e,connectionId:r}),u=(new i.TopicCreateTransaction).setTopicMemo(d).setAutoRenewAccountId(i.AccountId.fromString(s)).setAdminKey(l).setSubmitKey(l);this.logger.debug("Executing topic creation transaction");const p=await this.hwc.executeTransactionWithErrorHandling(u,!1);if(p?.error)throw this.logger.error(p.error),new Error(p.error);const h=p?.result;if(!h?.topicId)throw this.logger.error("Failed to create topic: topicId is null"),new Error("Failed to create topic: topicId is null");const g=h.topicId.toString(),m=`${e}@${s}`,f=await this.confirmConnection(e,g,t,r,m,o),y=await this.retrieveCommunicationTopics(s),b=await this.retrieveCommunicationTopics(t),w=`${b.inboundTopic}@${t}`;return await this.recordOutboundConnectionConfirmation({outboundTopicId:y.outboundTopic,requestorOutboundTopicId:b.outboundTopic,connectionRequestId:r,confirmedRequestId:f,connectionTopicId:g,operatorId:w,memo:`Connection established with ${t}`}),{connectionTopicId:g,confirmedConnectionSequenceNumber:f,operatorId:m}}async confirmConnection(e,t,r,i,o,n){this.logger.info("Confirming connection");const s={p:"hcs-10",op:"connection_created",connection_topic_id:t,connected_account_id:r,operator_id:o,connection_id:i,m:n},a=await this.submitPayload(e,s);if(!a?.topicSequenceNumber)throw this.logger.error("Failed to confirm connection: sequence number is null"),new Error("Failed to confirm connection: sequence number is null");return a.topicSequenceNumber.toNumber()}async create(e,t){const r=t?.progressCallback,i=new us({module:"ProfileCreate",logger:this.logger,callback:r});try{const r=e instanceof Ju;let o;if(o=t?.existingState?t.existingState:{currentStage:"init",completedPercentage:0,createdResources:[]},r){this.logger.info("Creating Agent Profile and HCS-10 Topics");const t=e.build();o.agentMetadata=t.metadata}else this.logger.info("Creating Person HCS-11 Profile");i.preparing(`Starting ${r?"agent":"person"} resource creation`,0,{state:o});const{inboundTopicId:n,outboundTopicId:s,state:a}=await this.createCommunicationTopics(t,i);let c,l,d;if(o=a,e.setInboundTopicId(n),e.setOutboundTopicId(s),r){const t=e.build();c=t.existingPfpTopicId||o.pfpTopicId,l=t.pfpBuffer,d=t.pfpFileName||"pfp.png"}else{const t=e.build();c=o.pfpTopicId,l=t.pfpBuffer,d=t.pfpFileName}!c&&l&&d?c=await this.handleProfilePictureCreation(l,d,o,i):c&&(i.preparing(`Using existing profile picture: ${c}`,50,{state:o}),o.pfpTopicId=c),await this.createAndInscribeProfile(r,e,c,o,n,s,t,i),o.currentStage="complete",o.completedPercentage=100,i.completed((r?"Agent":"Person")+" profile created successfully",{profileTopicId:o.profileTopicId,inboundTopicId:n,outboundTopicId:s,pfpTopicId:c,state:o});let u="";o.outboundTopicId&&(u=o.outboundTopicId);let p="";o.inboundTopicId&&(p=o.inboundTopicId);let h="";o.pfpTopicId&&(h=o.pfpTopicId);let g="";return o.profileTopicId&&(g=o.profileTopicId),{outboundTopicId:u,inboundTopicId:p,pfpTopicId:h,profileTopicId:g,success:!0,state:o}}catch(o){return i.failed("Error during profile creation",{error:o.message}),{outboundTopicId:"",inboundTopicId:"",pfpTopicId:"",profileTopicId:"",success:!1,error:o.message,state:{currentStage:"init",completedPercentage:0,error:o.message}}}}async handleProfilePictureCreation(e,t,r,i){r.currentStage="pfp",i.preparing("Creating profile picture",30,{state:r});const o=i.createSubProgress({minPercent:30,maxPercent:50,logPrefix:"PFP"}),n=await this.inscribePfp(e,t,{progressCallback:e=>o.report({...e,progressPercent:e.progressPercent??0,details:{...e.details,state:r}})});if(!n.success){let e="Failed to inscribe profile picture";throw n.error&&(e=n.error),new Error(e)}const s=n.pfpTopicId;return r.pfpTopicId=s,r.createdResources&&r.createdResources.push(`pfp:${r.pfpTopicId}`),i.preparing("Profile picture created",50,{state:r}),s}async createAndInscribeProfile(e,t,r,i,o,n,s,a){if(!this.hcs11Client)throw a&&a.failed("HCS11Client is not available"),new Error("HCS11Client is not available");if(this.logger.info("Creating and inscribing profile"),i.profileTopicId)a&&a.preparing(`Using existing ${e?"agent":"person"} profile`,95,{state:i});else{a&&a.preparing(`Storing HCS-11 ${e?"agent":"person"} profile`,80);const c=a?.createSubProgress({minPercent:80,maxPercent:95,logPrefix:"StoreProfile"});let l;if(e){const e=t.build(),i=e.metadata?.socials?Object.entries(e.metadata.socials).map(([e,t])=>({platform:e,handle:t})):[];l=this.hcs11Client.createAIAgentProfile(e.name,"manual"===e.metadata?.type?0:1,e.capabilities||[],e.metadata?.model||"unknown",{alias:e.name.toLowerCase().replace(/\s+/g,"_"),bio:e.bio,profileImage:r?`hcs://1/${r}`:void 0,socials:i,properties:e.metadata?.properties||{},inboundTopicId:o,outboundTopicId:n,creator:e.metadata?.creator})}else{const e=t.build(),{pfpBuffer:i,pfpFileName:s,...a}=e;l=this.hcs11Client.createPersonalProfile(e.display_name,{alias:e.alias,bio:e.bio,socials:e.socials,profileImage:r?`hcs://1/${r}`:e.profileImage,properties:e.properties,inboundTopicId:o,outboundTopicId:n})}const d=await this.hcs11Client.createAndInscribeProfile(l,s?.updateAccountMemo??!0,{progressCallback:e=>c?.report({...e,progressPercent:e.progressPercent??0})});if(!d.success){a&&a.failed(`Failed to inscribe ${e?"agent":"person"} profile`,{error:d.error});let t=`Failed to inscribe ${e?"agent":"person"} profile`;throw d.error&&(t=d.error),new Error(t)}i.profileTopicId=d.profileTopicId,i.createdResources&&i.createdResources.push(`profile:${d.profileTopicId}`),a&&a.preparing("HCS-11 Profile stored",95,{state:i})}}initializeRegistrationState(e,t){const r=t||{inboundTopicId:e,currentStage:"registration",completedPercentage:0,createdResources:[]};return"registration"!==r.currentStage&&"complete"!==r.currentStage&&(r.currentStage="registration"),r}updateStateForCompletedRegistration(e,t){e.currentStage="complete",e.completedPercentage=100,e.createdResources&&e.createdResources.push(`registration:${t}`)}async registerAgentWithGuardedRegistry(e,t=this.network,r){try{let o;if(this.logger.info("Registering agent with guarded registry"),r?.existingState?.inboundTopicId)this.logger.info("Using inboundTopicId from existing state"),o=r.existingState.inboundTopicId;else{const t=await this.retrieveProfile(e,!1,{maxRetries:5,retryDelay:3e3});if(!t.success||!t.profile||!t.topicInfo){const r=t.error||`Failed to retrieve profile for account ${e}. Make sure the agent profile is created and memo is updated before registration.`;return this.logger.error(r),{error:r,success:!1,state:{currentStage:"registration",completedPercentage:0,error:r}}}o=t.topicInfo.inboundTopic}const n=this.initializeRegistrationState(o,r?.existingState),s=new us({module:"AgentRegistration",logger:this.logger,callback:r?.progressCallback});s.preparing("Preparing agent registration",10,{inboundTopicId:o,accountId:e});const a=await this.executeRegistration(e,t,this.guardedRegistryBaseUrl,this.logger);if(!a.success)return{...a,state:n};if(s.submitting("Submitting registration to registry",30,{transactionId:a.transactionId}),a.transaction){const e=i.Transaction.fromBytes(globalThis.Buffer.from(a.transaction,"base64"));this.logger.info("Processing registration transaction");const t=await this.hwc.executeTransactionWithErrorHandling(e,!0);if(t.error)return{...a,error:t.error,success:!1,state:n};this.logger.info("Successfully processed registration transaction")}s.confirming("Confirming registration transaction",60,{accountId:e,inboundTopicId:o,transactionId:a.transactionId});const c=r?.maxAttempts??60,l=r?.delayMs??2e3,d=await this.waitForRegistrationConfirmation(a.transactionId,t,this.guardedRegistryBaseUrl,c,l,this.logger);return this.updateStateForCompletedRegistration(n,o),s.completed("Agent registration complete",{transactionId:a.transactionId,inboundTopicId:o,state:n,confirmed:d}),{...a,confirmed:d,state:n}}catch(o){return this.logger.error(`Registration error: ${o.message}`),{error:`Error during registration: ${o.message}`,success:!1,state:{currentStage:"registration",completedPercentage:0,error:o.message}}}}async createAndRegisterAgent(e,t){try{const r=e.build(),i=t?.progressCallback,o=new us({module:"AgentCreateRegister",logger:this.logger,callback:i});let n=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};if(n.agentMetadata=r.metadata,o.preparing("Starting agent creation process",0,{state:n}),"complete"!==n.currentStage||!n.inboundTopicId||!n.outboundTopicId||!n.profileTopicId){const t=await this.create(e,{progressCallback:e=>{const t=.3*(e.progressPercent||0);o.report({...e,progressPercent:t,details:{...e.details,state:e.details?.state||n}})},existingState:n,updateAccountMemo:!0});if(!("state"in t))throw new Error("Create method did not return expected agent state.");if(!t.success)throw new Error(t.error||"Failed to create agent resources");n=t.state,n.agentMetadata=r.metadata,this.logger.info("Waiting for account memo update to propagate..."),await new Promise(e=>setTimeout(e,5e3))}o.preparing(`Agent creation status: ${n.currentStage}, ${n.completedPercentage}%`,30,{state:n});const{accountId:s}=this.getAccountAndSigner();if("complete"!==n.currentStage||!n.createdResources?.includes(`registration:${n.inboundTopicId}`)){t?.baseUrl&&(this.guardedRegistryBaseUrl=t.baseUrl);const e=await this.registerAgentWithGuardedRegistry(s,r.network,{progressCallback:e=>{const t=30+.7*(e.progressPercent||0);o.report({...e,progressPercent:t,details:{...e.details,state:e.details?.state||n}})},maxAttempts:t?.maxAttempts,delayMs:t?.delayMs,existingState:n});if(!e.success)throw new Error(e.error||"Failed to register agent with registry");n=e.state}return o.completed("Agent creation and registration complete",{state:n}),{success:!0,state:n,metadata:{accountId:s,operatorId:`${n.inboundTopicId}@${s}`,inboundTopicId:n.inboundTopicId,outboundTopicId:n.outboundTopicId,profileTopicId:n.profileTopicId,pfpTopicId:n.pfpTopicId,privateKey:null,...n.agentMetadata}}}catch(r){return this.logger.error(`Failed to create and register agent: ${r.message}`),{success:!1,error:`Failed to create and register agent: ${r.message}`,state:t?.existingState||{currentStage:"init",completedPercentage:0,error:r.message}}}}async storeHCS11Profile(e,t,r,i,o=[],n={},s,a,c,l){try{const d=l?.progressCallback,u=new us({module:"StoreHCS11Profile",logger:this.logger,callback:d});u.preparing("Preparing agent profile data",0);let p=c;if(!p&&s&&a){const e=u.createSubProgress({minPercent:0,maxPercent:60,logPrefix:"PFP"}),t=await this.inscribePfp(s,a,{progressCallback:t=>{e.report({stage:t.stage,message:t.message,progressPercent:t.progressPercent||0,details:t.details})}});t.success?p=t.pfpTopicId:u.failed("Failed to inscribe profile picture, continuing without PFP")}else c?u.preparing(`Using existing profile picture: ${c}`,30):u.preparing("No profile picture provided",30);if(!this.hcs11Client)return u.failed("HCS11Client is not available in this environment"),{profileTopicId:"",success:!1,error:"HCS11Client is not available in this environment",transactionId:""};const h=this.hcs11Client.getAgentTypeFromMetadata({type:n.type||"autonomous"});u.preparing("Building agent profile",65);const g=n.socials?Object.entries(n.socials).filter(([e,t])=>t).map(([e,t])=>({platform:e,handle:t})):void 0,m=this.hcs11Client.createAIAgentProfile(e,h,o,n.model||"unknown",{alias:e.toLowerCase().replace(/\s+/g,"_"),bio:t,profileImage:p?`hcs://1/${p}`:void 0,socials:g,properties:{version:n.version||"1.0.0",creator:n.creator||"Unknown",supported_languages:n.supported_languages||["en"],permissions:n.permissions||[],model_details:n.model_details,training:n.training,capabilities_description:n.capabilities_description,...n},inboundTopicId:r,outboundTopicId:i,creator:n.creator}),f=u.createSubProgress({minPercent:65,maxPercent:100,logPrefix:"Profile"}),y=await this.hcs11Client.createAndInscribeProfile(m,l?.updateAccountMemo??!0,{progressCallback:e=>{f.report({stage:e.stage,message:e.message,progressPercent:e.progressPercent||0,details:e.details})}});return y.success?(u.completed("Profile stored successfully",{profileTopicId:y.profileTopicId}),{profileTopicId:y.profileTopicId,pfpTopicId:p,success:!0,transactionId:y.transactionId||""}):(u.failed("Failed to inscribe profile"),{profileTopicId:"",success:!1,error:y.error||"Failed to inscribe profile",transactionId:y.transactionId||""})}catch(d){return this.logger.error(`Error storing HCS11 profile: ${d.message}`),{profileTopicId:"",success:!1,error:d.message,transactionId:""}}}async createTopic(e,t,r){this.logger.info("Creating topic");const{accountId:o,signer:n}=this.getAccountAndSigner(),s=(new i.TopicCreateTransaction).setTopicMemo(e),a=await this.mirrorNode.getPublicKey(o);t&&a&&(s.setAdminKey(a),s.setAutoRenewAccountId(o)),r&&a&&s.setSubmitKey(a);const c=await this.hwc.executeTransactionWithErrorHandling(s,!1),l=c.error;if(l)return this.logger.error(l),{success:!1,error:l};const d=c.result;return d?.topicId?{success:!0,topicId:d.topicId.toString()}:(this.logger.error("Failed to create topic: topicId is null"),{success:!1,error:"Failed to create topic: topicId is null"})}async submitPayload(e,t,r,o){let n;this.logger.debug(`Submitting payload to topic ${e}`),n="string"==typeof t?t:JSON.stringify(t);const s=(new i.TopicMessageSubmitTransaction).setTopicId(e).setMessage(n),a=this.getHcs10TransactionMemo(t);let c;if(a&&s.setTransactionMemo(a),o&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),s.setMaxTransactionFee(new i.Hbar(this.feeAmount))),r){const{signer:e}=this.getAccountAndSigner();s.freezeWithSigner(e);const t=await s.sign(r);c=await this.hwc.executeTransactionWithErrorHandling(t,!0)}else c=await this.hwc.executeTransactionWithErrorHandling(s,!1);if(c?.error)throw this.logger.error(`Failed to submit payload: ${c.error}`),new Error(`Failed to submit payload: ${c.error}`);if(!c?.result)throw this.logger.error("Failed to submit message: receipt is null or undefined"),new Error("Failed to submit message: receipt is null or undefined");return this.logger.debug("Payload submitted successfully via HWC"),c.result}async inscribeFile(e,t,r){const{accountId:i,signer:o}=this.getAccountAndSigner(),n=S.lookup(t)||"application/octet-stream",s=await ds.createWithAuth({type:"client",accountId:i,signer:o,network:this.network}),a={mode:"file",waitForConfirmation:!0,waitMaxAttempts:r?.waitMaxAttempts||30,waitIntervalMs:r?.waitIntervalMs||4e3,progressCallback:r?.progressCallback,logging:{level:this.logger.getLevel?this.logger.getLevel():"info"}},c=await Da({type:"buffer",buffer:e,fileName:t,mimeType:n},o,{...a,network:this.network},s);if(!c.confirmed||!c.inscription)throw new Error("Inscription was not confirmed");return c.inscription}getAccountAndSigner(){const e=this?.hwc?.getAccountInfo(),t=e?.accountId?.toString(),r=this?.hwc?.dAppConnector?.signers?.find(e=>e.getAccountId().toString()===t);if(!r)throw this.logger.error("Failed to find signer",{accountId:t,signers:this?.hwc?.dAppConnector?.signers,accountInfo:e}),new Error("Failed to find signer");return{accountId:t,signer:r}}async inscribePfp(e,t,r){try{const i=r?.progressCallback,o=new us({module:"PFP-Inscription",logger:this.logger,callback:i});if(!this.hcs11Client)return o.failed("HCS11Client is not available in this environment"),{pfpTopicId:"",success:!1,error:"HCS11Client is not available in this environment",transactionId:""};o.preparing("Preparing to inscribe profile picture",10),this.logger.info("Inscribing profile picture using HCS-11 client");const n=e=>{o.report({stage:e.stage||"confirming",message:e.message||"Processing PFP inscription",progressPercent:e.progressPercent||50,details:e.details})},s=await this.hcs11Client.inscribeImage(e,t,{progressCallback:n});if(!s.success){let e="Failed to inscribe profile picture";s.error&&(e=s.error);let t="";return s.transactionId&&(t=s.transactionId),{pfpTopicId:"",success:!1,error:e,transactionId:t}}return o.completed("Successfully inscribed profile picture",{pfpTopicId:s.imageTopicId}),this.logger.info(`Successfully inscribed profile picture with topic ID: ${s.imageTopicId}`),{pfpTopicId:s.imageTopicId,success:!0,transactionId:s.transactionId||""}}catch(i){return this.logger.error(`Error inscribing profile picture: ${i.message}`),{pfpTopicId:"",success:!1,error:i.message,transactionId:""}}}async createCommunicationTopics(e,t){let r=e?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};t&&t.preparing("Starting communication topic creation",0,{state:r});const{accountId:i}=this.getAccountAndSigner();if(!r.outboundTopicId){r.currentStage="topics",t&&t.preparing("Creating outbound topic",5,{state:r});const o=this._generateHcs10Memo($u.OUTBOUND,{ttl:e?.ttl,accountId:i}),n=await this.createTopic(o,!0,!0);if(!n.success||!n.topicId)throw new Error(n.error||"Failed to create outbound topic");r.outboundTopicId=n.topicId,r.createdResources&&r.createdResources.push(`outbound:${r.outboundTopicId}`)}if(!r.inboundTopicId){r.currentStage="topics",t&&t.preparing("Creating inbound topic",10,{state:r});const o=this._generateHcs10Memo($u.INBOUND,{ttl:e?.ttl,accountId:i}),n=await this.createTopic(o,!0,!1);if(!n.success||!n.topicId)throw new Error(n.error||"Failed to create inbound topic");r.inboundTopicId=n.topicId,r.createdResources&&r.createdResources.push(`inbound:${r.inboundTopicId}`)}return{inboundTopicId:r.inboundTopicId,outboundTopicId:r.outboundTopicId,state:r}}},exports.CanonicalAgentDataSchema=_p,exports.ConnectionConfirmationError=Gu,exports.ConnectionsManager=class{constructor(e){this.connections=new Map,this.pendingRequests=new Map,this.profileCache=new Map,this.filterPendingAccountIds=new Set;const t={module:"ConnectionsManager",level:e?.logLevel||"info",prettyPrint:!0,silent:e?.silent};if(this.logger=O.getInstance(t),e?.filterPendingAccountIds&&(this.filterPendingAccountIds=new Set(e.filterPendingAccountIds)),!e.baseClient)throw new Error("ConnectionsManager requires a baseClient to operate");this.baseClient=e.baseClient}async fetchConnectionData(e){try{const t=await this.baseClient.retrieveCommunicationTopics(e),r=e=>Boolean(e)&&!e.includes(":");if(!r(t?.inboundTopic)||!r(t?.outboundTopic))return this.logger.warn("Invalid topic IDs detected in retrieved communication topics"),this.getAllConnections();const[i,o]=await Promise.all([this.baseClient.getMessages(t?.outboundTopic),this.baseClient.getMessages(t?.inboundTopic)]);this.processOutboundMessages(i.messages||[],e),this.processInboundMessages(o.messages||[]);const n=Array.from(this.connections.values()).filter(e=>"pending"===e.status||e.isPending).length;return this.logger.debug(`Processed ${i.messages?.length||0} outbound and ${o.messages?.length||0} inbound messages. Found ${n} pending connections.`),await this.checkTargetInboundTopicsForConfirmations(),await this.checkOutboundRequestsForConfirmations(),await this.fetchProfilesForConnections(),await this.fetchConnectionActivity(),this.getAllConnections()}catch(t){return this.logger.error("Error fetching connection data:",t),this.getAllConnections()}}async checkTargetInboundTopicsForConfirmations(){const e=Array.from(this.connections.values()).filter(e=>(e.isPending||"pending"===e.status)&&e.targetInboundTopicId);if(0===e.length)return;const t=new Map;e.forEach(e=>{if(e.targetInboundTopicId){const r=t.get(e.targetInboundTopicId)||[];r.push(e),t.set(e.targetInboundTopicId,r)}});for(const[i,o]of t.entries())for(let e=1;e<=2;e++)try{const t=(await this.baseClient.getMessages(i)).messages||[];let r=!1;for(const e of o){const i=e.connectionRequestId;if(!i)continue;const o=t.find(t=>{if("connection_created"!==t.op||!t.connection_topic_id)return!1;if(t.connection_id!==i)return!1;if(e.uniqueRequestKey){const r=e.uniqueRequestKey.split(":");if(r.length>1){const i=r[1];if(t.operator_id&&t.operator_id===i)return!0;if(t.connected_account_id===e.targetAccountId)return!0}}return!0});if(o?.connection_topic_id){r=!0;const t=o.connection_topic_id;let n=e.uniqueRequestKey;const s={connectionTopicId:t,targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName,targetInboundTopicId:e.targetInboundTopicId,status:"established",isPending:!1,needsConfirmation:!1,created:new Date(o.created||e.created),profileInfo:e.profileInfo,connectionRequestId:i,uniqueRequestKey:e.uniqueRequestKey,originTopicId:e.originTopicId,processed:e.processed,memo:e.memo};this.connections.set(t,s),n&&this.connections.delete(n),this.logger.debug(`Confirmed connection in target inbound topic: ${t}`)}}if(r||2===e)break;await new Promise(e=>setTimeout(e,500))}catch(r){if(this.logger.debug(`Error fetching target inbound topic ${i}:`,r),2===e)break;await new Promise(e=>setTimeout(e,500))}}async checkOutboundRequestsForConfirmations(){const e=Array.from(this.connections.values());this.logger.info(`Total connections in map: ${e.length}`);const t=e.filter(e=>"pending"===e.status);this.logger.info(`Connections with status='pending': ${t.length}`);const r=e.filter(e=>"pending"===e.status);if(Boolean(r?.length))for(const o of r){if(this.logger.debug(`Processing pending connection: ${o.connectionTopicId}`),!o.targetAccountId){this.logger.debug(`Skipping connection ${o.connectionTopicId} - no targetAccountId`);continue}let e=o.targetInboundTopicId;if(!e)try{const t=await this.baseClient.retrieveProfile(o.targetAccountId);if(!t?.profile?.inboundTopicId){this.logger.debug(`Couldn't get inbound topic ID for account ${o.targetAccountId}`);continue}e=t.profile.inboundTopicId,this.connections.set(o.connectionTopicId,{...o,targetInboundTopicId:e}),this.logger.debug(`Updated connection ${o.connectionTopicId} with inbound topic ID: ${e}`)}catch(i){this.logger.debug(`Error fetching profile for ${o.targetAccountId}: ${i}`);continue}if(!e||e.includes(":")){this.logger.debug(`Skipping invalid inbound topic format: ${e}`);continue}const t=o.connectionRequestId||o.inboundRequestId;if(t)try{this.logger.debug(`Checking for confirmations on topic ${e} for request ID ${t}`);const r=await this.baseClient.getMessages(e),i=(r.messages||[]).find(e=>"connection_created"===e.op&&e.connection_id===t&&e.connection_topic_id);if(i?.connection_topic_id){const e=i.connection_topic_id;this.logger.info(`Found confirmation for request #${t} to ${o.targetAccountId} on their inbound topic`);const r={connectionTopicId:e,targetAccountId:o.targetAccountId,targetAgentName:o.targetAgentName,targetInboundTopicId:o.targetInboundTopicId,targetOutboundTopicId:o.targetOutboundTopicId,status:"established",isPending:!1,needsConfirmation:!1,created:new Date(i.created||o.created),lastActivity:new Date(i.created||o.created),profileInfo:o.profileInfo,connectionRequestId:o.connectionRequestId,confirmedRequestId:o.confirmedRequestId,requesterOutboundTopicId:o.requesterOutboundTopicId,inboundRequestId:o.inboundRequestId,closedReason:o.closedReason,closeMethod:o.closeMethod,uniqueRequestKey:o.uniqueRequestKey,originTopicId:o.originTopicId,processed:o.processed,memo:o.memo};this.connections.set(e,r),o.connectionTopicId&&this.connections.delete(o.connectionTopicId)}else this.logger.debug(`No confirmation found for request ID ${t} on topic ${e}`)}catch(i){this.logger.warn(`Error checking for confirmations on target inbound topic for ${o.targetAccountId}: ${i}`)}else this.logger.debug(`Skipping connection ${o.connectionTopicId} - no request ID`)}else this.logger.info("No pending connections found")}async fetchProfilesForConnections(){const e=new Set;for(const r of this.connections.values())r.targetAccountId&&!this.profileCache.has(r.targetAccountId)&&e.add(r.targetAccountId);const t=Array.from(e).map(async e=>{try{const t=await this.baseClient.retrieveProfile(e);t.success&&t.profile&&(this.addProfileInfo(e,t.profile),this.updatePendingConnectionsWithProfileInfo(e,t.profile))}catch(t){this.logger.debug(`Failed to fetch profile for ${e}:`,t)}});await Promise.allSettled(t)}updatePendingConnectionsWithProfileInfo(e,t){const r=Array.from(this.connections.values()).filter(t=>t.targetAccountId===e&&(t.isPending||t.needsConfirmation)&&!t.targetInboundTopicId);if(r.length>0&&t.inboundTopicId)for(const i of r){const e={...i,targetInboundTopicId:t.inboundTopicId};this.connections.set(i.connectionTopicId,e)}}async fetchConnectionActivity(){const e=this.getActiveConnections().filter(e=>{const t=e.connectionTopicId;return!(!t||t.includes(":")||!t.match(/^0\.0\.\d+$/))||(this.logger.debug(`Skipping activity fetch for invalid topic ID format: ${t}`),!1)}).map(async e=>{try{const t=e.connectionTopicId,r=await this.baseClient.getMessages(t);r?.messages?.length>0&&this.processConnectionMessages(t,r.messages)}catch(t){this.logger.debug(`Failed to fetch activity for ${e.connectionTopicId}:`,t)}});await Promise.allSettled(e)}shouldFilterAccount(e){return!!this.filterPendingAccountIds.has(e)&&!this.hasEstablishedConnectionWithAccount(e)}processOutboundMessages(e,t){if(!Boolean(e?.length))return Array.from(this.connections.values());const r=e.filter(e=>"connection_request"===e.op&&e.connection_request_id);for(const n of r){const e=n.connection_request_id,r=n.operator_id||"",i=this.baseClient.extractAccountFromOperatorId(r),o=this.baseClient.extractTopicFromOperatorId(r);if(this.shouldFilterAccount(i)){this.logger.debug(`Filtering out outbound request to account: ${i}`);continue}const s=Array.from(this.connections.values()).some(t=>t.connectionRequestId===e&&!t.isPending&&t.targetAccountId===i),a=`req-${e}:${r}`;if(!s&&!this.pendingRequests.has(a)){const s={id:e,requesterId:t,requesterTopicId:n.outbound_topic_id||"",targetAccountId:i,targetTopicId:o,operatorId:r,sequenceNumber:n.sequence_number,created:n.created||new Date,memo:n.m,status:"pending"};if(this.pendingRequests.set(a,s),!this.connections.has(a)){const t={connectionTopicId:a,targetAccountId:i,targetInboundTopicId:o,status:"pending",isPending:!0,needsConfirmation:!1,created:n.created||new Date,connectionRequestId:e,uniqueRequestKey:a,originTopicId:n.outbound_topic_id||"",processed:!1,memo:n.m};this.connections.set(a,t)}}}const i=e.filter(e=>"connection_created"===e.op&&e.connection_topic_id&&e.connection_request_id);for(const n of i){const e=n.connection_request_id,t=n.connection_topic_id,r=this.baseClient.extractAccountFromOperatorId(n.operator_id||"");if(this.shouldFilterAccount(r)){this.logger.debug(`Filtering out outbound confirmation to account: ${r}`);continue}const i=`req-${e}:${n.operator_id}`,o=this.pendingRequests.get(i);if(o&&(o.status="confirmed"),this.connections.has(i)&&this.connections.delete(i),this.connections.has(t)){const r=this.connections.get(t);this.connections.set(t,{...r,status:"established",isPending:!1,needsConfirmation:!1,connectionRequestId:e,confirmedRequestId:n.confirmed_request_id,requesterOutboundTopicId:n.outbound_topic_id,uniqueRequestKey:i,originTopicId:n.outbound_topic_id||"",processed:!1,memo:n.m})}else this.connections.set(t,{connectionTopicId:t,targetAccountId:r,status:"established",isPending:!1,needsConfirmation:!1,created:n.created||new Date,connectionRequestId:e,confirmedRequestId:n.confirmed_request_id,requesterOutboundTopicId:n.outbound_topic_id,uniqueRequestKey:i,originTopicId:n.outbound_topic_id||"",processed:!1,memo:n.m})}const o=e.filter(e=>"connection_closed"===e.op||"close_connection"===e.op&&e.connection_topic_id);for(const n of o){const e=n.connection_topic_id;if(this.connections.has(e)){const t=this.connections.get(e);if(this.shouldFilterAccount(t.targetAccountId)&&"established"!==t.status)continue;const r=n.connection_request_id&&n.operator_id?`req-${n.connection_request_id}:${n.operator_id}`:void 0;this.connections.set(e,{...t,status:"closed",isPending:!1,needsConfirmation:!1,lastActivity:n.created||new Date,closedReason:n.reason,closeMethod:n.close_method,uniqueRequestKey:r,originTopicId:t.originTopicId,processed:!1,memo:n.m})}}return Array.from(this.connections.values()).filter(e=>"established"===e.status||"closed"===e.status||!this.filterPendingAccountIds.has(e.targetAccountId))}processInboundMessages(e){if(!Boolean(e?.length))return Array.from(this.connections.values());const t=e.filter(e=>"connection_request"===e.op&&e.sequence_number),r=e.filter(e=>"connection_created"===e.op&&e.connection_topic_id&&e.connection_id);for(const i of t){const e=i.sequence_number,t=i.operator_id||"",o=this.baseClient.extractAccountFromOperatorId(t),n=this.baseClient.extractTopicFromOperatorId(t);if(this.shouldFilterAccount(o)){this.logger.debug(`Filtering out request from account: ${o}`);continue}const s=`inb-${e}:${t}`;r.some(t=>t.connection_id===e)?this.logger.debug(`Skipping request from ${o} as it has already been confirmed`):this.connections.has(s)||this.connections.set(s,{connectionTopicId:s,targetAccountId:o,targetInboundTopicId:n,status:"needs_confirmation",isPending:!1,needsConfirmation:!0,created:i.created||new Date,inboundRequestId:e,uniqueRequestKey:s,originTopicId:n,processed:!1,memo:i.m})}for(const i of r){const e=i.connection_id,t=i.connection_topic_id,r=i.connected_account_id||"",o=i.operator_id||"";if(this.shouldFilterAccount(r)){this.logger.debug(`Filtering out confirmation for account: ${r}`);continue}const n=`inb-${e}:${o}`;if(this.connections.has(n)&&this.connections.delete(n),this.connections.has(t)){const r=this.connections.get(t);this.connections.set(t,{...r,status:"established",isPending:!1,needsConfirmation:!1,inboundRequestId:e,uniqueRequestKey:n,originTopicId:i.connection_topic_id,processed:!1,memo:i.m})}else this.connections.set(t,{connectionTopicId:t,targetAccountId:r,status:"established",isPending:!1,needsConfirmation:!1,created:i.created||new Date,inboundRequestId:e,uniqueRequestKey:n,originTopicId:i.connection_topic_id,processed:!1,memo:i.m})}return Array.from(this.connections.values()).filter(e=>"established"===e.status||"closed"===e.status||!this.filterPendingAccountIds.has(e.targetAccountId))}processConnectionMessages(e,t){if(!t||0===t.length||!this.connections.has(e))return this.connections.get(e);const r=t.filter(e=>e.created).sort((e,t)=>{const r=e.created?new Date(e.created).getTime():0;return(t.created?new Date(t.created).getTime():0)-r})[0];if(r?.created){const t=this.connections.get(e);this.connections.set(e,{...t,lastActivity:r.created})}const i=t.find(e=>"close_connection"===e.op);if(i){const t=this.connections.get(e);this.connections.set(e,{...t,status:"closed",lastActivity:i.created||new Date,closedReason:i.reason,closeMethod:"explicit"})}return this.connections.get(e)}addProfileInfo(e,t){this.profileCache.set(e,t);const r=Array.from(this.connections.values()).filter(t=>t.targetAccountId===e);for(const i of r)this.connections.set(i.connectionTopicId,{...i,profileInfo:t,targetAgentName:t.display_name,targetInboundTopicId:t.inboundTopicId,targetOutboundTopicId:t.outboundTopicId})}getAllConnections(){return Array.from(this.connections.values()).filter(e=>"established"===e.status||"closed"===e.status||!this.filterPendingAccountIds.has(e.targetAccountId))}getPendingRequests(){return Array.from(this.connections.values()).filter(e=>e.isPending&&!this.filterPendingAccountIds.has(e.targetAccountId))}hasEstablishedConnectionWithAccount(e){return Array.from(this.connections.values()).some(t=>t.targetAccountId===e&&"established"===t.status)}getActiveConnections(){return Array.from(this.connections.values()).filter(e=>"established"===e.status)}getConnectionsNeedingConfirmation(){return Array.from(this.connections.values()).filter(e=>e.needsConfirmation&&!this.filterPendingAccountIds.has(e.targetAccountId))}getConnectionByTopicId(e){return this.connections.get(e)}getConnectionByAccountId(e){return Array.from(this.connections.values()).find(t=>t.targetAccountId===e&&"established"===t.status)}getConnectionsByAccountId(e){return Array.from(this.connections.values()).filter(t=>t.targetAccountId===e)}updateOrAddConnection(e){this.connections.set(e.connectionTopicId,e)}clearAll(){this.connections.clear(),this.pendingRequests.clear()}isConnectionRequestProcessed(e,t){for(const r of this.connections.values()){if(r.originTopicId===e&&r.inboundRequestId===t&&r.processed)return!0;if(r.originTopicId===e&&r.connectionRequestId===t&&r.processed)return!0}return!1}markConnectionRequestProcessed(e,t){let r=!1;for(const[i,o]of this.connections.entries())o.originTopicId===e&&o.inboundRequestId===t&&(this.connections.set(i,{...o,processed:!0}),r=!0,this.logger.debug(`Marked inbound connection request #${t} on topic ${e} as processed`)),o.originTopicId===e&&o.connectionRequestId===t&&(this.connections.set(i,{...o,processed:!0}),r=!0,this.logger.debug(`Marked outbound connection request #${t} on topic ${e} as processed`));return r}async getPendingTransactions(e,t){try{const i=await this.baseClient.getTransactionRequests(e,t?{...t}:void 0),o=[];for(const e of i)try{const t=await this.baseClient.mirrorNode.getScheduledTransactionStatus(e.schedule_id);t.executed||t.deleted||o.push(e)}catch(r){this.logger.error(`Error checking transaction status: ${r}`),o.push(e)}return o}catch(r){return this.logger.error(`Error getting pending transactions: ${r}`),[]}}getScheduledTransactionStatus(e){return this.baseClient.mirrorNode.getScheduledTransactionStatus(e)}async getLastOperatorActivity(e,t){try{const r=(await this.baseClient.getMessageStream(e)).messages.filter(e=>e.operator_id&&e.operator_id.includes(t)&&e.created);if(0===r.length)return;return r.sort((e,t)=>t.created.getTime()-e.created.getTime()),r[0].created}catch(r){return void this.logger.error(`Error getting last operator activity: ${r}`)}}},exports.ContentResolverRegistry=Kg,exports.ContentResolverRegistryImpl=Bg,exports.ContentStoreService=Lg,exports.CustomFeeType=Dg,exports.DiscoveryError=Ag,exports.DiscoveryErrorCodes={INVALID_MESSAGE:"INVALID_MESSAGE",TIMEOUT:"TIMEOUT",INSUFFICIENT_PETALS:"INSUFFICIENT_PETALS",FLORA_CREATION_FAILED:"FLORA_CREATION_FAILED",ALREADY_IN_DISCOVERY:"ALREADY_IN_DISCOVERY",INVALID_STATE:"INVALID_STATE"},exports.DiscoveryOperation=Ig,exports.DiscoveryState=vg,exports.EVMBridge=class{constructor(e="mainnet-public",t="mirrornode.hedera.com/api/v1/contracts/call",r){this.network=e,this.mirrorNodeUrl=t,this.cache=r||new rc,this.logger=O.getInstance({module:"EVMBridge"})}async executeCommands(e,t={}){let r={...t};const o={};for(const s of e){const e=`${s.c.contractAddress}-${s.c.abi.name}`,t=await this.cache.get(e);if(t)o[s.c.abi.name]=JSON.parse(t),Object.assign(r,o[s.c.abi.name]);else try{const t=new c.ethers.Interface([{...s.c.abi}]),n=t.encodeFunctionData(s.c.abi.name),a=i.ContractId.fromSolidityAddress(s.c.contractAddress),l=await this.readFromMirrorNode(n,i.AccountId.fromString("0.0.800"),a);if(this.logger.info(`Result for ${s.c.contractAddress}:`,l?.result),!l?.result){this.logger.warn(`Failed to get result from mirror node for ${s.c.contractAddress}`),o[s.c.abi.name]="0",Object.assign(r,o[s.c.abi.name]);continue}const d=t?.decodeFunctionResult(s.c.abi.name,l.result);let u={values:[]};d&&s.c.abi.outputs?.forEach((e,t)=>{const r=ic(d[t],e.type);u.values.push(r),e.name&&(u[e.name]=r)}),await this.cache.set(e,JSON.stringify(u)),o[s.c.abi.name]=u,r[s.c.abi.name]=u}catch(n){this.logger.error(`Error executing command for ${s.c.contractAddress}:`,n),o[s.c.abi.name]="0",Object.assign(r,o[s.c.abi.name])}}return{results:o,stateData:r}}async executeCommand(e,t={}){const{results:r,stateData:i}=await this.executeCommands([e],t);return{result:r[e.c.abi.name],stateData:i}}async readFromMirrorNode(e,t,r){try{const i=r.toSolidityAddress(),o=t.toSolidityAddress(),n=await fetch(`https://${this.network}.${this.mirrorNodeUrl}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({block:"latest",data:e,estimate:!1,gas:3e5,gasPrice:1e8,from:o.startsWith("0x")?o:`0x${o}`,to:i?.startsWith("0x")?i:`0x${i}`,value:0})});if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);return await n.json()}catch(i){return this.logger.error("Error reading from mirror node:",i),null}}async clearCache(){await this.cache.clear()}async clearCacheForContract(e,t){await this.cache.delete(`${e}-${t}`)}setLogLevel(e){this.logger.setLogLevel(e)}},exports.EndpointType=lu,exports.FallbackCryptoAdapter=Yd,exports.FallbackHashAdapter=$d,exports.FallbackHmacAdapter=Vd,exports.FeeConfigBuilder=Mg,exports.FloraBuilder=class{constructor(){this.config={version:"1.0",type:3},this.logger=O.getInstance({module:"FloraBuilder"})}setDisplayName(e){return this.config.display_name=e,this}setBio(e){return this.config.bio=e,this}setMembers(e){return this.config.members=e,this}setThreshold(e){return this.config.threshold=e,this}setTopics(e){return this.config.topics=e,this.config.inboundTopicId=e.communication,this.config.outboundTopicId=e.transaction,this}setPolicies(e){return this.config.policies=e,this}setMetadata(e){return this.config.metadata=e,this}addMetadata(e,t){return this.config.metadata||(this.config.metadata={}),this.config.metadata[e]=t,this}build(){if(!this.config.display_name)throw new Error("Flora display name is required");if(!this.config.members||0===this.config.members.length)throw new Error("Flora must have at least one member");if(!this.config.threshold||this.config.threshold<1)throw new Error("Flora threshold must be at least 1");if(this.config.threshold>this.config.members.length)throw new Error("Flora threshold cannot exceed number of members");if(!this.config.topics)throw new Error("Flora topics are required");if(!this.config.inboundTopicId||!this.config.outboundTopicId)throw new Error("Flora inbound and outbound topic IDs are required");return this.config}},exports.FloraError=tg,exports.FloraOperation=eg,exports.FloraTopicType=Qh,exports.GutenbergBridge=class{constructor(e){this.logger=e}convertToGutenberg(e){if(this.logger.debug("Converting BlockDefinition to Gutenberg format",{name:e.name}),!e||!e.name)throw new Error("Invalid block definition: missing name");const t={apiVersion:e.apiVersion,name:e.name,title:e.title,category:e.category,icon:e.icon,description:e.description,keywords:e.keywords,attributes:e.attributes,supports:e.supports};return t.attributes||(t.attributes={}),t.supports||(t.supports={}),this.logger.debug("Converted to Gutenberg format",{name:t.name,attributeCount:Object.keys(t.attributes).length}),t}parseFromGutenberg(e){if(this.logger.debug("Parsing Gutenberg block to BlockDefinition",{name:e.name}),!e||!e.name)throw new Error("Invalid Gutenberg block: missing name");if(!e.title)throw new Error("Invalid Gutenberg block: missing title");const t={apiVersion:e.apiVersion||3,name:e.name,title:e.title,category:e.category||"common",template_t_id:"",icon:e.icon,description:e.description,keywords:e.keywords,attributes:e.attributes||{},supports:e.supports||{}};return this.logger.debug("Parsed from Gutenberg format",{name:t.name}),t}validateBlockStructure(e){this.logger.debug("Validating block structure",{name:e.name});const t={isValid:!0,errors:[],warnings:[]};return this.validateBasicStructure(e,t),this.validateBlockName(e,t),this.validateAttributes(e,t),this.validateSupports(e,t),this.validateParentChild(e,t),t.isValid=0===t.errors.filter(e=>"critical"===e.severity||"high"===e.severity).length,this.logger.debug("Block structure validation completed",{name:e.name,isValid:t.isValid,errorCount:t.errors.length,warningCount:t.warnings.length}),t}validateBasicStructure(e,t){e.name&&""!==e.name.trim()||t.errors.push({code:"MISSING_NAME",message:"Block name cannot be empty",field:"name",severity:"critical"}),e&&(e.title||t.errors.push({code:"MISSING_TITLE",message:"Block title is required",field:"data.title",severity:"high"}),e.description||t.warnings.push({code:"MISSING_DESCRIPTION",message:"Block description improves usability",field:"data.description",impact:"usability"})),e||t.errors.push({code:"MISSING_BLOCK_JSON",message:"data is required for Gutenberg compatibility",field:"data",severity:"critical"})}validateBlockName(e,t){if(!e.name)return;/^[a-z0-9-]+\/[a-z0-9-]+$/.test(e.name)||t.errors.push({code:"INVALID_BLOCK_NAME",message:"Block name must follow namespace/block-name format (lowercase, hyphens only)",field:"name",severity:"high"}),e&&e.name&&t.warnings.push({code:"NAME_MISMATCH",message:"Block name should match data.name",field:"name",impact:"functionality"})}validateAttributes(e,t){if(!e||!e.attributes)return;const r=e.attributes,i=["string","number","boolean","array","object"];for(const[o,n]of Object.entries(r))n.type?(i.includes(n.type)||t.errors.push({code:"INVALID_ATTRIBUTE_TYPE",message:`Attribute '${o}' has invalid type '${n.type}'`,field:`attributes.${o}.type`,severity:"high"}),n.enum&&n.default&&!n.enum.includes(n.default)&&t.warnings.push({code:"DEFAULT_NOT_IN_ENUM",message:`Attribute '${o}' default value not in enum`,field:`attributes.${o}.default`,impact:"functionality"})):t.errors.push({code:"MISSING_ATTRIBUTE_TYPE",message:`Attribute '${o}' must specify a type`,field:`attributes.${o}.type`,severity:"medium"})}validateSupports(e,t){if(!e||!e.supports)return;const r=e.supports;if(void 0!==r.align)if("boolean"==typeof r.align);else if(Array.isArray(r.align)){const e=["left","center","right","wide","full"],i=r.align.filter(t=>!e.includes(t));i.length>0&&t.warnings.push({code:"INVALID_ALIGNMENT",message:`Invalid alignment values: ${i.join(", ")}`,field:"supports.align",impact:"functionality"})}}validateParentChild(e,t){e&&(e.parent&&t.warnings.push({code:"REQUIRES_PARENT",message:"Block requires a specific parent block",field:"parent",impact:"usability"}),e.provides&&Object.keys(e.provides).length>0&&t.warnings.push({code:"PROVIDES_CONTEXT",message:"Block provides context to child blocks",field:"provides",impact:"functionality"}),e.usesContext&&e.usesContext.length>0&&t.warnings.push({code:"USES_CONTEXT",message:"Block depends on context from parent blocks",field:"usesContext",impact:"functionality"}))}},exports.HCS=M,exports.HCS10BaseClient=Hu,exports.HCS10Cache=qu,exports.HCS10Client=Yu,exports.HCS11Client=Ru,exports.HCS11ProfileSchema=xu,exports.HCS12BaseClient=kp,exports.HCS12BrowserClient=class extends kp{constructor(e){super(e),this.hwc=e.hwc,this.updateAccountFromWallet(),this.logger.info("HCS-12 Browser Client initialized",{network:e.network,accountId:this.accountId})}async updateAccountFromWallet(){try{const{accountId:e}=await this.getAccountAndSigner();this.accountId=e}catch(e){this.logger.warn("No active wallet connection")}}async getAccountAndSigner(){const e=this?.hwc?.getAccountInfo(),t=e?.accountId?.toString(),r=this?.hwc?.dAppConnector?.signers?.find(e=>e.getAccountId().toString()===t);if(!r||!t)throw this.logger.error("Failed to find signer",{accountId:t,signers:this?.hwc?.dAppConnector?.signers,accountInfo:e}),new Error("Failed to find signer or account");return{accountId:t,signer:r}}getOperatorAccountId(){throw new Error("Browser client does not have operator account")}getOperatorPrivateKey(){throw new Error("Browser client does not have operator private key")}initializeRegistries(e){super.initializeRegistries(e),this._actionRegistry=new bp(this.network,this.logger,this.actionRegistryTopicId,this),this._blockLoader=new wp(this.network,this.logger,this),this._assemblyRegistry=new Ip(this.network,this.logger,this._assemblyRegistryTopicId,this),this._hashLinksRegistry=new Tp(this.network,this.logger,this._hashLinksRegistryTopicId,this),this.logger.info("Registries initialized with signer",{actionTopicId:this.actionRegistryTopicId,assemblyTopicId:this._assemblyRegistryTopicId,hashLinksTopicId:this._hashLinksRegistryTopicId})}async createRegistryTopic(e,t,r){const{accountId:o,signer:n}=await this.getAccountAndSigner(),s={[Zu.ACTION]:"hcs-12:1:60:0",[Zu.ASSEMBLY]:"hcs-12:1:60:2",[Zu.HASHLINKS]:"hcs-12:1:60:3"}[e];this.logger.info("Creating registry topic via wallet",{registryType:Zu[e],memo:s,accountId:o});const a=(new i.TopicCreateTransaction).setTopicMemo(s).setTransactionId(i.TransactionId.generate(o));if(t)if("boolean"==typeof t&&t){const e=await n.getAccountKey();a.setAdminKey(e),a.setAutoRenewAccountId(i.AccountId.fromString(o))}else(t instanceof i.PublicKey||t instanceof i.KeyList)&&(a.setAdminKey(t),a.setAutoRenewAccountId(i.AccountId.fromString(o)));if(r)if("boolean"==typeof r&&r){const e=await n.getAccountKey();a.setSubmitKey(e)}else(r instanceof i.PublicKey||r instanceof i.KeyList)&&a.setSubmitKey(r);const c=await a.freezeWithSigner(n),l=await c.executeWithSigner(n),d=await l.getReceiptWithSigner(n);if(!d.topicId)throw new Error("Failed to create topic: topicId is null");const u=d.topicId.toString();switch(this.logger.info("Registry topic created via wallet",{topicId:u,registryType:Zu[e]}),e){case Zu.ACTION:this.actionRegistryTopicId=u;break;case Zu.ASSEMBLY:this._assemblyRegistryTopicId=u;case Zu.HASHLINKS:}return u}async createAssemblyTopic(){this.logger.info("Creating new assembly topic");return await this.createRegistryTopic(Zu.ASSEMBLY)}async registerAssemblyDirect(e,t){return this.logger.info("Registering assembly",{topicId:e,name:t.name,version:t.version}),this._submitMessage(e,JSON.stringify(t))}async addBlockToAssembly(e,t){return this.logger.info("Adding block to assembly",{assemblyTopicId:e,blockTopicId:t.block_t_id}),this._submitMessage(e,JSON.stringify(t))}async addActionToAssembly(e,t){return this.logger.info("Adding action to assembly",{assemblyTopicId:e,actionTopicId:t.t_id,alias:t.alias}),this._submitMessage(e,JSON.stringify(t))}async updateAssembly(e,t){return this.logger.info("Updating assembly",{assemblyTopicId:e,update:t}),this._submitMessage(e,JSON.stringify(t))}async storeBlock(e,t){if(!this.blockLoader)throw new Error("Block loader not initialized");return this.blockLoader.storeBlock(e,t)}async submitMessage(e,t,r){return this.logger.warn("submitMessage is deprecated. Use operation-specific methods instead."),this._submitMessage(e,t,r)}async _submitMessage(e,t,r){const{accountId:o,signer:n}=await this.getAccountAndSigner();this.logger.debug("Submitting message to topic via wallet",{topicId:e,messageLength:t.length,accountId:o});const s=(new i.TopicMessageSubmitTransaction).setTopicId(i.TopicId.fromString(e)).setMessage(t).setTransactionId(i.TransactionId.generate(o));r&&this.logger.warn("Submit key parameter ignored in browser client - using wallet signer");const a=await s.freezeWithSigner(n),c=await a.executeWithSigner(n),l=await c.getReceiptWithSigner(n);return this.logger.info("Message submitted successfully via wallet",{topicId:e,transactionId:c.transactionId.toString(),sequenceNumber:l.topicSequenceNumber?.toString()}),{transactionId:c.transactionId.toString(),sequenceNumber:l.topicSequenceNumber?Number(l.topicSequenceNumber):void 0}}getHashConnect(){return this.hwc}getAccountId(){return this.accountId}async isConnected(){try{return await this.getAccountAndSigner(),!0}catch{return!1}}async inscribeFile(e,t,r){const{accountId:i,signer:o}=await this.getAccountAndSigner();this.logger.info("Inscribing file via HCS-1 (browser)",{fileName:t});const n=S.lookup(t)||"application/octet-stream",s=await ds.createWithAuth({type:"client",accountId:i,signer:o,network:this.network}),a={mode:"file",waitForConfirmation:!0,waitMaxAttempts:r?.waitMaxAttempts||30,waitIntervalMs:r?.waitIntervalMs||4e3,progressCallback:r?.progressCallback,logging:{level:this.logger.getLevel?this.logger.getLevel():"info"},network:this.network},c=await Da({type:"buffer",buffer:e,fileName:t,mimeType:n},o,a,s);if(!c.confirmed||!c.inscription)throw new Error("Inscription failed to confirm");return c.inscription}async registerAction(e){const t=e.build();if(!this._actionRegistry)throw new Error("Action registry not initialized");const r=await this._submitMessage(this.actionRegistryTopicId,JSON.stringify(t));return this.logger.info("Action registered (browser)",{topicId:t.t_id,transactionId:r.transactionId}),e}async registerBlock(e){const t=e.getTemplate();if(t){const r=await this.inscribeFile(t,`${e.getName()||"block"}-template.html`);e.setTemplateTopicId(r.topic_id)}const r=e.build();if(!r.template_t_id)throw new Error("Block must have either a template buffer (via setTemplate) or template_t_id");const i=await this.inscribeFile(globalThis.Buffer.from(JSON.stringify(r,null,2)),`${r.name}-definition.json`);return this.logger.info("Block registered (browser)",{name:r.name,definitionTopicId:i.topic_id,templateTopicId:r.template_t_id}),e.setTopicId(i.topic_id),e}async createAssembly(e){if(!e)return this.createAssemblyTopic();const t=e.build(),r=await this.createAssemblyTopic();await this.registerAssemblyDirect(r,t);const i=e.getOperations();for(const o of i)switch(o.op){case"add-block":await this.addBlockToAssembly(r,o);break;case"add-action":await this.addActionToAssembly(r,o);break;case"update":await this.updateAssembly(r,o)}return this.logger.info("Assembly created (browser)",{topicId:r,name:t.name,version:t.version,operations:i.length}),r}},exports.HCS12Client=class extends kp{constructor(e){super(e),this.operatorAccountId=e.operatorId,this.operatorCtx=ie({network:this.network,operatorId:this.operatorAccountId,operatorKey:e.operatorPrivateKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:"mainnet"===e.network?i.Client.forMainnet():i.Client.forTestnet()}),this.client=this.operatorCtx.client,this.logger.info("HCS-12 SDK Client initialized",{network:e.network,operatorId:this.operatorAccountId,keyType:this.operatorCtx.keyType})}initializeRegistries(e){super.initializeRegistries(e),this._actionRegistry=new bp(this.network,this.logger,this.actionRegistryTopicId,this),this._blockLoader=new wp(this.network,this.logger,this),this._assemblyRegistry=new Ip(this.network,this.logger,this._assemblyRegistryTopicId,this),this._hashLinksRegistry=new Tp(this.network,this.logger,this._hashLinksRegistryTopicId,this),this.logger.info("Registries initialized",{actionTopicId:this.actionRegistryTopicId,assemblyTopicId:this._assemblyRegistryTopicId,hashLinksTopicId:this._hashLinksRegistryTopicId})}async createRegistryTopic(e,t,r){const i={[Zu.ACTION]:"hcs-12:1:60:0",[Zu.ASSEMBLY]:"hcs-12:1:60:2",[Zu.HASHLINKS]:"hcs-12:1:60:3"}[e];this.logger.info("Creating registry topic",{registryType:Zu[e],memo:i});const o=J({memo:i,adminKey:t,submitKey:r,operatorPublicKey:this.client.operatorPublicKey||void 0}),n=await o.execute(this.client),s=await n.getReceipt(this.client);if(!s.topicId)throw new Error("Failed to create topic: topicId is null");const a=s.topicId.toString();switch(this.logger.info("Registry topic created",{topicId:a,registryType:Zu[e]}),e){case Zu.ACTION:this.actionRegistryTopicId=a;break;case Zu.ASSEMBLY:this._assemblyRegistryTopicId=a;case Zu.HASHLINKS:}return a}async registerAssemblyDirect(e,t){return this.logger.info("Registering assembly",{topicId:e,name:t.name,version:t.version}),this._submitMessage(e,JSON.stringify(t))}async addBlockToAssembly(e,t){return this.logger.info("Adding block to assembly",{assemblyTopicId:e,blockTopicId:t.block_t_id}),this._submitMessage(e,JSON.stringify(t))}async addActionToAssembly(e,t){return this.logger.info("Adding action to assembly",{assemblyTopicId:e,actionTopicId:t.t_id,alias:t.alias}),this._submitMessage(e,JSON.stringify(t))}async updateAssembly(e,t){return this.logger.info("Updating assembly",{assemblyTopicId:e,update:t}),this._submitMessage(e,JSON.stringify(t))}async submitMessage(e,t,r){return this.logger.warn("submitMessage is deprecated. Use operation-specific methods instead."),this._submitMessage(e,t,r)}async _submitMessage(e,t,r){this.logger.debug("Submitting message to topic",{topicId:e,messageLength:t.length});const i=Y({topicId:e,message:t});let o;if(r){const e=i.freezeWith(this.client),t=await e.sign(r);o=await t.execute(this.client)}else o=await i.execute(this.client);const n=await o.getReceipt(this.client);return this.logger.info("Message submitted successfully",{topicId:e,transactionId:o.transactionId.toString(),sequenceNumber:n.topicSequenceNumber?.toString()}),{transactionId:o.transactionId.toString(),sequenceNumber:n.topicSequenceNumber?Number(n.topicSequenceNumber):void 0}}getClient(){return this.client}getOperatorAccountId(){return this.operatorAccountId}getOperatorPrivateKey(){return this.operatorCtx.operatorKey.toString()}async inscribeFile(e,t,r){this.logger.info("Inscribing file via HCS-1",{fileName:t});const i=S.lookup(t)||"application/octet-stream",o=await ds.createWithAuth({type:"server",accountId:this.operatorAccountId,privateKey:this.operatorCtx.operatorKey.toString(),network:this.network}),n={mode:"file",waitForConfirmation:!0,waitMaxAttempts:r?.waitMaxAttempts||30,waitIntervalMs:r?.waitIntervalMs||4e3,progressCallback:r?.progressCallback,logging:{level:this.logger.getLevel?this.logger.getLevel():"info"}},s=await za({type:"buffer",buffer:e,fileName:t,mimeType:i},{accountId:this.operatorAccountId,privateKey:this.operatorCtx.operatorKey,network:this.network},n,o);if(!s.confirmed||!s.inscription)throw new Error("Inscription failed to confirm");return s.inscription}async createAssemblyTopic(){if(!this._assemblyRegistry)throw new Error("Assembly registry not initialized");return this._assemblyRegistry.createAssemblyTopic()}async registerAction(e){const t=e.build();if(!this._actionRegistry)throw new Error("Action registry not initialized");const r=await this._submitMessage(this.actionRegistryTopicId,JSON.stringify(t));return this.logger.info("Action registered",{topicId:t.t_id,transactionId:r.transactionId}),e}async registerBlock(e){const t=e.getTemplate();if(t){const r=await this.inscribeFile(t,`${e.getName()||"block"}-template.html`);e.setTemplateTopicId(r.topic_id)}const r=e.build();if(!r.template_t_id)throw new Error("Block must have either a template buffer (via setTemplate) or template_t_id");const i=await this.inscribeFile(globalThis.Buffer.from(JSON.stringify(r,null,2)),`${r.name}-definition.json`);return this.logger.info("Block registered",{name:r.name,definitionTopicId:i.topic_id,templateTopicId:r.template_t_id}),e.setTopicId(i.topic_id),e}async createAssembly(e){const t=e.build(),r=await this.createAssemblyTopic();await this.registerAssemblyDirect(r,t);const i=e.getOperations();for(const o of i)switch(o.op){case"add-block":await this.addBlockToAssembly(r,o);break;case"add-action":await this.addActionToAssembly(r,o);break;case"update":await this.updateAssembly(r,o)}return this.logger.info("Assembly created",{topicId:r,name:t.name,version:t.version,operations:i.length}),r}},exports.HCS14Client=Qp,exports.HCS14_PROTOCOL_REGEX=Np,exports.HCS15BaseClient=Zh,exports.HCS15BrowserClient=class extends Zh{constructor(e){super(e),this.signer=e.signer||e.hwc?.dAppConnector?.signers?.[0]}requireSigner(){if(!this.signer)throw new Error("HCS-15 Browser client requires an active DAppSigner");return this.signer}async createBaseAccount(e){const t=this.requireSigner(),r=i.PrivateKey.generateECDSA(),o=r.publicKey,n=Yh({publicKey:o,initialBalance:new i.Hbar(e?.initialBalance??10),maxAutomaticTokenAssociations:e?.maxAutomaticTokenAssociations,accountMemo:e?.accountMemo}),s=await n.freezeWithSigner(t),a=await s.executeWithSigner(t),c=await a.getReceiptWithSigner(t),l=c?.accountId?.toString?.(),d=`0x${o.toEvmAddress()}`;return this.logger.info("Created HCS-15 base account (browser)",{accountId:l,evmAddress:d}),{accountId:l,privateKey:r,privateKeyHex:r.toStringRaw(),publicKey:o,evmAddress:d}}async createPetalAccount(e){const t=this.requireSigner(),r=Xh({publicKey:("string"==typeof e.basePrivateKey?i.PrivateKey.fromStringECDSA(e.basePrivateKey):e.basePrivateKey).publicKey,initialBalance:new i.Hbar(e.initialBalance??1),maxAutomaticTokenAssociations:e.maxAutomaticTokenAssociations,accountMemo:e.accountMemo}),o=await r.freezeWithSigner(t),n=await o.executeWithSigner(t),s=await n.getReceiptWithSigner(t),a=s?.accountId?.toString?.();return this.logger.info("Created HCS-15 petal account (browser)",{accountId:a}),{accountId:a}}},exports.HCS15Client=class extends Zh{constructor(e){super(e),this.operatorId=i.AccountId.fromString(e.operatorId),this.operatorCtx=ie({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:"mainnet"===this.network?i.Client.forMainnet():i.Client.forTestnet()}),this.client=this.operatorCtx.client}getKeyType(){return this.operatorCtx.keyType}async close(){try{this.client.close()}catch{}}async createBaseAccount(e){const t=i.PrivateKey.generateECDSA(),r=t.publicKey,o=Yh({publicKey:r,initialBalance:new i.Hbar(e?.initialBalance??10),maxAutomaticTokenAssociations:e?.maxAutomaticTokenAssociations,accountMemo:e?.accountMemo}),n=await o.execute(this.client),s=await n.getReceipt(this.client);if(!s.accountId)throw new Error("HCS-15 BASE_ACCOUNT_CREATE_FAILED");const a=s.accountId.toString(),c=`0x${r.toEvmAddress()}`;return this.logger.info("Created HCS-15 base account",{accountId:a,evmAddress:c}),{accountId:a,privateKey:t,privateKeyHex:t.toStringRaw(),publicKey:r,evmAddress:c,receipt:s}}async createPetalAccount(e){const t=Xh({publicKey:("string"==typeof e.basePrivateKey?i.PrivateKey.fromStringECDSA(e.basePrivateKey):e.basePrivateKey).publicKey,initialBalance:new i.Hbar(e.initialBalance??1),maxAutomaticTokenAssociations:e.maxAutomaticTokenAssociations,accountMemo:e.accountMemo}),r=await t.execute(this.client),o=await r.getReceipt(this.client);if(!o.accountId)throw new Error("HCS-15 PETAL_ACCOUNT_CREATE_FAILED");const n=o.accountId.toString();return this.logger.info("Created HCS-15 petal account",{accountId:n}),{accountId:n,receipt:o}}},exports.HCS16BaseClient=ug,exports.HCS16BrowserClient=class extends ug{constructor(e){super({network:e.network}),this.hwc=e.hwc,this.signer=e.signer}ensureConnected(){if(this.signer&&"function"==typeof this.signer.getAccountId)return this.signer.getAccountId().toString();const e=this.hwc?.getAccountInfo?.(),t=e?.accountId;if(!t)throw new Error("No active wallet connection");return t}getSigner(){if(this.signer)return this.signer;this.ensureConnected();const e=this.hwc?.dAppConnector?.signers?.[0];if(!e)throw new Error("No active wallet signer");return e}async createFloraTopic(e){this.ensureConnected();const t=this.getSigner(),r=rg({floraAccountId:e.floraAccountId,topicType:e.topicType,adminKey:e.adminKey,submitKey:e.submitKey,autoRenewAccountId:e.autoRenewAccountId}),i=await r.freezeWithSigner(t),o=await i.executeWithSigner(t),n=await o.getReceiptWithSigner(t);return n?.topicId?.toString?.()||""}async sendFloraCreated(e){const t=this.getSigner(),r=ng(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async sendTransaction(e){const t=this.getSigner(),r=sg(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async signSchedule(e){const t=this.getSigner(),r=await(new i.ScheduleSignTransaction).setScheduleId(e.scheduleId).freezeWithSigner(t);await r.executeWithSigner(t)}async sendStateUpdate(e){const t=this.getSigner(),r=ag(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async createFloraAccountWithTopics(e){const t=this.getSigner(),r=await this.assembleKeyList({members:e.members,threshold:e.threshold}),i=await this.assembleSubmitKeyList(e.members),o=ig({keyList:r,initialBalanceHbar:"number"==typeof e.initialBalanceHbar?e.initialBalanceHbar:5,maxAutomaticTokenAssociations:-1}),n=await o.freezeWithSigner(t),s=await n.executeWithSigner(t),a=await s.getReceiptWithSigner(t),c=a?.accountId?.toString?.();if(!c)throw new Error("Failed to create Flora account");const{communication:l,transaction:d,state:u}=this.buildFloraTopicCreateTxs({floraAccountId:c,keyList:r,submitList:i,autoRenewAccountId:e.autoRenewAccountId}),p=await(await(await l.freezeWithSigner(t)).executeWithSigner(t)).getReceiptWithSigner(t),h=await(await(await d.freezeWithSigner(t)).executeWithSigner(t)).getReceiptWithSigner(t),g=await(await(await u.freezeWithSigner(t)).executeWithSigner(t)).getReceiptWithSigner(t);return{floraAccountId:c,topics:{communication:p?.topicId?.toString?.()||"",transaction:h?.topicId?.toString?.()||"",state:g?.topicId?.toString?.()||""}}}async publishFloraCreated(e){const t=this.getSigner(),r=ng({topicId:e.communicationTopicId,operatorId:e.operatorId,floraAccountId:e.floraAccountId,topics:e.topics}),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async sendFloraJoinRequest(e){const t=this.getSigner(),r=cg(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async sendFloraJoinVote(e){const t=this.getSigner(),r=lg(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async sendFloraJoinAccepted(e){const t=this.getSigner(),r=dg(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}},exports.HCS16Client=class extends ug{constructor(e){super({network:e.network,logger:e.logger}),this.operatorId=i.AccountId.fromString(e.operatorId);const t=new V(e.network,this.logger);this.operatorCtx=ie({network:e.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:t,logger:this.logger,client:"mainnet"===e.network?i.Client.forMainnet():i.Client.forTestnet()}),this.client=this.operatorCtx.client}async createFloraTopic(e){const t=rg({floraAccountId:e.floraAccountId,topicType:e.topicType,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:this.client.operatorPublicKey||void 0,autoRenewAccountId:e.autoRenewAccountId}),r=await t.execute(this.client),i=await r.getReceipt(this.client);if(!i.topicId)throw new Error("Failed to create Flora topic");return i.topicId.toString()}async sendFloraCreated(e){const t=ng(e);return(await t.execute(this.client)).getReceipt(this.client)}async sendTransaction(e){const t=sg(e);return(await t.execute(this.client)).getReceipt(this.client)}async signSchedule(e){const t=await(new i.ScheduleSignTransaction).setScheduleId(e.scheduleId).freezeWith(this.client),r=await t.sign(e.signerKey);return(await r.execute(this.client)).getReceipt(this.client)}async sendStateUpdate(e){const t=ag(e);return(await t.execute(this.client)).getReceipt(this.client)}async assembleKeyList(e){return super.assembleKeyList(e)}async createFloraAccountWithTopics(e){const t=await this.assembleKeyList({members:e.members,threshold:e.threshold}),r=await this.assembleSubmitKeyList(e.members),i=ig({keyList:t,initialBalanceHbar:"number"==typeof e.initialBalanceHbar?e.initialBalanceHbar:5,maxAutomaticTokenAssociations:-1}),o=await i.execute(this.client),n=await o.getReceipt(this.client);if(!n.accountId)throw new Error("Failed to create Flora account");const s=n.accountId.toString(),{communication:a,transaction:c,state:l}=this.buildFloraTopicCreateTxs({floraAccountId:s,keyList:t,submitList:r,autoRenewAccountId:e.autoRenewAccountId}),d=await a.execute(this.client).then(e=>e.getReceipt(this.client)),u=await c.execute(this.client).then(e=>e.getReceipt(this.client)),p=await l.execute(this.client).then(e=>e.getReceipt(this.client));return{floraAccountId:s,topics:{communication:d.topicId.toString(),transaction:u.topicId.toString(),state:p.topicId.toString()}}}async publishFloraCreated(e){const t=ng({topicId:e.communicationTopicId,operatorId:e.operatorId,floraAccountId:e.floraAccountId,topics:e.topics});return(await t.execute(this.client)).getReceipt(this.client)}},exports.HCS17BaseClient=yg,exports.HCS17BrowserClient=class extends yg{constructor(e){super(e),this.hwc=e.hwc,this.signer=e.signer}ensureConnected(){if(this.signer&&"function"==typeof this.signer.getAccountId)return this.signer.getAccountId().toString();const e=this.hwc?.getAccountInfo?.(),t=e?.accountId;if(!t)throw new Error("No active wallet connection");return t}getSigner(){if(this.signer)return this.signer;this.ensureConnected();const e=this.hwc?.dAppConnector?.signers?.[0];if(!e)throw new Error("No active wallet signer");return e}async createStateTopic(e){this.ensureConnected();const t=this.getSigner(),r=bg({ttl:e?.ttl??86400}),i=await r.freezeWithSigner(t),o=await i.executeWithSigner(t),n=await o.getReceiptWithSigner(t),s=n?.topicId?.toString?.()||"";return this.logger.info(`Created HCS-17 state topic via wallet: ${s}`),s}async submitMessage(e,t){const{valid:r,errors:i}=this.validateMessage(t);if(!r)throw new Error(`Invalid HCS-17 message: ${i.join(", ")}`);const o=this.getSigner(),n=wg({topicId:e,stateHash:t.state_hash,accountId:t.account_id,topics:t.topics,memo:t.m}),s=await n.freezeWithSigner(o),a=await s.executeWithSigner(o);return await a.getReceiptWithSigner(o),{}}async computeAndPublish(e){this.ensureConnected();const t=this.getSigner(),r=[];for(const a of e.topics){const e=(await this.mirrorNode.getTopicMessages(a,{limit:1,order:"desc"}))[0],t=e&&e.running_hash||"";r.push({topicId:a,latestRunningHash:t})}const i={accountId:e.accountId,publicKey:e.accountPublicKey,topics:r},o=this.calculateAccountStateHash(i),n=wg({topicId:e.publishTopicId,stateHash:o.stateHash,accountId:e.accountId,topics:e.topics,memo:e.memo}),s=await n.freezeWithSigner(t);return await s.executeWithSigner(t),{stateHash:o.stateHash}}},exports.HCS17Client=class extends yg{constructor(e){super(e),this.operatorId=i.AccountId.fromString(e.operatorId),this.operatorCtx=ie({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:"mainnet"===e.network?i.Client.forMainnet():i.Client.forTestnet()}),this.client=this.operatorCtx.client}getKeyType(){return this.operatorCtx.keyType}async createStateTopic(e){const t=bg({ttl:e?.ttl??86400,adminKey:e?.adminKey,submitKey:e?.submitKey,operatorPublicKey:this.client.operatorPublicKey||void 0}),r=await t.execute(this.client),i=await r.getReceipt(this.client);if(!i.topicId)throw new Error("Failed to create topic: topicId empty");const o=i.topicId.toString();return this.logger.info(`Created HCS-17 state topic ${o}`),o}async submitMessage(e,t){const{valid:r,errors:i}=this.validateMessage(t);if(!r)throw new Error(`Invalid HCS-17 message: ${i.join(", ")}`);const o=wg({topicId:e,stateHash:t.state_hash,accountId:t.account_id,topics:t.topics,memo:t.m}),n=await o.execute(this.client);return await n.getReceipt(this.client)}async computeAndPublish(e){const t=[];for(const a of e.topics){const e=(await this.mirrorNode.getTopicMessages(a,{limit:1,order:"desc"}))[0],r=e?.running_hash||"";t.push({topicId:a,latestRunningHash:r})}const r={accountId:e.accountId,publicKey:e.accountPublicKey,topics:t},i=this.calculateAccountStateHash(r);this.createStateHashMessage(i.stateHash,e.accountId,e.topics,e.memo);const o=wg({topicId:e.publishTopicId,stateHash:i.stateHash,accountId:e.accountId,topics:e.topics,memo:e.memo}),n=await o.execute(this.client),s=await n.getReceipt(this.client);return{stateHash:i.stateHash,receipt:s}}},exports.HCS17TopicType=gg,exports.HCS18BaseClient=Og,exports.HCS18BrowserClient=class{constructor(e){this.hwc=e.hwc}async submit(e,t){return await this.hwc.submitMessageToTopic(e,JSON.stringify(t))}async announce(e){const t=Ng(e.data);return this.submit(e.discoveryTopicId,t)}async propose(e){const t=_g(e.data);return this.submit(e.discoveryTopicId,t)}async respond(e){const t=Pg(e.data);return this.submit(e.discoveryTopicId,t)}async complete(e){const t=Fg(e.data);return this.submit(e.discoveryTopicId,t)}async withdraw(e){const t=zg(e.data);return this.submit(e.discoveryTopicId,t)}},exports.HCS18Client=class extends Og{constructor(e){super({network:e.network,logger:O.getInstance({level:e.logLevel||"info",module:"HCS-18",silent:e.silent})}),this.operatorCtx=ie({network:this.network,operatorId:e.operatorId,operatorKey:e.operatorKey,mirrorNode:this.mirrorNode,logger:this.logger,client:i.Client.forName(this.network)}),this.client=this.operatorCtx.client}async ensureInitialized(){await this.operatorCtx.ensureInitialized()}async createDiscoveryTopic(e){await this.ensureInitialized();const t=e?.ttlSeconds;let r;try{r=this.operatorCtx.operatorKey.publicKey}catch{r=void 0}const i=xg({ttlSeconds:t,adminKey:e?.adminKey,submitKey:e?.submitKey,operatorPublicKey:r,memoOverride:e?.memoOverride}),o=await i.execute(this.client),n=await o.getReceipt(this.client),s=n.topicId?.toString();if(!s)throw new Error("Failed to create discovery topic");return{topicId:s,receipt:n}}async announce(e){await this.ensureInitialized();const t=Ng(e.data),r=Rg({topicId:e.discoveryTopicId,message:t,transactionMemo:e.memo}),i=await r.execute(this.client),o=await i.getReceipt(this.client),n=o.topicSequenceNumber.toNumber();return{receipt:o,sequenceNumber:n}}async propose(e){await this.ensureInitialized();const t=_g(e.data),r=Rg({topicId:e.discoveryTopicId,message:t,transactionMemo:e.memo}),i=await r.execute(this.client),o=await i.getReceipt(this.client),n=o.topicSequenceNumber.toNumber();return{receipt:o,sequenceNumber:n}}async respond(e){await this.ensureInitialized();const t=Pg(e.data),r=Rg({topicId:e.discoveryTopicId,message:t,transactionMemo:e.memo}),i=await r.execute(this.client);return await i.getReceipt(this.client)}async complete(e){await this.ensureInitialized();const t=Fg(e.data),r=Rg({topicId:e.discoveryTopicId,message:t,transactionMemo:e.memo}),i=await r.execute(this.client);return await i.getReceipt(this.client)}async withdraw(e){await this.ensureInitialized();const t=zg(e.data),r=Rg({topicId:e.discoveryTopicId,message:t,transactionMemo:e.memo}),i=await r.execute(this.client);return await i.getReceipt(this.client)}},exports.HCS20BaseClient=Mh,exports.HCS20BurnMessageSchema=Ah,exports.HCS20Client=class extends Mh{constructor(e){super(e),this.operatorAccountId="string"==typeof e.operatorId?i.AccountId.fromString(e.operatorId):e.operatorId,this.operatorId=this.operatorAccountId.toString();const t="mainnet"===this.network?i.Client.forMainnet():i.Client.forTestnet();this.operatorCtx=ie({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:t}),this.client=this.operatorCtx.client,this.operatorCtx.ensureInitialized()}async ensureInitialized(){await this.operatorCtx.ensureInitialized()}async submitPayload(e,t){let r;if(t){const i=e.freezeWith(this.client),o=await i.sign(t);r=await o.execute(this.client)}else r=await e.execute(this.client);const o=await r.getReceipt(this.client);if(!o||o.status!==i.Status.Success)throw new Error("Failed to submit message to topic");return{receipt:o,transactionId:r.transactionId.toString()}}async createPublicTopic(e){await this.ensureInitialized(),this.logger.info("Creating public HCS-20 topic...");const t=await(new i.TopicCreateTransaction).setTopicMemo(e||"HCS-20 Public Topic").execute(this.client),r=await t.getReceipt(this.client);if(r.status!==i.Status.Success||!r.topicId)throw new Error("Failed to create public topic");const o=r.topicId.toString();return this.logger.info(`Created public topic: ${o}`),this.publicTopicId=o,o}async createRegistryTopic(){await this.ensureInitialized(),this.logger.info("Creating HCS-20 registry topic...");const e=new yh({operatorId:this.operatorId,operatorKey:this.operatorCtx.operatorKey,network:this.network}),t=await e.createRegistry({submitKey:this.operatorCtx.operatorKey,adminKey:this.operatorCtx.operatorKey});if(!t.success)throw new Error("Failed to create registry topic");const r=t.topicId;return this.logger.info(`Created registry topic: ${r}`),this.registryTopicId=r,r}async deployPoints(e){await this.ensureInitialized();const{progressCallback:t}=e;try{let r;t?.({stage:"creating-topic",percentage:20});const i=new yh({operatorId:this.operatorId,operatorKey:this.operatorCtx.operatorKey,network:this.network});if(e.usePrivateTopic){const t=await i.createRegistry({submitKey:this.operatorCtx.operatorKey,adminKey:this.operatorCtx.operatorKey});if(!t.success)throw new _h("Failed to create topic",e.tick);r=t.topicId,this.logger.info(`Created private topic: ${r}`)}else r=this.publicTopicId;t?.({stage:"submitting-deploy",percentage:50,topicId:r});const o={p:"hcs-20",op:"deploy",name:e.name,tick:this.normalizeTick(e.tick),max:e.maxSupply,lim:e.limitPerMint,metadata:e.metadata,m:e.topicMemo},n=this.validateMessage(o);if(!n.valid)throw new zh("Invalid deploy message",n.errors);const s=Bh({topicId:r,name:e.name,tick:e.tick,max:e.maxSupply,lim:e.limitPerMint,metadata:e.metadata,memo:e.topicMemo}),{transactionId:a}=await this.submitPayload(s);t?.({stage:"confirming",percentage:80,topicId:r,deployTxId:a}),await this.waitForMirrorNodeConfirmation(r,a),t?.({stage:"complete",percentage:100,topicId:r,deployTxId:a});return{name:e.name,tick:this.normalizeTick(e.tick),maxSupply:e.maxSupply,limitPerMint:e.limitPerMint,metadata:e.metadata,topicId:r,deployerAccountId:this.operatorId,currentSupply:"0",deploymentTimestamp:(new Date).toISOString(),isPrivate:e.usePrivateTopic||!1}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async mintPoints(e){await this.ensureInitialized();const{progressCallback:t}=e;try{t?.({stage:"validating",percentage:20});const r=this.normalizeTick(e.tick);t?.({stage:"submitting",percentage:50});const i=e.topicId?this.topicToString(e.topicId):this.publicTopicId,o=Kh({topicId:i,tick:e.tick,amt:e.amount,to:this.accountToString(e.to),memo:e.memo}),{transactionId:n}=await this.submitPayload(o);t?.({stage:"confirming",percentage:80,mintTxId:n}),e.disableMirrorCheck||await this.waitForMirrorNodeConfirmation(i,n),t?.({stage:"complete",percentage:100,mintTxId:n});return{id:n,operation:"mint",tick:r,amount:e.amount,to:this.accountToString(e.to),timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:i,transactionId:n,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async transferPoints(e){await this.ensureInitialized();const{progressCallback:t}=e;try{t?.({stage:"validating-balance",percentage:20});const r=this.normalizeTick(e.tick),i=this.accountToString(e.from),o=this.accountToString(e.to);if(i!==this.operatorId)throw new Ph("For public topics, transaction payer must match sender",e.tick,i,o,e.amount);t?.({stage:"submitting",percentage:50});const n=e.topicId?this.topicToString(e.topicId):this.publicTopicId,s=Uh({topicId:n,tick:e.tick,amt:e.amount,from:i,to:o,memo:e.memo}),{transactionId:a}=await this.submitPayload(s);t?.({stage:"confirming",percentage:80,transferTxId:a}),await this.waitForMirrorNodeConfirmation(n,a),t?.({stage:"complete",percentage:100,transferTxId:a});return{id:a,operation:"transfer",tick:r,amount:e.amount,from:i,to:o,timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:n,transactionId:a,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async burnPoints(e){await this.ensureInitialized();const{progressCallback:t}=e;try{t?.({stage:"validating-balance",percentage:20});const r=this.normalizeTick(e.tick),i=this.accountToString(e.from);if(i!==this.operatorId)throw new Fh("For public topics, transaction payer must match burner",e.tick,i,e.amount);t?.({stage:"submitting",percentage:50});const o=e.topicId?this.topicToString(e.topicId):this.publicTopicId,n=Lh({topicId:o,tick:e.tick,amt:e.amount,from:i,memo:e.memo}),{transactionId:s}=await this.submitPayload(n);t?.({stage:"confirming",percentage:80,burnTxId:s}),await this.waitForMirrorNodeConfirmation(o,s),t?.({stage:"complete",percentage:100,burnTxId:s});return{id:s,operation:"burn",tick:r,amount:e.amount,from:i,timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:o,transactionId:s,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async registerTopic(e){await this.ensureInitialized();const{progressCallback:t}=e;try{t?.({stage:"validating",percentage:20});const r={p:"hcs-20",op:"register",name:e.name,metadata:e.metadata,private:e.isPrivate,t_id:this.topicToString(e.topicId),m:e.memo},i=this.validateMessage(r);if(!i.valid)throw new zh("Invalid register message",i.errors);if(!this.registryTopicId)throw new _h("Registry topic not available",e.name);t?.({stage:"submitting",percentage:50});const o=$h({registryTopicId:this.registryTopicId,name:e.name,topicId:this.topicToString(e.topicId),isPrivate:e.isPrivate,metadata:e.metadata,memo:e.memo}),{transactionId:n}=await this.submitPayload(o,this.operatorCtx.operatorKey);t?.({stage:"confirming",percentage:80,registerTxId:n}),await this.waitForMirrorNodeConfirmation(this.registryTopicId,n),t?.({stage:"complete",percentage:100,registerTxId:n}),this.logger.info(`Registered topic ${e.topicId} in registry`)}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async waitForMirrorNodeConfirmation(e,t,r=10){for(let o=0;o<r;o++){try{const r=await this.mirrorNode.getTopicMessages(e,{limit:10,order:"desc"});if(r.some(e=>{if("object"!=typeof e||null===e)return!1;return"string"==typeof e.consensus_timestamp}))return void this.logger.debug(`Transaction ${t} confirmed on mirror node`)}catch(i){this.logger.debug(`Mirror node check attempt ${o+1} failed:`,i)}await D(2e3)}this.logger.warn(`Transaction ${t} not found on mirror node after ${r} attempts`)}},exports.HCS20DeployMessageSchema=Eh,exports.HCS20Error=Nh,exports.HCS20MessageSchema=Rh,exports.HCS20MintMessageSchema=vh,exports.HCS20PointsIndexer=class{constructor(e,t,r){this.isProcessing=!1,this.lastIndexedSequence=new Map,this.logger=t||new O({level:"info",module:"HCS20PointsIndexer"}),this.mirrorNode=new V(e,this.logger,{customUrl:r}),this.state=this.initializeState()}initializeState(){return{deployedPoints:new Map,balances:new Map,transactions:[],lastProcessedSequence:0,lastProcessedTimestamp:(new Date).toISOString()}}getState(){return{...this.state,deployedPoints:new Map(this.state.deployedPoints),balances:new Map(this.state.balances),transactions:[...this.state.transactions]}}getPointsInfo(e){return this.state.deployedPoints.get(this.normalizeTick(e))}getBalance(e,t){const r=this.normalizeTick(e),i=this.state.balances.get(r);if(!i)return"0";const o=i.get(t);return o?.balance||"0"}async startIndexing(e){if(this.isProcessing)return void this.logger.warn("Indexing already in progress");this.isProcessing=!0;const t=!1!==e?.includePublicTopic,r=!1!==e?.includeRegistryTopic,i=t?e?.publicTopicId||wh.PUBLIC_TOPIC_ID:null,o=r?e?.registryTopicId||wh.REGISTRY_TOPIC_ID:null,n=e?.pollInterval||3e4;await this.indexTopics(i,o,e?.privateTopics);const s=async()=>{if(this.isProcessing){try{await this.indexTopics(i,o,e?.privateTopics)}catch(t){this.logger.error("Polling error:",t)}this.isProcessing&&setTimeout(s,n)}};setTimeout(s,n)}async indexOnce(e){const t=!1!==e?.includePublicTopic,r=!1!==e?.includeRegistryTopic,i=t?e?.publicTopicId||wh.PUBLIC_TOPIC_ID:null,o=r?e?.registryTopicId||wh.REGISTRY_TOPIC_ID:null;await this.indexTopics(i,o,e?.privateTopics)}stopIndexing(){this.isProcessing=!1,this.logger.info("Indexing stopped")}async indexTopics(e,t,r){this.logger.debug("Starting indexing cycle"),e&&await this.indexTopic(e,!1);const i=[...t?await this.getRegisteredTopics(t):[],...r||[]];for(const o of i)await this.indexTopic(o,!0);this.logger.debug("Indexing cycle complete")}async getRegisteredTopics(e){const t=[];try{(await this.mirrorNode.getTopicMessages(e,{limit:100,order:"asc"})).filter(e=>"hcs-20"===e.p&&"register"===e.op&&"string"==typeof e.t_id).forEach(e=>{t.push(e.t_id)})}catch(r){this.logger.error("Failed to fetch registry messages:",r)}return t}async indexTopic(e,t){try{const r=this.lastIndexedSequence.get(e);this.logger.debug(`Indexing topic ${e}, starting from sequence ${r||0}`);const i=await this.mirrorNode.getTopicMessages(e,{sequenceNumber:r?r+1:void 0,limit:1e3,order:"asc"});this.logger.debug(`Fetched ${i.length} messages from topic ${e}`);let o=r||0;for(const n of i){if("hcs-20"!==n.p)continue;const r=Rh.safeParse(n);if(!r.success){this.logger.debug("Skipping message due to schema mismatch");continue}const i=r.data,s=n.sequence_number??0;this.logger.debug(`Found HCS-20 message: op=${i.op}, sequence=${s}`),s>o&&(o=s);const a={consensus_timestamp:n.consensus_timestamp??"",sequence_number:s,payer_account_id:n.payer_account_id??n.payer??"",transaction_id:n.transaction_id??""};this.processMessage(i,a,e,t),this.state.lastProcessedSequence++,this.state.lastProcessedTimestamp=n.consensus_timestamp||""}o>(r||0)&&this.lastIndexedSequence.set(e,o)}catch(r){this.logger.error(`Failed to index topic ${e}:`,r)}}processMessage(e,t,r,i){switch(e.op){case"deploy":this.processDeployMessage(e,t,r,i);break;case"mint":this.processMintMessage(e,t,r,i);break;case"transfer":this.processTransferMessage(e,t,r,i);break;case"burn":this.processBurnMessage(e,t,r,i)}}processDeployMessage(e,t,r,i){const o=this.normalizeTick(e.tick);if(this.state.deployedPoints.has(o))return;const n={name:e.name,tick:o,maxSupply:e.max,limitPerMint:e.lim,metadata:e.metadata,topicId:r,deployerAccountId:t.payer_account_id,currentSupply:"0",deploymentTimestamp:t.consensus_timestamp,isPrivate:i};this.state.deployedPoints.set(o,n),this.logger.info(`Deployed points: ${o}`)}processMintMessage(e,t,r,i){const o=this.normalizeTick(e.tick),n=this.state.deployedPoints.get(o);if(!n)return;const s=BigInt(e.amt),a=BigInt(n.currentSupply);if(a+s>BigInt(n.maxSupply))return;if(n.limitPerMint&&s>BigInt(n.limitPerMint))return;n.currentSupply=(a+s).toString();let c=this.state.balances.get(o);c||(c=new Map,this.state.balances.set(o,c));const l=c.get(e.to),d=l?(BigInt(l.balance)+s).toString():e.amt;c.set(e.to,{tick:o,accountId:e.to,balance:d,lastUpdated:t.consensus_timestamp}),this.state.transactions.push({id:t.transaction_id||`${r}-${t.sequence_number}`,operation:"mint",tick:o,amount:e.amt,to:e.to,timestamp:t.consensus_timestamp,sequenceNumber:t.sequence_number,topicId:r,transactionId:t.transaction_id||"",memo:e.m})}processTransferMessage(e,t,r,i){const o=this.normalizeTick(e.tick),n=this.state.balances.get(o);if(!n)return;if(!i&&t.payer_account_id!==e.from)return;const s=n.get(e.from);if(!s||BigInt(s.balance)<BigInt(e.amt))return;const a=BigInt(e.amt);s.balance=(BigInt(s.balance)-a).toString(),s.lastUpdated=t.consensus_timestamp;const c=n.get(e.to);c?(c.balance=(BigInt(c.balance)+a).toString(),c.lastUpdated=t.consensus_timestamp):n.set(e.to,{tick:o,accountId:e.to,balance:e.amt,lastUpdated:t.consensus_timestamp}),this.state.transactions.push({id:t.transaction_id||`${r}-${t.sequence_number}`,operation:"transfer",tick:o,amount:e.amt,from:e.from,to:e.to,timestamp:t.consensus_timestamp,sequenceNumber:t.sequence_number,topicId:r,transactionId:t.transaction_id||"",memo:e.m})}processBurnMessage(e,t,r,i){const o=this.normalizeTick(e.tick),n=this.state.deployedPoints.get(o),s=this.state.balances.get(o);if(!n||!s)return;if(!i&&t.payer_account_id!==e.from)return;const a=s.get(e.from);if(!a||BigInt(a.balance)<BigInt(e.amt))return;const c=BigInt(e.amt);a.balance=(BigInt(a.balance)-c).toString(),a.lastUpdated=t.consensus_timestamp,n.currentSupply=(BigInt(n.currentSupply)-c).toString(),this.state.transactions.push({id:t.transaction_id||`${r}-${t.sequence_number}`,operation:"burn",tick:o,amount:e.amt,from:e.from,timestamp:t.consensus_timestamp,sequenceNumber:t.sequence_number,topicId:r,transactionId:t.transaction_id||"",memo:e.m})}normalizeTick(e){return e.toLowerCase().trim()}},exports.HCS20RegisterMessageSchema=xh,exports.HCS20TransferMessageSchema=Ch,exports.HCS20_CONSTANTS=wh,exports.HCS21BaseClient=Vh,exports.HCS21BrowserClient=class extends Vh{constructor(e){super({network:e.network,logger:e.logger}),this.hwc=e.hwc}async createRegistryTopic(e){const{publicKey:t}=await this.getSignerContext(),r=jh({ttl:e.ttl,indexed:e.indexed,type:e.type,metaTopicId:e.metaTopicId,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:t});e.transactionMemo&&r.setTransactionMemo(e.transactionMemo);const{receipt:o}=await this.executeWithWallet(r);if(o.status!==i.Status.Success||!o.topicId)throw new Hh("Failed to create HCS-21 registry topic","invalid_payload");return o.topicId.toString()}async createAdapterVersionPointerTopic(e){const{publicKey:t}=await this.getSignerContext(),r=gh({registryType:nh.NON_INDEXED,ttl:e.ttl,adminKey:e.adminKey,submitKey:e.submitKey,memoOverride:e.memoOverride,operatorPublicKey:t});e.transactionMemo&&r.setTransactionMemo(e.transactionMemo);const{receipt:o}=await this.executeWithWallet(r);if(o.status!==i.Status.Success||!o.topicId)throw new Hh("Failed to create HCS-2 registry version topic","invalid_payload");return o.topicId.toString()}async createRegistryDiscoveryTopic(e){const{publicKey:t}=await this.getSignerContext(),r=gh({registryType:nh.INDEXED,ttl:e.ttl,adminKey:e.adminKey,submitKey:e.submitKey,memoOverride:e.memoOverride,operatorPublicKey:t});e.transactionMemo&&r.setTransactionMemo(e.transactionMemo);const{receipt:o}=await this.executeWithWallet(r);if(o.status!==i.Status.Success||!o.topicId)throw new Hh("Failed to create registry-of-registries topic","invalid_payload");return o.topicId.toString()}async createAdapterCategoryTopic(e){const{publicKey:t}=await this.getSignerContext(),r=jh({ttl:e.ttl,indexed:e.indexed??0,type:pc.ADAPTER_CATEGORY,metaTopicId:e.metaTopicId,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:t});e.transactionMemo&&r.setTransactionMemo(e.transactionMemo);const{receipt:o}=await this.executeWithWallet(r);if(o.status!==i.Status.Success||!o.topicId)throw new Hh("Failed to create adapter category topic","invalid_payload");return o.topicId.toString()}async publishVersionPointer(e){const t=mh({registryTopicId:e.versionTopicId,targetTopicId:e.declarationTopicId,memo:e.memo,analyticsMemo:e.transactionMemo}),{receipt:r,transactionId:o}=await this.executeWithWallet(t);if(r.status!==i.Status.Success)throw new Hh("Failed to publish registry version pointer","invalid_payload");return{sequenceNumber:this.toNumber(r.topicSequenceNumber),transactionId:o}}async resolveVersionPointer(e){const[t]=await this.mirrorNode.getTopicMessages(e,{limit:1,order:"desc"});if(!t)throw new Hh("Version pointer topic has no messages","invalid_payload");const r=t.t_id;if("string"!=typeof r||0===r.length)throw new Hh("Version pointer topic does not include a declaration topic ID (`t_id`)","invalid_payload");const i="number"==typeof t.sequence_number?t.sequence_number:Number(t.sequence_number);return{versionTopicId:e,declarationTopicId:r,sequenceNumber:Number.isFinite(i)?i:0,payer:t.payer,memo:t.m,op:t.op}}async registerCategoryTopic(e){const t=mh({registryTopicId:e.discoveryTopicId,targetTopicId:e.categoryTopicId,metadata:e.metadata,memo:e.memo,analyticsMemo:e.transactionMemo}),{receipt:r,transactionId:o}=await this.executeWithWallet(t);if(r.status!==i.Status.Success)throw new Hh("Failed to register adapter category topic","invalid_payload");return{sequenceNumber:this.toNumber(r.topicSequenceNumber),transactionId:o}}async publishCategoryEntry(e){const t=e.memo??`adapter:${e.adapterId}`,r=mh({registryTopicId:e.categoryTopicId,targetTopicId:e.versionTopicId,metadata:e.metadata,memo:t,analyticsMemo:e.transactionMemo}),{receipt:o,transactionId:n}=await this.executeWithWallet(r);if(o.status!==i.Status.Success)throw new Hh("Failed to publish adapter category entry","invalid_payload");return{sequenceNumber:this.toNumber(o.topicSequenceNumber),transactionId:n}}async publishDeclaration(e){const t="p"in e.declaration?this.validateDeclaration(e.declaration):this.buildDeclaration(e.declaration),r=Wh({topicId:e.topicId,declaration:t,transactionMemo:e.transactionMemo}),{receipt:o,transactionId:n}=await this.executeWithWallet(r);if(o.status!==i.Status.Success)throw new Hh("Failed to submit HCS-21 declaration","invalid_payload");return{sequenceNumber:this.toNumber(o.topicSequenceNumber),transactionId:n}}async fetchDeclarations(e,t){const{messages:r=[]}=await this.hwc.getMessages(e),i=[];for(const s of r)if(s&&"hcs-21"===s.p)try{const e=this.validateDeclaration(s);i.push({declaration:e,consensusTimestamp:s.consensus_timestamp,sequenceNumber:Number(s.sequence_number??0),payer:s.payer})}catch(n){const e=n instanceof Error?n.message:"unknown error";this.logger.warn(`Skipping invalid HCS-21 browser message: ${e}`)}const o="desc"===t?.order?[...i].sort((e,t)=>t.sequenceNumber-e.sequenceNumber):i;return t?.limit&&t.limit>0?o.slice(0,t.limit):o}async getSignerContext(){if(this.signerCache)return this.signerCache;const e=this.hwc.getAccountInfo?.(),t="string"==typeof e?e:e?.accountId;if(!t)throw new Hh("Wallet is not connected","invalid_payload");const r=await this.hwc.requestAccount(t),o=r?.key?.key;if(!o)throw new Hh("Unable to resolve wallet public key","invalid_payload");const n=i.PublicKey.fromString(o);return this.signerCache={accountId:t,publicKey:n},this.signerCache}async executeWithWallet(e){const{accountId:t}=await this.getSignerContext(),r=i.TransactionId.generate(i.AccountId.fromString(t));e.setTransactionId(r);return{receipt:await this.hwc.executeTransaction(e,!1),transactionId:r.toString()}}toNumber(e){return"number"==typeof e?e:e&&"function"==typeof e.toNumber?e.toNumber():void 0}},exports.HCS21Client=class extends Vh{constructor(e){const t=e.logger||new O({level:e.logLevel||"info",module:"HCS-21"});super({network:e.network,logger:t,mirrorNodeUrl:e.mirrorNodeUrl});const r="mainnet"===e.network?i.Client.forMainnet():i.Client.forTestnet();this.operatorCtx=ie({network:e.network,operatorId:e.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:r}),this.operatorCtx.ensureInitialized(),this.client=this.operatorCtx.client}async inscribeMetadata(e){await this.operatorCtx.ensureInitialized();const t=bc.parse(e.document),r=JSON.stringify(t,null,2),i=globalThis.Buffer.from(r,"utf8"),o={waitForConfirmation:!0,connectionMode:e.inscriptionOptions?.connectionMode??(!1===e.inscriptionOptions?.websocket?"http":"auto"),websocket:e.inscriptionOptions?.websocket??!1,...e.inscriptionOptions||{},metadata:{...e.inscriptionOptions?.metadata||{},...t}},n=await za({type:"buffer",buffer:i,fileName:e.fileName||`hcs21-adapter-manifest-${Date.now()}.json`,mimeType:"application/json"},{accountId:this.operatorCtx.operatorId.toString(),privateKey:this.operatorCtx.operatorKey,network:this.network},o);if(!n.confirmed||!n.inscription)throw new Hh("Failed to inscribe HCS-21 metadata","invalid_payload");const s=n.inscription.jsonTopicId||n.inscription.topic_id||La(n.inscription);if(!s)throw new Hh("Metadata inscription did not return a topic ID","invalid_payload");const a=n.inscription.sequence_number??n.inscription.sequenceNumber,c=await this.resolveManifestPointer(s,a),l=n.result?.manifest_sequence,d=n.result&&"jobId"in n.result?{jobId:n.result.jobId,transactionId:n.result.transactionId,totalCostHbar:n.costSummary?.totalCostHbar,costBreakdown:n.costSummary?.breakdown}:{};return{pointer:c.pointer,topicId:s,sequenceNumber:c.sequenceNumber,manifestSequence:l||c.sequenceNumber,...d}}async createRegistryTopic(e){await this.operatorCtx.ensureInitialized();const t=jh({ttl:e.ttl,indexed:e.indexed,type:e.type,metaTopicId:e.metaTopicId,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:this.operatorCtx.operatorKey.publicKey});e.transactionMemo&&t.setTransactionMemo(e.transactionMemo);const r=await t.execute(this.client),o=await r.getReceipt(this.client);if(o.status!==i.Status.Success||!o.topicId)throw new Hh("Failed to create HCS-21 registry topic","invalid_payload");return o.topicId.toString()}async createAdapterVersionPointerTopic(e){await this.operatorCtx.ensureInitialized();const t=gh({registryType:nh.NON_INDEXED,ttl:e.ttl,adminKey:e.adminKey,submitKey:e.submitKey,memoOverride:e.memoOverride,operatorPublicKey:this.operatorCtx.operatorKey.publicKey});e.transactionMemo&&t.setTransactionMemo(e.transactionMemo);const r=await t.execute(this.client),o=await r.getReceipt(this.client);if(o.status!==i.Status.Success||!o.topicId)throw new Hh("Failed to create HCS-2 registry version topic","invalid_payload");return o.topicId.toString()}async createRegistryDiscoveryTopic(e){await this.operatorCtx.ensureInitialized();const t=gh({registryType:nh.INDEXED,ttl:e.ttl,adminKey:e.adminKey,submitKey:e.submitKey,memoOverride:e.memoOverride,operatorPublicKey:this.operatorCtx.operatorKey.publicKey});e.transactionMemo&&t.setTransactionMemo(e.transactionMemo);const r=await t.execute(this.client),o=await r.getReceipt(this.client);if(o.status!==i.Status.Success||!o.topicId)throw new Hh("Failed to create registry-of-registries topic","invalid_payload");return o.topicId.toString()}async createAdapterCategoryTopic(e){await this.operatorCtx.ensureInitialized();const t=jh({ttl:e.ttl,indexed:e.indexed??0,type:pc.ADAPTER_CATEGORY,metaTopicId:e.metaTopicId,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:this.operatorCtx.operatorKey.publicKey});e.transactionMemo&&t.setTransactionMemo(e.transactionMemo);const r=await t.execute(this.client),o=await r.getReceipt(this.client);if(o.status!==i.Status.Success||!o.topicId)throw new Hh("Failed to create adapter category topic","invalid_payload");return o.topicId.toString()}async publishVersionPointer(e){await this.operatorCtx.ensureInitialized();const t=mh({registryTopicId:e.versionTopicId,targetTopicId:e.declarationTopicId,memo:e.memo,analyticsMemo:e.transactionMemo}),r=await t.execute(this.client),o=await r.getReceipt(this.client);if(o.status!==i.Status.Success)throw new Hh("Failed to publish registry version pointer","invalid_payload");return{sequenceNumber:o.topicSequenceNumber?.toNumber(),transactionId:r.transactionId.toString()}}async resolveVersionPointer(e){const[t]=await this.mirrorNode.getTopicMessages(e,{limit:1,order:"desc"});if(!t)throw new Hh("Version pointer topic has no messages","invalid_payload");const r=t.t_id;if("string"!=typeof r||0===r.length)throw new Hh("Version pointer topic does not include a declaration topic ID (`t_id`)","invalid_payload");const i="number"==typeof t.sequence_number?t.sequence_number:Number(t.sequence_number);return{versionTopicId:e,declarationTopicId:r,sequenceNumber:Number.isFinite(i)?i:0,payer:t.payer,memo:t.m,op:t.op}}async registerCategoryTopic(e){await this.operatorCtx.ensureInitialized();const t=mh({registryTopicId:e.discoveryTopicId,targetTopicId:e.categoryTopicId,metadata:e.metadata,memo:e.memo,analyticsMemo:e.transactionMemo}),r=await t.execute(this.client),o=await r.getReceipt(this.client);if(o.status!==i.Status.Success)throw new Hh("Failed to register adapter category topic","invalid_payload");return{sequenceNumber:o.topicSequenceNumber?.toNumber(),transactionId:r.transactionId.toString()}}async publishCategoryEntry(e){await this.operatorCtx.ensureInitialized();const t=e.memo??`adapter:${e.adapterId}`,r=mh({registryTopicId:e.categoryTopicId,targetTopicId:e.versionTopicId,metadata:e.metadata,memo:t,analyticsMemo:e.transactionMemo}),o=await r.execute(this.client),n=await o.getReceipt(this.client);if(n.status!==i.Status.Success)throw new Hh("Failed to publish adapter category entry","invalid_payload");return{sequenceNumber:n.topicSequenceNumber?.toNumber(),transactionId:o.transactionId.toString()}}async publishDeclaration(e){await this.operatorCtx.ensureInitialized();const t=this.normalizeDeclarationInput(e.declaration),r=Wh({topicId:e.topicId,declaration:t,transactionMemo:e.transactionMemo}),o=await r.execute(this.client),n=await o.getReceipt(this.client);if(n.status!==i.Status.Success)throw new Hh("Failed to submit HCS-21 declaration","invalid_payload");return{sequenceNumber:n.topicSequenceNumber?.toNumber(),transactionId:o.transactionId.toString()}}normalizeDeclarationInput(e){return"p"in e?this.validateDeclaration(e):this.buildDeclaration(e)}async resolveManifestPointer(e,t){const r="string"==typeof t?Number(t):t;let i="number"==typeof r&&Number.isFinite(r)?r:void 0;if(!i){const[t]=await this.mirrorNode.getTopicMessages(e,{limit:1,order:"desc"});if(!t||!t.sequence_number)throw new Hh("Unable to resolve manifest sequence number","invalid_payload");i=Number(t.sequence_number)}if(!Number.isFinite(i))throw new Hh("Invalid manifest sequence number","invalid_payload");const o=`hcs://1/${e}`;if(!dc.test(o))throw new Hh("Manifest pointer format is invalid","invalid_payload");return{pointer:o,sequenceNumber:i}}},exports.HCS21ManifestPointerPattern=dc,exports.HCS21MetadataPointerPattern=uc,exports.HCS21TopicIdPattern=/^0\.0\.\d+$/,exports.HCS21TopicType=pc,exports.HCS21ValidationError=Hh,exports.HCS21_MAX_MESSAGE_BYTES=cc,exports.HCS21_PROTOCOL=ac,exports.HCS21_SAFE_MESSAGE_BYTES=lc,exports.HCS2BaseClient=hh,exports.HCS2Client=yh,exports.HCS2Operation=oh,exports.HCS2RegistryType=nh,exports.HCS5BrowserClient=class extends rh{constructor(e){super({network:e.network,logLevel:e.logLevel,silent:e.silent,logger:void 0,operatorId:"0.0.0",operatorKey:""}),this.hwc=e.hwc,this.signer=e.signer}getSigner(){if(this.signer)return this.signer;const e=this.hwc.getAccountInfo()?.accountId,t=this.hwc.dAppConnector?.signers?.find(t=>t.getAccountId().toString()===e);if(!t)throw new Error("No active wallet signer");return t}async mint(e){try{if(!e.metadataTopicId)return{success:!1,error:"metadataTopicId is required for mint()"};const t=th(e.metadataTopicId),r=ih({tokenId:e.tokenId,metadata:t});let o;if(e.supplyKey&&e.supplyKey instanceof i.PrivateKey){const t=this.getSigner();r.freezeWithSigner(t);const i=await r.sign(e.supplyKey);o=await this.hwc.executeTransactionWithErrorHandling(i,!0)}else o=await this.hwc.executeTransactionWithErrorHandling(r,!1);if(o.error)return{success:!1,error:o.error};const n=o.result;return{success:!0,serialNumber:n.serials?.[0]?Number(n.serials[0].toString()):void 0,transactionId:n?.transactionId?.toString?.(),metadata:t}}catch($g){return{success:!1,error:String($g)}}}async createHashinal(e){try{const t=this.getSigner(),r={...e.inscriptionOptions,mode:"hashinal",waitForConfirmation:!0,network:this.network},i=await Da(e.inscriptionInput,t,r),o=i.inscription?.jsonTopicId||i.inscription?.topic_id;return i.confirmed&&o?await this.mint({tokenId:e.tokenId,metadataTopicId:o,supplyKey:e.supplyKey,memo:e.memo}):{success:!1,error:"Failed to inscribe content"}}catch($g){return{success:!1,error:String($g)}}}},exports.HCS5Client=class extends rh{constructor(e){super(e),this.operatorId=i.AccountId.fromString(e.operatorId),this.operatorCtx=ie({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,mirrorNode:this.mirrorNode,logger:this.logger}),this.client=this.operatorCtx.client}async ensureInitialized(){await this.operatorCtx.ensureInitialized()}async mint(e){try{if(await this.ensureInitialized(),!e.metadataTopicId)return{success:!1,error:"metadataTopicId is required for mint()"};const t=th(e.metadataTopicId),r=ih({tokenId:e.tokenId,metadata:t}),i=await r.freezeWith(this.client);if(e.supplyKey){const t=new re({mirrorNode:this.mirrorNode,logger:this.logger}),r="string"==typeof e.supplyKey?await t.resolveSupplyKey(e.tokenId,e.supplyKey,this.operatorCtx.keyType):e.supplyKey;await i.sign(r)}const o=await i.execute(this.client),n=await o.getReceipt(this.client);return{success:!0,serialNumber:n.serials&&n.serials[0]?Number(n.serials[0].toString()):void 0,transactionId:o.transactionId?.toString?.(),metadata:t}}catch($g){const t=$g;return this.logger.error(`Failed to mint HCS-5 Hashinal: ${t.message}`),{success:!1,error:t.message}}}async createHashinal(e){try{await this.ensureInitialized();const t=await za(e.inscriptionInput,{accountId:this.operatorId.toString(),privateKey:this.operatorCtx.operatorKey,network:this.network},{...e.inscriptionOptions||{},mode:"hashinal",waitForConfirmation:!0});if(!t.confirmed||!t.inscription)return{success:!1,error:"Failed to inscribe content"};const r=t.inscription.jsonTopicId||t.inscription.topic_id;return r?await this.mint({tokenId:e.tokenId,metadataTopicId:r,supplyKey:e.supplyKey,memo:e.memo}):{success:!1,error:"No topic ID from inscription"}}catch($g){const t=$g;return this.logger.error(`Failed to inscribe and mint HCS-5 Hashinal: ${t.message}`),{success:!1,error:t.message}}}},exports.HCS6BaseClient=G,exports.HCS6BrowserClient=class extends G{constructor(e){super(e),this.hwc=e.hwc,this.signer=e.signer}ensureConnected(){const e=this.hwc.getAccountInfo(),t=e?.accountId;if(!t)throw new Error("No active wallet connection: wallet integration required to perform write operations");return t}getSigner(){const e=this.signer;if(e)return e;this.ensureConnected();const t=this.hwc.dAppConnector,r=t?.signers?.[0];if(!r)throw new Error("No active wallet signer");return r}async createRegistry(e){try{this.ensureConnected();const t=e?.ttl??86400,r=this.generateRegistryMemo(t),i=await this.hwc.createTopic(r);return this.logger.info(`Created HCS-6 registry topic via wallet: ${i} (TTL ${t})`),{success:!0,topicId:i}}catch(t){return this.logger.error(`Failed to create HCS-6 registry: ${t}`),{success:!1,error:String(t)}}}async registerEntry(e,t){try{if(!(await this.validateHCS6Topic(e)))throw new Error(`Topic ${e} is not a valid HCS-6 registry`);const r=this.createRegisterMessage(t.targetTopicId,t.memo),i=await this.submitMessage(e,r),o=i.topicSequenceNumber;return{success:!0,receipt:i,sequenceNumber:"number"==typeof o?o:o?.low}}catch(r){return this.logger.error(`Failed to register HCS-6 entry: ${r}`),{success:!1,error:String(r)}}}async getRegistry(e,t={}){try{const r=await this.mirrorNode.getTopicInfo(e);this.logger.debug(`Retrieved topic info for HCS-6 ${e}: ${JSON.stringify(r)}`);const i=this.parseRegistryTypeFromMemo(r.memo);if(!i)throw new Error(`Topic ${e} is not an HCS-6 registry (invalid memo format)`);this.logger.debug(`Retrieving messages for HCS-6 topic ${e} with limit ${t.limit??100}`);const o=await this.mirrorNode.getTopicMessages(e,{sequenceNumber:t.skip&&t.skip>0?`gt:${t.skip}`:void 0,limit:t.limit??100,order:t.order??"asc"}),n=t.limit?o.slice(0,t.limit):o;return this.logger.debug(`Retrieved ${o.length} messages, using ${n.length} after applying limit.`),this.parseRegistryEntries(e,n,i.registryType,i.ttl)}catch(r){throw this.logger.error(`Failed to get HCS-6 registry: ${r}`),r}}async submitMessage(e,t){this.ensureConnected();const{valid:r,errors:i}=this.validateMessage(t);if(!r)throw new Error(`Invalid HCS-6 message: ${i.join(", ")}`);return await this.hwc.submitMessageToTopic(e,JSON.stringify(t))}async createHashinal(e){try{if(!this.signer)return{success:!1,error:"No signer configured for browser createHashinal"};const t={...e.inscriptionOptions,mode:"hashinal",metadata:e.metadata,waitForConfirmation:!0,network:this.network},r={type:"buffer",buffer:globalThis.Buffer.from(JSON.stringify(e.metadata)),fileName:"metadata.json",mimeType:"application/json"},i=await Da(r,this.signer,t),o=i.inscription?.jsonTopicId||La(i.inscription);if(!o)return{success:!1,error:"Failed to inscribe metadata"};let n=e.registryTopicId;if(!n){const t=await this.createRegistry({ttl:e.ttl});if(!t.success||!t.topicId)return{success:!1,error:t.error};n=t.topicId}const s=await this.registerEntry(n,{targetTopicId:o,memo:e.memo||"Initial dynamic hashinal registration"});return s.success?{success:!0,registryTopicId:n,inscriptionTopicId:o}:{success:!1,error:s.error}}catch(t){return this.logger.error(`Failed to create dynamic hashinal: ${t}`),{success:!1,error:String(t)}}}async register(e){try{if(!this.signer)return{success:!1,error:"No signer configured for browser register"};let t;t=e.data?.base64?{type:"buffer",buffer:globalThis.Buffer.from(e.data.base64,"base64"),fileName:"data."+(e.data.mimeType?.split("/")[1]||"bin"),mimeType:e.data.mimeType||"application/octet-stream"}:e.data?.url?{type:"url",url:e.data.url}:{type:"buffer",buffer:globalThis.Buffer.from(JSON.stringify(e.metadata)),fileName:"metadata.json",mimeType:"application/json"};const r={...e.inscriptionOptions,mode:"hashinal",metadata:e.metadata,waitForConfirmation:!0,network:this.network},i=await Da(t,this.signer,r),o=i.inscription?.jsonTopicId||La(i.inscription);if(!o)return{success:!1,error:"Failed to inscribe data"};let n=e.registryTopicId;if(!n){const t=await this.createRegistry({ttl:e.ttl});if(!t.success||!t.topicId)return{success:!1,error:t.error};n=t.topicId}const s=await this.registerEntry(n,{targetTopicId:o,memo:e.memo||"Dynamic hashinal registration"});return s.success?{success:!0,registryTopicId:n,inscriptionTopicId:o}:{success:!1,error:s.error}}catch(t){return this.logger.error(`Failed to register dynamic hashinal: ${t}`),{success:!1,error:String(t)}}}async validateHCS6Topic(e){try{const t=await this.mirrorNode.getTopicInfo(e),r=this.parseRegistryTypeFromMemo(t.memo);return r?r.registryType===K.NON_INDEXED||(this.logger.warn(`Topic ${e} is not a valid HCS-6 registry (must be non-indexed)`),!1):(this.logger.warn(`Topic ${e} is not a valid HCS-6 registry (invalid memo format)`),!1)}catch(t){return this.logger.error(`Error validating HCS-6 topic ${e}: ${t}`),!1}}},exports.HCS6Client=class extends G{constructor(e){super({network:e.network,logLevel:e.logLevel,silent:e.silent,mirrorNodeUrl:e.mirrorNodeUrl,logger:e.logger}),this.operatorId="string"==typeof e.operatorId?i.AccountId.fromString(e.operatorId):e.operatorId,this.operatorCtx=ie({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:this.createClient(e.network)}),this.client=this.operatorCtx.client}async ensureInitialized(){await this.operatorCtx.ensureInitialized()}createClient(e){return"mainnet"===e?i.Client.forMainnet():i.Client.forTestnet()}close(){this.logger.info("HCS-6 client closed.")}getKeyType(){return this.operatorCtx.keyType}getOperatorKey(){return this.operatorCtx.operatorKey}async submitMessage(e,t){return this.submitMessageWithKey(e,t,void 0)}async submitMessageWithKey(e,t,r){const{valid:o,errors:n}=this.validateMessage(t);if(!o)throw new Error(`Invalid HCS-6 message: ${n.join(", ")}`);let s=(new i.TopicMessageSubmitTransaction).setTopicId(i.TopicId.fromString(e)).setMessage(JSON.stringify(t));if(!r){const e=await s.execute(this.client);return await e.getReceipt(this.client)}const a="string"==typeof r?i.PrivateKey.fromString(r):r,c=await s.freezeWith(this.client);await c.sign(a);const l=await c.execute(this.client);return await l.getReceipt(this.client)}async registerEntryWithKey(e,t,r){try{const i=this.createRegisterMessage(t.targetTopicId,t.memo),o=await this.submitMessageWithKey(e,i,r),n=o.topicSequenceNumber?.toNumber();return{success:!0,receipt:o,sequenceNumber:n}}catch(i){return this.logger.error(`Failed to register HCS-6 entry: ${i}`),{success:!1,error:String(i)}}}async createRegistry(e={}){try{await this.ensureInitialized();const t=e.ttl??86400;if(!(t>=3600))throw new Error("TTL must be at least 3600 seconds (1 hour)");let r,o;if(e.submitKey)if("string"==typeof e.submitKey)try{r=i.PublicKey.fromString(e.submitKey)}catch{const t=globalThis.Buffer.from(e.submitKey.replace(/^0x/i,""),"hex");r="ed25519"===this.operatorCtx.keyType?i.PublicKey.fromBytesED25519(t):i.PublicKey.fromBytesECDSA(t)}else"boolean"==typeof e.submitKey?r=this.operatorCtx.operatorKey.publicKey:(r=e.submitKey.publicKey,o=e.submitKey);let n=X({ttl:t,submitKey:r,adminKey:this.operatorCtx.operatorKey.publicKey,operatorPublicKey:this.operatorCtx.operatorKey.publicKey});const s=await n.freezeWith(this.client);o&&await s.sign(o);const a=await s.execute(this.client),c=(await a.getReceipt(this.client)).topicId;if(!c)throw new Error("Failed to create HCS-6 registry: No topic ID in receipt");return{success:!0,topicId:c.toString(),transactionId:a.transactionId.toString()}}catch(t){return this.logger.error(`Failed to create HCS-6 registry: ${t}`),{success:!1,error:`Failed to create HCS-6 registry: ${t}`}}}async registerEntry(e,t){return await this.ensureInitialized(),this.registerEntryWithKey(e,t,void 0)}async getRegistry(e,t={}){await this.ensureInitialized();const r=((await this.mirrorNode.getTopicInfo(e)).memo||"").match(/^hcs-6:(\d):(\d+)$/);if(!r)throw new Error(`Topic ${e} is not an HCS-6 registry (invalid memo format)`);const i=parseInt(r[2]),o=parseInt(r[1]),n=(await this.mirrorNode.getTopicMessages(e,{sequenceNumber:t.skip&&t.skip>0?`gt:${t.skip}`:void 0,limit:t.limit??100,order:t.order??"asc"})).map(t=>{try{const r=t,{valid:i}=this.validateMessage(r);return i?{topicId:e,sequence:r.sequence_number,timestamp:r.consensus_timestamp||"",payer:r.payer||"",message:r,consensus_timestamp:r.consensus_timestamp||"",registry_type:o}:null}catch{return null}}).filter(e=>Boolean(e)),s=n.length>0?n[n.length-1]:void 0;return{topicId:e,registryType:o,ttl:i,entries:n,latestEntry:s}}async mint(e){try{if(await this.ensureInitialized(),!e.metadataTopicId)return{success:!1,error:"metadataTopicId is required for mint()"};const t=U(e.metadataTopicId);let r=(new i.TokenMintTransaction).setTokenId(i.TokenId.fromString(e.tokenId)).setMetadata([globalThis.Buffer.from(t)]);const o=await r.freezeWith(this.client);if(e.supplyKey){const t=new re({mirrorNode:this.mirrorNode,logger:this.logger}),r="string"==typeof e.supplyKey?await t.resolveSupplyKey(e.tokenId,e.supplyKey,this.operatorCtx.keyType):e.supplyKey;await o.sign(r)}const n=await o.execute(this.client),s=await n.getReceipt(this.client);return{success:!0,serialNumber:s.serials&&s.serials[0]?Number(s.serials[0].toString()):void 0,transactionId:n.transactionId?.toString?.(),metadata:t}}catch($g){return{success:!1,error:String($g)}}}async inscribeAndMint(e){try{await this.ensureInitialized();const t={...e.inscriptionOptions,mode:"hashinal",waitForConfirmation:!0},r=await za(e.inscriptionInput,{accountId:this.operatorId.toString(),privateKey:this.operatorCtx.operatorKey,network:this.network},t);if(!r.confirmed||!r.inscription)return{success:!1,error:"Failed to inscribe content"};const i=r.inscription.jsonTopicId||r.inscription.topic_id;return i?await this.mint({tokenId:e.tokenId,metadataTopicId:i,supplyKey:e.supplyKey,memo:e.memo}):{success:!1,error:"No topic ID from inscription"}}catch($g){return{success:!1,error:String($g)}}}async createHashinal(e){try{let t,r;if(await this.ensureInitialized(),e.registryTopicId){t=e.registryTopicId;const r=(await this.mirrorNode.getTopicInfo(t)).memo||"";if(!/^hcs-6:\d:\d+$/.test(r))throw new Error(`Topic ${t} is not a valid HCS-6 registry`)}else{const i=await this.createRegistry({ttl:e.ttl,submitKey:!0});if(!i.success||!i.topicId)throw new Error(i.error||"Failed to create HCS-6 registry");t=i.topicId,r=i.transactionId}const i=globalThis.Buffer.from(JSON.stringify(e.metadata)),o={...e.inscriptionOptions,mode:"hashinal",metadata:e.metadata,waitForConfirmation:!0},n=await za({type:"buffer",buffer:i,fileName:"metadata.json",mimeType:"application/json"},{accountId:this.operatorId.toString(),privateKey:this.operatorCtx.operatorKey,network:this.network},o);if(!n.confirmed||!n.inscription)throw new Error("Failed to inscribe metadata");const s=n.inscription.jsonTopicId||n.inscription.topic_id;if(!s)throw new Error("No inscription topic ID available");const a=await this.registerEntryWithKey(t,{targetTopicId:s,memo:e.memo||"Dynamic hashinal registration"},e.submitKey);if(!a.success)throw new Error(a.error||"Failed to register entry");return{success:!0,registryTopicId:t,inscriptionTopicId:s,transactionId:r}}catch($g){return{success:!1,error:String($g)}}}async register(e){try{let t,r,i;if(await this.ensureInitialized(),e.registryTopicId){t=e.registryTopicId;const r=(await this.mirrorNode.getTopicInfo(t)).memo||"";if(!/^hcs-6:\d:\d+$/.test(r))throw new Error(`Topic ${t} is not a valid HCS-6 registry`)}else{const i=await this.createRegistry({ttl:e.ttl,submitKey:!0});if(!i.success||!i.topicId)throw new Error(i.error||"Failed to create HCS-6 registry");t=i.topicId,r=i.transactionId}if(e.data?.base64){i={type:"buffer",buffer:globalThis.Buffer.from(e.data.base64,"base64"),fileName:`data.${e.data.mimeType?.split("/")[1]||"bin"}`,mimeType:e.data.mimeType||"application/octet-stream"}}else i=e.data?.url?{type:"url",url:e.data.url}:{type:"buffer",buffer:globalThis.Buffer.from(JSON.stringify(e.metadata)),fileName:"metadata.json",mimeType:"application/json"};const o={...e.inscriptionOptions,mode:"hashinal",metadata:e.metadata,waitForConfirmation:!0},n=await za(i,{accountId:this.operatorId.toString(),privateKey:this.operatorCtx.operatorKey,network:this.network},o);if(!n.confirmed||!n.inscription)throw new Error("Failed to inscribe data");const s=n.inscription.jsonTopicId||n.inscription.topic_id;if(!s)throw new Error("No inscription topic ID available");const a=await this.registerEntryWithKey(t,{targetTopicId:s,memo:e.memo||"Dynamic hashinal registration"},e.submitKey);if(!a.success)throw new Error(a.error||"Failed to register entry");return{success:!0,registryTopicId:t,inscriptionTopicId:s,transactionId:r}}catch($g){return{success:!1,error:String($g)}}}},exports.HCS6Operation=B,exports.HCS6RegistryType=K,exports.HCS7BaseClient=Za,exports.HCS7BrowserClient=class extends Za{constructor(e){super(e),this.hwc=e.hwc}ensureConnected(){const e=this.hwc.getAccountInfo();if(!e?.accountId)throw new Error("No active wallet connection")}async createRegistry(e={}){try{this.ensureConnected();const t=e.ttl??86400;if(t<3600)throw new Error("TTL must be at least 3600 seconds");const r=this.generateRegistryMemo(t),i=await this.hwc.createTopic(r);return this.logger.info(`Created HCS-7 registry topic ${i}`),{success:!0,topicId:i}}catch(t){return this.logger.error("Failed to create HCS-7 registry in browser",t),{success:!1,error:String(t)}}}async registerConfig(e){const t=this.createConfigMessage({config:e.config,memo:e.memo});return this.submitWithWallet({topicId:e.registryTopicId,message:t})}async registerMetadata(e){const t=this.createMetadataMessage(e);return this.submitWithWallet({topicId:e.registryTopicId,message:t})}async submitWithWallet(e){try{this.ensureConnected();const{valid:t,errors:r}=this.validateMessage(e.message);if(!t)return{success:!1,error:`Invalid HCS-7 payload: ${r.join(", ")}`};const i=await this.hwc.submitMessageToTopic(e.topicId,JSON.stringify(e.message));return{success:!0,receipt:i,sequenceNumber:Qa(i)}}catch(t){return this.logger.error("Failed to submit HCS-7 browser message",t),{success:!1,error:String(t)}}}},exports.HCS7Client=class extends Za{constructor(e){super(e),this.closed=!1,this.operatorCtx=ie({network:this.network,operatorId:e.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger}),this.client=this.operatorCtx.client}close(){this.closed||(this.closed=!0,this.logger.info("HCS-7 client closed"))}getKeyType(){return this.operatorCtx.keyType}async ensureInitialized(){await this.operatorCtx.ensureInitialized()}resolvePublicKey(e){if(e){if("boolean"==typeof e)return e?this.operatorCtx.operatorKey.publicKey:void 0;if("string"==typeof e)try{return i.PublicKey.fromString(e)}catch{return}return e.publicKey}}coercePrivateKey(e){if(e instanceof i.PrivateKey)return e;try{return i.PrivateKey.fromStringED25519(e)}catch{return i.PrivateKey.fromStringECDSA(e)}}async createRegistry(e={}){const t=e.ttl??86400;if(t<3600)return{success:!1,error:"TTL must be at least 3600 seconds"};try{await this.ensureInitialized();const r=this.resolvePublicKey(e.submitKey);let i=ec({ttl:t,submitKey:r,adminKey:this.resolvePublicKey(e.adminKey),operatorPublicKey:this.operatorCtx.operatorKey.publicKey});i=await i.freezeWith(this.client);const o=await i.execute(this.client),n=await o.getReceipt(this.client),s=n.topicId?.toString();return s?{success:!0,topicId:s,transactionId:o.transactionId?.toString()}:{success:!1,error:"Topic creation receipt did not include a topic ID"}}catch(r){return this.logger.error("Failed to create HCS-7 registry topic",r),{success:!1,error:String(r)}}}async registerConfig(e){await this.ensureInitialized();const t=this.createConfigMessage({config:e.config,memo:e.memo});return this.submitMessage({topicId:e.registryTopicId,message:t,submitKey:e.submitKey,transactionMemo:e.transactionMemo})}async registerMetadata(e){await this.ensureInitialized();const t=this.createMetadataMessage(e);return this.submitMessage({topicId:e.registryTopicId,message:t,submitKey:e.submitKey,transactionMemo:e.transactionMemo})}async submitMessage(e){const{valid:t,errors:r}=this.validateMessage(e.message);if(!t)return{success:!1,error:`Invalid HCS-7 payload: ${r.join(", ")}`};try{let t=tc({topicId:e.topicId,message:e.message,transactionMemo:e.transactionMemo});if(e.submitKey){const r=this.coercePrivateKey(e.submitKey);t=await t.freezeWith(this.client),await t.sign(r);const i=await t.execute(this.client),o=await i.getReceipt(this.client);return{success:!0,receipt:o,sequenceNumber:o.topicSequenceNumber?.toNumber(),transactionId:i.transactionId?.toString()}}const r=await t.execute(this.client),i=await r.getReceipt(this.client);return{success:!0,receipt:i,sequenceNumber:i.topicSequenceNumber?.toNumber(),transactionId:r.transactionId?.toString()}}catch(i){return this.logger.error("Failed to submit HCS-7 message",i),{success:!1,error:String(i)}}}},exports.HCS7ConfigType=Ha,exports.HCS7Operation=$a,exports.HRLResolver=Kd,exports.HTSParser=ua,exports.HashLinkResolver=Cp,exports.HashLinkScanner=Ap,exports.HashLinksRegistry=Tp,exports.Hcs10MemoType=$u,exports.HederaHieroIssuer=Zp,exports.HederaMirrorNode=V,exports.HieroDidResolver=qp,exports.InboundTopicType=hu,exports.InsufficientBalanceError=class extends Nh{constructor(e,t,r,i){super(`Insufficient balance for ${t}: required ${r}, available ${i}`),this.accountId=e,this.tick=t,this.required=r,this.available=i,this.name="InsufficientBalanceError"}},exports.InvalidAccountFormatError=Dh,exports.InvalidMessageFormatError=class extends Nh{constructor(e,t){super(e),this.messageData=t,this.name="InvalidMessageFormatError"}},exports.InvalidNumberFormatError=class extends Nh{constructor(e,t){super(`Invalid number format for ${t}: ${e}`),this.value=e,this.field=t,this.name="InvalidNumberFormatError"}},exports.InvalidTickFormatError=class extends Nh{constructor(e){super(`Invalid tick format: ${e}`),this.tick=e,this.name="InvalidTickFormatError"}},exports.IssuerRegistry=Gp,exports.KeyType=Z,exports.KeyTypeDetector=ee,exports.Logger=O,exports.MAINNET_EXAMPLES=Rp,exports.MCPServerBuilder=class{constructor(){this.config={mcpServer:{}},this.socials=[],this.logger=O.getInstance({module:"MCPServerBuilder"})}setName(e){return this.config.name=e,this}setAlias(e){return this.config.alias=e,this}setBio(e){return this.config.bio=e,this}setDescription(e){return this.setBio(e)}setVersion(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.version=e,this}setConnectionInfo(e,t){this.config.mcpServer||(this.config.mcpServer={});const r={url:e,transport:t};return this.config.mcpServer.connectionInfo=r,this}setServerDescription(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.description=e,this}setServices(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.services=e,this}setHostRequirements(e){this.config.mcpServer||(this.config.mcpServer={});const t={minVersion:e};return this.config.mcpServer.host=t,this}setCapabilities(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.capabilities=e,this}addResource(e,t){this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.resources||(this.config.mcpServer.resources=[]);const r={name:e,description:t};return this.config.mcpServer.resources.push(r),this}setResources(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.resources=e,this}addTool(e,t){this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.tools||(this.config.mcpServer.tools=[]);const r={name:e,description:t};return this.config.mcpServer.tools.push(r),this}setTools(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.tools=e,this}setMaintainer(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.maintainer=e,this}setRepository(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.repository=e,this}setDocs(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.docs=e,this}setVerification(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.verification=e,this}addVerificationDNS(e,t){this.config.mcpServer||(this.config.mcpServer={});const r={type:pu.DNS,value:e,dns_field:t};return this.config.mcpServer.verification=r,this}addVerificationSignature(e){this.config.mcpServer||(this.config.mcpServer={});const t={type:pu.SIGNATURE,value:e};return this.config.mcpServer.verification=t,this}addVerificationChallenge(e){this.config.mcpServer||(this.config.mcpServer={});const t={type:pu.CHALLENGE,value:"",challenge_path:e};return this.config.mcpServer.verification=t,this}addSocial(e,t){const r=this.socials.find(t=>t.platform===e);if(r)r.handle=t;else{const r={platform:e,handle:t};this.socials.push(r)}return this}setSocials(e){return this.socials=e,this}setProfilePicture(e,t){return this.config.pfpBuffer=e,this.config.pfpFileName=t,this}setExistingProfilePicture(e){return this.config.existingPfpTopicId=e,this}setNetworkType(e){return this.config.network=e,this}setExistingAccount(e,t){return this.config.existingAccount={accountId:e,privateKey:t},this}build(){if(!this.config.name)throw new Error("MCP server name is required");if(!this.config.network)throw new Error("Network type is required");if(!this.config.mcpServer)throw new Error("MCP server details are required");if(!this.config.mcpServer.version)throw new Error("MCP server version is required");if(!this.config.mcpServer.connectionInfo)throw new Error("MCP server connection info is required");if(!this.config.mcpServer.services||0===this.config.mcpServer.services.length)throw new Error("At least one MCP service type is required");if(!this.config.mcpServer.description)throw new Error("MCP server description is required");return this.config.bio||this.logger.warn("No bio provided for MCP server profile"),this.config.pfpBuffer||this.config.existingPfpTopicId||this.logger.warn("No profile picture provided or referenced"),this.socials.length>0?{...this.config,socials:this.socials}:this.config}},exports.MCPServerCapability=uu,exports.MCPServerConnectionInfoSchema=yu,exports.MCPServerDetailsSchema=Su,exports.MCPServerHostSchema=wu,exports.MCPServerProfileSchema=Au,exports.MCPServerResourceSchema=Iu,exports.MCPServerToolSchema=Tu,exports.MCPServerVerificationSchema=bu,exports.MapCache=rc,exports.MintLimitExceededError=class extends Nh{constructor(e,t,r){super(`Mint limit exceeded for ${e}: requested ${t}, limit ${r}`),this.tick=e,this.requested=t,this.limit=r,this.name="MintLimitExceededError"}},exports.NodeCryptoAdapter=Gd,exports.NodeHashAdapter=Ud,exports.NodeHmacAdapter=jd,exports.PayloadSizeError=ju,exports.PersonBuilder=class{constructor(){this.config={version:"1.0",type:0},this.logger=O.getInstance({module:"PersonBuilder"})}setName(e){return this.config.display_name=e,this}setAlias(e){return this.config.alias=e,this}setBio(e){return this.config.bio=e,this}setDescription(e){return this.setBio(e)}addSocial(e,t){this.config.socials||(this.config.socials=[]);const r=this.config.socials.find(t=>t.platform===e);return r?r.handle=t:this.config.socials.push({platform:e,handle:t}),this}setProfileImage(e){return this.config.profileImage=e,this}setProfilePicture(e,t){return this.config.pfpBuffer=e,this.config.pfpFileName=t,this}setExistingProfilePicture(e){return this.config.profileImage=`hcs://1/${e}`,this}addProperty(e,t){return this.config.properties||(this.config.properties={}),this.config.properties[e]=t,this}setInboundTopicId(e){return this.config.inboundTopicId=e,this}setOutboundTopicId(e){return this.config.outboundTopicId=e,this}getProfilePicture(){return{pfpBuffer:this.config.pfpBuffer,pfpFileName:this.config.pfpFileName}}build(){if(!this.config.display_name)throw new Error("Display name is required for the profile");return this.config.bio||this.logger.warn("No bio provided for person profile"),this.config.pfpBuffer||this.config.profileImage||this.logger.warn("No profile picture provided or referenced"),{version:this.config.version,type:0,display_name:this.config.display_name,alias:this.config.alias,bio:this.config.bio,socials:this.config.socials,profileImage:this.config.profileImage,properties:this.config.properties,inboundTopicId:this.config.inboundTopicId,outboundTopicId:this.config.outboundTopicId,pfpBuffer:this.config.pfpBuffer,pfpFileName:this.config.pfpFileName}}},exports.PersonalProfileSchema=Eu,exports.PointsBurnError=Fh,exports.PointsDeploymentError=_h,exports.PointsMintError=class extends Nh{constructor(e,t,r,i){super(e),this.tick=t,this.requestedAmount=r,this.availableSupply=i,this.name="PointsMintError"}},exports.PointsNotFoundError=class extends Nh{constructor(e){super(`Points with tick "${e}" not found`),this.tick=e,this.name="PointsNotFoundError"}},exports.PointsTransferError=Ph,exports.PointsValidationError=zh,exports.ProfileType=au,exports.ProgressReporter=us,exports.REFERENCE_THRESHOLD=51200,exports.RedisCache=class{constructor(e={}){const{host:t="localhost",port:r=6379,password:i,db:o=0,keyPrefix:n="",tls:s=!1,connectTimeout:a=5e3,retryStrategy:c,logLevel:l="info"}=e;this.prefix=n,this.logger=O.getInstance({level:l,module:"RedisCache"}),this.client=function(e,t){const r=function(){if("function"!=typeof require)return null;try{const e=require("ioredis");if("function"==typeof e)return e;if("function"==typeof e.default)return e.default}catch{return null}return null}();if(!r)return e.warn("ioredis is not installed; RedisCache will use an in-memory cache instead"),function(){const e=new Map;return{get:async t=>e.get(t)??null,set:async(t,r)=>(e.set(t,r),"OK"),setex:async(t,r,i)=>(e.set(t,i),"OK"),async del(...t){let r=0;for(const i of t)e.delete(i)&&(r+=1);return r},async keys(t){if(t.endsWith("*")){const r=t.slice(0,-1);return Array.from(e.keys()).filter(e=>e.startsWith(r))}return e.has(t)?[t]:[]},async quit(){e.clear()},on(){}}}();const i=new r({host:t.host,port:t.port,password:t.password,db:t.db,tls:t.tls,keyPrefix:t.keyPrefix,connectTimeout:t.connectTimeout,retryStrategy:t.retryStrategy,maxRetriesPerRequest:t.maxRetriesPerRequest});return i.on("error",t=>{e.error("Redis connection error:",t)}),i.on("connect",()=>{e.debug("Redis connected")}),i}(this.logger,{host:t,port:r,password:i,db:o,tls:s?{}:void 0,keyPrefix:n,connectTimeout:a,retryStrategy:c||(e=>Math.min(50*e,2e3)),maxRetriesPerRequest:3})}getKey(e){return`${this.prefix}${e}`}async get(e){try{return await this.client.get(this.getKey(e))||void 0}catch(t){throw this.logger.error("Redis get error:",t),t}}async set(e,t,r){try{const i=this.getKey(e);r?await this.client.setex(i,r,t):await this.client.set(i,t)}catch(i){throw this.logger.error("Redis set error:",i),i}}async delete(e){try{await this.client.del(this.getKey(e))}catch(t){throw this.logger.error("Redis delete error:",t),t}}async clear(){try{const e=await this.client.keys(`${this.prefix}*`);e.length>0&&await this.client.del(...e)}catch(e){throw this.logger.error("Redis clear error:",e),e}}async disconnect(){await this.client.quit()}setLogLevel(e){this.logger.setLogLevel(e)}},exports.Registration=Nu,exports.RegistryBrokerClient=dd,exports.RegistryBrokerError=cd,exports.RegistryBrokerParseError=ld,exports.RegistryType=Zu,exports.ResolverRegistry=jp,exports.ResourceManager=class{constructor(e,t,r,i={}){this.cache=new Map,this.currentCacheSize=0,this.supportedImageTypes=new Set(["image/png","image/jpeg","image/jpg","image/gif","image/svg+xml","image/webp"]),this.dangerousJSPatterns=[/eval\s*\(/g,/Function\s*\(/g,/setTimeout\s*\(\s*["'].*["']/g,/setInterval\s*\(\s*["'].*["']/g,/document\.write/g,/innerHTML\s*=/g,/outerHTML\s*=/g],this.dangerousCSSPatterns=[/javascript\s*:/gi,/@import.*url\s*\(\s*["']?javascript:/gi,/expression\s*\(/gi,/behavior\s*:/gi],this.logger=t,this.hcs=r||new M,this.options={cacheTTL:i.cacheTTL||3e5,maxCacheSize:i.maxCacheSize||52428800,maxResourceSize:i.maxResourceSize||5242880}}async loadCSS(e){this.logger.debug("Loading CSS resource",{topicId:e});try{const t=await this.loadResource(e);if("text/css"!==t.contentType)throw new Error(`Expected CSS resource, got ${t.contentType}`);const r=t.content,i=this.sanitizeCSS(r);return this.logger.debug("CSS resource loaded successfully",{topicId:e,size:r.length,sanitized:i.length!==r.length}),i}catch(t){throw this.logger.error("Failed to load CSS resource",{topicId:e,error:t}),new Error(`Failed to load CSS resource: ${t instanceof Error?t.message:"Unknown error"}`)}}async loadJS(e){this.logger.debug("Loading JavaScript resource",{topicId:e});try{const t=await this.loadResource(e);if(!t.contentType.includes("javascript")&&!t.contentType.includes("ecmascript"))throw new Error(`Expected JavaScript resource, got ${t.contentType}`);const r=t.content;if(r.length>this.options.maxResourceSize)throw new Error("JavaScript resource too large");const i=this.sanitizeJavaScript(r);return this.logger.debug("JavaScript resource loaded successfully",{topicId:e,size:r.length,sanitized:i.length!==r.length}),i}catch(t){throw this.logger.error("Failed to load JavaScript resource",{topicId:e,error:t}),new Error(`Failed to load JavaScript resource: ${t instanceof Error?t.message:"Unknown error"}`)}}async loadImage(e){this.logger.debug("Loading image resource",{topicId:e});try{const t=await this.loadResource(e);if(!this.supportedImageTypes.has(t.contentType))throw new Error(`Unsupported image format: ${t.contentType}`);const r=t.content,i=new Uint8Array(r),o=new Blob([i.buffer],{type:t.contentType});return this.logger.debug("Image resource loaded successfully",{topicId:e,size:r.length,type:t.contentType}),o}catch(t){throw this.logger.error("Failed to load image resource",{topicId:e,error:t}),new Error(`Failed to load image resource: ${t instanceof Error?t.message:"Unknown error"}`)}}async loadTemplate(e){this.logger.debug("Loading template resource",{topicId:e});try{const t=(await this.loadResource(e)).content;this.validateTemplateSyntax(t);const r=this.sanitizeTemplate(t);return this.logger.debug("Template resource loaded successfully",{topicId:e,size:t.length}),r}catch(t){throw this.logger.error("Failed to load template resource",{topicId:e,error:t}),new Error(`Failed to load template resource: ${t instanceof Error?t.message:"Unknown error"}`)}}async loadWithIntegrityCheck(e,t){this.logger.debug("Loading resource with integrity check",{topicId:e,expectedHash:t});try{const r=await this.loadResource(e),i=await this.verifyIntegrity(r.content,t);if(!i)throw new Error("Resource integrity verification failed");return this.logger.debug("Resource integrity verified",{topicId:e}),{content:r.content,verified:i,contentType:r.contentType}}catch(r){throw this.logger.error("Resource integrity check failed",{topicId:e,error:r}),r}}async verifyIntegrity(e,t){try{if(qd())return this.logger.warn("Integrity verification skipped in SSR environment"),!0;if("undefined"==typeof crypto||!crypto.subtle)return this.logger.warn("WebCrypto not available, skipping integrity verification"),!0;const r="string"==typeof e?(new TextEncoder).encode(e):e,i=r instanceof Uint8Array?r:new Uint8Array(r),o=new Uint8Array(i),n=await crypto.subtle.digest("SHA-256",o.buffer),s=Array.from(new Uint8Array(n));return s.map(e=>e.toString(16).padStart(2,"0")).join("")===t.toLowerCase()}catch(r){return this.logger.error("Error verifying integrity",{error:r}),!1}}async loadDependencies(e){this.logger.debug("Loading dependencies",{count:e.length});try{this.detectCircularDependencies(e);const t=this.topologicalSort(e),r=[];for(const e of t){let t;switch(e.type){case"css":t=await this.loadCSS(e.topicId);break;case"js":t=await this.loadJS(e.topicId);break;case"template":t=await this.loadTemplate(e.topicId);break;case"image":const r=await this.loadImage(e.topicId);t=new Uint8Array(await r.arrayBuffer());break;default:throw new Error(`Unsupported dependency type: ${e.type}`)}r.push({topicId:e.topicId,content:t,contentType:this.getContentTypeForType(e.type),type:e.type})}return this.logger.debug("Dependencies loaded successfully",{count:r.length}),r}catch(t){throw this.logger.error("Failed to load dependencies",{error:t}),t}}clearCache(){this.cache.clear(),this.currentCacheSize=0,this.logger.debug("Resource cache cleared")}getCacheSize(){return this.currentCacheSize}async loadResource(e){const t=this.getFromCache(e);if(t)return this.logger.debug("Resource loaded from cache",{topicId:e}),t;const r=await this.hcs.retrieveHCS1Data(e),i=r.type||"application/octet-stream";let o;o=i.startsWith("text/")||i.includes("javascript")||i.includes("json")?await r.text():new Uint8Array(await r.arrayBuffer());const n={content:o,contentType:i,size:r.size};return this.addToCache(e,n),n}getFromCache(e){const t=this.cache.get(e);return t?Date.now()-t.timestamp>this.options.cacheTTL?(this.removeFromCache(e),null):t.data:null}addToCache(e,t){const r="string"==typeof t.content?t.content.length:t.content.byteLength;if(r>this.options.maxCacheSize/2)return void this.logger.warn("Resource too large for cache",{topicId:e,size:r});for(;this.currentCacheSize+r>this.options.maxCacheSize&&this.cache.size>0;)this.evictOldestEntry();const i={data:t,timestamp:Date.now(),size:r};this.cache.set(e,i),this.currentCacheSize+=r,this.logger.debug("Resource added to cache",{topicId:e,size:r,totalCacheSize:this.currentCacheSize})}removeFromCache(e){const t=this.cache.get(e);t&&(this.cache.delete(e),this.currentCacheSize-=t.size)}evictOldestEntry(){let e=null,t=Date.now();for(const[r,i]of this.cache)i.timestamp<t&&(t=i.timestamp,e=r);e&&(this.removeFromCache(e),this.logger.debug("Evicted oldest cache entry",{topicId:e}))}sanitizeCSS(e){let t=e;for(const r of this.dangerousCSSPatterns)t=t.replace(r,"");return t}sanitizeJavaScript(e){let t=e;for(const r of this.dangerousJSPatterns)t=t.replace(r,"");return t}sanitizeTemplate(e){return e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/on\w+\s*=\s*["'][^"']*["']/gi,"").replace(/javascript\s*:/gi,"")}validateTemplateSyntax(e){if((e.match(/\{\{/g)||[]).length!==(e.match(/\}\}/g)||[]).length)throw new Error("Invalid template syntax: unmatched braces");if((e.match(/\{\{#\w+/g)||[]).length!==(e.match(/\{\{\/\w+/g)||[]).length)throw new Error("Invalid template syntax: unclosed block helpers")}detectCircularDependencies(e){const t=new Map;for(const n of e)t.set(n.topicId,n.depends||[]);const r=new Set,i=new Set,o=e=>{if(i.has(e))throw new Error("Circular dependency detected");if(r.has(e))return;i.add(e);const n=t.get(e)||[];for(const t of n)o(t);i.delete(e),r.add(e)};for(const n of e)o(n.topicId)}topologicalSort(e){const t=new Map,r=new Map;for(const s of e)t.set(s.topicId,s),r.set(s.topicId,s.depends||[]);const i=[],o=new Set,n=e=>{if(o.has(e))return;const s=r.get(e)||[];for(const t of s)n(t);o.add(e);const a=t.get(e);a&&i.push(a)};for(const s of e)n(s.topicId);return i}getContentTypeForType(e){switch(e){case"css":return"text/css";case"js":return"application/javascript";case"template":return"text/html";case"image":return"image/*";default:return"application/octet-stream"}}},exports.SUPPORTED_SOCIAL_PLATFORMS=["twitter","github","discord","telegram","linkedin","youtube","website","x"],exports.ScheduleParser=ya,exports.SocialLinkSchema=mu,exports.StateHashError=hg,exports.SupplyLimitExceededError=class extends Nh{constructor(e,t,r,i){super(`Supply limit exceeded for ${e}: max ${r}, current ${i}, requested ${t}`),this.tick=e,this.requested=t,this.maxSupply=r,this.currentSupply=i,this.name="SupplyLimitExceededError"}},exports.TESTNET_EXAMPLES=xp,exports.TemplateEngine=class{constructor(e){this.templateCache=new Map,this.helpers=new Map,this.compiledTemplates=new Map,this.logger=e,this.setupBuiltinHelpers()}async render(e,t={}){this.logger.debug("Rendering template",{templateLength:e.length,context:JSON.stringify(t,null,2),attributesType:t.attributes?typeof t.attributes:"undefined",contextKeys:Object.keys(t)});try{const r=this.getCacheKey(e);let i=this.templateCache.get(r);i||(i=await this.compileTemplate(e),this.templateCache.set(r,i));const o=i.render(this.sanitizeContext(t));return this.logger.debug("Template rendered successfully",{resultLength:o.length}),o}catch(r){throw this.logger.error("Template rendering failed",{error:r,template:e}),new Error(`Template rendering failed: ${r instanceof Error?r.message:"Unknown error"}`)}}async precompile(e,t){this.logger.debug("Precompiling template",{name:e,templateLength:t.length});try{const r=await this.compileTemplate(t);this.compiledTemplates.set(e,r),this.logger.debug("Template precompiled successfully",{name:e})}catch(r){throw this.logger.error("Template precompilation failed",{error:r,name:e}),new Error(`Template precompilation failed: ${r instanceof Error?r.message:"Unknown error"}`)}}async renderCompiled(e,t={}){const r=this.compiledTemplates.get(e);if(!r)throw new Error(`Precompiled template '${e}' not found`);this.logger.debug("Rendering precompiled template",{name:e});try{const i=r.render(this.sanitizeContext(t));return this.logger.debug("Precompiled template rendered successfully",{name:e}),i}catch(i){throw this.logger.error("Precompiled template rendering failed",{error:i,name:e}),new Error(`Template rendering failed: ${i instanceof Error?i.message:"Unknown error"}`)}}registerHelper(e,t){this.helpers.set(e,t),this.logger.debug("Helper registered",{name:e})}clearCache(){this.templateCache.clear(),this.logger.debug("Template cache cleared")}getCacheSize(){return this.templateCache.size}async compileTemplate(e){this.validateTemplate(e);return{source:e,compiled:!0,render:t=>this.executeTemplate(e,t)}}executeTemplate(e,t){let r=e;return r=this.processHelpers(r,t),r=this.processLoops(r,t),r=this.processConditionals(r,t),r=this.processVariables(r,t),r}processConditionals(e,t){let r=e;r=r.replace(/\{\{#if\s+([^}]+)\}\}((?:[^{]|\{(?!\{)|\{\{(?!#if|\{#else|\{\/if))*?)\{\{#if\s+([^}]+)\}\}((?:[^{]|\{(?!\{)|\{\{(?!#if|#else|\/if))*?)\{\{else\}\}((?:[^{]|\{(?!\{)|\{\{(?!#if|#else|\/if))*?)\{\{\/if\}\}((?:[^{]|\{(?!\{)|\{\{(?!\/if))*?)\{\{\/if\}\}/gs,(e,r,i,o,n,s,a)=>{if(!this.evaluateCondition(r,t))return"";return i+(this.evaluateCondition(o,t)?n:s)+a});r=r.replace(/\{\{#if\s+([^}]+)\}\}((?:[^{]|\{(?!\{)|\{\{(?!else|\/if))*?)\{\{else\}\}((?:[^{]|\{(?!\{)|\{\{(?!\/if))*?)\{\{\/if\}\}/gs,(e,r,i,o)=>this.evaluateCondition(r,t)?i:o);r=r.replace(/\{\{#if\s+([^}]+)\}\}((?:[^{]|\{(?!\{)|\{\{(?!\/if))*?)\{\{\/if\}\}/gs,(e,r,i)=>this.evaluateCondition(r,t)?i:"");return r=r.replace(/\{\{#unless\s+([^}]+)\}\}((?:[^{]|\{(?!\{)|\{\{(?!\/unless))*?)\{\{\/unless\}\}/gs,(e,r,i)=>this.evaluateCondition(r,t)?"":i),r}processLoops(e,t){let r=e;return r=r.replace(/\{\{#each\s+([^}]+)\}\}(.*?)\{\{\/each\}\}/gs,(e,r,i)=>{const o=this.getNestedValue(r,t);if(!o)return"";let n="";if(Array.isArray(o))o.forEach((e,r)=>{let o=i;if(o=o.replace(/\{\{this\}\}/g,this.escapeHtml(String(e))),o=o.replace(/\{\{@index\}\}/g,String(r)),"object"==typeof e&&null!==e)for(const[t,i]of Object.entries(e)){const e=new RegExp(`\\{\\{${t}\\}\\}`,"g");o=o.replace(e,this.escapeHtml(String(i)))}o=o.replace(/\{\{\.\.\/([^}]+)\}\}/g,(e,r)=>{const i=this.getNestedValue(r,t);return this.escapeHtml(String(i||""))}),n+=o});else if("object"==typeof o)for(const[t,s]of Object.entries(o)){let e=i;e=e.replace(/\{\{@key\}\}/g,this.escapeHtml(t)),e=e.replace(/\{\{this\}\}/g,this.escapeHtml(String(s))),n+=e}return n}),r}processVariables(e,t){let r=e;r=r.replace(/\{\{\{([^}]+)\}\}\}/g,(e,r)=>{const i=this.getNestedValue(r.trim(),t);return this.sanitizeHtml(String(i||""))});return r=r.replace(/\{\{([^}#/]+)\}\}/g,(e,r)=>{const i=r.trim();if(i.startsWith("#")||i.startsWith("/")||i.startsWith("else"))return e;const o=this.getNestedValue(i,t);return 0===o||!1===o?this.escapeHtml(String(o)):this.escapeHtml(String(o||""))}),r}processHelpers(e,t){let r=e;r=r.replace(/\{\{#with\s+([^}]+)\}\}(.*?)\{\{\/with\}\}/gs,(e,r,i)=>{const o=this.getNestedValue(r.trim(),t);return o?this.executeTemplate(i,o):""});for(const[i,o]of this.helpers){const e=new RegExp(`\\{\\{${i}\\s+([^}]+)\\}\\}`,"g");r=r.replace(e,(e,r)=>{try{const e=this.getNestedValue(r.trim(),t);return this.escapeHtml(o.call(t,e))}catch(n){return this.logger.warn("Helper execution failed",{helperName:i,error:n}),""}})}return r}evaluateCondition(e,t){const r=this.getNestedValue(e.trim(),t);return Boolean(r)}getNestedValue(e,t){if(!e||!t)return;const r=e.split(".");let i=t;for(const o of r){if(null==i||"object"!=typeof i)return;i=i[o]}return i}sanitizeContext(e){if(null==e)return e;const t=new WeakSet,r=e=>{if(null===e||"object"!=typeof e)return e;if(t.has(e))return"[Circular]";if(t.add(e),Array.isArray(e))return e.map(r);const i={};for(const[t,o]of Object.entries(e))i[t]=r(o);return i};return r(e)}escapeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}sanitizeHtml(e){return e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"")}validateTemplate(e){if((e.match(/\{\{#\w+/g)||[]).length!==(e.match(/\{\{\/\w+/g)||[]).length)throw new Error("Invalid template syntax: unclosed block helpers");if(/\{\{[^}]*$|\{\{[^}]*\{\{/.test(e))throw new Error("Invalid template syntax: malformed handlebars")}getCacheKey(e){let t=0;for(let r=0;r<e.length;r++){t=(t<<5)-t+e.charCodeAt(r),t&=t}return t.toString()}setupBuiltinHelpers(){}},exports.TopicCreationError=Vu,exports.TopicRegistrationError=Oh,exports.TransactionParser=Ea,exports.TransactionParsingError=ps,exports.VerificationType=pu,exports.WasmBridge=class{constructor(){this.wasm=null,this.WASM_VECTOR_LEN=0,this.cachedUint8Memory=null,this.cachedDataViewMemory=null,this.textEncoder=new TextEncoder,this.textDecoder=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),this.textDecoder.decode(),this.logger=O.getInstance({module:"WasmBridge"})}setLogLevel(e){this.logger.setLogLevel(e)}get wasmInstance(){if(!this.wasm)throw new Error("WASM not initialized");return this.wasm}getUint8Memory(){if(!this.wasm)throw new Error("WASM not initialized");return null!==this.cachedUint8Memory&&0!==this.cachedUint8Memory.byteLength||(this.cachedUint8Memory=new Uint8Array(this.wasm.memory.buffer)),this.cachedUint8Memory}getDataViewMemory(){if(!this.wasm)throw new Error("WASM not initialized");return null!==this.cachedDataViewMemory&&this.cachedDataViewMemory.buffer===this.wasm.memory.buffer||(this.cachedDataViewMemory=new DataView(this.wasm.memory.buffer)),this.cachedDataViewMemory}encodeString(e,t){if(0===e.length)return{read:0,written:0};const r=this.textEncoder.encode(e);return t.set(r),{read:e.length,written:r.length}}passStringToWasm(e,t,r){if(void 0===r){const r=this.textEncoder.encode(e),i=t(r.length,1);return this.getUint8Memory().set(r,i),this.WASM_VECTOR_LEN=r.length,i}let i=this.textEncoder.encode(e).length,o=t(i,1);const n=this.getUint8Memory();let s=0;for(;s<i;s++){const t=e.charCodeAt(s);if(t>127)break;n[o+s]=t}if(s!==i){0!==s&&(e=e.slice(s)),o=r(o,i,i=s+3*this.textEncoder.encode(e).length,1);const t=this.getUint8Memory().subarray(o+s,o+i);s+=this.encodeString(e,t).written}return this.WASM_VECTOR_LEN=s,o}getStringFromWasm(e,t){return e>>>=0,this.textDecoder.decode(this.getUint8Memory().subarray(e,e+t))}createWasmFunction(e){if(!this.wasm)throw new Error("WASM not initialized");return(...t)=>{const r=this.wasm.__wbindgen_add_to_stack_pointer(-16);let i=[0,0];try{const o=[r,...t.map(e=>[this.passStringToWasm(e,this.wasm.__wbindgen_malloc,this.wasm.__wbindgen_realloc),this.WASM_VECTOR_LEN]).flat()];e.apply(this.wasm,o);const n=this.getDataViewMemory().getInt32(r+0,!0),s=this.getDataViewMemory().getInt32(r+4,!0);return i=[n,s],this.getStringFromWasm(n,s)}finally{this.wasm.__wbindgen_add_to_stack_pointer(16),this.wasm.__wbindgen_free(i[0],i[1],1)}}}async initWasm(e){const t=this,r={__wbindgen_placeholder__:{__wbindgen_throw:function(e,r){const i=t.getStringFromWasm(e,r);throw t.logger.error(`WASM error: ${i}`),new Error(i)}}};try{this.logger.debug("Compiling WASM module");const t=await WebAssembly.compile(e);this.logger.debug("Instantiating WASM module");const i=await WebAssembly.instantiate(t,r);return this.wasm=i.exports,this.logger.info("WASM module initialized successfully"),this.wasm}catch(i){throw this.logger.error("Failed to initialize WASM module",i),i}}createStateData(e,t={}){let r={};return e?.c?.inputType?.stateData&&(t.latestRoundData&&Object.keys(e.c.inputType.stateData).every(e=>e in t.latestRoundData)?(r.latestRoundData={},Object.entries(e.c.inputType.stateData).forEach(([e,i])=>{r.latestRoundData[e]=String(t.latestRoundData[e])})):Object.entries(e.c.inputType.stateData).forEach(([e,i])=>{const o=t[e];o&&"object"==typeof o&&"values"in o&&o.values.length>0?r[e]=String(o.values[0]):r[e]=this.getDefaultValueForType(i)})),r}getDefaultValueForType(e){return e.startsWith("uint")||e.startsWith("int")||"number"===e?"0":"bool"===e?"false":""}executeWasm(e,t){if(!this.wasm)throw this.logger.error("WASM not initialized"),new Error("WASM not initialized");try{this.logger.debug("Executing WASM with stateData",e);return this.createWasmFunction(this.wasmInstance.process_state)(JSON.stringify(e),JSON.stringify(t))}catch(r){throw this.logger.error("Error executing WASM",r),r}}getParams(){return this.createWasmFunction(this.wasmInstance.get_params)()}},exports.WasmExecutor=vp,exports.WasmValidator=class{constructor(e){this.cryptoAdapter=Xd(),this.REQUIRED_EXPORTS=["INFO","POST","GET"],this.ALLOWED_IMPORTS=new Set(["env.console_log","env.get_network","env.submit_hcs_message","env.memory"]),this.MAX_INITIAL_MEMORY=256,this.WARN_MODULE_SIZE=1048576,this.MAX_MODULE_SIZE=5242880,this.logger=e}async validate(e){const t=[],r=[],i={isValid:!0,errors:t,warnings:r};try{if(e.length>this.WARN_MODULE_SIZE&&r.push(`Large module size: ${(e.length/1024/1024).toFixed(2)} MB`),e.length>this.MAX_MODULE_SIZE&&(t.push("Module size exceeds maximum allowed"),i.isValid=!1),!this.validateMagicNumber(e))return t.push("Invalid WASM magic number"),i.isValid=!1,i;const o=this.getWasmVersion(e);if(i.version=o,1!==o)return t.push(`Unsupported WASM version: ${o}`),i.isValid=!1,i;const n=await this.parseModule(e);i.exports=n.exports;for(const e of this.REQUIRED_EXPORTS)n.exports.includes(e)||(t.push(`Missing required export: ${e}`),i.isValid=!1);i.imports=n.imports;for(const e of n.imports){const r=`${e.module}.${e.name}`;this.ALLOWED_IMPORTS.has(r)||(t.push(`Disallowed import: ${r}`),i.isValid=!1)}n.memory&&(i.memoryRequirements=n.memory,n.memory.initial>this.MAX_INITIAL_MEMORY&&(t.push(`Excessive initial memory: ${n.memory.initial} pages`),i.isValid=!1)),n.hasStartFunction&&r.push("Module has start function - may execute code on load"),n.functionCount>100&&r.push(`High function count: ${n.functionCount}`),this.hasSuspiciousPatterns(e)&&r.push("Potentially unsafe operation detected"),i.exportSignatures=n.exportSignatures}catch(o){this.logger.error("WASM validation failed",{error:o}),t.push(`Validation error: ${o instanceof Error?o.message:"Unknown error"}`),i.isValid=!1}return i}async validateInfoFunction(e){const t=[],r=[];try{const i=await e(),o=JSON.parse(i);return o.name&&o.version&&o.hashlinks_version?{isValid:!0,errors:t,warnings:r,moduleInfo:o}:(t.push("INFO missing required fields"),{isValid:!1,errors:t,warnings:r})}catch(i){return t.push("INFO function returned invalid JSON"),{isValid:!1,errors:t,warnings:r}}}async validateActionSchemas(e){const t=[];if(e.validation_rules)for(const[r,i]of Object.entries(e.validation_rules))"object"!=typeof i&&t.push(`Invalid validation rule for action: ${r}`);return{isValid:0===t.length,errors:t,warnings:[]}}async extractMetadata(e){return{size:e.length,hash:await this.calculateHash(e),producers:{language:["Unknown"]}}}async calculateHash(e){if(qd())return this.createSSRSafeHash(e);const t=this.cryptoAdapter.createHash("sha256").update(globalThis.Buffer.from(e)).digest("hex"),r=t instanceof Promise?await t:t;return"string"==typeof r?r:r.toString("hex")}createSSRSafeHash(e){let t=0;for(let r=0;r<Math.min(e.length,1024);r++)t=(t<<5)-t+e[r]&4294967295;return`ssr-wasm-${e.length}-${Math.abs(t).toString(16).padStart(8,"0")}`}validateMagicNumber(e){return e.length>=4&&0===e[0]&&97===e[1]&&115===e[2]&&109===e[3]}getWasmVersion(e){return e.length<8?0:e[4]|e[5]<<8|e[6]<<16|e[7]<<24}async parseModule(e){const t=e.slice(8),r=new TextDecoder("utf-8",{fatal:!1}).decode(t),i=[];r.includes("INFO")&&i.push("INFO"),r.includes("POST")&&i.push("POST"),r.includes("GET")&&i.push("GET"),0===i.length&&e.length>8&&i.push("INFO","POST","GET");const o=[],n=r.split("import:");for(let u=1;u<n.length;u++){const e=n[u].match(/^([a-zA-Z_]+[a-zA-Z0-9_]*)\.([a-zA-Z_]+[a-zA-Z0-9_]*)/);e&&o.push({module:e[1],name:e[2],type:"function"})}let s=1,a=16;const c=r.match(/memory:(\d+)(?:-(\d+))?/);c&&(s=parseInt(c[1]),c[2]&&(a=parseInt(c[2])));let l=10;const d=r.match(/functions:(\d+)/);d&&(l=parseInt(d[1]));return{exports:i,imports:o,memory:{initial:s,maximum:a},functionCount:l,hasStartFunction:r.includes("start:true"),exportSignatures:{INFO:{type:"function",params:[],results:["i32"]},POST:{type:"function",params:["i32","i32","i32","i32"],results:["i32"]},GET:{type:"function",params:["i32","i32","i32"],results:["i32"]}}}}hasSuspiciousPatterns(e){const t=new TextDecoder("utf-8",{fatal:!1}).decode(e);return["eval","__proto__","constructor"].some(e=>t.includes(e))}},exports.WebCryptoAdapter=Jd,exports.WebHashAdapter=Ld,exports.WebHmacAdapter=Wd,exports.accountIdsToExemptKeys=sc,exports.actionRegistrationSchema=sp,exports.adapterConfigContextSchema=gc,exports.adapterDeclarationSchema=mc,exports.adapterManifestSchema=fc,exports.adapterPackageSchema=hc,exports.assemblyMessageSchema=pp,exports.assemblyRegistrationSchema=hp,exports.baseMessageSchema=ah,exports.blockRegistrationSchema=ap,exports.buildHcs10ConfirmConnectionTx=Mu,exports.buildHcs10CreateConnectionTopicTx=zu,exports.buildHcs10CreateInboundTopicTx=Pu,exports.buildHcs10CreateOutboundTopicTx=Fu,exports.buildHcs10CreateRegistryTopicTx=Ou,exports.buildHcs10OutboundConnectionCreatedRecordTx=Ku,exports.buildHcs10OutboundConnectionRequestRecordTx=Bu,exports.buildHcs10RegistryDeleteTx=function(e){const t={p:"hcs-10",op:"delete",uid:e.uid,m:e.memo};return Y({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:_u(1,0)})},exports.buildHcs10RegistryMigrateTx=function(e){const t={p:"hcs-10",op:"migrate",t_id:e.targetTopicId,m:e.memo};return Y({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:_u(2,0)})},exports.buildHcs10RegistryRegisterTx=Lu,exports.buildHcs10SendMessageTx=Uu,exports.buildHcs10SubmitConnectionRequestTx=Du,exports.buildHcs12AddActionToAssemblyTx=function(e){return Y({topicId:e.assemblyTopicId,message:JSON.stringify(e.operation)})},exports.buildHcs12AddBlockToAssemblyTx=function(e){return Y({topicId:e.assemblyTopicId,message:JSON.stringify(e.operation)})},exports.buildHcs12CreateRegistryTopicTx=function(e){var t;return J({memo:e.memoOverride??(t=e.registry,`hcs-12:1:${e.ttl}:${{action:0,assembly:2,hashlinks:3}[t]}`),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})},exports.buildHcs12RegisterAssemblyTx=function(e){return Y({topicId:e.assemblyTopicId,message:JSON.stringify(e.registration)})},exports.buildHcs12SubmitMessageTx=function(e){const t="string"==typeof e.payload?e.payload:JSON.stringify(e.payload);return Y({topicId:e.topicId,message:t,transactionMemo:e.transactionMemo})},exports.buildHcs12UpdateAssemblyTx=function(e){return Y({topicId:e.assemblyTopicId,message:JSON.stringify(e.operation)})},exports.buildHcs15BaseAccountCreateTx=Yh,exports.buildHcs15PetalAccountCreateTx=Xh,exports.buildHcs16CreateAccountTx=ig,exports.buildHcs16CreateFloraTopicTx=rg,exports.buildHcs16CreateTransactionTopicTx=function(e){const t=(new i.TopicCreateTransaction).setTopicMemo(e.memo);if(e.adminKey&&t.setAdminKey(e.adminKey),e.submitKey&&t.setSubmitKey(e.submitKey),e.feeScheduleKey&&t.setFeeScheduleKey(e.feeScheduleKey),e.customFees&&e.customFees.length>0){const r=e.customFees.map(e=>{const t=(new i.CustomFixedFee).setAmount(e.amount).setFeeCollectorAccountId(i.AccountId.fromString(e.feeCollectorAccountId));return e.denominatingTokenId&&t.setDenominatingTokenId(i.TokenId.fromString(e.denominatingTokenId)),t});t.setCustomFees(r)}if(e.feeExemptKeys&&e.feeExemptKeys.length>0)throw new Error("feeExemptKeys not supported by installed @hashgraph/sdk");return t},exports.buildHcs16FloraCreatedTx=ng,exports.buildHcs16FloraJoinAcceptedTx=dg,exports.buildHcs16FloraJoinRequestTx=cg,exports.buildHcs16FloraJoinVoteTx=lg,exports.buildHcs16MessageTx=og,exports.buildHcs16ScheduleAccountKeyUpdateTx=function(e){const t=(new i.AccountUpdateTransaction).setAccountId(i.AccountId.fromString(e.floraAccountId)).setKey(e.newKeyList);return e.memo&&t.setTransactionMemo(e.memo),(new i.ScheduleCreateTransaction).setScheduledTransaction(t)},exports.buildHcs16ScheduleTopicKeyUpdateTx=function(e){const t=(new i.TopicUpdateTransaction).setTopicId(e.topicId);return e.adminKey&&t.setAdminKey(e.adminKey),e.submitKey&&t.setSubmitKey(e.submitKey),e.memo&&t.setTransactionMemo(e.memo),(new i.ScheduleCreateTransaction).setScheduledTransaction(t)},exports.buildHcs16StateUpdateTx=ag,exports.buildHcs16TransactionTx=sg,exports.buildHcs17CreateTopicTx=bg,exports.buildHcs17MessageTx=wg,exports.buildHcs18AnnounceMessage=Ng,exports.buildHcs18CompleteMessage=Fg,exports.buildHcs18CreateDiscoveryTopicTx=xg,exports.buildHcs18DiscoveryMemo=Cg,exports.buildHcs18ProposeMessage=_g,exports.buildHcs18RespondMessage=Pg,exports.buildHcs18SubmitDiscoveryMessageTx=Rg,exports.buildHcs18WithdrawMessage=zg,exports.buildHcs1Hrl=th,exports.buildHcs20BurnTx=Lh,exports.buildHcs20DeployTx=Bh,exports.buildHcs20MintTx=Kh,exports.buildHcs20RegisterTx=$h,exports.buildHcs20SubmitMessageTx=function(e){const t="string"==typeof e.payload?e.payload:JSON.stringify(e.payload);return Y({topicId:e.topicId,message:t,transactionMemo:e.transactionMemo})},exports.buildHcs20TransferTx=Uh,exports.buildHcs21CreateRegistryTx=jh,exports.buildHcs21MessageTx=Wh,exports.buildHcs21RegistryMemo=qh,exports.buildHcs2CreateRegistryTx=gh,exports.buildHcs2DeleteTx=function(e){const t={p:"hcs-2",op:oh.DELETE,uid:e.uid,m:e.memo};return Y({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})},exports.buildHcs2MigrateTx=function(e){const t={p:"hcs-2",op:oh.MIGRATE,t_id:e.targetTopicId,metadata:e.metadata,m:e.memo};return Y({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})},exports.buildHcs2RegisterTx=mh,exports.buildHcs2UpdateTx=function(e){const t={p:"hcs-2",op:oh.UPDATE,uid:e.uid,t_id:e.targetTopicId,metadata:e.metadata,m:e.memo};return Y({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})},exports.buildHcs5MintTx=ih,exports.buildHcs5MintWithHrlTx=function(e){const t=th(e.metadataTopicId);return ih({tokenId:e.tokenId,metadata:t,transactionMemo:e.transactionMemo})},exports.buildHcs6CreateRegistryTx=X,exports.buildHcs6Hrl=U,exports.buildHcs6RegisterEntryTx=function(e){const t={p:"hcs-6",op:B.REGISTER,t_id:e.targetTopicId,m:e.memo};return Y({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})},exports.buildHcs7CreateRegistryTx=ec,exports.buildHcs7EvmMessageTx=function(e){const t={p:"hcs-7",op:$a.REGISTER_CONFIG,t:Ha.EVM,c:{contractAddress:e.config.contractAddress,abi:e.config.abi},m:e.config.memo??""};return tc({topicId:e.topicId,message:t,transactionMemo:e.transactionMemo})},exports.buildHcs7SubmitMessageTx=tc,exports.buildHcs7WasmMessageTx=function(e){const t={p:"hcs-7",op:$a.REGISTER_CONFIG,t:Ha.WASM,c:{wasmTopicId:e.config.wasmTopicId,inputType:e.config.inputType,outputType:e.config.outputType},m:e.config.memo??""};return tc({topicId:e.topicId,message:t,transactionMemo:e.transactionMemo})},exports.canonicalize=Jh,exports.canonicalizeAgentData=zp,exports.canonicalizeLedgerNetwork=Ad,exports.capabilityNameToCapabilityMap=gu,exports.createLoggerAdapter=oc,exports.createPrivateKeySigner=xd,exports.createUaid=Up,exports.defaultIssuerRegistry=Jp,exports.defaultResolverRegistry=Wp,exports.deleteMessageSchema=dh,exports.detectCryptoEnvironment=Hd,exports.detectKeyTypeFromString=te,exports.ensureLoggerType=function(e){return nc(e)?e:oc(e)},exports.extractReferenceId=function(e){const t=e.trim(),r=t.match(/^content-ref:([a-f0-9]+)$/);if(r)return r[1];const i=t.match(/content-ref:([a-f0-9]+)/);return i?i[1]:null},exports.generateHCS17Memo=mg,exports.generateHCS6RegistryMemo=W,exports.generateQuote=Ka,exports.getCryptoAdapter=Xd,exports.getExampleTopics=function(e){return"mainnet"===e?Rp:xp},exports.getHumanReadableTransactionType=ka,exports.getOrCreateSDK=xa,exports.getParserConfig=function(e){return ba[e]},exports.getSchedulableTransactionType=function(e){for(const[t,r]of Object.entries(Ta))if(e[t])return r;return"unknown"},exports.getSupportedTransactionTypes=function(){return Object.keys(ba)},exports.getTopicId=La,exports.getTransactionTypeFromBody=Sa,exports.hash=async function(e,t="sha256"){const r=Xd().createHash(t),i="string"==typeof e?globalThis.Buffer.from(e):e,o=r.update(i).digest("hex");return o instanceof Promise?await o:o},exports.hashLinksRegistrationSchema=gp,exports.hcs17MessageSchema=pg,exports.hcs2MessageSchema=ph,exports.hcs6BaseMessageSchema=$,exports.hcs6MessageSchema=q,exports.hcs6RegisterMessageSchema=H,exports.hcs6TopicIdSchema=L,exports.hcs7MessageSchema=Xa,exports.humanReadableTypeRegistry=Ia,exports.inscribe=za,exports.inscribeWithSigner=Da,exports.isAnnounceMessage=function(e){if(!Eg(e))return!1;const t=e;if("announce"!==t.op)return!1;if(!Tg(t.data))return!1;const r=t.data;if(!Sg(r.account))return!1;if(!Tg(r.petal))return!1;const i=r.petal;return!(!Sg(i.name)||!kg(i.priority))&&(!!Tg(r.capabilities)&&(!!function(e){return Array.isArray(e)&&e.every(Sg)}(r.capabilities.protocols)&&!("valid_for"in r&&void 0!==r.valid_for&&null!==r.valid_for&&!kg(r.valid_for))))},exports.isBrowser=va,exports.isCompleteMessage=function(e){if(!Eg(e))return!1;const t=e;if("complete"!==t.op)return!1;if(!Tg(t.data))return!1;const r=t.data;if(!Sg(r.proposer))return!1;if(!kg(r.proposal_seq))return!1;if(!Sg(r.flora_account))return!1;if(!Tg(r.topics))return!1;const i=r.topics;return!!(Sg(i.communication)&&Sg(i.transaction)&&Sg(i.state))},exports.isConcreteLogger=nc,exports.isCryptoAvailable=function(){return"none"!==Hd().preferredAPI},exports.isDiscoveryMessage=Eg,exports.isEip155Caip10=nu,exports.isHederaCaip10=tu,exports.isHederaNetwork=Qd,exports.isPartialRegisterAgentResponse=e=>"partial"===e.status&&!1===e.success,exports.isPendingRegisterAgentResponse=e=>"pending"===e.status,exports.isProposeMessage=function(e){if(!Eg(e))return!1;const t=e;if("propose"!==t.op)return!1;if(!Tg(t.data))return!1;const r=t.data;if(!Sg(r.proposer))return!1;if(!function(e){return Array.isArray(e)}(r.members))return!1;if(!r.members.every(e=>{if(!Tg(e))return!1;const t=e;return!!Sg(t.account)&&(!(!("priority"in t)||!kg(t.priority))&&!("announce_seq"in t&&void 0!==t.announce_seq&&null!==t.announce_seq&&!kg(t.announce_seq)))}))return!1;if(!Tg(r.config))return!1;const i=r.config;return!(!Sg(i.name)||!kg(i.threshold))},exports.isRespondMessage=function(e){if(!Eg(e))return!1;const t=e;if("respond"!==t.op)return!1;if(!Tg(t.data))return!1;const r=t.data;return!!Sg(r.responder)&&(!!kg(r.proposal_seq)&&(!!Sg(r.decision)&&!!["accept","reject"].includes(r.decision)))},exports.isSSREnvironment=qd,exports.isSuccessRegisterAgentResponse=e=>!0===e.success&&"pending"!==e.status,exports.isTransactionTypeSupported=function(e){return e in ba},exports.isWithdrawMessage=function(e){if(!Eg(e))return!1;const t=e;if("withdraw"!==t.op)return!1;if(!Tg(t.data))return!1;const r=t.data;return!!Sg(r.account)&&(!!kg(r.announce_seq)&&!("reason"in r&&void 0!==r.reason&&null!==r.reason&&!Sg(r.reason)))},exports.mcpServiceNameToCapabilityMap={resource_provider:0,tool_provider:1,prompt_template_provider:2,local_file_access:3,database_integration:4,api_integration:5,web_access:6,knowledge_base:7,memory_persistence:8,code_analysis:9,content_generation:10,communication:11,document_processing:12,calendar_schedule:13,search:14,assistant_orchestration:15},exports.metadataDocumentSchema=bc,exports.migrateMessageSchema=uh,exports.normalizeTransactionId=Na,exports.parseHCS17Memo=fg,exports.parseHcs14Did=Lp,exports.parseHederaCaip10=iu,exports.protoFieldToTypeRegistry=wa,exports.registerDefaultResolvers=Vp,exports.registerMessageSchema=ch,exports.registryMetadataSchema=yc,exports.resolveTransactionSummary=aa,exports.retrieveInscription=Ma,exports.safeValidate=function(e,t){const r=e.safeParse(t);return r.success?{success:!0,data:r.data}:{success:!1,errors:r.error}},exports.schedulableTransactionTypeRegistry=Ta,exports.setLoggerFactory=function(e){z=e,O.clearInstances()},exports.shouldUseReference=function(e){return("string"==typeof e?globalThis.Buffer.byteLength(e,"utf8"):e.length)>51200},exports.sleep=D,exports.toEip155Caip10=su,exports.toHederaCaip10=ru,exports.topicIdSchema=sh,exports.transactionParserRegistry=ba,exports.transactionSummaryRegistry=sa,exports.updateMessageSchema=lh,exports.validateActionRegistration=mp,exports.validateAssemblyMessage=fp,exports.validateAssemblyRegistration=function(e){return hp.parse(e)},exports.validateBlockRegistration=function(e){return ap.parse(e)},exports.validateHCS6RegistryMemo=function(e){const t=e.match(/^hcs-6:(\d):(\d+)$/);if(!t)return!1;const r=parseInt(t[1]),i=parseInt(t[2]);return 1===r&&j(i)},exports.validateHCS6TTL=j,exports.validateHashLinksRegistration=function(e){return gp.parse(e)},exports.validateWithSchema=yp,exports.verifyArtifactDigest=function(e,t){const r=b.createHash("sha384");r.update(e);const i=r.digest("hex").toLowerCase(),o=globalThis.Buffer.from(i,"hex").toString("base64").toLowerCase(),n=t.replace(/^sha384[-:]?/i,"").trim().toLowerCase();return n===i||n===o},exports.verifyDeclarationSignature=function(e,t){if(!e.signature)return!1;try{const{signature:r,...o}=e,n=Jh(o),s=globalThis.Buffer.from(r,"base64");return i.PublicKey.fromString(t).verify(globalThis.Buffer.from(n,"utf8"),s)}catch{return!1}},exports.verifyManifestSignature=function(e,t,r){try{const o=Jh(e),n=globalThis.Buffer.from(t,"base64");return i.PublicKey.fromString(r).verify(globalThis.Buffer.from(o,"utf8"),n)}catch{return!1}},exports.waitForInscriptionConfirmation=Ua;
11
11
  //# sourceMappingURL=standards-sdk.cjs.map