@hashgraphonline/standards-sdk 0.1.143 → 0.1.144

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 (185) hide show
  1. package/dist/cjs/hcs-12/validation/schemas.d.ts +8 -8
  2. package/dist/cjs/hcs-21/types.d.ts +75 -75
  3. package/dist/cjs/services/registry-broker/client/adapters.d.ts +20 -0
  4. package/dist/cjs/services/registry-broker/client/adapters.d.ts.map +1 -0
  5. package/dist/cjs/services/registry-broker/client/agents.d.ts +16 -0
  6. package/dist/cjs/services/registry-broker/client/agents.d.ts.map +1 -0
  7. package/dist/cjs/services/registry-broker/client/base-client.d.ts +57 -0
  8. package/dist/cjs/services/registry-broker/client/base-client.d.ts.map +1 -0
  9. package/dist/cjs/services/registry-broker/client/chat-history.d.ts +23 -0
  10. package/dist/cjs/services/registry-broker/client/chat-history.d.ts.map +1 -0
  11. package/dist/cjs/services/registry-broker/client/chat.d.ts +33 -0
  12. package/dist/cjs/services/registry-broker/client/chat.d.ts.map +1 -0
  13. package/dist/cjs/services/registry-broker/client/credits.d.ts +40 -0
  14. package/dist/cjs/services/registry-broker/client/credits.d.ts.map +1 -0
  15. package/dist/cjs/services/registry-broker/client/encrypted-chat-manager.d.ts +35 -0
  16. package/dist/cjs/services/registry-broker/client/encrypted-chat-manager.d.ts.map +1 -0
  17. package/dist/cjs/services/registry-broker/client/encryption.d.ts +33 -0
  18. package/dist/cjs/services/registry-broker/client/encryption.d.ts.map +1 -0
  19. package/dist/cjs/services/registry-broker/client/errors.d.ts +19 -0
  20. package/dist/cjs/services/registry-broker/client/errors.d.ts.map +1 -0
  21. package/dist/cjs/services/registry-broker/client/ledger-auth.d.ts +10 -0
  22. package/dist/cjs/services/registry-broker/client/ledger-auth.d.ts.map +1 -0
  23. package/dist/cjs/services/registry-broker/client/search.d.ts +19 -0
  24. package/dist/cjs/services/registry-broker/client/search.d.ts.map +1 -0
  25. package/dist/cjs/services/registry-broker/client/utils.d.ts +21 -0
  26. package/dist/cjs/services/registry-broker/client/utils.d.ts.map +1 -0
  27. package/dist/cjs/services/registry-broker/client.d.ts +2 -205
  28. package/dist/cjs/services/registry-broker/client.d.ts.map +1 -1
  29. package/dist/cjs/services/registry-broker/schemas.d.ts +1426 -154
  30. package/dist/cjs/services/registry-broker/schemas.d.ts.map +1 -1
  31. package/dist/cjs/services/registry-broker/types.d.ts +45 -2
  32. package/dist/cjs/services/registry-broker/types.d.ts.map +1 -1
  33. package/dist/cjs/standards-sdk.cjs +3 -3
  34. package/dist/cjs/standards-sdk.cjs.map +1 -1
  35. package/dist/es/hcs-12/validation/schemas.d.ts +8 -8
  36. package/dist/es/hcs-21/types.d.ts +75 -75
  37. package/dist/es/services/registry-broker/client/adapters.d.ts +20 -0
  38. package/dist/es/services/registry-broker/client/adapters.d.ts.map +1 -0
  39. package/dist/es/services/registry-broker/client/agents.d.ts +16 -0
  40. package/dist/es/services/registry-broker/client/agents.d.ts.map +1 -0
  41. package/dist/es/services/registry-broker/client/base-client.d.ts +57 -0
  42. package/dist/es/services/registry-broker/client/base-client.d.ts.map +1 -0
  43. package/dist/es/services/registry-broker/client/chat-history.d.ts +23 -0
  44. package/dist/es/services/registry-broker/client/chat-history.d.ts.map +1 -0
  45. package/dist/es/services/registry-broker/client/chat.d.ts +33 -0
  46. package/dist/es/services/registry-broker/client/chat.d.ts.map +1 -0
  47. package/dist/es/services/registry-broker/client/credits.d.ts +40 -0
  48. package/dist/es/services/registry-broker/client/credits.d.ts.map +1 -0
  49. package/dist/es/services/registry-broker/client/encrypted-chat-manager.d.ts +35 -0
  50. package/dist/es/services/registry-broker/client/encrypted-chat-manager.d.ts.map +1 -0
  51. package/dist/es/services/registry-broker/client/encryption.d.ts +33 -0
  52. package/dist/es/services/registry-broker/client/encryption.d.ts.map +1 -0
  53. package/dist/es/services/registry-broker/client/errors.d.ts +19 -0
  54. package/dist/es/services/registry-broker/client/errors.d.ts.map +1 -0
  55. package/dist/es/services/registry-broker/client/ledger-auth.d.ts +10 -0
  56. package/dist/es/services/registry-broker/client/ledger-auth.d.ts.map +1 -0
  57. package/dist/es/services/registry-broker/client/search.d.ts +19 -0
  58. package/dist/es/services/registry-broker/client/search.d.ts.map +1 -0
  59. package/dist/es/services/registry-broker/client/utils.d.ts +21 -0
  60. package/dist/es/services/registry-broker/client/utils.d.ts.map +1 -0
  61. package/dist/es/services/registry-broker/client.d.ts +2 -205
  62. package/dist/es/services/registry-broker/client.d.ts.map +1 -1
  63. package/dist/es/services/registry-broker/schemas.d.ts +1426 -154
  64. package/dist/es/services/registry-broker/schemas.d.ts.map +1 -1
  65. package/dist/es/services/registry-broker/types.d.ts +45 -2
  66. package/dist/es/services/registry-broker/types.d.ts.map +1 -1
  67. package/dist/es/standards-sdk.es.js +16 -7
  68. package/dist/es/standards-sdk.es.js.map +1 -1
  69. package/dist/es/standards-sdk.es100.js +1 -1
  70. package/dist/es/standards-sdk.es102.js +1 -1
  71. package/dist/es/standards-sdk.es104.js +1 -1
  72. package/dist/es/standards-sdk.es110.js +11 -5
  73. package/dist/es/standards-sdk.es110.js.map +1 -1
  74. package/dist/es/standards-sdk.es111.js +5 -5
  75. package/dist/es/standards-sdk.es12.js +1 -1
  76. package/dist/es/standards-sdk.es121.js +1 -1
  77. package/dist/es/standards-sdk.es122.js +1 -1
  78. package/dist/es/standards-sdk.es123.js +5 -5
  79. package/dist/es/standards-sdk.es125.js +1 -1
  80. package/dist/es/standards-sdk.es126.js +1 -1
  81. package/dist/es/standards-sdk.es128.js +140 -2176
  82. package/dist/es/standards-sdk.es128.js.map +1 -1
  83. package/dist/es/standards-sdk.es129.js +200 -60
  84. package/dist/es/standards-sdk.es129.js.map +1 -1
  85. package/dist/es/standards-sdk.es13.js +1 -1
  86. package/dist/es/standards-sdk.es130.js +96 -79
  87. package/dist/es/standards-sdk.es130.js.map +1 -1
  88. package/dist/es/standards-sdk.es131.js +115 -153
  89. package/dist/es/standards-sdk.es131.js.map +1 -1
  90. package/dist/es/standards-sdk.es132.js +248 -8
  91. package/dist/es/standards-sdk.es132.js.map +1 -1
  92. package/dist/es/standards-sdk.es133.js +169 -75
  93. package/dist/es/standards-sdk.es133.js.map +1 -1
  94. package/dist/es/standards-sdk.es134.js +118 -61
  95. package/dist/es/standards-sdk.es134.js.map +1 -1
  96. package/dist/es/standards-sdk.es135.js +327 -29
  97. package/dist/es/standards-sdk.es135.js.map +1 -1
  98. package/dist/es/standards-sdk.es136.js +352 -124
  99. package/dist/es/standards-sdk.es136.js.map +1 -1
  100. package/dist/es/standards-sdk.es137.js +13 -38
  101. package/dist/es/standards-sdk.es137.js.map +1 -1
  102. package/dist/es/standards-sdk.es138.js +66 -765
  103. package/dist/es/standards-sdk.es138.js.map +1 -1
  104. package/dist/es/standards-sdk.es139.js +74 -12261
  105. package/dist/es/standards-sdk.es139.js.map +1 -1
  106. package/dist/es/standards-sdk.es140.js +152 -49
  107. package/dist/es/standards-sdk.es140.js.map +1 -1
  108. package/dist/es/standards-sdk.es141.js +7 -82
  109. package/dist/es/standards-sdk.es141.js.map +1 -1
  110. package/dist/es/standards-sdk.es142.js +81 -12
  111. package/dist/es/standards-sdk.es142.js.map +1 -1
  112. package/dist/es/standards-sdk.es143.js +55 -162
  113. package/dist/es/standards-sdk.es143.js.map +1 -1
  114. package/dist/es/standards-sdk.es144.js +28 -322
  115. package/dist/es/standards-sdk.es144.js.map +1 -1
  116. package/dist/es/standards-sdk.es145.js +120 -328
  117. package/dist/es/standards-sdk.es145.js.map +1 -1
  118. package/dist/es/standards-sdk.es146.js +40 -451
  119. package/dist/es/standards-sdk.es146.js.map +1 -1
  120. package/dist/es/standards-sdk.es147.js +12225 -267
  121. package/dist/es/standards-sdk.es147.js.map +1 -1
  122. package/dist/es/standards-sdk.es148.js +15 -74
  123. package/dist/es/standards-sdk.es148.js.map +1 -1
  124. package/dist/es/standards-sdk.es149.js +59 -0
  125. package/dist/es/standards-sdk.es149.js.map +1 -0
  126. package/dist/es/standards-sdk.es150.js +85 -0
  127. package/dist/es/standards-sdk.es150.js.map +1 -0
  128. package/dist/es/standards-sdk.es151.js +175 -0
  129. package/dist/es/standards-sdk.es151.js.map +1 -0
  130. package/dist/es/standards-sdk.es152.js +325 -0
  131. package/dist/es/standards-sdk.es152.js.map +1 -0
  132. package/dist/es/standards-sdk.es153.js +349 -0
  133. package/dist/es/standards-sdk.es153.js.map +1 -0
  134. package/dist/es/standards-sdk.es154.js +456 -0
  135. package/dist/es/standards-sdk.es154.js.map +1 -0
  136. package/dist/es/standards-sdk.es155.js +334 -0
  137. package/dist/es/standards-sdk.es155.js.map +1 -0
  138. package/dist/es/standards-sdk.es156.js +79 -0
  139. package/dist/es/standards-sdk.es156.js.map +1 -0
  140. package/dist/es/standards-sdk.es157.js +874 -0
  141. package/dist/es/standards-sdk.es157.js.map +1 -0
  142. package/dist/es/standards-sdk.es158.js +242 -0
  143. package/dist/es/standards-sdk.es158.js.map +1 -0
  144. package/dist/es/standards-sdk.es159.js +247 -0
  145. package/dist/es/standards-sdk.es159.js.map +1 -0
  146. package/dist/es/standards-sdk.es17.js +11 -5
  147. package/dist/es/standards-sdk.es17.js.map +1 -1
  148. package/dist/es/standards-sdk.es19.js +14 -9
  149. package/dist/es/standards-sdk.es19.js.map +1 -1
  150. package/dist/es/standards-sdk.es20.js +12 -7
  151. package/dist/es/standards-sdk.es20.js.map +1 -1
  152. package/dist/es/standards-sdk.es23.js +1 -1
  153. package/dist/es/standards-sdk.es28.js +14 -9
  154. package/dist/es/standards-sdk.es28.js.map +1 -1
  155. package/dist/es/standards-sdk.es31.js +1 -1
  156. package/dist/es/standards-sdk.es32.js +1 -1
  157. package/dist/es/standards-sdk.es36.js +11 -6
  158. package/dist/es/standards-sdk.es36.js.map +1 -1
  159. package/dist/es/standards-sdk.es37.js +3 -3
  160. package/dist/es/standards-sdk.es38.js +1 -1
  161. package/dist/es/standards-sdk.es5.js +1 -1
  162. package/dist/es/standards-sdk.es54.js +1 -1
  163. package/dist/es/standards-sdk.es57.js +1 -1
  164. package/dist/es/standards-sdk.es59.js +1 -1
  165. package/dist/es/standards-sdk.es60.js +1 -1
  166. package/dist/es/standards-sdk.es61.js +12 -7
  167. package/dist/es/standards-sdk.es61.js.map +1 -1
  168. package/dist/es/standards-sdk.es63.js +1 -1
  169. package/dist/es/standards-sdk.es65.js +1 -1
  170. package/dist/es/standards-sdk.es66.js +2 -2
  171. package/dist/es/standards-sdk.es69.js +2 -2
  172. package/dist/es/standards-sdk.es70.js +1 -1
  173. package/dist/es/standards-sdk.es72.js +1 -1
  174. package/dist/es/standards-sdk.es77.js +1 -1
  175. package/dist/es/standards-sdk.es78.js +11 -5
  176. package/dist/es/standards-sdk.es78.js.map +1 -1
  177. package/dist/es/standards-sdk.es79.js +1 -1
  178. package/dist/es/standards-sdk.es8.js +1 -1
  179. package/dist/es/standards-sdk.es82.js +1 -1
  180. package/dist/es/standards-sdk.es84.js +1 -1
  181. package/dist/es/standards-sdk.es88.js +1 -1
  182. package/dist/es/standards-sdk.es92.js +1 -1
  183. package/dist/es/standards-sdk.es93.js +1 -1
  184. package/dist/es/standards-sdk.es98.js +1 -1
  185. package/package.json +11 -12
@@ -1,11 +1,11 @@
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("mime-types"),f=require("date-fns"),y=require("crypto");var b="undefined"!=typeof document?document.currentScript:null;function w(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 I=w(u),T=w(m),S=/^\d+\.\d+\.\d+$/u,k=Symbol.for("standards-sdk.topic-auto-renew.patch"),E=Symbol.for("standards-sdk.account-id.patch"),v=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:b&&"SCRIPT"===b.tagName.toUpperCase()&&b.src||new URL("standards-sdk.cjs",document.baseURI).href)}catch{return null}if("function"==typeof require)return require;return null}();function A(e,t){try{return e(t)}catch{return null}}function C(e,t){if(!e||!t)return;!function(e){if(Reflect.get(e,E))return;const t=e.fromString.bind(e);e.fromString=function(e){if("string"==typeof e)return t(e);const r=R(e);if(r)return t(r);if(N(e)){const r=P(e.shard),i=P(e.realm),o=P(e.num);if(r&&i&&o)return t(`${r}.${i}.${o}`)}return t(e)},Reflect.set(e,E,!0)}(t);const r=e.prototype;if(Reflect.get(r,k))return;const i=r.setAutoRenewAccountId,o=r.freezeWith;r.setAutoRenewAccountId=function(e){const r=x(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=x(r,t)??x(i,t);o&&(this._autoRenewAccountId=o)}return o.call(this,e)},Reflect.set(r,k,!0)}function x(e,t){if(e instanceof t)return e;if("string"==typeof e&&S.test(e))return t.fromString(e);const r=function(e){if("string"==typeof e&&S.test(e))return e;const t=R(e);if(t)return t;if(N(e)){const t=P(e.shard),r=P(e.realm),i=P(e.num);if(t&&r&&i){const e=`${t}.${r}.${i}`;if(S.test(e))return e}}return null}(e);return r?t.fromString(r):null}function R(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:S.test(r)?r:null}function N(e){if("object"!=typeof e||null===e)return!1;const t=e;return _(t.shard)&&_(t.realm)&&_(t.num)}function _(e){return"object"==typeof e&&null!==e&&"function"==typeof e.toString}function P(e){if("number"==typeof e&&Number.isFinite(e))return String(Math.trunc(e));if("bigint"==typeof e)return e.toString();if(_(e)){const t=e.toString();if(/^\d+$/u.test(t))return t}return null}v?function(e){const t=A(e,"@hashgraph/sdk/lib/account/AccountId.cjs"),r=A(e,"@hashgraph/sdk/lib/topic/TopicCreateTransaction.cjs"),i=A(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)C(n.topic,n.accountId);Reflect.set(globalThis,"__standardsSdkTopicAutoRenewPatched",!0)}(v):Reflect.set(globalThis,"__standardsSdkTopicAutoRenewPatched",!1);let F=null;let O=((e=class{constructor(e={}){if(F)return F(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=F?F(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 z=e=>new Promise(t=>setTimeout(t,e));class D{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 z(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 M=(e=>(e.REGISTER="register",e))(M||{}),K=(e=>(e[e.NON_INDEXED=1]="NON_INDEXED",e))(K||{});function B(e){return`hcs://6/${e}`}const U=r.z.string().regex(/^\d+\.\d+\.\d+$/,{message:"Topic ID must be in Hedera format (e.g., '0.0.123456')"}),L=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()}),$=L.extend({op:r.z.literal("register"),t_id:U}),H=r.z.discriminatedUnion("op",[$]);function q(e){return e>=3600}function j(e){if(!q(e))throw new Error("TTL must be at least 3600 seconds (1 hour)");return`hcs-6:1:${e}`}class W{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 V{constructor(e){this.network=e.network,this.logger=e.logger||O.getInstance({level:e.logLevel||"info",module:"HCS6Client",silent:e.silent}),this.mirrorNode=new W(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&&q(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 j(e)}validateMessage(e){try{return H.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:M.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 G(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 J(e){const t=(new i.TopicMessageSubmitTransaction).setTopicId(i.TopicId.fromString(e.topicId)).setMessage(e.message);return e.transactionMemo&&t.setTransactionMemo(e.transactionMemo),t}function Y(e){return G({memo:e.memoOverride??`hcs-6:1:${e.ttl}`,submitKey:e.submitKey,adminKey:e.adminKey,operatorPublicKey:e.operatorPublicKey})}var X=(e=>(e.ED25519="ed25519",e.ECDSA="ecdsa",e.UNKNOWN="unknown",e))(X||{});const Z=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}};Z.ED25519_PUBLIC_KEY_LENGTH=32,Z.ED25519_EXPANDED_PRIVATE_KEY_LENGTH=64,Z.ED25519_PUBLIC_KEY_PREFIX=globalThis.Buffer.from([48,42,48,5,6,3,43,101,112,3,33,0]),Z.ED25519_PRIVATE_KEY_PREFIX=globalThis.Buffer.from([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]),Z.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]),Z.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX=globalThis.Buffer.from([48,116,2,1,1,4,32]),Z.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]),Z.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_LONG=globalThis.Buffer.from([48,119,2,1,1,4,32]);let Q=Z;function ee(e){const t=Q.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 te{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=ee(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 re(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 te({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 ie=Object.defineProperty,oe=((e,t,r)=>((e,t,r)=>t in e?ie(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r)),ne={},se={byteLength:function(e){var t=pe(e),r=t[0],i=t[1];return 3*(r+i)/4-i},toByteArray:function(e){var t,r,i=pe(e),o=i[0],n=i[1],s=new le(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=ce[e.charCodeAt(r)]<<18|ce[e.charCodeAt(r+1)]<<12|ce[e.charCodeAt(r+2)]<<6|ce[e.charCodeAt(r+3)],s[a++]=t>>16&255,s[a++]=t>>8&255,s[a++]=255&t;2===n&&(t=ce[e.charCodeAt(r)]<<2|ce[e.charCodeAt(r+1)]>>4,s[a++]=255&t);1===n&&(t=ce[e.charCodeAt(r)]<<10|ce[e.charCodeAt(r+1)]<<4|ce[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(ge(e,s,s+n>a?a:s+n));1===i?(t=e[r-1],o.push(ae[t>>2]+ae[t<<4&63]+"==")):2===i&&(t=(e[r-2]<<8)+e[r-1],o.push(ae[t>>10]+ae[t>>4&63]+ae[t<<2&63]+"="));return o.join("")}},ae=[],ce=[],le="undefined"!=typeof Uint8Array?Uint8Array:Array,de="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ue=0;ue<64;++ue)ae[ue]=de[ue],ce[de.charCodeAt(ue)]=ue;function pe(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 he(e){return ae[e>>18&63]+ae[e>>12&63]+ae[e>>6&63]+ae[63&e]}function ge(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(he(i));return o.join("")}ce["-".charCodeAt(0)]=62,ce["_".charCodeAt(0)]=63;var me={
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"),u=require("bignumber.js"),d=require("path"),p=require("crypto"),h=require("@noble/curves/secp256k1.js"),g=require("mime-types"),m=require("date-fns");var f="undefined"!=typeof document?document.currentScript:null;function y(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 b=y(d),w=y(g),I=/^\d+\.\d+\.\d+$/u,T=Symbol.for("standards-sdk.topic-auto-renew.patch"),S=Symbol.for("standards-sdk.account-id.patch"),k=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:f&&"SCRIPT"===f.tagName.toUpperCase()&&f.src||new URL("standards-sdk.cjs",document.baseURI).href)}catch{return null}if("function"==typeof require)return require;return null}();function E(e,t){try{return e(t)}catch{return null}}function v(e,t){if(!e||!t)return;!function(e){if(Reflect.get(e,S))return;const t=e.fromString.bind(e);e.fromString=function(e){if("string"==typeof e)return t(e);const r=C(e);if(r)return t(r);if(x(e)){const r=N(e.shard),i=N(e.realm),o=N(e.num);if(r&&i&&o)return t(`${r}.${i}.${o}`)}return t(e)},Reflect.set(e,S,!0)}(t);const r=e.prototype;if(Reflect.get(r,T))return;const i=r.setAutoRenewAccountId,o=r.freezeWith;r.setAutoRenewAccountId=function(e){const r=A(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=A(r,t)??A(i,t);o&&(this._autoRenewAccountId=o)}return o.call(this,e)},Reflect.set(r,T,!0)}function A(e,t){if(e instanceof t)return e;if("string"==typeof e&&I.test(e))return t.fromString(e);const r=function(e){if("string"==typeof e&&I.test(e))return e;const t=C(e);if(t)return t;if(x(e)){const t=N(e.shard),r=N(e.realm),i=N(e.num);if(t&&r&&i){const e=`${t}.${r}.${i}`;if(I.test(e))return e}}return null}(e);return r?t.fromString(r):null}function C(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:I.test(r)?r:null}function x(e){if("object"!=typeof e||null===e)return!1;const t=e;return R(t.shard)&&R(t.realm)&&R(t.num)}function R(e){return"object"==typeof e&&null!==e&&"function"==typeof e.toString}function N(e){if("number"==typeof e&&Number.isFinite(e))return String(Math.trunc(e));if("bigint"==typeof e)return e.toString();if(R(e)){const t=e.toString();if(/^\d+$/u.test(t))return t}return null}k?function(e){const t=E(e,"@hashgraph/sdk/lib/account/AccountId.cjs"),r=E(e,"@hashgraph/sdk/lib/topic/TopicCreateTransaction.cjs"),i=E(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)v(n.topic,n.accountId);Reflect.set(globalThis,"__standardsSdkTopicAutoRenewPatched",!0)}(k):Reflect.set(globalThis,"__standardsSdkTopicAutoRenewPatched",!1);let _=null;let P=((e=class{constructor(e={}){if(_)return _(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=_?_(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 F=e=>new Promise(t=>setTimeout(t,e));class z{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=P.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 F(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 O=(e=>(e.REGISTER="register",e))(O||{}),D=(e=>(e[e.NON_INDEXED=1]="NON_INDEXED",e))(D||{});function M(e){return`hcs://6/${e}`}const B=r.z.string().regex(/^\d+\.\d+\.\d+$/,{message:"Topic ID must be in Hedera format (e.g., '0.0.123456')"}),K=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()}),U=K.extend({op:r.z.literal("register"),t_id:B}),L=r.z.discriminatedUnion("op",[U]);function $(e){return e>=3600}function H(e){if(!$(e))throw new Error("TTL must be at least 3600 seconds (1 hour)");return`hcs-6:1:${e}`}class q{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 P({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||P.getInstance({level:e.logLevel||"info",module:"HCS6Client",silent:e.silent}),this.mirrorNode=new q(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===D.NON_INDEXED&&$(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 H(e)}validateMessage(e){try{return L.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:O.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===D.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 W(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 V(e){const t=(new i.TopicMessageSubmitTransaction).setTopicId(i.TopicId.fromString(e.topicId)).setMessage(e.message);return e.transactionMemo&&t.setTransactionMemo(e.transactionMemo),t}function G(e){return W({memo:e.memoOverride??`hcs-6:1:${e.ttl}`,submitKey:e.submitKey,adminKey:e.adminKey,operatorPublicKey:e.operatorPublicKey})}var J=(e=>(e.ED25519="ed25519",e.ECDSA="ecdsa",e.UNKNOWN="unknown",e))(J||{});const Y=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}};Y.ED25519_PUBLIC_KEY_LENGTH=32,Y.ED25519_EXPANDED_PRIVATE_KEY_LENGTH=64,Y.ED25519_PUBLIC_KEY_PREFIX=globalThis.Buffer.from([48,42,48,5,6,3,43,101,112,3,33,0]),Y.ED25519_PRIVATE_KEY_PREFIX=globalThis.Buffer.from([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]),Y.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]),Y.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX=globalThis.Buffer.from([48,116,2,1,1,4,32]),Y.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]),Y.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_LONG=globalThis.Buffer.from([48,119,2,1,1,4,32]);let X=Y;function Z(e){const t=X.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 Q{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=Z(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 ee(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 Q({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 te=Object.defineProperty,re=((e,t,r)=>((e,t,r)=>t in e?te(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r)),ie={},oe={byteLength:function(e){var t=ue(e),r=t[0],i=t[1];return 3*(r+i)/4-i},toByteArray:function(e){var t,r,i=ue(e),o=i[0],n=i[1],s=new ae(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=se[e.charCodeAt(r)]<<18|se[e.charCodeAt(r+1)]<<12|se[e.charCodeAt(r+2)]<<6|se[e.charCodeAt(r+3)],s[a++]=t>>16&255,s[a++]=t>>8&255,s[a++]=255&t;2===n&&(t=se[e.charCodeAt(r)]<<2|se[e.charCodeAt(r+1)]>>4,s[a++]=255&t);1===n&&(t=se[e.charCodeAt(r)]<<10|se[e.charCodeAt(r+1)]<<4|se[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(pe(e,s,s+n>a?a:s+n));1===i?(t=e[r-1],o.push(ne[t>>2]+ne[t<<4&63]+"==")):2===i&&(t=(e[r-2]<<8)+e[r-1],o.push(ne[t>>10]+ne[t>>4&63]+ne[t<<2&63]+"="));return o.join("")}},ne=[],se=[],ae="undefined"!=typeof Uint8Array?Uint8Array:Array,ce="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",le=0;le<64;++le)ne[le]=ce[le],se[ce.charCodeAt(le)]=le;function ue(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 de(e){return ne[e>>18&63]+ne[e>>12&63]+ne[e>>6&63]+ne[63&e]}function pe(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(de(i));return o.join("")}se["-".charCodeAt(0)]=62,se["_".charCodeAt(0)]=63;var he={
2
2
  /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
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}};
3
+ read:function(e,t,r,i,o){var n,s,a=8*o-i-1,c=(1<<a)-1,l=c>>1,u=-7,d=r?o-1:0,p=r?-1:1,h=e[t+d];for(d+=p,n=h&(1<<-u)-1,h>>=-u,u+=a;u>0;n=256*n+e[t+d],d+=p,u-=8);for(s=n&(1<<-u)-1,n>>=-u,u+=i;u>0;s=256*s+e[t+d],d+=p,u-=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,u=(1<<l)-1,d=u>>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=u):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),(t+=s+d>=1?p/c:p*Math.pow(2,1-d))*c>=2&&(s++,c/=2),s+d>=u?(a=0,s=u):s+d>=1?(a=(t*c-1)*Math.pow(2,o),s+=d):(a=t*Math.pow(2,d-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
  /*!
5
5
  * The buffer module from node.js, for the browser.
6
6
  *
7
7
  * @author Feross Aboukhadijeh <https://feross.org>
8
8
  * @license MIT
9
9
  */
10
- !function(e){const t=se,r=me,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 z(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 K(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 B(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){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 z(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);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 z(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 K(this,e,t,!0,r)},l.prototype.writeFloatBE=function(e,t,r){return K(this,e,t,!1,r)},l.prototype.writeDoubleLE=function(e,t,r){return B(this,e,t,!0,r)},l.prototype.writeDoubleBE=function(e,t,r){return B(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")}}(ne);const fe=ne.Buffer,ye=ne.Buffer,be=globalThis||self;function we(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ie,Te,Se={exports:{}},ke=Se.exports={};function Ee(){throw new Error("setTimeout has not been defined")}function ve(){throw new Error("clearTimeout has not been defined")}function Ae(e){if(Ie===setTimeout)return setTimeout(e,0);if((Ie===Ee||!Ie)&&setTimeout)return Ie=setTimeout,setTimeout(e,0);try{return Ie(e,0)}catch(t){try{return Ie.call(null,e,0)}catch(r){return Ie.call(this,e,0)}}}!function(){try{Ie="function"==typeof setTimeout?setTimeout:Ee}catch(e){Ie=Ee}try{Te="function"==typeof clearTimeout?clearTimeout:ve}catch(e){Te=ve}}();var Ce,xe=[],Re=!1,Ne=-1;function _e(){Re&&Ce&&(Re=!1,Ce.length?xe=Ce.concat(xe):Ne=-1,xe.length&&Pe())}function Pe(){if(!Re){var e=Ae(_e);Re=!0;for(var t=xe.length;t;){for(Ce=xe,xe=[];++Ne<t;)Ce&&Ce[Ne].run();Ne=-1,t=xe.length}Ce=null,Re=!1,function(e){if(Te===clearTimeout)return clearTimeout(e);if((Te===ve||!Te)&&clearTimeout)return Te=clearTimeout,clearTimeout(e);try{return Te(e)}catch(t){try{return Te.call(null,e)}catch(r){return Te.call(this,e)}}}(e)}}function Fe(e,t){this.fun=e,this.array=t}function Oe(){}ke.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];xe.push(new Fe(e,t)),1!==xe.length||Re||Ae(Pe)},Fe.prototype.run=function(){this.fun.apply(null,this.array)},ke.title="browser",ke.browser=!0,ke.env={},ke.argv=[],ke.version="",ke.versions={},ke.on=Oe,ke.addListener=Oe,ke.once=Oe,ke.off=Oe,ke.removeListener=Oe,ke.removeAllListeners=Oe,ke.emit=Oe,ke.prependListener=Oe,ke.prependOnceListener=Oe,ke.listeners=function(e){return[]},ke.binding=function(e){throw new Error("process.binding is not supported")},ke.cwd=function(){return"/"},ke.chdir=function(e){throw new Error("process.chdir is not supported")},ke.umask=function(){return 0};const ze=we(Se.exports);function De(e,t){return function(){return e.apply(t,arguments)}}const{toString:Me}=Object.prototype,{getPrototypeOf:Ke}=Object,{iterator:Be,toStringTag:Ue}=Symbol,Le=(e=>t=>{const r=Me.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),$e=e=>(e=e.toLowerCase(),t=>Le(t)===e),He=e=>t=>typeof t===e,{isArray:qe}=Array,je=He("undefined");function We(e){return null!==e&&!je(e)&&null!==e.constructor&&!je(e.constructor)&&Je(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const Ve=$e("ArrayBuffer");const Ge=He("string"),Je=He("function"),Ye=He("number"),Xe=e=>null!==e&&"object"==typeof e,Ze=e=>{if("object"!==Le(e))return!1;const t=Ke(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Ue in e||Be in e)},Qe=$e("Date"),et=$e("File"),tt=$e("Blob"),rt=$e("FileList"),it=$e("URLSearchParams"),[ot,nt,st,at]=["ReadableStream","Request","Response","Headers"].map($e);function ct(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let i,o;if("object"!=typeof e&&(e=[e]),qe(e))for(i=0,o=e.length;i<o;i++)t.call(null,e[i],i,e);else{if(We(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 lt(e,t){if(We(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 dt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:be,ut=e=>!je(e)&&e!==dt;const pt=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&Ke(Uint8Array)),ht=$e("HTMLFormElement"),gt=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),mt=$e("RegExp"),ft=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),i={};ct(r,(r,o)=>{let n;!1!==(n=t(r,o,e))&&(i[o]=n||r)}),Object.defineProperties(e,i)};const yt=$e("AsyncFunction"),bt=(wt="function"==typeof setImmediate,It=Je(dt.postMessage),wt?setImmediate:It?(Tt=`axios@${Math.random()}`,St=[],dt.addEventListener("message",({source:e,data:t})=>{e===dt&&t===Tt&&St.length&&St.shift()()},!1),e=>{St.push(e),dt.postMessage(Tt,"*")}):e=>setTimeout(e));var wt,It,Tt,St;const kt="undefined"!=typeof queueMicrotask?queueMicrotask.bind(dt):void 0!==ze&&ze.nextTick||bt,Et={isArray:qe,isArrayBuffer:Ve,isBuffer:We,isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||Je(e.append)&&("formdata"===(t=Le(e))||"object"===t&&Je(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&Ve(e.buffer),t},isString:Ge,isNumber:Ye,isBoolean:e=>!0===e||!1===e,isObject:Xe,isPlainObject:Ze,isEmptyObject:e=>{if(!Xe(e)||We(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(t){return!1}},isReadableStream:ot,isRequest:nt,isResponse:st,isHeaders:at,isUndefined:je,isDate:Qe,isFile:et,isBlob:tt,isRegExp:mt,isFunction:Je,isStream:e=>Xe(e)&&Je(e.pipe),isURLSearchParams:it,isTypedArray:pt,isFileList:rt,forEach:ct,merge:function e(){const{caseless:t}=ut(this)&&this||{},r={},i=(i,o)=>{const n=t&&lt(r,o)||o;Ze(r[n])&&Ze(i)?r[n]=e(r[n],i):Ze(i)?r[n]=e({},i):qe(i)?r[n]=i.slice():r[n]=i};for(let o=0,n=arguments.length;o<n;o++)arguments[o]&&ct(arguments[o],i);return r},extend:(e,t,r,{allOwnKeys:i}={})=>(ct(t,(t,i)=>{r&&Je(t)?e[i]=De(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:Le,kindOfTest:$e,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(qe(e))return e;let t=e.length;if(!Ye(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{const r=(e&&e[Be]).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:ht,hasOwnProperty:gt,hasOwnProp:gt,reduceDescriptors:ft,freezeMethods:e=>{ft(e,(t,r)=>{if(Je(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const i=e[r];Je(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 qe(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:lt,global:dt,isContextDefined:ut,isSpecCompliantForm:function(e){return!!(e&&Je(e.append)&&"FormData"===e[Ue]&&e[Be])},toJSONObject:e=>{const t=new Array(10),r=(e,i)=>{if(Xe(e)){if(t.indexOf(e)>=0)return;if(We(e))return e;if(!("toJSON"in e)){t[i]=e;const o=qe(e)?[]:{};return ct(e,(e,t)=>{const n=r(e,i+1);!je(n)&&(o[t]=n)}),t[i]=void 0,o}}return e};return r(e,0)},isAsyncFn:yt,isThenable:e=>e&&(Xe(e)||Je(e))&&Je(e.then)&&Je(e.catch),setImmediate:bt,asap:kt,isIterable:e=>null!=e&&Je(e[Be])};function vt(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)}Et.inherits(vt,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:Et.toJSONObject(this.config),code:this.code,status:this.status}}});const At=vt.prototype,Ct={};["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=>{Ct[e]={value:e}}),Object.defineProperties(vt,Ct),Object.defineProperty(At,"isAxiosError",{value:!0}),vt.from=(e,t,r,i,o,n)=>{const s=Object.create(At);return Et.toFlatObject(e,s,function(e){return e!==Error.prototype},e=>"isAxiosError"!==e),vt.call(s,e.message,t,r,i,o),s.cause=e,s.name=e.name,n&&Object.assign(s,n),s};function xt(e){return Et.isPlainObject(e)||Et.isArray(e)}function Rt(e){return Et.endsWith(e,"[]")?e.slice(0,-2):e}function Nt(e,t,r){return e?e.concat(t).map(function(e,t){return e=Rt(e),!r&&t?"["+e+"]":e}).join(r?".":""):t}const _t=Et.toFlatObject(Et,{},null,function(e){return/^is[A-Z]/.test(e)});function Pt(e,t,r){if(!Et.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const i=(r=Et.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!Et.isUndefined(t[e])})).metaTokens,o=r.visitor||l,n=r.dots,s=r.indexes,a=(r.Blob||"undefined"!=typeof Blob&&Blob)&&Et.isSpecCompliantForm(t);if(!Et.isFunction(o))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(Et.isDate(e))return e.toISOString();if(Et.isBoolean(e))return e.toString();if(!a&&Et.isBlob(e))throw new vt("Blob is not supported. Use a Buffer instead.");return Et.isArrayBuffer(e)||Et.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):fe.from(e):e}function l(e,r,o){let a=e;if(e&&!o&&"object"==typeof e)if(Et.endsWith(r,"{}"))r=i?r:r.slice(0,-2),e=JSON.stringify(e);else if(Et.isArray(e)&&function(e){return Et.isArray(e)&&!e.some(xt)}(e)||(Et.isFileList(e)||Et.endsWith(r,"[]"))&&(a=Et.toArray(e)))return r=Rt(r),a.forEach(function(e,i){!Et.isUndefined(e)&&null!==e&&t.append(!0===s?Nt([r],i,n):null===s?r:r+"[]",c(e))}),!1;return!!xt(e)||(t.append(Nt(o,r,n),c(e)),!1)}const d=[],u=Object.assign(_t,{defaultVisitor:l,convertValue:c,isVisitable:xt});if(!Et.isObject(e))throw new TypeError("data must be an object");return function e(r,i){if(!Et.isUndefined(r)){if(-1!==d.indexOf(r))throw Error("Circular reference detected in "+i.join("."));d.push(r),Et.forEach(r,function(r,n){!0===(!(Et.isUndefined(r)||null===r)&&o.call(t,r,Et.isString(n)?n.trim():n,i,u))&&e(r,i?i.concat(n):[n])}),d.pop()}}(e),t}function Ft(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&&Pt(e,this,t)}const zt=Ot.prototype;function Dt(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Mt(e,t,r){if(!t)return e;const i=r&&r.encode||Dt;Et.isFunction(r)&&(r={serialize:r});const o=r&&r.serialize;let n;if(n=o?o(t,r):Et.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}zt.append=function(e,t){this._pairs.push([e,t])},zt.toString=function(e){const t=e?function(t){return e.call(this,t,Ft)}:Ft;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){Et.forEach(this.handlers,function(t){null!==t&&e(t)})}}const Bt={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Ut={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"]},Lt="undefined"!=typeof window&&"undefined"!=typeof document,$t="object"==typeof navigator&&navigator||void 0,Ht=Lt&&(!$t||["ReactNative","NativeScript","NS"].indexOf($t.product)<0),qt="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,jt=Lt&&window.location.href||"http://localhost",Wt={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Lt,hasStandardBrowserEnv:Ht,hasStandardBrowserWebWorkerEnv:qt,navigator:$t,origin:jt},Symbol.toStringTag,{value:"Module"})),...Ut};function Vt(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&&Et.isArray(i)?i.length:n,a)return Et.hasOwnProp(i,n)?i[n]=[i[n],r]:i[n]=r,!s;i[n]&&Et.isObject(i[n])||(i[n]=[]);return t(e,r,i[n],o)&&Et.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(Et.isFormData(e)&&Et.isFunction(e.entries)){const r={};return Et.forEachEntry(e,(e,i)=>{t(function(e){return Et.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0])}(e),i,r,0)}),r}return null}const Gt={transitional:Bt,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const r=t.getContentType()||"",i=r.indexOf("application/json")>-1,o=Et.isObject(e);o&&Et.isHTMLForm(e)&&(e=new FormData(e));if(Et.isFormData(e))return i?JSON.stringify(Vt(e)):e;if(Et.isArrayBuffer(e)||Et.isBuffer(e)||Et.isStream(e)||Et.isFile(e)||Et.isBlob(e)||Et.isReadableStream(e))return e;if(Et.isArrayBufferView(e))return e.buffer;if(Et.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 Pt(e,new Wt.classes.URLSearchParams,{visitor:function(e,t,r,i){return Wt.isNode&&Et.isBuffer(e)?(this.append(t,e.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},...t})}(e,this.formSerializer).toString();if((n=Et.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return Pt(n?{"files[]":e}:e,t&&new t,this.formSerializer)}}return o||i?(t.setContentType("application/json",!1),function(e,t,r){if(Et.isString(e))try{return(t||JSON.parse)(e),Et.trim(e)}catch(i){if("SyntaxError"!==i.name)throw i}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||Gt.transitional,r=t&&t.forcedJSONParsing,i="json"===this.responseType;if(Et.isResponse(e)||Et.isReadableStream(e))return e;if(e&&Et.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 vt.from(o,vt.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:Wt.classes.FormData,Blob:Wt.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};Et.forEach(["delete","get","head","post","put","patch"],e=>{Gt.headers[e]={}});const Jt=Et.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"]),Yt=Symbol("internals");function Xt(e){return e&&String(e).trim().toLowerCase()}function Zt(e){return!1===e||null==e?e:Et.isArray(e)?e.map(Zt):String(e)}function Qt(e,t,r,i,o){return Et.isFunction(i)?i.call(this,t,r):(o&&(t=r),Et.isString(t)?Et.isString(i)?-1!==t.indexOf(i):Et.isRegExp(i)?i.test(t):void 0:void 0)}let er=class{constructor(e){e&&this.set(e)}set(e,t,r){const i=this;function o(e,t,r){const o=Xt(t);if(!o)throw new Error("header name must be a non-empty string");const n=Et.findKey(i,o);(!n||void 0===i[n]||!0===r||void 0===r&&!1!==i[n])&&(i[n||t]=Zt(e))}const n=(e,t)=>Et.forEach(e,(e,r)=>o(e,r,t));if(Et.isPlainObject(e)||e instanceof this.constructor)n(e,t);else if(Et.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]&&Jt[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(Et.isObject(e)&&Et.isIterable(e)){let r,i,o={};for(const t of e){if(!Et.isArray(t))throw TypeError("Object iterator must return a key-value pair");o[i=t[0]]=(r=o[i])?Et.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=Xt(e)){const r=Et.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(Et.isFunction(t))return t.call(this,e,r);if(Et.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=Xt(e)){const r=Et.findKey(this,e);return!(!r||void 0===this[r]||t&&!Qt(0,this[r],r,t))}return!1}delete(e,t){const r=this;let i=!1;function o(e){if(e=Xt(e)){const o=Et.findKey(r,e);!o||t&&!Qt(0,r[o],o,t)||(delete r[o],i=!0)}}return Et.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&&!Qt(0,this[o],o,e,!0)||(delete this[o],i=!0)}return i}normalize(e){const t=this,r={};return Et.forEach(this,(i,o)=>{const n=Et.findKey(r,o);if(n)return t[n]=Zt(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]=Zt(i),r[s]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return Et.forEach(this,(r,i)=>{null!=r&&!1!==r&&(t[i]=e&&Et.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[Yt]=this[Yt]={accessors:{}}).accessors,r=this.prototype;function i(e){const i=Xt(e);t[i]||(!function(e,t){const r=Et.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 Et.isArray(e)?e.forEach(i):i(e),this}};function tr(e,t){const r=this||Gt,i=t||r,o=er.from(i.headers);let n=i.data;return Et.forEach(e,function(e){n=e.call(r,n,o.normalize(),t?t.status:void 0)}),o.normalize(),n}function rr(e){return!(!e||!e.__CANCEL__)}function ir(e,t,r){vt.call(this,null==e?"canceled":e,vt.ERR_CANCELED,t,r),this.name="CanceledError"}function or(e,t,r){const i=r.config.validateStatus;r.status&&i&&!i(r.status)?t(new vt("Request failed with status code "+r.status,[vt.ERR_BAD_REQUEST,vt.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}er.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),Et.reduceDescriptors(er.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}}),Et.freezeMethods(er),Et.inherits(ir,vt,{__CANCEL__:!0});const nr=(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)},sr=(e,t)=>{const r=null!=e;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},ar=e=>(...t)=>Et.asap(()=>e(...t)),cr=Wt.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,Wt.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(Wt.origin),Wt.navigator&&/(msie|trident)/i.test(Wt.navigator.userAgent)):()=>!0,lr=Wt.hasStandardBrowserEnv?{write(e,t,r,i,o,n){const s=[e+"="+encodeURIComponent(t)];Et.isNumber(r)&&s.push("expires="+new Date(r).toGMTString()),Et.isString(i)&&s.push("path="+i),Et.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 dr(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 ur=e=>e instanceof er?{...e}:e;function pr(e,t){t=t||{};const r={};function i(e,t,r,i){return Et.isPlainObject(e)&&Et.isPlainObject(t)?Et.merge.call({caseless:i},e,t):Et.isPlainObject(t)?Et.merge({},t):Et.isArray(t)?t.slice():t}function o(e,t,r,o){return Et.isUndefined(t)?Et.isUndefined(e)?void 0:i(void 0,e,0,o):i(e,t,0,o)}function n(e,t){if(!Et.isUndefined(t))return i(void 0,t)}function s(e,t){return Et.isUndefined(t)?Et.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(ur(e),ur(t),0,!0)};return Et.forEach(Object.keys({...e,...t}),function(i){const n=c[i]||o,s=n(e[i],t[i],i);Et.isUndefined(s)&&n!==a||(r[i]=s)}),r}const hr=e=>{const t=pr({},e);let r,{data:i,withXSRFToken:o,xsrfHeaderName:n,xsrfCookieName:s,headers:a,auth:c}=t;if(t.headers=a=er.from(a),t.url=Mt(dr(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),Et.isFormData(i))if(Wt.hasStandardBrowserEnv||Wt.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(Wt.hasStandardBrowserEnv&&(o&&Et.isFunction(o)&&(o=o(t)),o||!1!==o&&cr(t.url))){const e=n&&s&&lr.read(s);e&&a.set(n,e)}return t},gr="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise(function(t,r){const i=hr(e);let o=i.data;const n=er.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=er.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders());or(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 vt("Request aborted",vt.ECONNABORTED,e,m)),m=null)},m.onerror=function(){r(new vt("Network Error",vt.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||Bt;i.timeoutErrorMessage&&(t=i.timeoutErrorMessage),r(new vt(t,o.clarifyTimeoutError?vt.ETIMEDOUT:vt.ECONNABORTED,e,m)),m=null},void 0===o&&n.setContentType(null),"setRequestHeader"in m&&Et.forEach(n.toJSON(),function(e,t){m.setRequestHeader(t,e)}),Et.isUndefined(i.withCredentials)||(m.withCredentials=!!i.withCredentials),u&&"json"!==u&&(m.responseType=i.responseType),h&&([c,d]=nr(h,!0),m.addEventListener("progress",c)),p&&m.upload&&([a,l]=nr(p),m.upload.addEventListener("progress",a),m.upload.addEventListener("loadend",l)),(i.cancelToken||i.signal)&&(s=t=>{m&&(r(!t||t.type?new ir(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===Wt.protocols.indexOf(y)?r(new vt("Unsupported protocol "+y+":",vt.ERR_BAD_REQUEST,e)):m.send(o||null)})},mr=(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 vt?t:new ir(t instanceof Error?t.message:t))}};let n=t&&setTimeout(()=>{n=null,o(new vt(`timeout ${t} of ms exceeded`,vt.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=()=>Et.asap(s),a}},fr=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},yr=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()}},br=(e,t,r,i)=>{const o=async function*(e,t){for await(const r of yr(e))yield*fr(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})},wr="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,Ir=wr&&"function"==typeof ReadableStream,Tr=wr&&("function"==typeof TextEncoder?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),Sr=(e,...t)=>{try{return!!e(...t)}catch(r){return!1}},kr=Ir&&Sr(()=>{let e=!1;const t=new Request(Wt.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),Er=Ir&&Sr(()=>Et.isReadableStream(new Response("").body)),vr={stream:Er&&(e=>e.body)};var Ar;wr&&(Ar=new Response,["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!vr[e]&&(vr[e]=Et.isFunction(Ar[e])?t=>t[e]():(t,r)=>{throw new vt(`Response type '${e}' is not supported`,vt.ERR_NOT_SUPPORT,r)})}));const Cr=async(e,t)=>{const r=Et.toFiniteNumber(e.getContentLength());return null==r?(async e=>{if(null==e)return 0;if(Et.isBlob(e))return e.size;if(Et.isSpecCompliantForm(e)){const t=new Request(Wt.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return Et.isArrayBufferView(e)||Et.isArrayBuffer(e)?e.byteLength:(Et.isURLSearchParams(e)&&(e+=""),Et.isString(e)?(await Tr(e)).byteLength:void 0)})(t):r},xr={http:null,xhr:gr,fetch:wr&&(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}=hr(e);l=l?(l+"").toLowerCase():"text";let h,g=mr([o,n&&n.toAbortSignal()],s);const m=g&&g.unsubscribe&&(()=>{g.unsubscribe()});let f;try{if(c&&kr&&"get"!==r&&"head"!==r&&0!==(f=await Cr(d,i))){let e,r=new Request(t,{method:"POST",body:i,duplex:"half"});if(Et.isFormData(i)&&(e=r.headers.get("content-type"))&&d.setContentType(e),r.body){const[e,t]=sr(f,nr(ar(c)));i=br(r.body,65536,e,t)}}Et.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=Er&&("stream"===l||"response"===l);if(Er&&(a||s&&m)){const e={};["status","statusText","headers"].forEach(t=>{e[t]=n[t]});const t=Et.toFiniteNumber(n.headers.get("content-length")),[r,i]=a&&sr(t,nr(ar(a),!0))||[];n=new Response(br(n.body,65536,r,()=>{i&&i(),m&&m()}),e)}l=l||"text";let y=await vr[Et.findKey(vr,l)||"text"](n,e);return!s&&m&&m(),await new Promise((t,r)=>{or(t,r,{data:y,headers:er.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 vt("Network Error",vt.ERR_NETWORK,e,h),{cause:y.cause||y});throw vt.from(y,y&&y.code,e,h)}})};Et.forEach(xr,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(r){}Object.defineProperty(e,"adapterName",{value:t})}});const Rr=e=>`- ${e}`,Nr=e=>Et.isFunction(e)||null===e||!1===e,_r=e=>{e=Et.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,!Nr(r)&&(i=xr[(t=String(r)).toLowerCase()],void 0===i))throw new vt(`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 vt("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(Rr).join("\n"):" "+Rr(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return i};function Pr(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new ir(null,e)}function Fr(e){Pr(e),e.headers=er.from(e.headers),e.data=tr.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return _r(e.adapter||Gt.adapter)(e).then(function(t){return Pr(e),t.data=tr.call(e,e.transformResponse,t),t.headers=er.from(t.headers),t},function(t){return rr(t)||(Pr(e),t&&t.response&&(t.response.data=tr.call(e,e.transformResponse,t.response),t.response.headers=er.from(t.response.headers))),Promise.reject(t)})}const Or="1.11.0",zr={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{zr[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const Dr={};zr.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 vt(i(o," has been removed"+(t?" in "+t:"")),vt.ERR_DEPRECATED);return t&&!Dr[o]&&(Dr[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)}},zr.spelling=function(e){return(t,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};const Mr={assertOptions:function(e,t,r){if("object"!=typeof e)throw new vt("options must be an object",vt.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 vt("option "+n+" must be "+r,vt.ERR_BAD_OPTION_VALUE);continue}if(!0!==r)throw new vt("Unknown option "+n,vt.ERR_BAD_OPTION)}},validators:zr},Kr=Mr.validators;let Br=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=pr(this.defaults,t);const{transitional:r,paramsSerializer:i,headers:o}=t;void 0!==r&&Mr.assertOptions(r,{silentJSONParsing:Kr.transitional(Kr.boolean),forcedJSONParsing:Kr.transitional(Kr.boolean),clarifyTimeoutError:Kr.transitional(Kr.boolean)},!1),null!=i&&(Et.isFunction(i)?t.paramsSerializer={serialize:i}:Mr.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),Mr.assertOptions(t,{baseUrl:Kr.spelling("baseURL"),withXsrfToken:Kr.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let n=o&&Et.merge(o.common,o[t.method]);o&&Et.forEach(["delete","get","head","post","put","patch","common"],e=>{delete o[e]}),t.headers=er.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=[Fr.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=Fr.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 Mt(dr((e=pr(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};Et.forEach(["delete","get","head","options"],function(e){Br.prototype[e]=function(t,r){return this.request(pr(r||{},{method:e,url:t,data:(r||{}).data}))}}),Et.forEach(["post","put","patch"],function(e){function t(t){return function(r,i,o){return this.request(pr(o||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:i}))}}Br.prototype[e]=t(),Br.prototype[e+"Form"]=t(!0)});const Ur={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(Ur).forEach(([e,t])=>{Ur[t]=e});const Lr=function e(t){const r=new Br(t),i=De(Br.prototype.request,r);return Et.extend(i,Br.prototype,r,{allOwnKeys:!0}),Et.extend(i,r,null,{allOwnKeys:!0}),i.create=function(r){return e(pr(t,r))},i}(Gt);Lr.Axios=Br,Lr.CanceledError=ir,Lr.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 ir(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}}},Lr.isCancel=rr,Lr.VERSION=Or,Lr.toFormData=Pt,Lr.AxiosError=vt,Lr.Cancel=Lr.CanceledError,Lr.all=function(e){return Promise.all(e)},Lr.spread=function(e){return function(t){return e.apply(null,t)}},Lr.isAxiosError=function(e){return Et.isObject(e)&&!0===e.isAxiosError},Lr.mergeConfig=pr,Lr.AxiosHeaders=er,Lr.formToJSON=e=>Vt(Et.isHTMLForm(e)?new FormData(e):e),Lr.getAdapter=_r,Lr.HttpStatusCode=Ur,Lr.default=Lr;const{Axios:$r,AxiosError:Hr,CanceledError:qr,isCancel:jr,CancelToken:Wr,VERSION:Vr,all:Gr,Cancel:Jr,isAxiosError:Yr,spread:Xr,toFormData:Zr,AxiosHeaders:Qr,HttpStatusCode:ei,formToJSON:ti,getAdapter:ri,mergeConfig:ii}=Lr,oi=class e{constructor(){oe(this,"isProduction"),this.isProduction="production"===ze.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)}};oe(oi,"instance");let ni=oi;class si extends Error{constructor(e){super(e),this.name="ValidationError"}}class ai{constructor(e){if(oe(this,"accountId"),oe(this,"privateKey"),oe(this,"baseUrl"),oe(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 Lr.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 Lr.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 ye.from(r).toString("hex")}}class ci{constructor(e){oe(this,"accountId"),oe(this,"signer"),oe(this,"baseUrl"),oe(this,"network"),oe(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 Lr.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 Lr.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 ye.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 li(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function di(e){return new DataView(e.buffer,e.byteOffset)}const ui={len:1,get:(e,t)=>di(e).getUint8(t),put:(e,t,r)=>(di(e).setUint8(t,r),t+1)},pi={len:2,get:(e,t)=>di(e).getUint16(t,!0),put:(e,t,r)=>(di(e).setUint16(t,r,!0),t+2)},hi={len:2,get:(e,t)=>di(e).getUint16(t),put:(e,t,r)=>(di(e).setUint16(t,r),t+2)},gi={len:4,get:(e,t)=>di(e).getUint32(t,!0),put:(e,t,r)=>(di(e).setUint32(t,r,!0),t+4)},mi={len:4,get:(e,t)=>di(e).getUint32(t),put:(e,t,r)=>(di(e).setUint32(t,r),t+4)},fi={len:4,get:(e,t)=>di(e).getInt32(t),put:(e,t,r)=>(di(e).setInt32(t,r),t+4)},yi={len:8,get:(e,t)=>di(e).getBigUint64(t,!0),put:(e,t,r)=>(di(e).setBigUint64(t,r,!0),t+8)};class bi{constructor(e,t){if(this.len=e,t&&"windows-1252"===t.toLowerCase())this.decoder=bi.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):bi.win1252Map[i-128]}return t}}bi.win1252Map="€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ";class wi extends Error{constructor(){super("End-Of-Stream"),this.name="EndOfStreamError"}}class Ii extends Error{constructor(e="The operation was aborted"){super(e),this.name="AbortError"}}class Ti{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 wi;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 Ii;const i=await this.readFromStream(e.subarray(r),t);if(0===i)break;r+=i}if(!t&&r<e.length)throw new wi;return r}}class Si extends Ti{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}}class ki extends Si{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 Ei extends Ti{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 wi;return r}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}}class vi{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 wi;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 wi;return e.get(r,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new wi;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new wi;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 Ai extends vi{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 wi;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 wi)return 0;throw o}if(!r.mayBeLess&&i<r.length)throw new wi}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 Ci extends vi{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 wi;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 xi(e,t){const r=function(e){try{const t=e.getReader({mode:"byob"});return t instanceof ReadableStreamDefaultReader?new Ei(t):new ki(t)}catch(t){if(t instanceof TypeError)return new Ei(e.getReader());throw t}}(e),i=t??{},o=i.onClose;return i.onClose=async()=>{if(await r.close(),o)return o()},new Ai(r,i)}var Ri=Uint8Array,Ni=Uint16Array,_i=Int32Array,Pi=new Ri([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]),Fi=new Ri([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 Ri([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),zi=function(e,t){for(var r=new Ni(31),i=0;i<31;++i)r[i]=t+=1<<e[i-1];var o=new _i(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}},Di=zi(Pi,2),Mi=Di.b,Ki=Di.r;Mi[28]=258,Ki[258]=28;for(var Bi=zi(Fi,0).b,Ui=new Ni(32768),Li=0;Li<32768;++Li){var $i=(43690&Li)>>1|(21845&Li)<<1;$i=(61680&($i=(52428&$i)>>2|(13107&$i)<<2))>>4|(3855&$i)<<4,Ui[Li]=((65280&$i)>>8|(255&$i)<<8)>>1}var Hi=function(e,t,r){for(var i=e.length,o=0,n=new Ni(t);o<i;++o)e[o]&&++n[e[o]-1];var s,a=new Ni(t);for(o=1;o<t;++o)a[o]=a[o-1]+n[o-1]<<1;s=new Ni(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[Ui[u]>>c]=l;return s},qi=new Ri(288);for(Li=0;Li<144;++Li)qi[Li]=8;for(Li=144;Li<256;++Li)qi[Li]=9;for(Li=256;Li<280;++Li)qi[Li]=7;for(Li=280;Li<288;++Li)qi[Li]=8;var ji=new Ri(32);for(Li=0;Li<32;++Li)ji[Li]=5;var Wi=Hi(qi,9),Vi=Hi(ji,5),Gi=function(e){for(var t=e[0],r=1;r<e.length;++r)e[r]>t&&(t=e[r]);return t},Ji=function(e,t,r){var i=t/8|0;return(e[i]|e[i+1]<<8)>>(7&t)&r},Yi=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(7&t)},Xi=function(e){return(e+7)/8|0},Zi=["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"],Qi=function(e,t,r){var i=new Error(t||Zi[e]);if(i.code=e,Error.captureStackTrace&&Error.captureStackTrace(i,Qi),!r)throw i;return i},eo=function(e,t,r,i){var o=e.length;if(!o||t.f&&!t.l)return r||new Ri(0);var n=!r,s=n||2!=t.i,a=t.i;n&&(r=new Ri(3*o));var c=function(e){var t=r.length;if(e>t){var i=new Ri(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=Ji(e,d,1);var y=Ji(e,d+1,3);if(d+=3,!y){var b=e[(R=Xi(d)+4)-4]|e[R-3]<<8,w=R+b;if(w>o){a&&Qi(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=Wi,h=Vi,g=9,m=5;else if(2==y){var I=Ji(e,d,31)+257,T=Ji(e,d+10,15)+4,S=I+Ji(e,d+5,31)+1;d+=14;for(var k=new Ri(S),E=new Ri(19),v=0;v<T;++v)E[Oi[v]]=Ji(e,d+3*v,7);d+=3*T;var A=Gi(E),C=(1<<A)-1,x=Hi(E,A);for(v=0;v<S;){var R,N=x[Ji(e,d,C)];if(d+=15&N,(R=N>>4)<16)k[v++]=R;else{var _=0,P=0;for(16==R?(P=3+Ji(e,d,3),d+=2,_=k[v-1]):17==R?(P=3+Ji(e,d,7),d+=3):18==R&&(P=11+Ji(e,d,127),d+=7);P--;)k[v++]=_}}var F=k.subarray(0,I),O=k.subarray(I);g=Gi(F),m=Gi(O),p=Hi(F,g),h=Hi(O,m)}else Qi(1);if(d>f){a&&Qi(0);break}}s&&c(u+131072);for(var z=(1<<g)-1,D=(1<<m)-1,M=d;;M=d){var K=(_=p[Yi(e,d)&z])>>4;if((d+=15&_)>f){a&&Qi(0);break}if(_||Qi(2),K<256)r[u++]=K;else{if(256==K){M=d,p=null;break}var B=K-254;if(K>264){var U=Pi[v=K-257];B=Ji(e,d,(1<<U)-1)+Mi[v],d+=U}var L=h[Yi(e,d)&D],$=L>>4;L||Qi(3),d+=15&L;O=Bi[$];if($>3){U=Fi[$];O+=Yi(e,d)&(1<<U)-1,d+=U}if(d>f){a&&Qi(0);break}s&&c(u+131072);var H=u+B;if(u<O){var q=0-O,j=Math.min(O,H);for(q+u<0&&Qi(3);u<j;++u)r[u]=i[q+u]}for(;u<H;++u)r[u]=r[u-O]}}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 Ri(e.subarray(t,r))}(r,0,u):r.subarray(0,u)},to=new Ri(0);function ro(e,t){var r,i,o=function(e){31==e[0]&&139==e[1]&&8==e[2]||Qi(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&&Qi(6,"invalid gzip data"),eo(e.subarray(o,-8),{i:2},new Ri((i=(r=e).length,(r[i-4]|r[i-3]<<8|r[i-2]<<16|r[i-1]<<24)>>>0)),t)}function io(e,t){return eo(e.subarray(((8!=(15&(r=e)[0])||r[0]>>4>7||(r[0]<<8|r[1])%31)&&Qi(6,"invalid zlib data"),1==(r[1]>>5&1)&&Qi(6,"invalid zlib data: "+(32&r[1]?"need":"unexpected")+" dictionary"),2+(r[1]>>3&4)),-4),{i:2},t,t);var r}function oo(e,t){return 31==e[0]&&139==e[1]&&8==e[2]?ro(e,t):8!=(15&e[0])||e[0]>>4>7||(e[0]<<8|e[1])%31?function(e,t){return eo(e,{i:2},t,t)}(e,t):io(e,t)}var no="undefined"!=typeof TextDecoder&&new TextDecoder;try{no.decode(to,{stream:!0})}catch(mg){}var so,ao,co,lo,uo,po={exports:{}};function ho(){if(ao)return so;ao=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 so=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 go=(uo||(uo=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!==ze&&"env"in ze&&(e=ze.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=(lo||(lo=1,co=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=ho(),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}),co)(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}(po,po.exports)),po.exports);const mo=li(go),fo=67324752,yo=134695760,bo=33639248,wo=101010256,Io={get:e=>(pi.get(e,6),{signature:gi.get(e,0),compressedSize:gi.get(e,8),uncompressedSize:gi.get(e,12)}),len:16},To={get(e){const t=pi.get(e,6);return{signature:gi.get(e,0),minVersion:pi.get(e,4),dataDescriptor:!!(8&t),compressedMethod:pi.get(e,8),compressedSize:gi.get(e,18),uncompressedSize:gi.get(e,22),filenameLength:pi.get(e,26),extraFieldLength:pi.get(e,28),filename:null}},len:30},So={get:e=>({signature:gi.get(e,0),nrOfThisDisk:pi.get(e,4),nrOfThisDiskWithTheStart:pi.get(e,6),nrOfEntriesOnThisDisk:pi.get(e,8),nrOfEntriesOfSize:pi.get(e,10),sizeOfCd:gi.get(e,12),offsetOfStartOfCd:gi.get(e,16),zipFileCommentLength:pi.get(e,20)}),len:22},ko={get(e){const t=pi.get(e,8);return{signature:gi.get(e,0),minVersion:pi.get(e,6),dataDescriptor:!!(8&t),compressedMethod:pi.get(e,10),compressedSize:gi.get(e,20),uncompressedSize:gi.get(e,24),filenameLength:pi.get(e,28),extraFieldLength:pi.get(e,30),fileCommentLength:pi.get(e,32),relativeOffsetOfLocalHeader:gi.get(e,42),filename:null}},len:46};function Eo(e){const t=new Uint8Array(gi.len);return gi.put(t,0,e),t}const vo=mo("tokenizer:inflate"),Ao=262144,Co=Eo(yo),xo=Eo(wo);class Ro{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(Ao)}async isZip(){return await this.peekSignature()===fo}peekSignature(){return this.tokenizer.peekToken(gi)}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]===xo[0]&&r[i+1]===xo[1]&&r[i+2]===xo[2]&&r[i+3]===xo[3])return e.fileInfo.size-t+i;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess())return void vo("Cannot reading central-directory without random-read support");vo("Reading central-directory...");const e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){vo("Central-directory 32-bit signature found");const r=await this.tokenizer.readToken(So,t),i=[];this.tokenizer.setPosition(r.offsetOfStartOfCd);for(let e=0;e<r.nrOfEntriesOfSize;++e){const t=await this.tokenizer.readToken(ko);if(t.signature!==bo)throw new Error("Expected Central-File-Header signature");t.filename=await this.tokenizer.readToken(new bi(t.filenameLength,"utf-8")),await this.tokenizer.ignore(t.extraFieldLength),await this.tokenizer.ignore(t.fileCommentLength),i.push(t),vo(`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=Ao;vo("Compressed-file-size unknown, scanning for next data-descriptor-signature....");let o=-1;for(;o<0&&r===Ao;){r=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),o=No(this.syncBuffer.subarray(0,r),Co);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)}vo(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),i.handler&&await this.inflate(t,_o(e),i.handler)}else i.handler?(vo(`Reading compressed-file-data: ${t.compressedSize} bytes`),o=new Uint8Array(t.compressedSize),await this.tokenizer.readBuffer(o),await this.inflate(t,o,i.handler)):(vo(`Ignoring compressed-file-data: ${t.compressedSize} bytes`),await this.tokenizer.ignore(t.compressedSize));if(vo(`Reading data-descriptor at pos=${this.tokenizer.position}`),t.dataDescriptor){if(134695760!==(await this.tokenizer.readToken(Io)).signature)throw new Error("Expected data-descriptor-signature at position "+(this.tokenizer.position-Io.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);vo(`Decompress filename=${e.filename}, compressed-size=${t.length}`);return r(oo(t))}async readLocalFileHeader(){const e=await this.tokenizer.peekToken(gi);if(e===fo){const e=await this.tokenizer.readToken(To);return e.filename=await this.tokenizer.readToken(new bi(e.filenameLength,"utf-8")),e}if(e===bo)return!1;if(3759263696===e)throw new Error("Encrypted ZIP");throw new Error("Unexpected signature")}}function No(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 _o(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 Po(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 Fo={get:(e,t)=>127&e[t+3]|e[t+2]<<7|e[t+1]<<14|e[t]<<21,len:4},Oo=4100;function zo(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 Do(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 Mo{constructor(e){oe(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(Fo);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 Ro(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=zo(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=zo(e))}else{t=t.slice(0,Math.max(0,i));const e=t.lastIndexOf('"'),o=t.slice(Math.max(0,e+1));r=zo(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),Do(i,[79,112,117,115,72,101,97,100])?{ext:"opus",mime:"audio/ogg; codecs=opus"}:Do(i,[128,116,104,101,111,114,97])?{ext:"ogv",mime:"video/ogg"}:Do(i,[1,118,105,100,101,111,0])?{ext:"ogm",mime:"video/ogg"}:Do(i,[127,70,76,65,67])?{ext:"oga",mime:"audio/ogg"}:Do(i,[83,112,101,101,120,32,32])?{ext:"spx",mime:"audio/ogg"}:Do(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(ui);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:Po(i),len:Po(o)}}async function c(t){for(;t>0;){const r=await a();if(17026===r.id){return(await e.readToken(new bi(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 bi(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 bi(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(fi),type:await e.readToken(new bi(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 bi(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(yi))}}for(await e.ignore(30);e.position+24<e.fileInfo.size;){const m=await g();let f=m.size-24;if(Do(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),Do(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(Do(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 bi(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 bi(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)}),oe(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 Ci(r,i)))}async fromBlob(e){return this.fromStream(e.stream())}async fromStream(e){const t=await xi(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 wi))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 Do(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?hi:pi);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?hi:pi);for(let r=0;r<t;++r){const t=await this.readTiffTag(e);if(t)return t}}async readTiffHeader(e){const t=(e?hi:pi).get(this.buffer,2),r=(e?mi:gi).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?hi:pi).get(this.buffer,8),r=(e?hi:pi).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 Bo=Object.create(null);Object.keys(Ko).forEach(e=>{Bo[Ko[e]]=e});const Uo={type:"error",data:"parser error"},Lo="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),$o="function"==typeof ArrayBuffer,Ho=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,qo=({type:e,data:t},r,i)=>Lo&&t instanceof Blob?r?i(t):jo(t,i):$o&&(t instanceof ArrayBuffer||Ho(t))?r?i(t):jo(new Blob([t]),i):i(Ko[e]+(t||"")),jo=(e,t)=>{const r=new FileReader;return r.onload=function(){const e=r.result.split(",")[1];t("b"+(e||""))},r.readAsDataURL(e)};function Wo(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let Vo;const Go="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Jo="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let yg=0;yg<64;yg++)Jo[Go.charCodeAt(yg)]=yg;const Yo="function"==typeof ArrayBuffer,Xo=(e,t)=>{if("string"!=typeof e)return{type:"message",data:Qo(e,t)};const r=e.charAt(0);if("b"===r)return{type:"message",data:Zo(e.substring(1),t)};return Bo[r]?e.length>1?{type:Bo[r],data:e.substring(1)}:{type:Bo[r]}:Uo},Zo=(e,t)=>{if(Yo){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=Jo[e.charCodeAt(t)],i=Jo[e.charCodeAt(t+1)],o=Jo[e.charCodeAt(t+2)],n=Jo[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 Qo(r,t)}return{base64:!0,data:e}},Qo=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,en=String.fromCharCode(30);function tn(){return new TransformStream({transform(e,t){!function(e,t){Lo&&e.data instanceof Blob?e.data.arrayBuffer().then(Wo).then(t):$o&&(e.data instanceof ArrayBuffer||Ho(e.data))?t(Wo(e.data)):qo(e,!1,e=>{Vo||(Vo=new TextEncoder),t(Vo.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 rn;function on(e){return e.reduce((e,t)=>e+t.length,0)}function nn(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 sn(e){if(e)return function(e){for(var t in sn.prototype)e[t]=sn.prototype[t];return e}(e)}sn.prototype.on=sn.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},sn.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},sn.prototype.off=sn.prototype.removeListener=sn.prototype.removeAllListeners=sn.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},sn.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},sn.prototype.emitReserved=sn.prototype.emit,sn.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},sn.prototype.hasListeners=function(e){return!!this.listeners(e).length};const an="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),cn="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function ln(e,...t){return t.reduce((t,r)=>(e.hasOwnProperty(r)&&(t[r]=e[r]),t),{})}const dn=cn.setTimeout,un=cn.clearTimeout;function pn(e,t){t.useNativeTimers?(e.setTimeoutFn=dn.bind(cn),e.clearTimeoutFn=un.bind(cn)):(e.setTimeoutFn=cn.setTimeout.bind(cn),e.clearTimeoutFn=cn.clearTimeout.bind(cn))}function hn(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 gn(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class mn extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}}class fn extends sn{constructor(e){super(),this.writable=!1,pn(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 mn(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=Xo(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 yn extends fn{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(en),i=[];for(let o=0;o<r.length;o++){const e=Xo(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)=>{qo(e,!1,e=>{i[n]=e,++o===r&&t(i.join(en))})})})(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]=gn()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let bn=!1;try{bn="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(fg){}const wn=bn;function In(){}class Tn extends yn{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 Sn=class e extends sn{constructor(e,t,r){super(),this.createRequest=e,pn(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=ln(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(mg){}if("POST"===this._method)try{i.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(mg){}try{i.setRequestHeader("Accept","*/*")}catch(mg){}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(mg){return void this.setTimeoutFn(()=>{this._onError(mg)},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=In,t)try{this._xhr.abort()}catch(mg){}"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(Sn.requestsCount=0,Sn.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",kn);else if("function"==typeof addEventListener){addEventListener("onpagehide"in cn?"pagehide":"unload",kn,!1)}function kn(){for(let e in Sn.requests)Sn.requests.hasOwnProperty(e)&&Sn.requests[e].abort()}const En=function(){const e=vn({xdomain:!1});return e&&null!==e.responseType}();function vn(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||wn))return new XMLHttpRequest}catch(mg){}if(!t)try{return new(cn[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(mg){}}const An="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class Cn extends fn{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,r=An?{}:ln(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(fg){return this.emitReserved("error",fg)}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;qo(r,this.supportsBinary,e=>{try{this.doWrite(r,e)}catch(mg){}i&&an(()=>{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]=gn()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const xn=cn.WebSocket||cn.MozWebSocket;const Rn={websocket:class extends Cn{createSocket(e,t,r){return An?new xn(e,t,r):t?new xn(e,t):new xn(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends fn{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(fg){return this.emitReserved("error",fg)}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){rn||(rn=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(on(r)<1)break;const e=nn(r,1);n=!(128&~e[0]),o=127&e[0],i=o<126?3:126===o?1:2}else if(1===i){if(on(r)<2)break;const e=nn(r,2);o=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),i=3}else if(2===i){if(on(r)<8)break;const e=nn(r,8),t=new DataView(e.buffer,e.byteOffset,e.length),n=t.getUint32(0);if(n>Math.pow(2,21)-1){a.enqueue(Uo);break}o=n*Math.pow(2,32)+t.getUint32(4),i=3}else{if(on(r)<o)break;const e=nn(r,o);a.enqueue(Xo(n?e:rn.decode(e),t)),i=0}if(0===o||o>e){a.enqueue(Uo);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),i=tn();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&&an(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this._transport)||void 0===e||e.close()}},polling:class extends Tn{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=En&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Sn(vn,this.uri(),e)}}},Nn=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,_n=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Pn(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=Nn.exec(e||""),n={},s=14;for(;s--;)n[_n[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 Fn="function"==typeof addEventListener&&"function"==typeof removeEventListener,On=[];Fn&&addEventListener("offline",()=>{On.forEach(e=>e())},!1);class zn extends sn{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=Pn(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=Pn(t.host).host);pn(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)),Fn&&(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&&zn.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",zn.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+=hn(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,an(()=>{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(zn.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(),Fn&&(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}}}zn.protocol=4;class Dn extends zn{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;zn.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;zn.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 Mn=class extends Dn{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=>Rn[e]).filter(e=>!!e)),super(e,r)}};const Kn="function"==typeof ArrayBuffer,Bn=Object.prototype.toString,Un="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Bn.call(Blob),Ln="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Bn.call(File);function $n(e){return Kn&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||Un&&e instanceof Blob||Ln&&e instanceof File}function Hn(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if(Hn(e[t]))return!0;return!1}if($n(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return Hn(e.toJSON(),!0);for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&Hn(e[r]))return!0;return!1}function qn(e){const t=[],r=e.data,i=e;return i.data=jn(r,t),i.attachments=t.length,{packet:i,buffers:t}}function jn(e,t){if(!e)return e;if($n(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]=jn(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]=jn(e[i],t));return r}return e}function Wn(e,t){return e.data=Vn(e.data,t),delete e.attachments,e}function Vn(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]=Vn(e[r],t);else if("object"==typeof e)for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=Vn(e[r],t));return e}const Gn=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Jn,Yn;(Yn=Jn||(Jn={}))[Yn.CONNECT=0]="CONNECT",Yn[Yn.DISCONNECT=1]="DISCONNECT",Yn[Yn.EVENT=2]="EVENT",Yn[Yn.ACK=3]="ACK",Yn[Yn.CONNECT_ERROR=4]="CONNECT_ERROR",Yn[Yn.BINARY_EVENT=5]="BINARY_EVENT",Yn[Yn.BINARY_ACK=6]="BINARY_ACK";function Xn(e){return"[object Object]"===Object.prototype.toString.call(e)}class Zn extends sn{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===Jn.BINARY_EVENT;r||t.type===Jn.BINARY_ACK?(t.type=r?Jn.EVENT:Jn.ACK,this.reconstructor=new Qn(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!$n(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===Jn[r.type])throw new Error("unknown packet type "+r.type);if(r.type===Jn.BINARY_EVENT||r.type===Jn.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(!Zn.isPayloadValid(r.type,i))throw new Error("invalid payload");r.data=i}return r}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(mg){return!1}}static isPayloadValid(e,t){switch(e){case Jn.CONNECT:return Xn(t);case Jn.DISCONNECT:return void 0===t;case Jn.CONNECT_ERROR:return"string"==typeof t||Xn(t);case Jn.EVENT:case Jn.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===Gn.indexOf(t[0]));case Jn.ACK:case Jn.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Qn{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=Wn(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const es=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Zn,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==Jn.EVENT&&e.type!==Jn.ACK||!Hn(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===Jn.EVENT?Jn.BINARY_EVENT:Jn.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==Jn.BINARY_EVENT&&e.type!==Jn.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=qn(e),r=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(r),i}},get PacketType(){return Jn},protocol:5},Symbol.toStringTag,{value:"Module"}));function ts(e,t,r){return e.on(t,r),function(){e.off(t,r)}}const rs=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class is extends sn{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=[ts(e,"open",this.onopen.bind(this)),ts(e,"packet",this.onpacket.bind(this)),ts(e,"error",this.onerror.bind(this)),ts(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(rs.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:Jn.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:Jn.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 Jn.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 Jn.EVENT:case Jn.BINARY_EVENT:this.onevent(e);break;case Jn.ACK:case Jn.BINARY_ACK:this.onack(e);break;case Jn.DISCONNECT:this.ondisconnect();break;case Jn.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:Jn.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:Jn.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 os(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}os.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)},os.prototype.reset=function(){this.attempts=0},os.prototype.setMin=function(e){this.ms=e},os.prototype.setMax=function(e){this.max=e},os.prototype.setJitter=function(e){this.jitter=e};class ns extends sn{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,pn(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 os({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||es;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 Mn(this.uri,this.opts);const t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const i=ts(t,"open",function(){r.onopen(),e&&e()}),o=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},n=ts(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(ts(e,"ping",this.onping.bind(this)),ts(e,"data",this.ondata.bind(this)),ts(e,"error",this.onerror.bind(this)),ts(e,"close",this.onclose.bind(this)),ts(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(mg){this.onclose("parse error",mg)}}ondecoded(e){an(()=>{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 is(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 ss={};function as(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=Pn(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=ss[o]&&n in ss[o].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||s?a=new ns(i,t):(ss[o]||(ss[o]=new ns(i,t)),a=ss[o]),r.query&&!t.query&&(t.query=r.queryKey),a.socket(r.path,t)}Object.assign(as,{Manager:ns,Socket:is,io:as,connect:as});const cs=class e{constructor(e){if(oe(this,"client"),oe(this,"config"),oe(this,"logger",ni.getInstance()),oe(this,"socket",null),oe(this,"socketConnected",!1),oe(this,"connectionMode","auto"),oe(this,"wsBaseUrl",null),this.config=e,!e.apiKey)throw new si("API key is required");if(!e.network)throw new si("Network is required");const t={"x-api-key":e.apiKey,"Content-Type":"application/json"};this.client=Lr.create({baseURL:"https://v2-api.tier.bot/api",headers:t}),this.logger=ni.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 Lr.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 si("Unable to fetch file metadata")}}getMimeType(t){const r=t.toLowerCase().split(".").pop();if(!r)throw new si("File must have an extension");const i=e.VALID_MIME_TYPES[r];if(!i)throw new si(`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 si("holderId is required");if(!e.VALID_MODES.includes(t.mode))throw new si(`Invalid mode: ${t.mode}. Must be one of: ${e.VALID_MODES.join(", ")}`);if("hashinal"===t.mode&&!t.jsonFileURL&&!t.metadataObject)throw new si("Hashinal mode requires either jsonFileURL or metadataObject");if(t.onlyJSONCollection&&"hashinal-collection"!==t.mode)throw new si("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 si("Base64 data is required");const r=t.base64.replace(/^data:.*?;base64,/,"");if(Math.ceil(.75*r.length)>e.MAX_BASE64_SIZE)throw new si(`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 si("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 si("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=fe.from(t,"base64"),i=await async function(e,t){return new Mo(t).fromBuffer(e)}(r);return(null==i?void 0:i.mime)||"application/octet-stream"}catch(fg){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 si(`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 si("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 si)throw o;if(Lr.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(fe.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(fe.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=as(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(mg){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=as(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 si("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 ai(e).authenticate()}static async createWithAuth(t){const r="client"===t.type?new ci({...t,logger:ni.getInstance()}):new ai(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(fg){this.logger.warn(`Error in progress callback: ${fg}`)}};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 si("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),Lr.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}}};oe(cs,"VALID_MODES",["file","upload","hashinal","hashinal-collection"]),oe(cs,"MAX_BASE64_SIZE",2097152),oe(cs,"MAX_URL_FILE_SIZE",104857600),oe(cs,"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 ls=cs;class ds{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 ds.instance?(e.callback&&ds.instance.setCallback(e.callback),e.module&&ds.instance.setModule(e.module),e.logger&&ds.instance.setLogger(e.logger),void 0!==e.minPercent&&ds.instance.setMinPercent(e.minPercent),void 0!==e.maxPercent&&ds.instance.setMaxPercent(e.maxPercent)):ds.instance=new ds(e),ds.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 ds({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(fg){this.logger.warn(`Error in progress callback: ${fg}`)}}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 us 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,us)}}const ps=(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)}),hs=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},gs=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},ms=e=>e.tokenMint?`Mint ${e.tokenMint.amount} tokens for token ${e.tokenMint.tokenId}`:e.humanReadableType,fs=e=>e.tokenBurn?`Burn ${e.tokenBurn.amount} tokens for token ${e.tokenBurn.tokenId}`:e.humanReadableType,ys=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},bs=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},ws=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},Is=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},Ts=e=>e.fileAppend?`Append to File ${e.fileAppend.fileId||"(Unknown ID)"}`:e.humanReadableType,Ss=e=>e.fileUpdate?`Update File ${e.fileUpdate.fileId||"(Unknown ID)"}`:e.humanReadableType,ks=e=>e.fileDelete?`Delete File ${e.fileDelete.fileId||"(Unknown ID)"}`:e.humanReadableType,Es=e=>e.consensusUpdateTopic?`Update Topic ${e.consensusUpdateTopic.topicId||"(Unknown ID)"}`:e.humanReadableType,vs=e=>e.consensusDeleteTopic?`Delete Topic ${e.consensusDeleteTopic.topicId||"(Unknown ID)"}`:e.humanReadableType,As=e=>e.tokenFreeze?`Freeze Token ${e.tokenFreeze.tokenId} for Account ${e.tokenFreeze.accountId}`:e.humanReadableType,Cs=e=>e.tokenUnfreeze?`Unfreeze Token ${e.tokenUnfreeze.tokenId} for Account ${e.tokenUnfreeze.accountId}`:e.humanReadableType,xs=e=>e.tokenGrantKyc?`Grant KYC for Token ${e.tokenGrantKyc.tokenId} to Account ${e.tokenGrantKyc.accountId}`:e.humanReadableType,Rs=e=>e.tokenRevokeKyc?`Revoke KYC for Token ${e.tokenRevokeKyc.tokenId} from Account ${e.tokenRevokeKyc.accountId}`:e.humanReadableType,Ns=e=>e.tokenPause?`Pause Token ${e.tokenPause.tokenId}`:e.humanReadableType,_s=e=>e.tokenUnpause?`Unpause Token ${e.tokenUnpause.tokenId}`:e.humanReadableType,Ps=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},Fs=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,zs=e=>e.tokenDissociate?`Dissociate Account ${e.tokenDissociate.accountId} from Tokens: ${(e.tokenDissociate.tokenIds||[]).join(", ")}`:e.humanReadableType,Ds=e=>e.cryptoDelete?`Delete Account ${e.cryptoDelete.deleteAccountId}`:e.humanReadableType,Ms=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,Bs=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},Us=e=>{if(e.cryptoDeleteAllowance){return`Delete ${(e.cryptoDeleteAllowance.nftAllowancesToRemove||[]).length} NFT Crypto Allowance(s)`}return e.humanReadableType},Ls=e=>{if(e.contractCreate){let t="Create Contract";return e.contractCreate.memo&&(t+=` (Memo: ${e.contractCreate.memo})`),t}return e.humanReadableType},$s=e=>e.contractUpdate?`Update Contract ${e.contractUpdate.contractIdToUpdate||"(Unknown ID)"}`:e.humanReadableType,Hs=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},qs=e=>e.tokenUpdate?`Update Token ${e.tokenUpdate.tokenId||"(Unknown ID)"}`:e.humanReadableType,js=e=>e.tokenFeeScheduleUpdate?`Update Fee Schedule for Token ${e.tokenFeeScheduleUpdate.tokenId||"(Unknown ID)"}`:e.humanReadableType,Ws=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)`},Vs=e=>{if(!e.scheduleCreate)return e.humanReadableType;let t="Create Schedule";return e.scheduleCreate.memo&&(t+=` (Memo: ${e.scheduleCreate.memo})`),t},Gs=e=>e.scheduleSign?"Sign Schedule":e.humanReadableType,Js=e=>e.scheduleDelete?"Delete Schedule":e.humanReadableType,Ys=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,Xs=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,Zs=e=>"Network Freeze",Qs=e=>"Ethereum Transaction",ea=e=>e.uncheckedSubmit&&e.uncheckedSubmit.topicId?`Unchecked Submit to topic ${e.uncheckedSubmit.topicId}`:"Unchecked Submit",ta=e=>"Create Node",ra=e=>"Update Node",ia=e=>"Delete Node",oa=e=>`Atomic Batch (${Array.isArray(e.atomicBatch?.transactions)?e.atomicBatch.transactions.length:0} transaction(s))`,na={CRYPTOTRANSFER:{fn:hs},cryptoTransfer:{fn:hs},CONTRACTCALL:{fn:gs},contractCall:{fn:gs},TOKENMINT:{fn:ms},tokenMint:{fn:ms},TOKENBURN:{fn:fs},tokenBurn:{fn:fs},TOKENCREATE:{fn:ys},tokenCreation:{fn:ys},TOPICCREATE:{fn:bs},consensusCreateTopic:{fn:bs},CONSENSUSSUBMITMESSAGE:{fn:ws},consensusSubmitMessage:{fn:ws},TOPICUPDATE:{fn:Es},consensusUpdateTopic:{fn:Es},TOPICDELETE:{fn:vs},consensusDeleteTopic:{fn:vs},FILECREATE:{fn:Is},fileCreate:{fn:Is},FILEAPPEND:{fn:Ts},fileAppend:{fn:Ts},FILEUPDATE:{fn:Ss},fileUpdate:{fn:Ss},FILEDELETE:{fn:ks},fileDelete:{fn:ks},TOKENUPDATE:{fn:qs},tokenUpdate:{fn:qs},TOKENFEESCHEDULEUPDATE:{fn:js},tokenFeeScheduleUpdate:{fn:js},TOKENFREEZE:{fn:As},tokenFreeze:{fn:As},TOKENUNFREEZE:{fn:Cs},tokenUnfreeze:{fn:Cs},TOKENGRANTKYC:{fn:xs},tokenGrantKyc:{fn:xs},TOKENREVOKEKYC:{fn:Rs},tokenRevokeKyc:{fn:Rs},TOKENPAUSE:{fn:Ns},tokenPause:{fn:Ns},TOKENUNPAUSE:{fn:_s},tokenUnpause:{fn:_s},TOKENWIPE:{fn:Ps},TOKENWIPEACCOUNT:{fn:Ps},tokenWipe:{fn:Ps},tokenWipeAccount:{fn:Ps},TOKENDELETE:{fn:Fs},tokenDelete:{fn:Fs},TOKENASSOCIATE:{fn:Os},tokenAssociate:{fn:Os},TOKENDISSOCIATE:{fn:zs},tokenDissociate:{fn:zs},ACCOUNTDELETE:{fn:Ds},cryptoDelete:{fn:Ds},ACCOUNTCREATE:{fn:Ms},cryptoCreateAccount:{fn:Ms},ACCOUNTUPDATE:{fn:Ks},cryptoUpdateAccount:{fn:Ks},APPROVEALLOWANCE:{fn:Bs},cryptoApproveAllowance:{fn:Bs},DELETEALLOWANCE:{fn:Us},cryptoDeleteAllowance:{fn:Us},CONTRACTCREATE:{fn:Ls},contractCreate:{fn:Ls},CONTRACTUPDATE:{fn:$s},contractUpdate:{fn:$s},CONTRACTDELETE:{fn:Hs},contractDelete:{fn:Hs},TOKENAIRDROP:{fn:Ws},tokenAirdrop:{fn:Ws},SCHEDULECREATE:{fn:Vs},scheduleCreate:{fn:Vs},SCHEDULESIGN:{fn:Gs},scheduleSign:{fn:Gs},SCHEDULEDELETE:{fn:Js},scheduleDelete:{fn:Js},SYSTEMDELETE:{fn:Ys},systemDelete:{fn:Ys},SYSTEMUNDELETE:{fn:Xs},systemUndelete:{fn:Xs},FREEZE:{fn:Zs},freeze:{fn:Zs},ETHEREUMTRANSACTION:{fn:Qs},ethereumTransaction:{fn:Qs},UNCHECKEDSUBMIT:{fn:ea},uncheckedSubmit:{fn:ea},NODECREATE:{fn:ta},nodeCreate:{fn:ta},NODEUPDATE:{fn:ra},nodeUpdate:{fn:ra},NODEDELETE:{fn:ia},nodeDelete:{fn:ia},ATOMICBATCH:{fn:oa},atomicBatch:{fn:oa}},sa=e=>{const t=na[e.type];if(t){if(t.fn)return t.fn(e);if(t.template)return ps(t.template,e)}const r=na[e.humanReadableType];if(r){if(r.fn)return r.fn(e);if(r.template)return ps(r.template,e)}return"cryptoTransfer"===e.type||"CRYPTOTRANSFER"===e.type?hs(e):e.contractCall?gs(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 aa(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=>aa(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=>aa(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 ca(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 la(e,t){const r=ca(e);return!(!r||!r[t])}class da{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=aa(e.adminKey),t.kycKey=aa(e.kycKey),t.freezeKey=aa(e.freezeKey),t.wipeKey=aa(e.wipeKey),t.supplyKey=aa(e.supplyKey),t.feeScheduleKey=aa(e.feeScheduleKey),t.pauseKey=aa(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=aa(e.adminKey),t.kycKey=aa(e.kycKey),t.freezeKey=aa(e.freezeKey),t.wipeKey=aa(e.wipeKey),t.supplyKey=aa(e.supplyKey),t.feeScheduleKey=aa(e.feeScheduleKey),t.pauseKey=aa(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(la(e,"tokenAirdrop")){const t=ca(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(mg){}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 ua{static parseConsensusCreateTopic(e){if(!e)return;const t={};return e.memo&&(t.memo=e.memo),t.adminKey=aa(e.adminKey),t.submitKey=aa(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=aa(e.adminKey):t.adminKey=void 0,null===e.submitKey?(t.clearSubmitKey=!0,t.submitKey=void 0):e.submitKey?t.submitKey=aa(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 pa{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(la(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=aa({keyList:r})}return t._expirationTime&&(e.expirationTime=t._expirationTime.toString()),t._memo&&(e.memo=t._memo),{type:"FILECREATE",humanReadableType:"File Create",fileCreate:e}}if(la(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(la(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=aa({keyList:r})}return t._expirationTime&&(e.expirationTime=t._expirationTime.toString()),t._memo&&(e.memo=t._memo),{type:"FILEUPDATE",humanReadableType:"File Update",fileUpdate:e}}if(la(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=aa({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=aa({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 ha{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=aa(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=aa(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 ga{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(la(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=aa(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(la(e,"contractUpdateInstance")){const e={contractIdToUpdate:t._contractId.toString()};return t._memo&&(e.memo=t._memo),t._adminKey&&(e.adminKey=aa(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(la(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=aa(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=aa(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 ma{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(la(e,"utilPrng")){const e={};return t._range&&0!==t._range&&(e.range=t._range),{type:"PRNG",humanReadableType:"Pseudo Random Number",utilPrng:e}}if(la(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(la(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(la(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 fa{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(la(e,"scheduleCreate")){return{type:"SCHEDULECREATE",humanReadableType:"Schedule Create",scheduleCreate:{scheduledTransactionBody:globalThis.Buffer.from(t._scheduledTransaction).toString("base64"),memo:t._scheduleMemo,adminKey:t._adminKey?aa(t._adminKey):void 0,payerAccountId:t._payerAccountId?.toString(),expirationTime:t._expirationTime?.toString(),waitForExpiry:t._waitForExpiry||!1}}}if(la(e,"scheduleSign")){return{type:"SCHEDULESIGN",humanReadableType:"Schedule Sign",scheduleSign:{scheduleId:t._scheduleId.toString()}}}if(la(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=aa(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 ya={TOKENCREATE:{bodyField:"tokenCreation",parser:da.parseTokenCreate,resultField:"tokenCreation"},TOKENMINT:{bodyField:"tokenMint",parser:da.parseTokenMint,resultField:"tokenMint"},TOKENBURN:{bodyField:"tokenBurn",parser:da.parseTokenBurn,resultField:"tokenBurn"},TOKENUPDATE:{bodyField:"tokenUpdate",parser:da.parseTokenUpdate,resultField:"tokenUpdate"},TOKENDELETE:{bodyField:"tokenDeletion",parser:da.parseTokenDelete,resultField:"tokenDelete"},TOKENASSOCIATE:{bodyField:"tokenAssociate",parser:da.parseTokenAssociate,resultField:"tokenAssociate"},TOKENDISSOCIATE:{bodyField:"tokenDissociate",parser:da.parseTokenDissociate,resultField:"tokenDissociate"},TOKENFREEZE:{bodyField:"tokenFreeze",parser:da.parseTokenFreeze,resultField:"tokenFreeze"},TOKENUNFREEZE:{bodyField:"tokenUnfreeze",parser:da.parseTokenUnfreeze,resultField:"tokenUnfreeze"},TOKENGRANTKYC:{bodyField:"tokenGrantKyc",parser:da.parseTokenGrantKyc,resultField:"tokenGrantKyc"},TOKENREVOKEKYC:{bodyField:"tokenRevokeKyc",parser:da.parseTokenRevokeKyc,resultField:"tokenRevokeKyc"},TOKENPAUSE:{bodyField:"tokenPause",parser:da.parseTokenPause,resultField:"tokenPause"},TOKENUNPAUSE:{bodyField:"tokenUnpause",parser:da.parseTokenUnpause,resultField:"tokenUnpause"},TOKENWIPEACCOUNT:{bodyField:"tokenWipe",parser:da.parseTokenWipeAccount,resultField:"tokenWipeAccount"},TOKENFEESCHEDULEUPDATE:{bodyField:"tokenFeeScheduleUpdate",parser:da.parseTokenFeeScheduleUpdate,resultField:"tokenFeeScheduleUpdate"},TOKENAIRDROP:{bodyField:"tokenAirdrop",parser:da.parseTokenAirdropFromProto,resultField:"tokenAirdrop"},TOPICCREATE:{bodyField:"consensusCreateTopic",parser:ua.parseConsensusCreateTopic,resultField:"consensusCreateTopic"},CONSENSUSSUBMITMESSAGE:{bodyField:"consensusSubmitMessage",parser:ua.parseConsensusSubmitMessage,resultField:"consensusSubmitMessage"},TOPICUPDATE:{bodyField:"consensusUpdateTopic",parser:ua.parseConsensusUpdateTopic,resultField:"consensusUpdateTopic"},TOPICDELETE:{bodyField:"consensusDeleteTopic",parser:ua.parseConsensusDeleteTopic,resultField:"consensusDeleteTopic"},ACCOUNTCREATE:{bodyField:"cryptoCreateAccount",parser:ha.parseCryptoCreateAccount,resultField:"cryptoCreateAccount"},ACCOUNTUPDATE:{bodyField:"cryptoUpdateAccount",parser:ha.parseCryptoUpdateAccount,resultField:"cryptoUpdateAccount"},ACCOUNTDELETE:{bodyField:"cryptoDelete",parser:ha.parseCryptoDelete,resultField:"cryptoDelete"},CRYPTOTRANSFER:{bodyField:"cryptoTransfer",parser:e=>{const t={transfers:[],tokenTransfers:[]};return ha.parseCryptoTransfers(e,t),t},resultField:"transfers",spreadResult:!0},APPROVEALLOWANCE:{bodyField:"cryptoApproveAllowance",parser:ha.parseCryptoApproveAllowance,resultField:"cryptoApproveAllowance"},DELETEALLOWANCE:{bodyField:"cryptoDeleteAllowance",parser:ha.parseCryptoDeleteAllowance,resultField:"cryptoDeleteAllowance"},FILECREATE:{bodyField:"fileCreate",parser:pa.parseFileCreate,resultField:"fileCreate"},FILEUPDATE:{bodyField:"fileUpdate",parser:pa.parseFileUpdate,resultField:"fileUpdate"},FILEDELETE:{bodyField:"fileDelete",parser:pa.parseFileDelete,resultField:"fileDelete"},FILEAPPEND:{bodyField:"fileAppend",parser:pa.parseFileAppend,resultField:"fileAppend"},CONTRACTCREATE:{bodyField:"contractCreateInstance",parser:ga.parseContractCreate,resultField:"contractCreate"},CONTRACTUPDATE:{bodyField:"contractUpdateInstance",parser:ga.parseContractUpdate,resultField:"contractUpdate"},CONTRACTDELETE:{bodyField:"contractDeleteInstance",parser:ga.parseContractDelete,resultField:"contractDelete"},CONTRACTCALL:{bodyField:"contractCall",parser:ga.parseContractCall,resultField:"contractCall"},ETHEREUMTRANSACTION:{bodyField:"ethereumTransaction",parser:ga.parseEthereumTransaction,resultField:"ethereumTransaction"},SCHEDULECREATE:{bodyField:"scheduleCreate",parser:fa.parseScheduleCreateFromProto,resultField:"scheduleCreate"},SCHEDULESIGN:{bodyField:"scheduleSign",parser:fa.parseScheduleSignFromProto,resultField:"scheduleSign"},SCHEDULEDELETE:{bodyField:"scheduleDelete",parser:fa.parseScheduleDeleteFromProto,resultField:"scheduleDelete"},PRNG:{bodyField:"utilPrng",parser:ma.parseUtilPrng,resultField:"utilPrng"},FREEZE:{bodyField:"freeze",parser:ma.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:da.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 ba={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"}},wa={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"},Ia={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 Ta(e){for(const[t,r]of Object.entries(ba))if(e[t])return r;return{type:"UNKNOWN",humanReadableType:"Unknown Transaction"}}function Sa(e){return wa[e]||"Unknown Transaction"}class ka{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 us(`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 us("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=da.parseFromTransactionObject(e),a=ha.parseFromTransactionObject(e),c=ua.parseFromTransactionObject(e),l=pa.parseFromTransactionObject(e),d=ga.parseFromTransactionObject(e),u=fa.parseFromTransactionObject(e),p=ma.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 Ta(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 Ta(e).type}static getHumanReadableType(e){return Sa(e)}static getTransactionSummary(e){return sa(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 us("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 us("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 us("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[da.parseFromTransactionObject(e),ha.parseFromTransactionObject(e),ua.parseFromTransactionObject(e),pa.parseFromTransactionObject(e),ga.parseFromTransactionObject(e),fa.parseFromTransactionObject(e),ma.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&&ha.parseCryptoTransfers(e.cryptoTransfer,t),e.cryptoDelete&&(t.cryptoDelete=ha.parseCryptoDelete(e.cryptoDelete)),e.cryptoCreateAccount&&(t.cryptoCreateAccount=ha.parseCryptoCreateAccount(e.cryptoCreateAccount)),e.cryptoUpdateAccount&&(t.cryptoUpdateAccount=ha.parseCryptoUpdateAccount(e.cryptoUpdateAccount)),e.cryptoApproveAllowance&&(t.cryptoApproveAllowance=ha.parseCryptoApproveAllowance(e.cryptoApproveAllowance)),e.cryptoDeleteAllowance&&(t.cryptoDeleteAllowance=ha.parseCryptoDeleteAllowance(e.cryptoDeleteAllowance)),e.contractCall&&(t.contractCall=ga.parseContractCall(e.contractCall)),e.contractCreateInstance&&(t.contractCreate=ga.parseContractCreate(e.contractCreateInstance)),e.contractUpdateInstance&&(t.contractUpdate=ga.parseContractUpdate(e.contractUpdateInstance)),e.contractDeleteInstance&&(t.contractDelete=ga.parseContractDelete(e.contractDeleteInstance)),e.tokenCreation&&(t.tokenCreation=da.parseTokenCreate(e.tokenCreation)),e.tokenMint&&(t.tokenMint=da.parseTokenMint(e.tokenMint)),e.tokenBurn&&(t.tokenBurn=da.parseTokenBurn(e.tokenBurn)),e.tokenUpdate&&(t.tokenUpdate=da.parseTokenUpdate(e.tokenUpdate)),e.tokenFeeScheduleUpdate&&(t.tokenFeeScheduleUpdate=da.parseTokenFeeScheduleUpdate(e.tokenFeeScheduleUpdate)),e.tokenFreeze&&(t.tokenFreeze=da.parseTokenFreeze(e.tokenFreeze)),e.tokenUnfreeze&&(t.tokenUnfreeze=da.parseTokenUnfreeze(e.tokenUnfreeze)),e.tokenGrantKyc&&(t.tokenGrantKyc=da.parseTokenGrantKyc(e.tokenGrantKyc)),e.tokenRevokeKyc&&(t.tokenRevokeKyc=da.parseTokenRevokeKyc(e.tokenRevokeKyc)),e.tokenPause&&(t.tokenPause=da.parseTokenPause(e.tokenPause)),e.tokenUnpause&&(t.tokenUnpause=da.parseTokenUnpause(e.tokenUnpause)),e.tokenWipe&&(t.tokenWipeAccount=da.parseTokenWipeAccount(e.tokenWipe)),e.tokenDeletion&&(t.tokenDelete=da.parseTokenDelete(e.tokenDeletion)),e.tokenAssociate&&(t.tokenAssociate=da.parseTokenAssociate(e.tokenAssociate)),e.tokenDissociate&&(t.tokenDissociate=da.parseTokenDissociate(e.tokenDissociate)),e.tokenAirdrop&&(t.tokenAirdrop=da.parseTokenAirdropFromProto(e.tokenAirdrop)),e.consensusCreateTopic&&(t.consensusCreateTopic=ua.parseConsensusCreateTopic(e.consensusCreateTopic)),e.consensusSubmitMessage&&(t.consensusSubmitMessage=ua.parseConsensusSubmitMessage(e.consensusSubmitMessage)),e.consensusUpdateTopic&&(t.consensusUpdateTopic=ua.parseConsensusUpdateTopic(e.consensusUpdateTopic)),e.consensusDeleteTopic&&(t.consensusDeleteTopic=ua.parseConsensusDeleteTopic(e.consensusDeleteTopic)),e.fileCreate&&(t.fileCreate=pa.parseFileCreate(e.fileCreate)),e.fileAppend&&(t.fileAppend=pa.parseFileAppend(e.fileAppend)),e.fileUpdate&&(t.fileUpdate=pa.parseFileUpdate(e.fileUpdate)),e.fileDelete&&(t.fileDelete=pa.parseFileDelete(e.fileDelete)),e.utilPrng&&(t.utilPrng=ma.parseUtilPrng(e.utilPrng))}static parseTransactionBodyDetails(e,t){const r={},i=ya[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(ya).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=da.extractTokenCreationFromTransaction(r);i&&(e[t]=i)}else if("tokenAirdrop"===t&&"TOKENAIRDROP"===e.type){const i=da.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 Ea="undefined"!=typeof window&&void 0!==window.document;const va=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()}},Aa=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 Ca(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=Aa.get(o);if(n)return n;let s;return s=t.apiKey?new ls({apiKey:t.apiKey,network:e.network||"mainnet",connectionMode:i}):await ls.createWithAuth({type:"server",accountId:e.accountId,privateKey:"string"==typeof e.privateKey?e.privateKey:e.privateKey.toString(),network:e.network||"mainnet",connectionMode:i}),Aa.set(o,s),s}let xa={};const Ra=e=>{if(!e.includes("@"))return e;const t=e?.split("@");return`${t[0]}-${t[1].replace(".","-")}`};const Na=1e3;async function _a(e){if(Ea)throw new Error("File path operations are not supported in browser environment. Use buffer input type instead.");if(await async function(){if(!Ea&&!xa.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");xa.readFileSync=e.readFileSync,xa.basename=r.basename,xa.extname=r.extname}}catch(e){console.warn("Node.js modules not available, file path operations will be disabled")}}(),!xa.readFileSync||!xa.basename||!xa.extname)throw new Error("Node.js file system modules are not available. Cannot read file from path.");try{const r=xa.readFileSync(e),i=r.toString("base64"),o=xa.basename(e);let n="application/octet-stream";try{const e=await l.fileTypeFromBuffer(r);e&&(n=e.mime)}catch(t){const r=xa.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=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&&Ma(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 ls({apiKey:r.apiKey,network:t.network||"mainnet",connectionMode:"auto"});else{o.debug("Initializing InscriptionSDK with server auth");const e=Pa(t);n=await ls.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 _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),d=l.jobId||l.tx_id||l.transactionId||"",u=l.transactionId||d||"",p=Ra(d),h=Ra(u),g=Ra(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 Ba(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 W(t,i),n=Ra(e),s=n.split("-")[0];for(let c=0;c<3;c++)try{const e=await o.getTransaction(n);if(!e){c<2&&await z(Na);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 z(Na);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 z(Na)}}async function za(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&&Ma(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 ls({apiKey:r.apiKey,network:r.network||"mainnet",connectionMode:"websocket"})):(o.debug("Initializing InscriptionSDK with client auth (websocket)"),s=await ls.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"});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=Ra(l.tx_id||l.id||""),u=Ra(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 Ba(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 Da(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 ls({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 ls.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 Ma(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=va.createCacheKey(e,t,r);return va.get(i)}(e,t,r);if(n)return o.debug("Returning cached quote"),{confirmed:!1,quote:!0,result:n};"hashinal"===r.mode&&r.metadata&&Ma(r.metadata,o);const s=await Ca(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 ka.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=va.createCacheKey(e,t,r);va.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 Ba(e,t,r=30,i=4e3,o){const n=O.getInstance({module:"Inscriber"}),s=Ra(t),a=new ds({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(mg){return n.debug("Falling back to standard waitForInscription method",{error:mg}),a.verifying("Verifying inscription status",50,{error:mg}),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 Ua(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 La=(e=>(e.REGISTER_CONFIG="register-config",e.REGISTER="register",e))(La||{}),$a=(e=>(e.EVM="evm",e.WASM="wasm",e))($a||{});const Ha=r.z.object({name:r.z.string().optional(),type:r.z.string()}),qa=r.z.object({name:r.z.string(),inputs:r.z.array(Ha),outputs:r.z.array(Ha),stateMutability:r.z.enum(["view","pure"]),type:r.z.literal("function")}),ja=r.z.enum(["number","string","bool"]),Wa=r.z.object({p:r.z.literal("hcs-7"),m:r.z.string().optional()}),Va=Wa.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:qa})}),Ga=Wa.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(ja)}),outputType:r.z.object({type:r.z.literal("string"),format:r.z.literal("topic-id")})})}),Ja=Wa.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())}),Ya=r.z.union([Va,Ga,Ja]);class Xa{constructor(e){this.network=e.network,this.logger=e.logger||O.getInstance({level:e.logLevel||"info",module:"HCS7Client",silent:e.silent}),this.mirrorNode=new W(this.network,this.logger,e.mirrorNodeUrl?{customUrl:e.mirrorNodeUrl}:void 0)}generateRegistryMemo(e){return`hcs-7:indexed:${e}`}createConfigMessage(e){return e.config.type===$a.EVM?{p:"hcs-7",op:La.REGISTER_CONFIG,t:$a.EVM,c:{contractAddress:e.config.contractAddress,abi:e.config.abi},m:e.memo}:{p:"hcs-7",op:La.REGISTER_CONFIG,t:$a.WASM,c:{wasmTopicId:e.config.wasmTopicId,inputType:e.config.inputType,outputType:e.config.outputType},m:e.memo}}createMetadataMessage(e){return{p:"hcs-7",op:La.REGISTER,t_id:e.metadataTopicId,m:e.memo,d:{weight:e.weight,tags:e.tags,...e.data||{}}}}validateMessage(e){const t=Ya.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=Ya.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 Za(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 Qa(e){return G({memo:`hcs-7:indexed:${e.ttl}`,submitKey:e.submitKey,adminKey:e.adminKey,operatorPublicKey:e.operatorPublicKey})}function ec(e){const t={p:"hcs-7",...e.message};return J({topicId:e.topicId,message:JSON.stringify(t),transactionMemo:e.transactionMemo})}class tc{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 rc(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 ic(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 oc(e){return e instanceof O}async function nc(e,t,r){const i=new W(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 sc=e=>e.trim().toLowerCase(),ac=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"}]]),cc={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},lc=new Map(Object.entries(cc).map(([e,t])=>[t,e])),dc=e=>{const t=sc(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=cc[t];void 0!==e&&(i=e,r=t)}else lc.has(i)&&(r=lc.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}},uc=e=>{if("string"!=typeof e||0===e.trim().length)throw new Error("Ledger network is required.");const t=sc(e);return t.startsWith("hedera:")||t.includes("hedera-")||t.includes("hedera_")||"mainnet"===t||"testnet"===t?(e=>{const t=sc(e),r=ac.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):dc(t)};var pc=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTONOMOUS=1]="AUTONOMOUS",e))(pc||{}),hc=(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))(hc||{});const gc=r.z.nativeEnum(hc),mc=r.z.union([gc,r.z.string()]),fc=r.z.union([r.z.string(),r.z.number(),r.z.boolean(),r.z.null()]),yc=r.z.lazy(()=>r.z.union([fc,r.z.array(yc),r.z.record(yc)])),bc=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(yc).optional(),aiAgent:r.z.object({type:r.z.nativeEnum(pc),creator:r.z.string().optional(),model:r.z.string().optional(),capabilities:r.z.array(gc).optional()}).optional(),uaid:r.z.string().optional()}).catchall(yc),wc=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()}),Ic=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(wc)}),Tc=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()}),Sc=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(yc).optional(),submittedAt:r.z.string()}),kc=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:Sc.optional(),responder:Sc.optional()}),Ec=r.z.object({enabled:r.z.boolean(),algorithm:r.z.string(),requireCiphertext:r.z.boolean(),requester:Tc.nullable().optional(),responder:Tc.nullable().optional(),handshake:kc.nullable().optional()}),vc=r.z.object({messageId:r.z.string(),role:r.z.enum(["user","agent"]),content:r.z.string(),timestamp:r.z.string(),cipherEnvelope:Ic.optional(),metadata:r.z.record(yc).optional()}),Ac=r.z.record(r.z.union([r.z.array(yc),r.z.record(yc),yc])).optional(),Cc=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(mc),endpoints:r.z.union([r.z.record(yc),r.z.array(r.z.string())]).optional(),metadata:r.z.record(yc).optional(),metadataFacet:Ac,profile:bc.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(),xc=r.z.object({hits:r.z.array(Cc),total:r.z.number(),page:r.z.number(),limit:r.z.number()}),Rc=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()}),Nc=r.z.object({registries:r.z.array(r.z.string())}),_c=r.z.object({searches:r.z.array(r.z.string())}),Pc=r.z.object({agent:Cc}),Fc=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(yc).nullable().optional(),skills:r.z.array(r.z.string()).optional()}),history:r.z.array(vc).optional().default([]),historyTtlSeconds:r.z.number().nullable().optional(),encryption:Ec.nullable().optional()}),Oc=r.z.object({sessionId:r.z.string(),uaid:r.z.string().nullable().optional(),message:r.z.string(),timestamp:r.z.string(),rawResponse:yc.optional(),content:r.z.string().optional(),history:r.z.array(vc).optional(),historyTtlSeconds:r.z.number().nullable().optional(),encrypted:r.z.boolean().optional()}),zc=r.z.object({sessionId:r.z.string(),history:r.z.array(vc),historyTtlSeconds:r.z.number()});r.z.object({preserveEntries:r.z.number().int().min(0).optional()}).strict();const Dc=r.z.object({sessionId:r.z.string(),history:r.z.array(vc),summaryEntry:vc,preservedEntries:r.z.array(vc),historyTtlSeconds:r.z.number(),creditsDebited:r.z.number(),metadata:r.z.record(yc).optional()}),Mc=r.z.object({sessionId:r.z.string(),encryption:Ec.nullable()}),Kc=r.z.object({sessionId:r.z.string(),handshake:kc}),Bc=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()}),Uc=r.z.object({challengeId:r.z.string(),message:r.z.string(),expiresAt:r.z.string()}),Lc=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()}),$c=r.z.object({key:r.z.string(),apiKey:Lc,accountId:r.z.string(),network:r.z.string(),networkCanonical:r.z.string().optional()}),Hc=r.z.object({protocols:r.z.array(r.z.string())}),qc=r.z.object({protocol:r.z.string().nullable()}),jc=r.z.object({hits:r.z.array(Cc),total:r.z.number(),page:r.z.number().optional(),limit:r.z.number().optional()}),Wc=r.z.union([r.z.string(),r.z.number()]),Vc=r.z.object({capabilities:r.z.array(Wc).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:Vc.optional(),limit:r.z.number().int().min(1).max(100).optional(),offset:r.z.number().int().min(0).optional()}).strict();const Gc=r.z.object({agent:Cc,score:r.z.number().optional(),highlights:r.z.record(r.z.array(r.z.string())).optional()}),Jc=r.z.object({hits:r.z.array(Gc),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()}),Yc=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()}),Xc=r.z.object({storageMode:r.z.string(),vectorStatus:Yc}),Zc=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()}),Qc=r.z.object({p50:r.z.number(),p90:r.z.number(),p95:r.z.number(),p99:r.z.number()}),el=r.z.object({http:r.z.object({requestsTotal:r.z.number(),activeConnections:r.z.number(),requestDuration:Qc}),search:r.z.object({queriesTotal:r.z.number(),queryDuration:Qc}),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:Qc}),cache:r.z.object({hits:r.z.number(),misses:r.z.number(),hitRate:r.z.number()}),websocket:r.z.object({connections:r.z.number()})}),tl=r.z.object({uaid:r.z.string(),valid:r.z.boolean(),formats:r.z.array(r.z.string())}),rl=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(fc).optional(),createdAt:r.z.string()}),il=r.z.object({connected:r.z.boolean(),connection:rl.optional(),adapter:r.z.string().optional(),agentId:r.z.string().optional()}),ol=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()}),nl=r.z.object({id:r.z.string(),name:r.z.string(),type:r.z.string(),endpoint:r.z.string().optional(),capabilities:r.z.array(mc),registry:r.z.string().optional(),protocol:r.z.string().optional(),profile:bc.optional(),nativeId:r.z.string().optional(),metadata:r.z.record(yc).optional()}),sl=r.z.object({tId:r.z.string().nullable(),sizeBytes:r.z.number().optional()}),al=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(),cl=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(yc).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()}),ll=r.z.object({base:r.z.number(),additional:r.z.number(),total:r.z.number()}),dl=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(),ul=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(),pl=r.z.object({id:r.z.string(),label:r.z.string(),networks:r.z.array(ul)}),hl=r.z.object({registries:r.z.array(pl)}),gl=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:nl,openConvAI:r.z.object({compatible:r.z.boolean(),hcs11Profile:bc.optional(),bridgeEndpoint:r.z.string().optional()}).optional(),profile:sl.optional(),profileRegistry:al.nullable().optional(),hcs10Registry:dl.nullable().optional(),credits:ll.optional(),additionalRegistries:r.z.array(cl).optional(),additionalRegistryCredits:r.z.array(cl).optional(),additionalRegistryCostPerRegistry:r.z.number().optional()}),ml=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:nl,openConvAI:r.z.object({compatible:r.z.boolean(),hcs11Profile:bc.optional(),bridgeEndpoint:r.z.string().optional()}).optional(),profile:sl.optional(),profileRegistry:al.nullable().optional(),hcs10Registry:dl.nullable().optional(),credits:ll,additionalRegistries:r.z.array(cl),additionalRegistryCredits:r.z.array(cl).optional(),additionalRegistryCostPerRegistry:r.z.number().optional()}),fl=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:nl,openConvAI:r.z.object({compatible:r.z.boolean(),hcs11Profile:bc.optional(),bridgeEndpoint:r.z.string().optional()}).optional(),profile:sl.optional(),profileRegistry:al.nullable().optional(),hcs10Registry:dl.nullable().optional(),credits:ll.optional(),additionalRegistries:r.z.array(cl).optional(),additionalRegistryCredits:r.z.array(cl).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)}),yl=r.z.union([gl,ml,fl]),bl=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(yc).optional(),lastUpdated:r.z.string()}),wl=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(),bl),errors:r.z.array(r.z.string()).optional()}),Il=r.z.object({progress:wl}),Tl=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()}),Sl=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()}),kl=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(),El=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(yc).optional(),settlement:kl.optional()}).optional()}),vl=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()}),Al=r.z.object({adapters:r.z.array(r.z.string())}),Cl=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()}),xl=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())}),Rl=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:Cl.optional(),capabilities:xl,enabled:r.z.boolean(),priority:r.z.number(),status:r.z.enum(["running","stopped"])}),Nl=r.z.object({adapters:r.z.array(Rl)}),_l=r.z.object({value:r.z.union([r.z.string(),r.z.number(),r.z.boolean()]),label:r.z.string()}),Pl=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(_l).optional()}),Fl=r.z.object({facets:r.z.array(Pl)});let Ol;function zl(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 Dl(e){try{return await import(e)}catch(t){if(zl(e,t))return null;throw t}}async function Ml(e){if(Ea)return Dl(e);const t=await async function(){if(void 0!==Ol)return Ol;if(Ea)return Ol=null,Ol;try{const e="undefined"!=typeof global?global:globalThis,t=e.process?.mainModule?.require??e.require;Ol="function"==typeof t&&"function"==typeof t.resolve?t:null}catch{Ol=null}return Ol}();if(t)try{return t(e)}catch(r){if(!zl(e,r))throw r}return Dl(e)}const Kl=e=>new Error(`${e} is not supported by the in-memory signer`),Bl=e=>{const t=Ll(),{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 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")}}};let Ul=null;const Ll=()=>{if(Ul)return Ul;const e=function(e){if(Ea)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(!zl(e,t))throw t}return null}("@hashgraph/sdk");if(!e){throw new Error("@hashgraph/sdk is required for ledger signing. Install it as a dependency to enable createPrivateKeySigner.")}return Ul=e,e},$l=()=>"function"==typeof DOMException?new DOMException("Aborted","AbortError"):new Error("The operation was aborted"),Hl=/application\/json/i,ql=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:ql(e));if("object"==typeof e){const t={};return Object.entries(e).forEach(([e,r])=>{void 0!==r&&(t[e]=ql(r))}),t}throw new TypeError("Only JSON-compatible values are supported")},jl=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Wl=e=>{const t=ql(e);if(jl(t))return t;throw new TypeError("Expected JSON object value")},Vl=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},Gl=e=>{const t={profile:Wl(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=Wl(e.metadata)),t};class Jl extends Error{constructor(e,t){super(e),this.status=t.status,this.statusText=t.statusText,this.body=t.body}}class Yl extends Error{constructor(e,t,r){super(e),this.cause=t,this.rawValue=r}}class Xl{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","@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 Jl("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 Zl(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 Xl(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}}async loadViemAccount(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}}async loadX402Dependencies(){try{const[{default:e},t,r]=await Promise.all([import("axios"),Ml("x402-axios"),Ml("x402/types")]);if(!t||!r)throw new Error("x402-axios and x402/types are required for X402 flows. Install them to enable ledger payments.");const i=t.withPaymentInterceptor,o=t.decodeXPaymentResponse,n=r.createSigner;return{createPaymentClient:t=>{const r=e.create({baseURL:this.baseUrl,headers:{...this.getDefaultHeaders(),"content-type":"application/json"}}),o=i(r,t);return{post:async(e,t)=>{const r=await o.post(e,t);return{data:r.data,headers:r.headers}}}},decodePaymentResponse:o,createX402Signer:n}}catch(e){const t=new Error('X402 credit purchases require optional dependencies "axios", "x402-axios", and "x402/types". Install them to enable this feature.');throw t.cause=e,t}}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,xc,"search response")}async stats(){const e=await this.requestJson("/stats",{method:"GET"});return this.parseWithSchema(e,Rc,"stats response")}async registries(){const e=await this.requestJson("/registries",{method:"GET"});return this.parseWithSchema(e,Nc,"registries response")}async getAdditionalRegistries(){const e=await this.requestJson("/register/additional-registries",{method:"GET"});return this.parseWithSchema(e,hl,"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=g.secp256k1.getPublicKey(t,!0);return p.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,_c,"popular searches response")}async resolveUaid(e){const t=await this.requestJson(`/resolve/${encodeURIComponent(e)}`,{method:"GET"});return this.parseWithSchema(t,Pc,"resolve UAID response")}async performRegisterAgent(e){const t=await this.requestJson("/register",{method:"POST",body:Gl(e),headers:{"content-type":"application/json"}});return this.parseWithSchema(t,yl,"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:Gl(e),headers:{"content-type":"application/json"}});return this.parseWithSchema(t,Tl,"registration quote response")}async updateAgent(e,t){const r=await this.requestJson(`/register/${encodeURIComponent(e)}`,{method:"PUT",body:Gl(t),headers:{"content-type":"application/json"}});return this.parseWithSchema(r,yl,"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,Il,"registration progress response").progress}catch(r){if(r instanceof Jl&&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 $l();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 Jl("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,Sl,"credit purchase response")}async getX402Minimums(){const e=await this.requestJson("/credits/purchase/x402/minimums",{method:"GET"});return this.parseWithSchema(e,vl,"x402 minimums response")}async purchaseCreditsWithX402(e){const{createPaymentClient:t,decodePaymentResponse:r}=await this.loadX402Dependencies();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,El,"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}}async buyCreditsWithX402(e){const t=e.network??"base",{createX402Signer:r}=await this.loadX402Dependencies(),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})}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 Jl))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:jl(e)&&"string"==typeof e.error?e.error:jl(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 Jl)||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=uc(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,Uc,"ledger challenge response")}async verifyLedgerChallenge(e){const t=uc(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,$c,"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=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}}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=uc(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=Bl({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 this.loadViemAccount(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}async listProtocols(){const e=await this.requestJson("/protocols",{method:"GET"});return this.parseWithSchema(e,Hc,"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,qc,"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,jc,"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,Jc,"vector search response")}catch(t){if(t instanceof Jl&&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,Xc,"search status response")}async adaptersDetailed(){const e=await this.requestJson("/adapters/details",{method:"GET"});return this.parseWithSchema(e,Nl,"adapter details response")}async websocketStats(){const e=await this.requestJson("/websocket/stats",{method:"GET"});return this.parseWithSchema(e,Zc,"websocket stats response")}async metricsSummary(){const e=await this.requestJson("/metrics",{method:"GET"});return this.parseWithSchema(e,el,"metrics summary response")}async validateUaid(e){const t=await this.requestJson(`/uaids/validate/${encodeURIComponent(e)}`,{method:"GET"});return this.parseWithSchema(t,tl,"UAID validation response")}async getUaidConnectionStatus(e){const t=await this.requestJson(`/uaids/connections/${encodeURIComponent(e)}/status`,{method:"GET"});return this.parseWithSchema(t,il,"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,ol,"dashboard stats response")}async adapters(){const e=await this.requestJson("/adapters",{method:"GET"});return this.parseWithSchema(e,Al,"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,Fl,"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=Vl(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,Fc,"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 Ql){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 Ql&&"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,zc,"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:p.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=p.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,Dc,"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,Mc,"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,Kc,"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,Bc,"register encryption key response")}async sendMessage(e){const t={message:e.message};void 0!==e.streaming&&(t.streaming=e.streaming),e.auth&&(t.auth=Vl(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,Oc,"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=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?I.resolve(e.envPath):void 0;if(s){const t=await(async()=>{const e=await Ml("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}}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 $l()}else await new Promise((r,i)=>{const o=setTimeout(()=>{t&&t.removeEventListener("abort",n),r()},e),n=()=>{clearTimeout(o),t?.removeEventListener("abort",n),i($l())};if(t){if(t.aborted)return clearTimeout(o),void i($l());t.addEventListener("abort",n,{once:!0})}})}async requestJson(e,t){const r=await this.request(e,t),i=r.headers?.get("content-type")??"";if(!Hl.test(i)){const e=await r.text();throw new Yl("Expected JSON response from registry broker",e)}return await r.json()}async extractErrorBody(e){const t=e.headers?.get("content-type")??"";if(Hl.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 Yl(`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=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")}}class Zl{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 Ql(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 Ql(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:p.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=p.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 Ql extends Error{constructor(e,t){super("Encryption is not enabled for this session"),this.sessionId=e,this.summary=t}}class ed{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 W(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(mg){const t=`Error resolving HRL for content and type: ${mg.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(mg){const t=`Error resolving HRL reference: ${mg.message}`;throw this.logger.error(t),new Error(t)}}}class td{constructor(e){this.nodeHash=e}update(e){return this.nodeHash.update(e),this}digest(e){return this.nodeHash.digest(e)}}class rd{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 id{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 od(){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 nd(){return"undefined"==typeof window}class sd{constructor(e){this.nodeHmac=e}update(e){return this.nodeHmac.update(e),this}digest(e){return this.nodeHmac.digest(e)}}class ad{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 cd{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 ld{constructor(){try{const e="crypto";this.crypto=require(e)}catch(e){throw new Error("Node.js crypto module not available")}}createHash(e){return new td(this.crypto.createHash(e))}createHmac(e,t){return new sd(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 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=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 ud{createHash(e){return new id(e)}createHmac(e,t){return new cd(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 pd(){switch(od().preferredAPI){case"node":try{return new ld}catch{return new ud}case"web":return new dd;default:return new ud}}const hd=["mainnet","testnet","previewnet","devnet"];function gd(e){return hd.includes(e)}const md=/^hedera:(mainnet|testnet|previewnet|devnet):\d+\.\d+\.\d+(?:-[a-zA-Z0-9]{5})?$/;function fd(e){return md.test(e)}function yd(e,t){if(!gd(e))throw new Error("Invalid Hedera network");if(t.startsWith("hedera:")){if(fd(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 bd(e){if(!fd(e))throw new Error("Invalid Hedera CAIP-10");const[,t,r]=e.match(/^hedera:([^:]+):(.+)$/);return{network:t,accountId:r}}const wd=/^eip155:(\d+):(0x[0-9a-fA-F]{39,40})$/;function Id(e){return wd.test(e)}function Td(e,t){const r=`eip155:${"number"==typeof e?String(e):e}:${t.startsWith("0x")?t:`0x${t}`}`;if(!Id(r))throw new Error("Invalid EIP-155 CAIP-10");return r}var Sd=(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))(Sd||{}),kd=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTONOMOUS=1]="AUTONOMOUS",e))(kd||{}),Ed=(e=>(e[e.REST=0]="REST",e[e.WEBSOCKET=1]="WEBSOCKET",e[e.GRPC=2]="GRPC",e))(Ed||{}),vd=(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))(vd||{}),Ad=(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))(Ad||{}),Cd=(e=>(e.DNS="dns",e.SIGNATURE="signature",e.CHALLENGE="challenge",e))(Cd||{}),xd=(e=>(e.PUBLIC="PUBLIC",e.CONTROLLED="CONTROLLED",e.FEE_BASED="FEE_BASED",e))(xd||{});const Rd={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},Nd=r.z.object({platform:r.z.string().min(1),handle:r.z.string().min(1)}),_d=r.z.object({type:r.z.nativeEnum(kd),capabilities:r.z.array(r.z.nativeEnum(vd)).min(1),model:r.z.string().min(1),creator:r.z.string().optional()}),Pd=r.z.object({url:r.z.string().min(1),transport:r.z.enum(["stdio","sse"])}),Fd=r.z.object({type:r.z.nativeEnum(Cd),value:r.z.string(),dns_field:r.z.string().optional(),challenge_path:r.z.string().optional()}),Od=r.z.object({minVersion:r.z.string().optional()}),zd=r.z.object({name:r.z.string().min(1),description:r.z.string().min(1)}),Dd=r.z.object({name:r.z.string().min(1),description:r.z.string().min(1)}),Md=r.z.object({version:r.z.string().min(1),connectionInfo:Pd,services:r.z.array(r.z.nativeEnum(Ad)).min(1),description:r.z.string().min(1),verification:Fd.optional(),host:Od.optional(),capabilities:r.z.array(r.z.string()).optional(),resources:r.z.array(zd).optional(),tools:r.z.array(Dd).optional(),maintainer:r.z.string().optional(),repository:r.z.string().optional(),docs:r.z.string().optional()}),Kd=r.z.object({version:r.z.string().min(1),type:r.z.nativeEnum(Sd),display_name:r.z.string().min(1),alias:r.z.string().optional(),bio:r.z.string().optional(),socials:r.z.array(Nd).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()}),Bd=Kd.extend({type:r.z.literal(Sd.PERSONAL),language:r.z.string().optional(),timezone:r.z.string().optional()}),Ud=Kd.extend({type:r.z.literal(Sd.AI_AGENT),aiAgent:_d}),Ld=Kd.extend({type:r.z.literal(Sd.MCP_SERVER),mcpServer:Md}),$d=r.z.object({version:r.z.string(),type:r.z.literal(Sd.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()}),Hd=r.z.union([Bd,Ud,Ld,$d]);class qd{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 W(this.network,this.logger),this.auth.privateKey?(this.operatorCtx=re({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:Sd.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:Sd.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:Sd.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:Sd.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:Sd.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=Hd.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 ds({module:"HCS11-Image",logger:this.logger,callback:o});n.preparing("Preparing to inscribe image",0);const s=T.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 za({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:Ua(c.inscription)}),{imageTopicId:Ua(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 ds({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 za(r,this.auth.signer,n)}if(!c.confirmed||!Ua(c.inscription))return o.failed("Failed to inscribe profile content"),{profileTopicId:"",transactionId:"",success:!1,error:"Failed to inscribe profile content"};const l=Ua(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&&gd(this.network))try{const{HCS14Client:t}=await Promise.resolve().then(()=>mp),r=new t({client:this.client}),i=await r.createDid({method:"hedera",client:this.client}),o=yd(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(mg){this.logger.warn("Hiero registrar not available; skipping UAID generation for profile",mg)}}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 ds({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[vd.TEXT_GENERATION];for(const r of e){const e=Rd[r.toLowerCase()];void 0===e||t.includes(e)||t.push(e)}return 0===t.length&&t.push(vd.TEXT_GENERATION),t}getAgentTypeFromMetadata(e){return"autonomous"===e.type?kd.AUTONOMOUS:kd.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=Hd.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=Hd.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=Hd.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 jd{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 qd({network:t,auth:{operatorId:"0.0.0"}});i?.info(`Fetching profile by account ID ${e} on ${t}`),await z(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(mg){return{registrations:[],error:`Error fetching registrations: ${mg.message}`,success:!1}}}}function Wd(e,t){return`hcs-10:op:${e}:${t}`}function Vd(e){var t,r;return G({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 Gd(e){return G({memo:e.memoOverride??`hcs-10:0:${e.ttl}:1`,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function Jd(e){var t,r,i;return G({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 Yd(e){var t,r;return G({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 Xd(e){const t={p:"hcs-10",op:"connection_request",operator_id:e.operatorId,m:e.memo};return J({topicId:e.inboundTopicId,message:JSON.stringify(t),transactionMemo:Wd(3,1)})}function Zd(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 J({topicId:e.inboundTopicId,message:JSON.stringify(t),transactionMemo:Wd(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 J({topicId:e.outboundTopicId,message:JSON.stringify(t),transactionMemo:Wd(3,2)})}function eu(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 J({topicId:e.outboundTopicId,message:JSON.stringify(t),transactionMemo:Wd(4,2)})}function tu(e){const t={p:"hcs-10",op:"message",operator_id:e.operatorId,data:e.data,m:e.memo};return J({topicId:e.connectionTopicId,message:JSON.stringify(t),transactionMemo:Wd(6,3)})}function ru(e){const t={p:"hcs-10",op:"register",account_id:e.accountId,...e.inboundTopicId?{inbound_topic_id:e.inboundTopicId}:{},m:e.memo};return J({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:Wd(0,0)})}var iu=(e=>(e.INBOUND="inbound",e.OUTBOUND="outbound",e.CONNECTION="connection",e.REGISTRY="registry",e))(iu||{});class ou extends jd{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 W(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(mg){throw this.logger.error("Failed to fetch account",mg),mg}}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=nu.getInstance().get(r);if(t)return this.logger.debug(`Cache hit for profile: ${e}`),t}try{const t=new qd({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 nu.getInstance().set(r,l),l}catch(mg){if(n<i){this.logger.info(`Error retrieving profile for account ${e}, retrying in ${o}ms... (${mg.message})`),n++,await new Promise(e=>setTimeout(e,o));continue}const r=`Failed to retrieve profile: ${mg.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(mg){const t=mg,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(mg){const t=`Failed to retrieve outbound messages: ${mg.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(mg){const t=`Failed to check connection created: ${mg.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 ed(this.logger.getLevel());if(!r.isValidHRL(e))return e;return(await r.resolveHRL(e,{network:this.network,returnRaw:t})).content}catch(mg){const t=`Error resolving HRL reference: ${mg.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 ed(this.logger.getLevel());return await r.getContentWithType(e,{network:this.network,returnRaw:t})}catch(mg){const t=`Error resolving HRL reference with type: ${mg.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=Xd({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=eu({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(){nu.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(mg){const t=mg,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 nu{constructor(){this.CACHE_TTL=36e5,this.cache=new Map,this.cacheExpiry=new Map}static getInstance(){return nu.instance||(nu.instance=new nu),nu.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 su extends Error{constructor(e,t){super(e),this.payloadSize=t,this.name="PayloadSizeError"}}class au extends Error{constructor(e){super(e),this.name="AccountCreationError"}}class cu extends Error{constructor(e){super(e),this.name="TopicCreationError"}}class lu extends Error{constructor(e){super(e),this.name="ConnectionConfirmationError"}}class du{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=xd.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===xd.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 uu extends ou{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=re({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 qd({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 au("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(iu.INBOUND,{accountId:e,ttl:r}),t){case xd.PUBLIC:o=!1;break;case xd.CONTROLLED:o=!0;break;case xd.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=Vd({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 ds({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 du;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(mg){const t=mg,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(mg){const t=mg,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 nc(i,this.network,this.logger)}catch(mg){const t=`Error getting exempt keys: ${mg.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=Jd({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 cu(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=Zd({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 lu("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(!Ua(i))throw new Error("Failed to inscribe large message content");a.data=`hcs://1/${Ua(i)}`,this.logger.info(`Large message inscribed with topic ID: ${Ua(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=tu({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=G({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 su("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 su("Payload size exceeds 1000 bytes limit",s);const a=J({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=T.lookup(t)||"application/octet-stream",o=this.operatorCtx.operatorKey,n=await ls.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 uu({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 te({mirrorNode:this.mirrorNode,logger:this.logger}),l=await i.resolveOperatorKey(c.accountId,c.privateKey),d=l.privateKey.publicKey.toString();a=new uu({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(mg){const r=mg,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(mg){const t=mg,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=ru({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 xd.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`),xd.FEE_BASED}return xd.CONTROLLED}catch(mg){const t=`Error determining topic type: ${mg.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=f.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=Gd({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=Vd({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,xd.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=Gd({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===xd.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=ee(c.privateKey),t=("ed25519"===e.detectedType?i.PrivateKey.fromStringED25519(c.privateKey):i.PrivateKey.fromStringECDSA(c.privateKey)).publicKey.toString();a=new uu({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 te({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 uu({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(mg){const r=mg,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=Ua(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=Yd({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 pu="undefined"!=typeof window;var hu=(e=>(e[e.ACTION=0]="ACTION",e[e.ASSEMBLY=2]="ASSEMBLY",e[e.HASHLINKS=3]="HASHLINKS",e))(hu||{});class gu{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:hu[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:hu[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 za({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:hu[this.registryType]})}getStats(){return{entryCount:this.entries.size,lastSync:this.lastSyncTimestamp,topicId:this.topicId,registryType:hu[this.registryType]}}}const mu=r.z.object({p:r.z.literal("hcs-12")}),fu=r.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid Hedera address format"),yu=r.z.string().regex(/^[a-f0-9]{64}$/,"Invalid SHA-256 hash format"),bu=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()}),wu=r.z.object({source_t_id:fu,source_hash:yu,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:yu,source_structure:bu}),Iu=r.z.lazy(()=>r.z.object({type:r.z.string().optional(),required:r.z.array(r.z.string()).optional(),properties:r.z.record(Iu).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()})),Tu=r.z.object({p:r.z.literal("hcs-12"),op:r.z.literal("register"),t_id:fu,hash:yu,wasm_hash:yu,js_t_id:fu.optional(),js_hash:yu.optional(),interface_version:r.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid version format").optional(),info_t_id:fu.optional(),source_verification:wu.optional(),previous_version:r.z.string().optional(),migration_notes:r.z.string().optional(),validation_rules:r.z.record(Iu).optional(),m:r.z.string().optional()}),Su=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:fu.optional()});r.z.enum(["register","add-action","add-block","update"]);const ku=mu.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()}),Eu=mu.extend({op:r.z.literal("add-action"),t_id:fu,alias:r.z.string(),config:r.z.any().optional(),data:fu.optional()}),vu=mu.extend({op:r.z.literal("add-block"),block_t_id:fu,actions:r.z.record(r.z.string(),fu).optional(),attributes:r.z.record(r.z.any()).optional(),children:r.z.array(r.z.string()).optional(),data:fu.optional()}),Au=mu.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:fu,source_hash:yu,description:r.z.string().optional()});const Cu=r.z.discriminatedUnion("op",[ku,Eu,vu,Au]),xu=ku,Ru=mu.extend({op:r.z.literal("register"),t_id:fu,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 Nu(e){return Tu.parse(e)}function _u(e){return Cu.parse(e)}function Pu(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 Fu extends gu{constructor(e,t,r,i){super(e,t,hu.ACTION,r,i),this.actionsByHash=new Map,this.cryptoAdapter=pd()}async registerWithWasm(e,t,r){let i,o;if(nd()){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(nd())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(nd())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{Nu(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 Ou{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 ed,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 ed,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 zu extends gu{constructor(e,t,r,i){super(e,t,hu.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{_u(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 Du extends gu{constructor(e,t,r,i){super(e,t,hu.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=Pu(e,Ru);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 Mu{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 Ku{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 W(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 Ou(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 zu(this.network,this.logger,e,this);await t.sync();return new Mu(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 Mu(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 Bu{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 Bu).setName(e).setTitle(t).setCategory("formatting").enableCommonSupports()}static createInteractiveBlock(e,t){return(new Bu).setName(e).setTitle(t).setCategory("widgets").enableCommonSupports()}static createWidgetBlock(e,t){return this.createInteractiveBlock(e,t)}static createContainerBlock(e,t){return(new Bu).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 Uu{constructor(e,t){this.wasmCache=new Map,this.logger=e,this.network=t,this.hrlResolver=new ed}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(mg){throw URL.revokeObjectURL(o),mg}}}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 Lu{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(mg){this.logger.warn("Failed to parse data-attributes",{uri:n,attributes:o[2],error:mg.message})}const c=s.match(/data-actions=(['"])((?:(?!\1).)*)\1/s);let l;if(c)try{const e=c[2];l=JSON.parse(e)}catch(mg){this.logger.warn("Failed to parse data-actions",{uri:n,actions:c[2],error:mg.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 $u{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 Hu={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"}},qu={ACTIONS:{},BLOCKS:{},ASSEMBLIES:{}};const ju=/^[a-z0-9][a-z0-9-]*$/,Wu=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 Vu(e){return e.trim()}function Gu(e){return e.trim().toLowerCase()}function Ju(e){const t=Wu.parse(e);if("hcs-10"===t.protocol.trim().toLowerCase()&&!fd(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()&&!Id(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:Gu(t.registry),name:Vu(t.name),version:Vu(t.version),protocol:Gu(t.protocol),nativeId:Vu(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 Yu="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function Xu(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+=Yu[r[o]];return i}function Zu(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=Yu.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 ep(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"+Xu(globalThis.Buffer.from(c,"utf8"))));const l=Qu(a);return l?`uaid:did:${s};${l}`:`uaid:did:${s}`}function tp(e,t,r){return"string"==typeof e?ep(e,t):async function(e,t,r){const{normalized:i,canonicalJson:o}=Ju(e),n=pd().createHash("sha384").update(globalThis.Buffer.from(o,"utf8")).digest(),s=await Promise.resolve(n),a=Xu(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 rp(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 ip=["@hiero-did-sdk","resolver"].join("/");let op=null;class np{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 op||(op=Ml(ip).then(e=>e?.resolveDID??null)),op}();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 sp{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=rp(e);if("uaid"!==t.method)return null;const r=t.params.src;if(r){const e=globalThis.Buffer.from(Zu(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 ap=new sp;function cp(){ap.register(new np)}class lp{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 dp=new lp,up=["@hiero-did-sdk","registrar"].join("/");let pp=null;class hp{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 pp||(pp=Ml(up).then(e=>e?.createDID??null)),pp}();if(!t)throw new Error("Hiero registrar unavailable. Ensure @hiero-did-sdk/registrar is installed.");return(await t({},{client:e.client})).did}}class gp{constructor(e){this.registry=e?.registry??ap,this.issuers=new lp,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=re({network:e,operatorId:t,operatorKey:r,mirrorNode:new W(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 hp)}async createDid(e){return this.issuers.issue(e)}canonicalizeAgentData(e){return Ju(e)}createUaid(e,t,r){return"string"==typeof e?tp(e,t):tp(e,t,r)}parseHcs14Did(e){return rp(e)}isHederaNetwork(e){return gd(e)}isHederaCaip10(e){return fd(e)}toHederaCaip10(e,t){return yd(e,t)}parseHederaCaip10(e){return bd(e)}isEip155Caip10(e){return Id(e)}toEip155Caip10(e,t){return Td(e,t)}getResolverRegistry(){return this.registry}registerHederaResolver(){this.registry.register(new np)}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=yd(this.network,this.operatorId)}if(!r&&"hcs-10"===i&&this.network&&this.operatorId)try{if(!this.hcs10Client&&this.operatorPrivateKey&&(this.hcs10Client=new uu({network:this.network,operatorId:this.operatorId,operatorPrivateKey:this.operatorPrivateKey,silent:!0})),this.hcs10Client)r=await this.hcs10Client.getOperatorId();else{const e=new qd({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:rp(n)}}}const mp=Object.freeze(Object.defineProperty({__proto__:null,CanonicalAgentDataSchema:Wu,HCS14Client:gp,HCS14_PROTOCOL_REGEX:ju,HederaHieroIssuer:hp,HieroDidResolver:np,IssuerRegistry:lp,ResolverRegistry:sp,canonicalizeAgentData:Ju,createUaid:tp,defaultIssuerRegistry:dp,defaultResolverRegistry:ap,isEip155Caip10:Id,isHederaCaip10:fd,isHederaNetwork:gd,parseHcs14Did:rp,parseHederaCaip10:bd,registerDefaultResolvers:cp,toEip155Caip10:Td,toHederaCaip10:yd},Symbol.toStringTag,{value:"Module"}));function fp(e){return`hcs://1/${e}`}class yp{constructor(e){this.network=e.network,this.logger=e.logger||O.getInstance({level:e.logLevel||"info",module:"HCS5Client",silent:e.silent}),this.mirrorNode=new W(this.network,this.logger)}}function bp(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 wp=(e=>(e.REGISTER="register",e.UPDATE="update",e.DELETE="delete",e.MIGRATE="migrate",e))(wp||{}),Ip=(e=>(e[e.INDEXED=0]="INDEXED",e[e.NON_INDEXED=1]="NON_INDEXED",e))(Ip||{});const Tp=r.z.string().regex(/^\d+\.\d+\.\d+$/,{message:"Topic ID must be in Hedera format (e.g., '0.0.123456')"}),Sp=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()}),kp=Sp.extend({op:r.z.literal("register"),t_id:Tp,metadata:r.z.string().optional()}),Ep=Sp.extend({op:r.z.literal("update"),uid:r.z.string(),t_id:Tp,metadata:r.z.string().optional()}),vp=Sp.extend({op:r.z.literal("delete"),uid:r.z.string()}),Ap=Sp.extend({op:r.z.literal("migrate"),t_id:Tp,metadata:r.z.string().optional()}),Cp=r.z.discriminatedUnion("op",[kp,Ep,vp,Ap]);class xp{constructor(e){this.network=e.network,this.logger=e.logger||O.getInstance({level:e.logLevel||"info",module:"HCS2Client",silent:e.silent}),this.mirrorNode=new W(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 Cp.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:wp.REGISTER,t_id:e,metadata:t,m:r}}createUpdateMessage(e,t,r,i,o="hcs-2"){return{p:o,op:wp.UPDATE,t_id:e,uid:t,metadata:r,m:i}}createDeleteMessage(e,t,r="hcs-2"){return{p:r,op:wp.DELETE,uid:e,m:t}}createMigrateMessage(e,t,r,i="hcs-2"){return{p:i,op:wp.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===Ip.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===Ip.INDEXED?o:n?[n]:[],latestEntry:n}}}function Rp(e){var t,r;return G({memo:e.memoOverride??(t=e.registryType,r=e.ttl,`hcs-2:${t}:${r}`),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function Np(e){const t={p:"hcs-2",op:wp.REGISTER,t_id:e.targetTopicId,metadata:e.metadata,m:e.memo};return J({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})}const _p=class e extends xp{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=re({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??Ip.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=Rp({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===Ip.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(wp.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!==Ip.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(wp.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!==Ip.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(wp.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(wp.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===Ip.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===Ip.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=J({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}};_p.operationAnalyticsCode={[wp.REGISTER]:0,[wp.UPDATE]:1,[wp.DELETE]:2,[wp.MIGRATE]:3};let Pp=_p;class Fp extends xp{constructor(e){super({network:e.network,logLevel:e.logLevel,silent:e.silent,mirrorNodeUrl:e.mirrorNodeUrl,logger:e.logger}),this.hwc=e.hwc,Ea?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??Ip.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=Q.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=Q.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===Ip.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!==wp.REGISTER)throw new Error(`Invalid operation type: ${r.op}, expected ${wp.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!==Ip.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!==Ip.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=J({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 Op={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*))$/},zp=r.z.string().regex(Op.HEDERA_ACCOUNT_REGEX,"Invalid Hedera account ID format"),Dp=r.z.string().regex(/^\d+$/,"Must be a valid number").max(Op.MAX_NUMBER_LENGTH,`Max ${Op.MAX_NUMBER_LENGTH} digits`),Mp=r.z.string().min(1,"Tick cannot be empty").transform(e=>e.toLowerCase().trim()),Kp=r.z.object({p:r.z.literal("hcs-20"),m:r.z.string().optional()}),Bp=Kp.extend({op:r.z.literal("deploy"),name:r.z.string().min(1).max(Op.MAX_NAME_LENGTH),tick:Mp,max:Dp,lim:Dp.optional(),metadata:r.z.string().max(Op.MAX_METADATA_LENGTH).optional()}),Up=Kp.extend({op:r.z.literal("mint"),tick:Mp,amt:Dp,to:zp}),Lp=Kp.extend({op:r.z.literal("burn"),tick:Mp,amt:Dp,from:zp}),$p=Kp.extend({op:r.z.literal("transfer"),tick:Mp,amt:Dp,from:zp,to:zp}),Hp=Kp.extend({op:r.z.literal("register"),name:r.z.string().min(1).max(Op.MAX_NAME_LENGTH),metadata:r.z.string().max(Op.MAX_METADATA_LENGTH).optional(),private:r.z.boolean(),t_id:zp}),qp=r.z.discriminatedUnion("op",[Bp,Up,Lp,$p,Hp]);class jp extends Error{constructor(e){super(e),this.name="HCS20Error"}}class Wp extends jp{constructor(e,t){super(e),this.tick=t,this.name="PointsDeploymentError"}}class Vp extends jp{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 Gp extends jp{constructor(e,t,r,i,o){super(e),this.tick=t,this.from=r,this.amount=i,this.availableBalance=o,this.name="PointsBurnError"}}class Jp extends jp{constructor(e,t){super(e),this.validationErrors=t,this.name="PointsValidationError"}}class Yp extends jp{constructor(e,t){super(e),this.topicId=t,this.name="TopicRegistrationError"}}class Xp extends jp{constructor(e){super(`Invalid Hedera account format: ${e}`),this.account=e,this.name="InvalidAccountFormatError"}}class Zp{constructor(e){this.logger=e.logger||new O({module:"HCS20Client"}),this.network="mainnet"===e.network?"mainnet":"testnet",this.mirrorNode=new W(this.network,this.logger,e.mirrorNodeUrl?{customUrl:e.mirrorNodeUrl}:void 0),this.registryTopicId=e.registryTopicId||Op.REGISTRY_TOPIC_ID,this.publicTopicId=e.publicTopicId||Op.PUBLIC_TOPIC_ID}validateMessage(e){try{return qp.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(!Op.HEDERA_ACCOUNT_REGEX.test(e))throw new Xp(e);return e}return e.toString()}topicToString(e){if("string"==typeof e){if(!Op.HEDERA_ACCOUNT_REGEX.test(e))throw new Xp(e);return e}return e.toString()}}function Qp(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 J({topicId:e.topicId,message:JSON.stringify(t)})}function eh(e){const t={p:"hcs-20",op:"mint",tick:e.tick.toLowerCase().trim(),amt:e.amt,to:e.to,m:e.memo};return J({topicId:e.topicId,message:JSON.stringify(t)})}function th(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 J({topicId:e.topicId,message:JSON.stringify(t)})}function rh(e){const t={p:"hcs-20",op:"burn",tick:e.tick.toLowerCase().trim(),amt:e.amt,from:e.from,m:e.memo};return J({topicId:e.topicId,message:JSON.stringify(t)})}function ih(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 J({topicId:e.registryTopicId,message:JSON.stringify(t)})}const oh="hcs-21",nh=1024,sh=1e3,ah=/^(?:hcs:\/\/1\/0\.0\.\d+|ipfs:\/\/\S+|ar:\/\/\S+|oci:\/\/\S+|https?:\/\/\S+)$/,ch=/^(?:0\.0\.\d+|hcs:\/\/1\/0\.0\.\d+(?:\/\d+)?|ipfs:\/\/\S+|ar:\/\/\S+|oci:\/\/\S+|https?:\/\/\S+)$/;var lh=(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))(lh||{});const dh=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)}),uh=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()),ph=r.z.object({p:r.z.literal(oh),op:r.z.enum(["register","update","delete"]),adapter_id:r.z.string().min(1),entity:r.z.string().min(1),package:dh,manifest:r.z.string().regex(ah,"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:uh,state_model:r.z.string().min(1).optional(),signature:r.z.string().min(1).optional()}),hh=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")})}),gh=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()}),mh=r.z.union([hh,gh]);class fh extends Error{constructor(e,t){super(e),this.code=t,this.name="HCS21ValidationError"}}function yh(e){const t=e.indexed??0,r=e.type??lh.ADAPTER_REGISTRY;if(e.metaTopicId&&!ch.test(e.metaTopicId))throw new fh("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 bh(e){return G({memo:yh({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>sh)throw new fh(`HCS-21 payload exceeds safe limit of 1000 bytes (${r}); Hedera cap is 1024`,"size_exceeded");return J({topicId:e.topicId,message:JSON.stringify(e.declaration),transactionMemo:e.transactionMemo})}class Ih{constructor(e){this.network=e.network,this.logger=e.logger||new O({level:"info",module:"HCS-21"}),this.mirrorNode=new W(this.network,this.logger,{customUrl:e.mirrorNodeUrl})}buildDeclaration(e){const t={p:oh,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=ph.parse(t);return this.assertSizeLimit(r),r}catch(t){const e=t instanceof Error?t.message:"Invalid adapter declaration";throw new fh(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===oh)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>sh)throw new fh(`HCS-21 payload exceeds safe limit of 1000 bytes (${r}); Hedera cap is 1024`,"size_exceeded")}}function Th(e){if(Array.isArray(e))return e.map(Th);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]=Th(i);return r}return e}function Sh(e){const t=Th(e);return JSON.stringify(t)}function kh(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 Eh(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 vh{constructor(e){this.network=e.network,this.logger=e.logger||new O({module:"HCS-15",level:e.logLevel||"info"}),this.mirrorNode=new W(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(mg){return this.logger.warn("verifyPetalAccount failed",{error:String(mg)}),!1}}}var Ah=(e=>(e[e.COMMUNICATION=0]="COMMUNICATION",e[e.TRANSACTION=1]="TRANSACTION",e[e.STATE=2]="STATE",e))(Ah||{}),Ch=(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))(Ch||{});class xh extends Error{constructor(e,t){super(e),this.code=t,this.name="FloraError"}}function Rh(e){const t=function(e){return`hcs-16:${e.floraAccountId}:${e.topicType}`}({floraAccountId:e.floraAccountId,topicType:e.topicType}),r=G({memo:t,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey});return e.autoRenewAccountId&&r.setAutoRenewAccountId(i.AccountId.fromString(e.autoRenewAccountId)),r}function Nh(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 _h(e){const t={p:"hcs-16",op:e.op,operator_id:e.operatorId,...e.body||{}};return J({topicId:e.topicId,message:JSON.stringify(t)})}function Ph(e){return _h({topicId:e.topicId,operatorId:e.operatorId,op:Ch.FLORA_CREATED,body:{flora_account_id:e.floraAccountId,topics:e.topics}})}function Fh(e){return _h({topicId:e.topicId,operatorId:e.operatorId,op:Ch.TRANSACTION,body:{schedule_id:e.scheduleId,data:e.data,m:e.data}})}function Oh(e){return _h({topicId:e.topicId,operatorId:e.operatorId,op:Ch.STATE_UPDATE,body:{hash:e.hash,epoch:e.epoch,timestamp:(new Date).toISOString()}})}function zh(e){return _h({topicId:e.topicId,operatorId:e.operatorId,op:Ch.FLORA_JOIN_REQUEST,body:{candidate_account_id:e.candidateAccountId}})}function Dh(e){return _h({topicId:e.topicId,operatorId:e.operatorId,op:Ch.FLORA_JOIN_VOTE,body:{candidate_account_id:e.candidateAccountId,approve:e.approve}})}function Mh(e){return _h({topicId:e.topicId,operatorId:e.operatorId,op:Ch.FLORA_JOIN_ACCEPTED,body:{members:e.members,epoch:e.epoch}})}class Kh{constructor(e){this.network=e.network,this.logger=e.logger||new O({level:"info",module:"HCS-16"}),this.mirrorNode=new W(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:Rh({floraAccountId:e.floraAccountId,topicType:Ah.COMMUNICATION,adminKey:e.keyList,submitKey:e.submitList,autoRenewAccountId:e.autoRenewAccountId}),transaction:Rh({floraAccountId:e.floraAccountId,topicType:Ah.TRANSACTION,adminKey:e.keyList,submitKey:e.submitList,autoRenewAccountId:e.autoRenewAccountId}),state:Rh({floraAccountId:e.floraAccountId,topicType:Ah.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!==Ah.COMMUNICATION&&i!==Ah.TRANSACTION&&i!==Ah.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 Bh=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 Uh extends Error{constructor(e,t){super(e),this.code=t,this.name="StateHashError"}}var Lh=(e=>(e[e.STATE=0]="STATE",e))(Lh||{});function $h(e){return`hcs-17:0:${e}`}function Hh(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 qh{constructor(e){this.network=e.network,this.logger=e.logger||new O({level:e.logLevel||"info",module:"HCS-17"}),this.mirrorNode=new W(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=Bh.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 $h(e)}async validateHCS17Topic(e){try{const t=Hh((await this.mirrorNode.getTopicInfo(e)).memo);return t?t.type!==Lh.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(mg){return{valid:!1,error:String(mg)}}}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(fg){this.logger.debug(`Failed to parse HCS-17 message: ${fg}`)}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=y.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=y.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=y.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 jh(e){return G({memo:$h(e.ttl),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function Wh(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 J({topicId:e.topicId,message:JSON.stringify(t),transactionMemo:e.transactionMemo})}var Vh=(e=>(e.ANNOUNCE="announce",e.PROPOSE="propose",e.RESPOND="respond",e.COMPLETE="complete",e.WITHDRAW="withdraw",e))(Vh||{});function Gh(e){return"object"==typeof e&&null!==e}function Jh(e){return"string"==typeof e}function Yh(e){return"number"==typeof e&&Number.isFinite(e)}function Xh(e){if(!Gh(e))return!1;if("hcs-18"!==e.p)return!1;if(!Jh(e.op))return!1;const t=e.op;return!!["announce","propose","respond","complete","withdraw"].includes(t)&&"data"in e}var Zh=(e=>(e.IDLE="idle",e.ANNOUNCED="announced",e.PROPOSING="proposing",e.FORMING="forming",e.ACTIVE="active",e.WITHDRAWN="withdrawn",e))(Zh||{});class Qh extends Error{constructor(e,t){super(e),this.code=t,this.name="DiscoveryError"}}function eg(e,t){return t&&t.trim().length>0?t:e&&e>0?`hcs-18:0:${e}`:"hcs-18:0"}function tg(e){return G({memo:eg(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 Vh.ANNOUNCE:return 0;case Vh.PROPOSE:return 1;case Vh.RESPOND:return 2;case Vh.COMPLETE:return 3;case Vh.WITHDRAW:return 4;default:return 0}}(e.message.op)}`;return(new i.TopicMessageSubmitTransaction).setTopicId(e.topicId).setMessage(JSON.stringify(e.message)).setTransactionMemo(t)}function ig(e){return{p:"hcs-18",op:Vh.ANNOUNCE,data:e}}function og(e){return{p:"hcs-18",op:Vh.PROPOSE,data:e}}function ng(e){return{p:"hcs-18",op:Vh.RESPOND,data:e}}function sg(e){return{p:"hcs-18",op:Vh.COMPLETE,data:e}}function ag(e){return{p:"hcs-18",op:Vh.WITHDRAW,data:e}}class cg{constructor(e){this.network=e.network,this.logger=e.logger||O.getInstance({module:"HCS-18"}),this.mirrorNode=new W(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 lg=(e=>(e.FIXED_FEE="FIXED_FEE",e.FRACTIONAL_FEE="FRACTIONAL_FEE",e.ROYALTY_FEE="ROYALTY_FEE",e))(lg||{});class dg{constructor(e){this.customFees=[],this.logger=e.logger,this.mirrorNode=new W(e.network,e.logger),this.defaultCollectorAccountId=e.defaultCollectorAccountId||""}static forHbar(e,t,r,i,o=[]){return new dg({network:r,logger:i,defaultCollectorAccountId:t}).addHbarFee(e,t,o)}static async forToken(e,t,r,i,o,n=[],s){const a=new dg({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:lg.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:lg.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 ug{constructor(){this.resolver=null,this.onUnavailableCallbacks=[],this.logger=O.getInstance({module:"ContentResolverRegistry"})}static getInstance(){return ug._instance||(ug._instance=new ug),ug._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 pg=ug.getInstance();class hg{constructor(){this.contentStore=null,this.logger=O.getInstance({module:"ContentStoreService"})}static getInstance(){return hg._instance||(hg._instance=new hg),hg._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 gg=hg.getInstance();exports.AIAgentCapability=vd,exports.AIAgentDetailsSchema=_d,exports.AIAgentProfileSchema=Ud,exports.AIAgentType=kd,exports.AccountCreationError=au,exports.ActionBuilder=class{constructor(e){this.cryptoAdapter=pd(),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(nd())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(nd())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(nd())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=Fu,exports.AgentBuilder=du,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=Mu,exports.AssemblyRegistry=zu,exports.BaseProfileSchema=Kd,exports.BaseRegistry=gu,exports.BlockBuilder=Bu,exports.BlockLoader=Ou,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 Lu(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 Uu(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(mg){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 $u(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 Zp{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 Fp({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 Fp({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 Jp("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 Jp("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 Yp(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=Fp,exports.BrowserHCSClient=class extends ou{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}),pu)try{const{accountId:t,signer:r}=this.getAccountAndSigner();this.hcs11Client=new qd({network:e.network,auth:{operatorId:t,signer:r},logLevel:e.logLevel,silent:e.silent})}catch(fg){this.logger.warn(`Failed to initialize HCS11Client: ${fg}`)}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(!Ua(i))throw new Error("Failed to inscribe large message content");n.data=`hcs://1/${Ua(i)}`,this.logger.info(`Large message inscribed with topic ID: ${Ua(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(iu.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 ds({module:"ProfileCreate",logger:this.logger,callback:r});try{const r=e instanceof du;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 ds({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 ds({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 ds({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=T.lookup(t)||"application/octet-stream",s=await ls.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 za({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 ds({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(iu.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(iu.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=Wu,exports.ConnectionConfirmationError=lu,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=pg,exports.ContentResolverRegistryImpl=ug,exports.ContentStoreService=gg,exports.CustomFeeType=lg,exports.DiscoveryError=Qh,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=Vh,exports.DiscoveryState=Zh,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 tc,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=rc(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=Ed,exports.FallbackCryptoAdapter=ud,exports.FallbackHashAdapter=id,exports.FallbackHmacAdapter=cd,exports.FeeConfigBuilder=dg,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=xh,exports.FloraOperation=Ch,exports.FloraTopicType=Ah,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=D,exports.HCS10BaseClient=ou,exports.HCS10Cache=nu,exports.HCS10Client=uu,exports.HCS11Client=qd,exports.HCS11ProfileSchema=Hd,exports.HCS12BaseClient=Ku,exports.HCS12BrowserClient=class extends Ku{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 Fu(this.network,this.logger,this.actionRegistryTopicId,this),this._blockLoader=new Ou(this.network,this.logger,this),this._assemblyRegistry=new zu(this.network,this.logger,this._assemblyRegistryTopicId,this),this._hashLinksRegistry=new Du(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={[hu.ACTION]:"hcs-12:1:60:0",[hu.ASSEMBLY]:"hcs-12:1:60:2",[hu.HASHLINKS]:"hcs-12:1:60:3"}[e];this.logger.info("Creating registry topic via wallet",{registryType:hu[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:hu[e]}),e){case hu.ACTION:this.actionRegistryTopicId=u;break;case hu.ASSEMBLY:this._assemblyRegistryTopicId=u;case hu.HASHLINKS:}return u}async createAssemblyTopic(){this.logger.info("Creating new assembly topic");return await this.createRegistryTopic(hu.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=T.lookup(t)||"application/octet-stream",s=await ls.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 za({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 Ku{constructor(e){super(e),this.operatorAccountId=e.operatorId,this.operatorCtx=re({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 Fu(this.network,this.logger,this.actionRegistryTopicId,this),this._blockLoader=new Ou(this.network,this.logger,this),this._assemblyRegistry=new zu(this.network,this.logger,this._assemblyRegistryTopicId,this),this._hashLinksRegistry=new Du(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={[hu.ACTION]:"hcs-12:1:60:0",[hu.ASSEMBLY]:"hcs-12:1:60:2",[hu.HASHLINKS]:"hcs-12:1:60:3"}[e];this.logger.info("Creating registry topic",{registryType:hu[e],memo:i});const o=G({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:hu[e]}),e){case hu.ACTION:this.actionRegistryTopicId=a;break;case hu.ASSEMBLY:this._assemblyRegistryTopicId=a;case hu.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=J({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=T.lookup(t)||"application/octet-stream",o=await ls.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=gp,exports.HCS14_PROTOCOL_REGEX=ju,exports.HCS15BaseClient=vh,exports.HCS15BrowserClient=class extends vh{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=kh({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=Eh({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 vh{constructor(e){super(e),this.operatorId=i.AccountId.fromString(e.operatorId),this.operatorCtx=re({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=kh({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=Eh({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=Rh({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=Ph(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async sendTransaction(e){const t=this.getSigner(),r=Fh(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=Oh(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=Nh({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=Ph({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=zh(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async sendFloraJoinVote(e){const t=this.getSigner(),r=Dh(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async sendFloraJoinAccepted(e){const t=this.getSigner(),r=Mh(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 W(e.network,this.logger);this.operatorCtx=re({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=Rh({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=Ph(e);return(await t.execute(this.client)).getReceipt(this.client)}async sendTransaction(e){const t=Fh(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=Oh(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=Nh({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=Ph({topicId:e.communicationTopicId,operatorId:e.operatorId,floraAccountId:e.floraAccountId,topics:e.topics});return(await t.execute(this.client)).getReceipt(this.client)}},exports.HCS17BaseClient=qh,exports.HCS17BrowserClient=class extends qh{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=jh({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=Wh({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=Wh({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 qh{constructor(e){super(e),this.operatorId=i.AccountId.fromString(e.operatorId),this.operatorCtx=re({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=jh({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=Wh({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=Wh({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=Lh,exports.HCS18BaseClient=cg,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=ig(e.data);return this.submit(e.discoveryTopicId,t)}async propose(e){const t=og(e.data);return this.submit(e.discoveryTopicId,t)}async respond(e){const t=ng(e.data);return this.submit(e.discoveryTopicId,t)}async complete(e){const t=sg(e.data);return this.submit(e.discoveryTopicId,t)}async withdraw(e){const t=ag(e.data);return this.submit(e.discoveryTopicId,t)}},exports.HCS18Client=class extends cg{constructor(e){super({network:e.network,logger:O.getInstance({level:e.logLevel||"info",module:"HCS-18",silent:e.silent})}),this.operatorCtx=re({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=tg({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=ig(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=og(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=ng(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=sg(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=ag(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=Zp,exports.HCS20BurnMessageSchema=Lp,exports.HCS20Client=class extends Zp{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=re({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 Pp({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 Pp({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 Wp("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 Jp("Invalid deploy message",n.errors);const s=Qp({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=eh({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 Vp("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=th({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 Gp("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=rh({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 Jp("Invalid register message",i.errors);if(!this.registryTopicId)throw new Wp("Registry topic not available",e.name);t?.({stage:"submitting",percentage:50});const o=ih({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 z(2e3)}this.logger.warn(`Transaction ${t} not found on mirror node after ${r} attempts`)}},exports.HCS20DeployMessageSchema=Bp,exports.HCS20Error=jp,exports.HCS20MessageSchema=qp,exports.HCS20MintMessageSchema=Up,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 W(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||Op.PUBLIC_TOPIC_ID:null,o=r?e?.registryTopicId||Op.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||Op.PUBLIC_TOPIC_ID:null,o=r?e?.registryTopicId||Op.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=qp.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=Hp,exports.HCS20TransferMessageSchema=$p,exports.HCS20_CONSTANTS=Op,exports.HCS21BaseClient=Ih,exports.HCS21BrowserClient=class extends Ih{constructor(e){super({network:e.network,logger:e.logger}),this.hwc=e.hwc}async createRegistryTopic(e){const{publicKey:t}=await this.getSignerContext(),r=bh({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 fh("Failed to create HCS-21 registry topic","invalid_payload");return o.topicId.toString()}async createAdapterVersionPointerTopic(e){const{publicKey:t}=await this.getSignerContext(),r=Rp({registryType:Ip.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 fh("Failed to create HCS-2 registry version topic","invalid_payload");return o.topicId.toString()}async createRegistryDiscoveryTopic(e){const{publicKey:t}=await this.getSignerContext(),r=Rp({registryType:Ip.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 fh("Failed to create registry-of-registries topic","invalid_payload");return o.topicId.toString()}async createAdapterCategoryTopic(e){const{publicKey:t}=await this.getSignerContext(),r=bh({ttl:e.ttl,indexed:e.indexed??0,type:lh.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 fh("Failed to create adapter category topic","invalid_payload");return o.topicId.toString()}async publishVersionPointer(e){const t=Np({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 fh("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 fh("Version pointer topic has no messages","invalid_payload");const r=t.t_id;if("string"!=typeof r||0===r.length)throw new fh("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=Np({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 fh("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=Np({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 fh("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 fh("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 fh("Wallet is not connected","invalid_payload");const r=await this.hwc.requestAccount(t),o=r?.key?.key;if(!o)throw new fh("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 Ih{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=re({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=mh.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 Fa({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 fh("Failed to inscribe HCS-21 metadata","invalid_payload");const s=n.inscription.jsonTopicId||n.inscription.topic_id||Ua(n.inscription);if(!s)throw new fh("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=bh({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 fh("Failed to create HCS-21 registry topic","invalid_payload");return o.topicId.toString()}async createAdapterVersionPointerTopic(e){await this.operatorCtx.ensureInitialized();const t=Rp({registryType:Ip.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 fh("Failed to create HCS-2 registry version topic","invalid_payload");return o.topicId.toString()}async createRegistryDiscoveryTopic(e){await this.operatorCtx.ensureInitialized();const t=Rp({registryType:Ip.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 fh("Failed to create registry-of-registries topic","invalid_payload");return o.topicId.toString()}async createAdapterCategoryTopic(e){await this.operatorCtx.ensureInitialized();const t=bh({ttl:e.ttl,indexed:e.indexed??0,type:lh.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 fh("Failed to create adapter category topic","invalid_payload");return o.topicId.toString()}async publishVersionPointer(e){await this.operatorCtx.ensureInitialized();const t=Np({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 fh("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 fh("Version pointer topic has no messages","invalid_payload");const r=t.t_id;if("string"!=typeof r||0===r.length)throw new fh("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=Np({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 fh("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=Np({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 fh("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 fh("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 fh("Unable to resolve manifest sequence number","invalid_payload");i=Number(t.sequence_number)}if(!Number.isFinite(i))throw new fh("Invalid manifest sequence number","invalid_payload");const o=`hcs://1/${e}`;if(!ah.test(o))throw new fh("Manifest pointer format is invalid","invalid_payload");return{pointer:o,sequenceNumber:i}}},exports.HCS21ManifestPointerPattern=ah,exports.HCS21MetadataPointerPattern=ch,exports.HCS21TopicIdPattern=/^0\.0\.\d+$/,exports.HCS21TopicType=lh,exports.HCS21ValidationError=fh,exports.HCS21_MAX_MESSAGE_BYTES=nh,exports.HCS21_PROTOCOL=oh,exports.HCS21_SAFE_MESSAGE_BYTES=sh,exports.HCS2BaseClient=xp,exports.HCS2Client=Pp,exports.HCS2Operation=wp,exports.HCS2RegistryType=Ip,exports.HCS5BrowserClient=class extends yp{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=fp(e.metadataTopicId),r=bp({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(mg){return{success:!1,error:String(mg)}}}async createHashinal(e){try{const t=this.getSigner(),r={...e.inscriptionOptions,mode:"hashinal",waitForConfirmation:!0,network:this.network},i=await za(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(mg){return{success:!1,error:String(mg)}}}},exports.HCS5Client=class extends yp{constructor(e){super(e),this.operatorId=i.AccountId.fromString(e.operatorId),this.operatorCtx=re({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=fp(e.metadataTopicId),r=bp({tokenId:e.tokenId,metadata:t}),i=await r.freezeWith(this.client);if(e.supplyKey){const t=new te({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(mg){const t=mg;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(mg){const t=mg;return this.logger.error(`Failed to inscribe and mint HCS-5 Hashinal: ${t.message}`),{success:!1,error:t.message}}}},exports.HCS6BaseClient=V,exports.HCS6BrowserClient=class extends V{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 za(r,this.signer,t),o=i.inscription?.jsonTopicId||Ua(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 za(t,this.signer,r),o=i.inscription?.jsonTopicId||Ua(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 V{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=re({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=Y({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=B(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 te({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(mg){return{success:!1,error:String(mg)}}}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(mg){return{success:!1,error:String(mg)}}}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(mg){return{success:!1,error:String(mg)}}}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(mg){return{success:!1,error:String(mg)}}}},exports.HCS6Operation=M,exports.HCS6RegistryType=K,exports.HCS7BaseClient=Xa,exports.HCS7BrowserClient=class extends Xa{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:Za(i)}}catch(t){return this.logger.error("Failed to submit HCS-7 browser message",t),{success:!1,error:String(t)}}}},exports.HCS7Client=class extends Xa{constructor(e){super(e),this.closed=!1,this.operatorCtx=re({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=Qa({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=ec({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=$a,exports.HCS7Operation=La,exports.HRLResolver=ed,exports.HTSParser=da,exports.HashLinkResolver=$u,exports.HashLinkScanner=Lu,exports.HashLinksRegistry=Du,exports.Hcs10MemoType=iu,exports.HederaHieroIssuer=hp,exports.HederaMirrorNode=W,exports.HieroDidResolver=np,exports.InboundTopicType=xd,exports.InsufficientBalanceError=class extends jp{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=Xp,exports.InvalidMessageFormatError=class extends jp{constructor(e,t){super(e),this.messageData=t,this.name="InvalidMessageFormatError"}},exports.InvalidNumberFormatError=class extends jp{constructor(e,t){super(`Invalid number format for ${t}: ${e}`),this.value=e,this.field=t,this.name="InvalidNumberFormatError"}},exports.InvalidTickFormatError=class extends jp{constructor(e){super(`Invalid tick format: ${e}`),this.tick=e,this.name="InvalidTickFormatError"}},exports.IssuerRegistry=lp,exports.KeyType=X,exports.KeyTypeDetector=Q,exports.Logger=O,exports.MAINNET_EXAMPLES=qu,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:Cd.DNS,value:e,dns_field:t};return this.config.mcpServer.verification=r,this}addVerificationSignature(e){this.config.mcpServer||(this.config.mcpServer={});const t={type:Cd.SIGNATURE,value:e};return this.config.mcpServer.verification=t,this}addVerificationChallenge(e){this.config.mcpServer||(this.config.mcpServer={});const t={type:Cd.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=Ad,exports.MCPServerConnectionInfoSchema=Pd,exports.MCPServerDetailsSchema=Md,exports.MCPServerHostSchema=Od,exports.MCPServerProfileSchema=Ld,exports.MCPServerResourceSchema=zd,exports.MCPServerToolSchema=Dd,exports.MCPServerVerificationSchema=Fd,exports.MapCache=tc,exports.MintLimitExceededError=class extends jp{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=ld,exports.NodeHashAdapter=td,exports.NodeHmacAdapter=sd,exports.PayloadSizeError=su,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=Bd,exports.PointsBurnError=Gp,exports.PointsDeploymentError=Wp,exports.PointsMintError=class extends jp{constructor(e,t,r,i){super(e),this.tick=t,this.requestedAmount=r,this.availableSupply=i,this.name="PointsMintError"}},exports.PointsNotFoundError=class extends jp{constructor(e){super(`Points with tick "${e}" not found`),this.tick=e,this.name="PointsNotFoundError"}},exports.PointsTransferError=Vp,exports.PointsValidationError=Jp,exports.ProfileType=Sd,exports.ProgressReporter=ds,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=jd,exports.RegistryBrokerClient=Xl,exports.RegistryBrokerError=Jl,exports.RegistryBrokerParseError=Yl,exports.RegistryType=hu,exports.ResolverRegistry=sp,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 D,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(nd())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=fa,exports.SocialLinkSchema=Nd,exports.StateHashError=Uh,exports.SupplyLimitExceededError=class extends jp{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=Hu,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=cu,exports.TopicRegistrationError=Yp,exports.TransactionParser=ka,exports.TransactionParsingError=us,exports.VerificationType=Cd,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=Uu,exports.WasmValidator=class{constructor(e){this.cryptoAdapter=pd(),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(nd())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=dd,exports.WebHashAdapter=rd,exports.WebHmacAdapter=ad,exports.accountIdsToExemptKeys=nc,exports.actionRegistrationSchema=Tu,exports.adapterConfigContextSchema=uh,exports.adapterDeclarationSchema=ph,exports.adapterManifestSchema=hh,exports.adapterPackageSchema=dh,exports.assemblyMessageSchema=Cu,exports.assemblyRegistrationSchema=xu,exports.baseMessageSchema=Sp,exports.blockRegistrationSchema=Su,exports.buildHcs10ConfirmConnectionTx=Zd,exports.buildHcs10CreateConnectionTopicTx=Jd,exports.buildHcs10CreateInboundTopicTx=Vd,exports.buildHcs10CreateOutboundTopicTx=Gd,exports.buildHcs10CreateRegistryTopicTx=Yd,exports.buildHcs10OutboundConnectionCreatedRecordTx=eu,exports.buildHcs10OutboundConnectionRequestRecordTx=Qd,exports.buildHcs10RegistryDeleteTx=function(e){const t={p:"hcs-10",op:"delete",uid:e.uid,m:e.memo};return J({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:Wd(1,0)})},exports.buildHcs10RegistryMigrateTx=function(e){const t={p:"hcs-10",op:"migrate",t_id:e.targetTopicId,m:e.memo};return J({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:Wd(2,0)})},exports.buildHcs10RegistryRegisterTx=ru,exports.buildHcs10SendMessageTx=tu,exports.buildHcs10SubmitConnectionRequestTx=Xd,exports.buildHcs12AddActionToAssemblyTx=function(e){return J({topicId:e.assemblyTopicId,message:JSON.stringify(e.operation)})},exports.buildHcs12AddBlockToAssemblyTx=function(e){return J({topicId:e.assemblyTopicId,message:JSON.stringify(e.operation)})},exports.buildHcs12CreateRegistryTopicTx=function(e){var t;return G({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 J({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 J({topicId:e.topicId,message:t,transactionMemo:e.transactionMemo})},exports.buildHcs12UpdateAssemblyTx=function(e){return J({topicId:e.assemblyTopicId,message:JSON.stringify(e.operation)})},exports.buildHcs15BaseAccountCreateTx=kh,exports.buildHcs15PetalAccountCreateTx=Eh,exports.buildHcs16CreateAccountTx=Nh,exports.buildHcs16CreateFloraTopicTx=Rh,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=Ph,exports.buildHcs16FloraJoinAcceptedTx=Mh,exports.buildHcs16FloraJoinRequestTx=zh,exports.buildHcs16FloraJoinVoteTx=Dh,exports.buildHcs16MessageTx=_h,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=Oh,exports.buildHcs16TransactionTx=Fh,exports.buildHcs17CreateTopicTx=jh,exports.buildHcs17MessageTx=Wh,exports.buildHcs18AnnounceMessage=ig,exports.buildHcs18CompleteMessage=sg,exports.buildHcs18CreateDiscoveryTopicTx=tg,exports.buildHcs18DiscoveryMemo=eg,exports.buildHcs18ProposeMessage=og,exports.buildHcs18RespondMessage=ng,exports.buildHcs18SubmitDiscoveryMessageTx=rg,exports.buildHcs18WithdrawMessage=ag,exports.buildHcs1Hrl=fp,exports.buildHcs20BurnTx=rh,exports.buildHcs20DeployTx=Qp,exports.buildHcs20MintTx=eh,exports.buildHcs20RegisterTx=ih,exports.buildHcs20SubmitMessageTx=function(e){const t="string"==typeof e.payload?e.payload:JSON.stringify(e.payload);return J({topicId:e.topicId,message:t,transactionMemo:e.transactionMemo})},exports.buildHcs20TransferTx=th,exports.buildHcs21CreateRegistryTx=bh,exports.buildHcs21MessageTx=wh,exports.buildHcs21RegistryMemo=yh,exports.buildHcs2CreateRegistryTx=Rp,exports.buildHcs2DeleteTx=function(e){const t={p:"hcs-2",op:wp.DELETE,uid:e.uid,m:e.memo};return J({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})},exports.buildHcs2MigrateTx=function(e){const t={p:"hcs-2",op:wp.MIGRATE,t_id:e.targetTopicId,metadata:e.metadata,m:e.memo};return J({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})},exports.buildHcs2RegisterTx=Np,exports.buildHcs2UpdateTx=function(e){const t={p:"hcs-2",op:wp.UPDATE,uid:e.uid,t_id:e.targetTopicId,metadata:e.metadata,m:e.memo};return J({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})},exports.buildHcs5MintTx=bp,exports.buildHcs5MintWithHrlTx=function(e){const t=fp(e.metadataTopicId);return bp({tokenId:e.tokenId,metadata:t,transactionMemo:e.transactionMemo})},exports.buildHcs6CreateRegistryTx=Y,exports.buildHcs6Hrl=B,exports.buildHcs6RegisterEntryTx=function(e){const t={p:"hcs-6",op:M.REGISTER,t_id:e.targetTopicId,m:e.memo};return J({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})},exports.buildHcs7CreateRegistryTx=Qa,exports.buildHcs7EvmMessageTx=function(e){const t={p:"hcs-7",op:La.REGISTER_CONFIG,t:$a.EVM,c:{contractAddress:e.config.contractAddress,abi:e.config.abi},m:e.config.memo??""};return ec({topicId:e.topicId,message:t,transactionMemo:e.transactionMemo})},exports.buildHcs7SubmitMessageTx=ec,exports.buildHcs7WasmMessageTx=function(e){const t={p:"hcs-7",op:La.REGISTER_CONFIG,t:$a.WASM,c:{wasmTopicId:e.config.wasmTopicId,inputType:e.config.inputType,outputType:e.config.outputType},m:e.config.memo??""};return ec({topicId:e.topicId,message:t,transactionMemo:e.transactionMemo})},exports.canonicalize=Sh,exports.canonicalizeAgentData=Ju,exports.canonicalizeLedgerNetwork=uc,exports.capabilityNameToCapabilityMap=Rd,exports.createLoggerAdapter=ic,exports.createPrivateKeySigner=Bl,exports.createUaid=tp,exports.defaultIssuerRegistry=dp,exports.defaultResolverRegistry=ap,exports.deleteMessageSchema=vp,exports.detectCryptoEnvironment=od,exports.detectKeyTypeFromString=ee,exports.ensureLoggerType=function(e){return oc(e)?e:ic(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=$h,exports.generateHCS6RegistryMemo=j,exports.generateQuote=Ka,exports.getCryptoAdapter=pd,exports.getExampleTopics=function(e){return"mainnet"===e?qu:Hu},exports.getHumanReadableTransactionType=Sa,exports.getOrCreateSDK=Ca,exports.getParserConfig=function(e){return ya[e]},exports.getSchedulableTransactionType=function(e){for(const[t,r]of Object.entries(Ia))if(e[t])return r;return"unknown"},exports.getSupportedTransactionTypes=function(){return Object.keys(ya)},exports.getTopicId=Ua,exports.getTransactionTypeFromBody=Ta,exports.hash=async function(e,t="sha256"){const r=pd().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=Ru,exports.hcs17MessageSchema=Bh,exports.hcs2MessageSchema=Cp,exports.hcs6BaseMessageSchema=L,exports.hcs6MessageSchema=H,exports.hcs6RegisterMessageSchema=$,exports.hcs6TopicIdSchema=U,exports.hcs7MessageSchema=Ya,exports.humanReadableTypeRegistry=wa,exports.inscribe=Fa,exports.inscribeWithSigner=za,exports.isAnnounceMessage=function(e){if(!Xh(e))return!1;const t=e;if("announce"!==t.op)return!1;if(!Gh(t.data))return!1;const r=t.data;if(!Jh(r.account))return!1;if(!Gh(r.petal))return!1;const i=r.petal;return!(!Jh(i.name)||!Yh(i.priority))&&(!!Gh(r.capabilities)&&(!!function(e){return Array.isArray(e)&&e.every(Jh)}(r.capabilities.protocols)&&!("valid_for"in r&&void 0!==r.valid_for&&null!==r.valid_for&&!Yh(r.valid_for))))},exports.isBrowser=Ea,exports.isCompleteMessage=function(e){if(!Xh(e))return!1;const t=e;if("complete"!==t.op)return!1;if(!Gh(t.data))return!1;const r=t.data;if(!Jh(r.proposer))return!1;if(!Yh(r.proposal_seq))return!1;if(!Jh(r.flora_account))return!1;if(!Gh(r.topics))return!1;const i=r.topics;return!!(Jh(i.communication)&&Jh(i.transaction)&&Jh(i.state))},exports.isConcreteLogger=oc,exports.isCryptoAvailable=function(){return"none"!==od().preferredAPI},exports.isDiscoveryMessage=Xh,exports.isEip155Caip10=Id,exports.isHederaCaip10=fd,exports.isHederaNetwork=gd,exports.isPartialRegisterAgentResponse=e=>"partial"===e.status&&!1===e.success,exports.isPendingRegisterAgentResponse=e=>"pending"===e.status,exports.isProposeMessage=function(e){if(!Xh(e))return!1;const t=e;if("propose"!==t.op)return!1;if(!Gh(t.data))return!1;const r=t.data;if(!Jh(r.proposer))return!1;if(!function(e){return Array.isArray(e)}(r.members))return!1;if(!r.members.every(e=>{if(!Gh(e))return!1;const t=e;return!!Jh(t.account)&&(!(!("priority"in t)||!Yh(t.priority))&&!("announce_seq"in t&&void 0!==t.announce_seq&&null!==t.announce_seq&&!Yh(t.announce_seq)))}))return!1;if(!Gh(r.config))return!1;const i=r.config;return!(!Jh(i.name)||!Yh(i.threshold))},exports.isRespondMessage=function(e){if(!Xh(e))return!1;const t=e;if("respond"!==t.op)return!1;if(!Gh(t.data))return!1;const r=t.data;return!!Jh(r.responder)&&(!!Yh(r.proposal_seq)&&(!!Jh(r.decision)&&!!["accept","reject"].includes(r.decision)))},exports.isSSREnvironment=nd,exports.isSuccessRegisterAgentResponse=e=>!0===e.success&&"pending"!==e.status,exports.isTransactionTypeSupported=function(e){return e in ya},exports.isWithdrawMessage=function(e){if(!Xh(e))return!1;const t=e;if("withdraw"!==t.op)return!1;if(!Gh(t.data))return!1;const r=t.data;return!!Jh(r.account)&&(!!Yh(r.announce_seq)&&!("reason"in r&&void 0!==r.reason&&null!==r.reason&&!Jh(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=mh,exports.migrateMessageSchema=Ap,exports.normalizeTransactionId=Ra,exports.parseHCS17Memo=Hh,exports.parseHcs14Did=rp,exports.parseHederaCaip10=bd,exports.protoFieldToTypeRegistry=ba,exports.registerDefaultResolvers=cp,exports.registerMessageSchema=kp,exports.registryMetadataSchema=gh,exports.resolveTransactionSummary=sa,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=Ia,exports.setLoggerFactory=function(e){F=e,O.clearInstances()},exports.shouldUseReference=function(e){return("string"==typeof e?globalThis.Buffer.byteLength(e,"utf8"):e.length)>51200},exports.sleep=z,exports.toEip155Caip10=Td,exports.toHederaCaip10=yd,exports.topicIdSchema=Tp,exports.transactionParserRegistry=ya,exports.transactionSummaryRegistry=na,exports.updateMessageSchema=Ep,exports.validateActionRegistration=Nu,exports.validateAssemblyMessage=_u,exports.validateAssemblyRegistration=function(e){return xu.parse(e)},exports.validateBlockRegistration=function(e){return Su.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&&q(i)},exports.validateHCS6TTL=q,exports.validateHashLinksRegistration=function(e){return Ru.parse(e)},exports.validateWithSchema=Pu,exports.verifyArtifactDigest=function(e,t){const r=y.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=Sh(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=Sh(e),n=globalThis.Buffer.from(t,"base64");return i.PublicKey.fromString(r).verify(globalThis.Buffer.from(o,"utf8"),n)}catch{return!1}},exports.waitForInscriptionConfirmation=Ba;
10
+ !function(e){const t=oe,r=he,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 u(e,t,r)}function u(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 d(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 d(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 u(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 d(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),u=this.slice(i,o),d=e.slice(t,r);for(let n=0;n<c;++n)if(u[n]!==d[n]){s=u[n],a=d[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")}}(ie);const ge=ie.Buffer,me=ie.Buffer,fe=globalThis||self;function ye(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var be,we,Ie={exports:{}},Te=Ie.exports={};function Se(){throw new Error("setTimeout has not been defined")}function ke(){throw new Error("clearTimeout has not been defined")}function Ee(e){if(be===setTimeout)return setTimeout(e,0);if((be===Se||!be)&&setTimeout)return be=setTimeout,setTimeout(e,0);try{return be(e,0)}catch(t){try{return be.call(null,e,0)}catch(r){return be.call(this,e,0)}}}!function(){try{be="function"==typeof setTimeout?setTimeout:Se}catch(e){be=Se}try{we="function"==typeof clearTimeout?clearTimeout:ke}catch(e){we=ke}}();var ve,Ae=[],Ce=!1,xe=-1;function Re(){Ce&&ve&&(Ce=!1,ve.length?Ae=ve.concat(Ae):xe=-1,Ae.length&&Ne())}function Ne(){if(!Ce){var e=Ee(Re);Ce=!0;for(var t=Ae.length;t;){for(ve=Ae,Ae=[];++xe<t;)ve&&ve[xe].run();xe=-1,t=Ae.length}ve=null,Ce=!1,function(e){if(we===clearTimeout)return clearTimeout(e);if((we===ke||!we)&&clearTimeout)return we=clearTimeout,clearTimeout(e);try{return we(e)}catch(t){try{return we.call(null,e)}catch(r){return we.call(this,e)}}}(e)}}function _e(e,t){this.fun=e,this.array=t}function Pe(){}Te.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];Ae.push(new _e(e,t)),1!==Ae.length||Ce||Ee(Ne)},_e.prototype.run=function(){this.fun.apply(null,this.array)},Te.title="browser",Te.browser=!0,Te.env={},Te.argv=[],Te.version="",Te.versions={},Te.on=Pe,Te.addListener=Pe,Te.once=Pe,Te.off=Pe,Te.removeListener=Pe,Te.removeAllListeners=Pe,Te.emit=Pe,Te.prependListener=Pe,Te.prependOnceListener=Pe,Te.listeners=function(e){return[]},Te.binding=function(e){throw new Error("process.binding is not supported")},Te.cwd=function(){return"/"},Te.chdir=function(e){throw new Error("process.chdir is not supported")},Te.umask=function(){return 0};const Fe=ye(Ie.exports);function ze(e,t){return function(){return e.apply(t,arguments)}}const{toString:Oe}=Object.prototype,{getPrototypeOf:De}=Object,{iterator:Me,toStringTag:Be}=Symbol,Ke=(e=>t=>{const r=Oe.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),Ue=e=>(e=e.toLowerCase(),t=>Ke(t)===e),Le=e=>t=>typeof t===e,{isArray:$e}=Array,He=Le("undefined");function qe(e){return null!==e&&!He(e)&&null!==e.constructor&&!He(e.constructor)&&Ve(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const je=Ue("ArrayBuffer");const We=Le("string"),Ve=Le("function"),Ge=Le("number"),Je=e=>null!==e&&"object"==typeof e,Ye=e=>{if("object"!==Ke(e))return!1;const t=De(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Be in e||Me in e)},Xe=Ue("Date"),Ze=Ue("File"),Qe=Ue("Blob"),et=Ue("FileList"),tt=Ue("URLSearchParams"),[rt,it,ot,nt]=["ReadableStream","Request","Response","Headers"].map(Ue);function st(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let i,o;if("object"!=typeof e&&(e=[e]),$e(e))for(i=0,o=e.length;i<o;i++)t.call(null,e[i],i,e);else{if(qe(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 at(e,t){if(qe(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 ct="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:fe,lt=e=>!He(e)&&e!==ct;const ut=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&De(Uint8Array)),dt=Ue("HTMLFormElement"),pt=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),ht=Ue("RegExp"),gt=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),i={};st(r,(r,o)=>{let n;!1!==(n=t(r,o,e))&&(i[o]=n||r)}),Object.defineProperties(e,i)};const mt=Ue("AsyncFunction"),ft=(yt="function"==typeof setImmediate,bt=Ve(ct.postMessage),yt?setImmediate:bt?(wt=`axios@${Math.random()}`,It=[],ct.addEventListener("message",({source:e,data:t})=>{e===ct&&t===wt&&It.length&&It.shift()()},!1),e=>{It.push(e),ct.postMessage(wt,"*")}):e=>setTimeout(e));var yt,bt,wt,It;const Tt="undefined"!=typeof queueMicrotask?queueMicrotask.bind(ct):void 0!==Fe&&Fe.nextTick||ft,St={isArray:$e,isArrayBuffer:je,isBuffer:qe,isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||Ve(e.append)&&("formdata"===(t=Ke(e))||"object"===t&&Ve(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:We,isNumber:Ge,isBoolean:e=>!0===e||!1===e,isObject:Je,isPlainObject:Ye,isEmptyObject:e=>{if(!Je(e)||qe(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(t){return!1}},isReadableStream:rt,isRequest:it,isResponse:ot,isHeaders:nt,isUndefined:He,isDate:Xe,isFile:Ze,isBlob:Qe,isRegExp:ht,isFunction:Ve,isStream:e=>Je(e)&&Ve(e.pipe),isURLSearchParams:tt,isTypedArray:ut,isFileList:et,forEach:st,merge:function e(){const{caseless:t}=lt(this)&&this||{},r={},i=(i,o)=>{const n=t&&at(r,o)||o;Ye(r[n])&&Ye(i)?r[n]=e(r[n],i):Ye(i)?r[n]=e({},i):$e(i)?r[n]=i.slice():r[n]=i};for(let o=0,n=arguments.length;o<n;o++)arguments[o]&&st(arguments[o],i);return r},extend:(e,t,r,{allOwnKeys:i}={})=>(st(t,(t,i)=>{r&&Ve(t)?e[i]=ze(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&&De(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:Ke,kindOfTest:Ue,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($e(e))return e;let t=e.length;if(!Ge(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{const r=(e&&e[Me]).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:dt,hasOwnProperty:pt,hasOwnProp:pt,reduceDescriptors:gt,freezeMethods:e=>{gt(e,(t,r)=>{if(Ve(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const i=e[r];Ve(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 $e(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:at,global:ct,isContextDefined:lt,isSpecCompliantForm:function(e){return!!(e&&Ve(e.append)&&"FormData"===e[Be]&&e[Me])},toJSONObject:e=>{const t=new Array(10),r=(e,i)=>{if(Je(e)){if(t.indexOf(e)>=0)return;if(qe(e))return e;if(!("toJSON"in e)){t[i]=e;const o=$e(e)?[]:{};return st(e,(e,t)=>{const n=r(e,i+1);!He(n)&&(o[t]=n)}),t[i]=void 0,o}}return e};return r(e,0)},isAsyncFn:mt,isThenable:e=>e&&(Je(e)||Ve(e))&&Ve(e.then)&&Ve(e.catch),setImmediate:ft,asap:Tt,isIterable:e=>null!=e&&Ve(e[Me])};function kt(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)}St.inherits(kt,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:St.toJSONObject(this.config),code:this.code,status:this.status}}});const Et=kt.prototype,vt={};["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=>{vt[e]={value:e}}),Object.defineProperties(kt,vt),Object.defineProperty(Et,"isAxiosError",{value:!0}),kt.from=(e,t,r,i,o,n)=>{const s=Object.create(Et);return St.toFlatObject(e,s,function(e){return e!==Error.prototype},e=>"isAxiosError"!==e),kt.call(s,e.message,t,r,i,o),s.cause=e,s.name=e.name,n&&Object.assign(s,n),s};function At(e){return St.isPlainObject(e)||St.isArray(e)}function Ct(e){return St.endsWith(e,"[]")?e.slice(0,-2):e}function xt(e,t,r){return e?e.concat(t).map(function(e,t){return e=Ct(e),!r&&t?"["+e+"]":e}).join(r?".":""):t}const Rt=St.toFlatObject(St,{},null,function(e){return/^is[A-Z]/.test(e)});function Nt(e,t,r){if(!St.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const i=(r=St.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!St.isUndefined(t[e])})).metaTokens,o=r.visitor||l,n=r.dots,s=r.indexes,a=(r.Blob||"undefined"!=typeof Blob&&Blob)&&St.isSpecCompliantForm(t);if(!St.isFunction(o))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(St.isDate(e))return e.toISOString();if(St.isBoolean(e))return e.toString();if(!a&&St.isBlob(e))throw new kt("Blob is not supported. Use a Buffer instead.");return St.isArrayBuffer(e)||St.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):ge.from(e):e}function l(e,r,o){let a=e;if(e&&!o&&"object"==typeof e)if(St.endsWith(r,"{}"))r=i?r:r.slice(0,-2),e=JSON.stringify(e);else if(St.isArray(e)&&function(e){return St.isArray(e)&&!e.some(At)}(e)||(St.isFileList(e)||St.endsWith(r,"[]"))&&(a=St.toArray(e)))return r=Ct(r),a.forEach(function(e,i){!St.isUndefined(e)&&null!==e&&t.append(!0===s?xt([r],i,n):null===s?r:r+"[]",c(e))}),!1;return!!At(e)||(t.append(xt(o,r,n),c(e)),!1)}const u=[],d=Object.assign(Rt,{defaultVisitor:l,convertValue:c,isVisitable:At});if(!St.isObject(e))throw new TypeError("data must be an object");return function e(r,i){if(!St.isUndefined(r)){if(-1!==u.indexOf(r))throw Error("Circular reference detected in "+i.join("."));u.push(r),St.forEach(r,function(r,n){!0===(!(St.isUndefined(r)||null===r)&&o.call(t,r,St.isString(n)?n.trim():n,i,d))&&e(r,i?i.concat(n):[n])}),u.pop()}}(e),t}function _t(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function Pt(e,t){this._pairs=[],e&&Nt(e,this,t)}const Ft=Pt.prototype;function zt(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Ot(e,t,r){if(!t)return e;const i=r&&r.encode||zt;St.isFunction(r)&&(r={serialize:r});const o=r&&r.serialize;let n;if(n=o?o(t,r):St.isURLSearchParams(t)?t.toString():new Pt(t,r).toString(i),n){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+n}return e}Ft.append=function(e,t){this._pairs.push([e,t])},Ft.toString=function(e){const t=e?function(t){return e.call(this,t,_t)}:_t;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};class Dt{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){St.forEach(this.handlers,function(t){null!==t&&e(t)})}}const Mt={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Bt={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:Pt,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},Kt="undefined"!=typeof window&&"undefined"!=typeof document,Ut="object"==typeof navigator&&navigator||void 0,Lt=Kt&&(!Ut||["ReactNative","NativeScript","NS"].indexOf(Ut.product)<0),$t="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,Ht=Kt&&window.location.href||"http://localhost",qt={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Kt,hasStandardBrowserEnv:Lt,hasStandardBrowserWebWorkerEnv:$t,navigator:Ut,origin:Ht},Symbol.toStringTag,{value:"Module"})),...Bt};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&&St.isArray(i)?i.length:n,a)return St.hasOwnProp(i,n)?i[n]=[i[n],r]:i[n]=r,!s;i[n]&&St.isObject(i[n])||(i[n]=[]);return t(e,r,i[n],o)&&St.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(St.isFormData(e)&&St.isFunction(e.entries)){const r={};return St.forEachEntry(e,(e,i)=>{t(function(e){return St.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0])}(e),i,r,0)}),r}return null}const Wt={transitional:Mt,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const r=t.getContentType()||"",i=r.indexOf("application/json")>-1,o=St.isObject(e);o&&St.isHTMLForm(e)&&(e=new FormData(e));if(St.isFormData(e))return i?JSON.stringify(jt(e)):e;if(St.isArrayBuffer(e)||St.isBuffer(e)||St.isStream(e)||St.isFile(e)||St.isBlob(e)||St.isReadableStream(e))return e;if(St.isArrayBufferView(e))return e.buffer;if(St.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 Nt(e,new qt.classes.URLSearchParams,{visitor:function(e,t,r,i){return qt.isNode&&St.isBuffer(e)?(this.append(t,e.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},...t})}(e,this.formSerializer).toString();if((n=St.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return Nt(n?{"files[]":e}:e,t&&new t,this.formSerializer)}}return o||i?(t.setContentType("application/json",!1),function(e,t,r){if(St.isString(e))try{return(t||JSON.parse)(e),St.trim(e)}catch(i){if("SyntaxError"!==i.name)throw i}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||Wt.transitional,r=t&&t.forcedJSONParsing,i="json"===this.responseType;if(St.isResponse(e)||St.isReadableStream(e))return e;if(e&&St.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 kt.from(o,kt.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:qt.classes.FormData,Blob:qt.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};St.forEach(["delete","get","head","post","put","patch"],e=>{Wt.headers[e]={}});const Vt=St.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"]),Gt=Symbol("internals");function Jt(e){return e&&String(e).trim().toLowerCase()}function Yt(e){return!1===e||null==e?e:St.isArray(e)?e.map(Yt):String(e)}function Xt(e,t,r,i,o){return St.isFunction(i)?i.call(this,t,r):(o&&(t=r),St.isString(t)?St.isString(i)?-1!==t.indexOf(i):St.isRegExp(i)?i.test(t):void 0:void 0)}let Zt=class{constructor(e){e&&this.set(e)}set(e,t,r){const i=this;function o(e,t,r){const o=Jt(t);if(!o)throw new Error("header name must be a non-empty string");const n=St.findKey(i,o);(!n||void 0===i[n]||!0===r||void 0===r&&!1!==i[n])&&(i[n||t]=Yt(e))}const n=(e,t)=>St.forEach(e,(e,r)=>o(e,r,t));if(St.isPlainObject(e)||e instanceof this.constructor)n(e,t);else if(St.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]&&Vt[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(St.isObject(e)&&St.isIterable(e)){let r,i,o={};for(const t of e){if(!St.isArray(t))throw TypeError("Object iterator must return a key-value pair");o[i=t[0]]=(r=o[i])?St.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=Jt(e)){const r=St.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(St.isFunction(t))return t.call(this,e,r);if(St.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=Jt(e)){const r=St.findKey(this,e);return!(!r||void 0===this[r]||t&&!Xt(0,this[r],r,t))}return!1}delete(e,t){const r=this;let i=!1;function o(e){if(e=Jt(e)){const o=St.findKey(r,e);!o||t&&!Xt(0,r[o],o,t)||(delete r[o],i=!0)}}return St.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&&!Xt(0,this[o],o,e,!0)||(delete this[o],i=!0)}return i}normalize(e){const t=this,r={};return St.forEach(this,(i,o)=>{const n=St.findKey(r,o);if(n)return t[n]=Yt(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]=Yt(i),r[s]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return St.forEach(this,(r,i)=>{null!=r&&!1!==r&&(t[i]=e&&St.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[Gt]=this[Gt]={accessors:{}}).accessors,r=this.prototype;function i(e){const i=Jt(e);t[i]||(!function(e,t){const r=St.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 St.isArray(e)?e.forEach(i):i(e),this}};function Qt(e,t){const r=this||Wt,i=t||r,o=Zt.from(i.headers);let n=i.data;return St.forEach(e,function(e){n=e.call(r,n,o.normalize(),t?t.status:void 0)}),o.normalize(),n}function er(e){return!(!e||!e.__CANCEL__)}function tr(e,t,r){kt.call(this,null==e?"canceled":e,kt.ERR_CANCELED,t,r),this.name="CanceledError"}function rr(e,t,r){const i=r.config.validateStatus;r.status&&i&&!i(r.status)?t(new kt("Request failed with status code "+r.status,[kt.ERR_BAD_REQUEST,kt.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}Zt.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),St.reduceDescriptors(Zt.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}}),St.freezeMethods(Zt),St.inherits(tr,kt,{__CANCEL__:!0});const ir=(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 u=s,d=0;for(;u!==n;)d+=r[u++],u%=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*d/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)},or=(e,t)=>{const r=null!=e;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},nr=e=>(...t)=>St.asap(()=>e(...t)),sr=qt.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,qt.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(qt.origin),qt.navigator&&/(msie|trident)/i.test(qt.navigator.userAgent)):()=>!0,ar=qt.hasStandardBrowserEnv?{write(e,t,r,i,o,n){const s=[e+"="+encodeURIComponent(t)];St.isNumber(r)&&s.push("expires="+new Date(r).toGMTString()),St.isString(i)&&s.push("path="+i),St.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 cr(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 lr=e=>e instanceof Zt?{...e}:e;function ur(e,t){t=t||{};const r={};function i(e,t,r,i){return St.isPlainObject(e)&&St.isPlainObject(t)?St.merge.call({caseless:i},e,t):St.isPlainObject(t)?St.merge({},t):St.isArray(t)?t.slice():t}function o(e,t,r,o){return St.isUndefined(t)?St.isUndefined(e)?void 0:i(void 0,e,0,o):i(e,t,0,o)}function n(e,t){if(!St.isUndefined(t))return i(void 0,t)}function s(e,t){return St.isUndefined(t)?St.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(lr(e),lr(t),0,!0)};return St.forEach(Object.keys({...e,...t}),function(i){const n=c[i]||o,s=n(e[i],t[i],i);St.isUndefined(s)&&n!==a||(r[i]=s)}),r}const dr=e=>{const t=ur({},e);let r,{data:i,withXSRFToken:o,xsrfHeaderName:n,xsrfCookieName:s,headers:a,auth:c}=t;if(t.headers=a=Zt.from(a),t.url=Ot(cr(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),St.isFormData(i))if(qt.hasStandardBrowserEnv||qt.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(qt.hasStandardBrowserEnv&&(o&&St.isFunction(o)&&(o=o(t)),o||!1!==o&&sr(t.url))){const e=n&&s&&ar.read(s);e&&a.set(n,e)}return t},pr="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise(function(t,r){const i=dr(e);let o=i.data;const n=Zt.from(i.headers).normalize();let s,a,c,l,u,{responseType:d,onUploadProgress:p,onDownloadProgress:h}=i;function g(){l&&l(),u&&u(),i.cancelToken&&i.cancelToken.unsubscribe(s),i.signal&&i.signal.removeEventListener("abort",s)}let m=new XMLHttpRequest;function f(){if(!m)return;const i=Zt.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders());rr(function(e){t(e),g()},function(e){r(e),g()},{data:d&&"text"!==d&&"json"!==d?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 kt("Request aborted",kt.ECONNABORTED,e,m)),m=null)},m.onerror=function(){r(new kt("Network Error",kt.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||Mt;i.timeoutErrorMessage&&(t=i.timeoutErrorMessage),r(new kt(t,o.clarifyTimeoutError?kt.ETIMEDOUT:kt.ECONNABORTED,e,m)),m=null},void 0===o&&n.setContentType(null),"setRequestHeader"in m&&St.forEach(n.toJSON(),function(e,t){m.setRequestHeader(t,e)}),St.isUndefined(i.withCredentials)||(m.withCredentials=!!i.withCredentials),d&&"json"!==d&&(m.responseType=i.responseType),h&&([c,u]=ir(h,!0),m.addEventListener("progress",c)),p&&m.upload&&([a,l]=ir(p),m.upload.addEventListener("progress",a),m.upload.addEventListener("loadend",l)),(i.cancelToken||i.signal)&&(s=t=>{m&&(r(!t||t.type?new tr(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===qt.protocols.indexOf(y)?r(new kt("Unsupported protocol "+y+":",kt.ERR_BAD_REQUEST,e)):m.send(o||null)})},hr=(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 kt?t:new tr(t instanceof Error?t.message:t))}};let n=t&&setTimeout(()=>{n=null,o(new kt(`timeout ${t} of ms exceeded`,kt.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=()=>St.asap(s),a}},gr=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},mr=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()}},fr=(e,t,r,i)=>{const o=async function*(e,t){for await(const r of mr(e))yield*gr(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})},yr="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,br=yr&&"function"==typeof ReadableStream,wr=yr&&("function"==typeof TextEncoder?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),Ir=(e,...t)=>{try{return!!e(...t)}catch(r){return!1}},Tr=br&&Ir(()=>{let e=!1;const t=new Request(qt.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),Sr=br&&Ir(()=>St.isReadableStream(new Response("").body)),kr={stream:Sr&&(e=>e.body)};var Er;yr&&(Er=new Response,["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!kr[e]&&(kr[e]=St.isFunction(Er[e])?t=>t[e]():(t,r)=>{throw new kt(`Response type '${e}' is not supported`,kt.ERR_NOT_SUPPORT,r)})}));const vr=async(e,t)=>{const r=St.toFiniteNumber(e.getContentLength());return null==r?(async e=>{if(null==e)return 0;if(St.isBlob(e))return e.size;if(St.isSpecCompliantForm(e)){const t=new Request(qt.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return St.isArrayBufferView(e)||St.isArrayBuffer(e)?e.byteLength:(St.isURLSearchParams(e)&&(e+=""),St.isString(e)?(await wr(e)).byteLength:void 0)})(t):r},Ar={http:null,xhr:pr,fetch:yr&&(async e=>{let{url:t,method:r,data:i,signal:o,cancelToken:n,timeout:s,onDownloadProgress:a,onUploadProgress:c,responseType:l,headers:u,withCredentials:d="same-origin",fetchOptions:p}=dr(e);l=l?(l+"").toLowerCase():"text";let h,g=hr([o,n&&n.toAbortSignal()],s);const m=g&&g.unsubscribe&&(()=>{g.unsubscribe()});let f;try{if(c&&Tr&&"get"!==r&&"head"!==r&&0!==(f=await vr(u,i))){let e,r=new Request(t,{method:"POST",body:i,duplex:"half"});if(St.isFormData(i)&&(e=r.headers.get("content-type"))&&u.setContentType(e),r.body){const[e,t]=or(f,ir(nr(c)));i=fr(r.body,65536,e,t)}}St.isString(d)||(d=d?"include":"omit");const o="credentials"in Request.prototype;h=new Request(t,{...p,signal:g,method:r.toUpperCase(),headers:u.normalize().toJSON(),body:i,duplex:"half",credentials:o?d:void 0});let n=await fetch(h,p);const s=Sr&&("stream"===l||"response"===l);if(Sr&&(a||s&&m)){const e={};["status","statusText","headers"].forEach(t=>{e[t]=n[t]});const t=St.toFiniteNumber(n.headers.get("content-length")),[r,i]=a&&or(t,ir(nr(a),!0))||[];n=new Response(fr(n.body,65536,r,()=>{i&&i(),m&&m()}),e)}l=l||"text";let y=await kr[St.findKey(kr,l)||"text"](n,e);return!s&&m&&m(),await new Promise((t,r)=>{rr(t,r,{data:y,headers:Zt.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 kt("Network Error",kt.ERR_NETWORK,e,h),{cause:y.cause||y});throw kt.from(y,y&&y.code,e,h)}})};St.forEach(Ar,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(r){}Object.defineProperty(e,"adapterName",{value:t})}});const Cr=e=>`- ${e}`,xr=e=>St.isFunction(e)||null===e||!1===e,Rr=e=>{e=St.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,!xr(r)&&(i=Ar[(t=String(r)).toLowerCase()],void 0===i))throw new kt(`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 kt("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(Cr).join("\n"):" "+Cr(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return i};function Nr(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new tr(null,e)}function _r(e){Nr(e),e.headers=Zt.from(e.headers),e.data=Qt.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return Rr(e.adapter||Wt.adapter)(e).then(function(t){return Nr(e),t.data=Qt.call(e,e.transformResponse,t),t.headers=Zt.from(t.headers),t},function(t){return er(t)||(Nr(e),t&&t.response&&(t.response.data=Qt.call(e,e.transformResponse,t.response),t.response.headers=Zt.from(t.response.headers))),Promise.reject(t)})}const Pr="1.11.0",Fr={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Fr[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const zr={};Fr.transitional=function(e,t,r){function i(e,t){return"[Axios v"+Pr+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,o,n)=>{if(!1===e)throw new kt(i(o," has been removed"+(t?" in "+t:"")),kt.ERR_DEPRECATED);return t&&!zr[o]&&(zr[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)}},Fr.spelling=function(e){return(t,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};const Or={assertOptions:function(e,t,r){if("object"!=typeof e)throw new kt("options must be an object",kt.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 kt("option "+n+" must be "+r,kt.ERR_BAD_OPTION_VALUE);continue}if(!0!==r)throw new kt("Unknown option "+n,kt.ERR_BAD_OPTION)}},validators:Fr},Dr=Or.validators;let Mr=class{constructor(e){this.defaults=e||{},this.interceptors={request:new Dt,response:new Dt}}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=ur(this.defaults,t);const{transitional:r,paramsSerializer:i,headers:o}=t;void 0!==r&&Or.assertOptions(r,{silentJSONParsing:Dr.transitional(Dr.boolean),forcedJSONParsing:Dr.transitional(Dr.boolean),clarifyTimeoutError:Dr.transitional(Dr.boolean)},!1),null!=i&&(St.isFunction(i)?t.paramsSerializer={serialize:i}:Or.assertOptions(i,{encode:Dr.function,serialize:Dr.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Or.assertOptions(t,{baseUrl:Dr.spelling("baseURL"),withXsrfToken:Dr.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let n=o&&St.merge(o.common,o[t.method]);o&&St.forEach(["delete","get","head","post","put","patch","common"],e=>{delete o[e]}),t.headers=Zt.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 u,d=0;if(!a){const e=[_r.bind(this),void 0];for(e.unshift(...s),e.push(...c),u=e.length,l=Promise.resolve(t);d<u;)l=l.then(e[d++],e[d++]);return l}u=s.length;let p=t;for(d=0;d<u;){const e=s[d++],t=s[d++];try{p=e(p)}catch(h){t.call(this,h);break}}try{l=_r.call(this,p)}catch(h){return Promise.reject(h)}for(d=0,u=c.length;d<u;)l=l.then(c[d++],c[d++]);return l}getUri(e){return Ot(cr((e=ur(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};St.forEach(["delete","get","head","options"],function(e){Mr.prototype[e]=function(t,r){return this.request(ur(r||{},{method:e,url:t,data:(r||{}).data}))}}),St.forEach(["post","put","patch"],function(e){function t(t){return function(r,i,o){return this.request(ur(o||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:i}))}}Mr.prototype[e]=t(),Mr.prototype[e+"Form"]=t(!0)});const Br={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(Br).forEach(([e,t])=>{Br[t]=e});const Kr=function e(t){const r=new Mr(t),i=ze(Mr.prototype.request,r);return St.extend(i,Mr.prototype,r,{allOwnKeys:!0}),St.extend(i,r,null,{allOwnKeys:!0}),i.create=function(r){return e(ur(t,r))},i}(Wt);Kr.Axios=Mr,Kr.CanceledError=tr,Kr.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 tr(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}}},Kr.isCancel=er,Kr.VERSION=Pr,Kr.toFormData=Nt,Kr.AxiosError=kt,Kr.Cancel=Kr.CanceledError,Kr.all=function(e){return Promise.all(e)},Kr.spread=function(e){return function(t){return e.apply(null,t)}},Kr.isAxiosError=function(e){return St.isObject(e)&&!0===e.isAxiosError},Kr.mergeConfig=ur,Kr.AxiosHeaders=Zt,Kr.formToJSON=e=>jt(St.isHTMLForm(e)?new FormData(e):e),Kr.getAdapter=Rr,Kr.HttpStatusCode=Br,Kr.default=Kr;const{Axios:Ur,AxiosError:Lr,CanceledError:$r,isCancel:Hr,CancelToken:qr,VERSION:jr,all:Wr,Cancel:Vr,isAxiosError:Gr,spread:Jr,toFormData:Yr,AxiosHeaders:Xr,HttpStatusCode:Zr,formToJSON:Qr,getAdapter:ei,mergeConfig:ti}=Kr,ri=class e{constructor(){re(this,"isProduction"),this.isProduction="production"===Fe.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)}};re(ri,"instance");let ii=ri;class oi extends Error{constructor(e){super(e),this.name="ValidationError"}}class ni{constructor(e){if(re(this,"accountId"),re(this,"privateKey"),re(this,"baseUrl"),re(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 Kr.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 Kr.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 me.from(r).toString("hex")}}class si{constructor(e){re(this,"accountId"),re(this,"signer"),re(this,"baseUrl"),re(this,"network"),re(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 Kr.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 Kr.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 me.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 ai(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function ci(e){return new DataView(e.buffer,e.byteOffset)}const li={len:1,get:(e,t)=>ci(e).getUint8(t),put:(e,t,r)=>(ci(e).setUint8(t,r),t+1)},ui={len:2,get:(e,t)=>ci(e).getUint16(t,!0),put:(e,t,r)=>(ci(e).setUint16(t,r,!0),t+2)},di={len:2,get:(e,t)=>ci(e).getUint16(t),put:(e,t,r)=>(ci(e).setUint16(t,r),t+2)},pi={len:4,get:(e,t)=>ci(e).getUint32(t,!0),put:(e,t,r)=>(ci(e).setUint32(t,r,!0),t+4)},hi={len:4,get:(e,t)=>ci(e).getUint32(t),put:(e,t,r)=>(ci(e).setUint32(t,r),t+4)},gi={len:4,get:(e,t)=>ci(e).getInt32(t),put:(e,t,r)=>(ci(e).setInt32(t,r),t+4)},mi={len:8,get:(e,t)=>ci(e).getBigUint64(t,!0),put:(e,t,r)=>(ci(e).setBigUint64(t,r,!0),t+8)};class fi{constructor(e,t){if(this.len=e,t&&"windows-1252"===t.toLowerCase())this.decoder=fi.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):fi.win1252Map[i-128]}return t}}fi.win1252Map="€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ";class yi extends Error{constructor(){super("End-Of-Stream"),this.name="EndOfStreamError"}}class bi extends Error{constructor(e="The operation was aborted"){super(e),this.name="AbortError"}}class wi{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 yi;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 bi;const i=await this.readFromStream(e.subarray(r),t);if(0===i)break;r+=i}if(!t&&r<e.length)throw new yi;return r}}class Ii extends wi{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}}class Ti extends Ii{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 Si extends wi{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 yi;return r}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}}class ki{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 yi;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 yi;return e.get(r,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new yi;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new yi;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 Ei extends ki{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 yi;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 yi)return 0;throw o}if(!r.mayBeLess&&i<r.length)throw new yi}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 vi extends ki{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 yi;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 Ai(e,t){const r=function(e){try{const t=e.getReader({mode:"byob"});return t instanceof ReadableStreamDefaultReader?new Si(t):new Ti(t)}catch(t){if(t instanceof TypeError)return new Si(e.getReader());throw t}}(e),i=t??{},o=i.onClose;return i.onClose=async()=>{if(await r.close(),o)return o()},new Ei(r,i)}var Ci=Uint8Array,xi=Uint16Array,Ri=Int32Array,Ni=new Ci([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]),_i=new Ci([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]),Pi=new Ci([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Fi=function(e,t){for(var r=new xi(31),i=0;i<31;++i)r[i]=t+=1<<e[i-1];var o=new Ri(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}},zi=Fi(Ni,2),Oi=zi.b,Di=zi.r;Oi[28]=258,Di[258]=28;for(var Mi=Fi(_i,0).b,Bi=new xi(32768),Ki=0;Ki<32768;++Ki){var Ui=(43690&Ki)>>1|(21845&Ki)<<1;Ui=(61680&(Ui=(52428&Ui)>>2|(13107&Ui)<<2))>>4|(3855&Ui)<<4,Bi[Ki]=((65280&Ui)>>8|(255&Ui)<<8)>>1}var Li=function(e,t,r){for(var i=e.length,o=0,n=new xi(t);o<i;++o)e[o]&&++n[e[o]-1];var s,a=new xi(t);for(o=1;o<t;++o)a[o]=a[o-1]+n[o-1]<<1;s=new xi(1<<t);var c=15-t;for(o=0;o<i;++o)if(e[o])for(var l=o<<4|e[o],u=t-e[o],d=a[e[o]-1]++<<u,p=d|(1<<u)-1;d<=p;++d)s[Bi[d]>>c]=l;return s},$i=new Ci(288);for(Ki=0;Ki<144;++Ki)$i[Ki]=8;for(Ki=144;Ki<256;++Ki)$i[Ki]=9;for(Ki=256;Ki<280;++Ki)$i[Ki]=7;for(Ki=280;Ki<288;++Ki)$i[Ki]=8;var Hi=new Ci(32);for(Ki=0;Ki<32;++Ki)Hi[Ki]=5;var qi=Li($i,9),ji=Li(Hi,5),Wi=function(e){for(var t=e[0],r=1;r<e.length;++r)e[r]>t&&(t=e[r]);return t},Vi=function(e,t,r){var i=t/8|0;return(e[i]|e[i+1]<<8)>>(7&t)&r},Gi=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(7&t)},Ji=function(e){return(e+7)/8|0},Yi=["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"],Xi=function(e,t,r){var i=new Error(t||Yi[e]);if(i.code=e,Error.captureStackTrace&&Error.captureStackTrace(i,Xi),!r)throw i;return i},Zi=function(e,t,r,i){var o=e.length;if(!o||t.f&&!t.l)return r||new Ci(0);var n=!r,s=n||2!=t.i,a=t.i;n&&(r=new Ci(3*o));var c=function(e){var t=r.length;if(e>t){var i=new Ci(Math.max(2*t,e));i.set(r),r=i}},l=t.f||0,u=t.p||0,d=t.b||0,p=t.l,h=t.d,g=t.m,m=t.n,f=8*o;do{if(!p){l=Vi(e,u,1);var y=Vi(e,u+1,3);if(u+=3,!y){var b=e[(R=Ji(u)+4)-4]|e[R-3]<<8,w=R+b;if(w>o){a&&Xi(0);break}s&&c(d+b),r.set(e.subarray(R,w),d),t.b=d+=b,t.p=u=8*w,t.f=l;continue}if(1==y)p=qi,h=ji,g=9,m=5;else if(2==y){var I=Vi(e,u,31)+257,T=Vi(e,u+10,15)+4,S=I+Vi(e,u+5,31)+1;u+=14;for(var k=new Ci(S),E=new Ci(19),v=0;v<T;++v)E[Pi[v]]=Vi(e,u+3*v,7);u+=3*T;var A=Wi(E),C=(1<<A)-1,x=Li(E,A);for(v=0;v<S;){var R,N=x[Vi(e,u,C)];if(u+=15&N,(R=N>>4)<16)k[v++]=R;else{var _=0,P=0;for(16==R?(P=3+Vi(e,u,3),u+=2,_=k[v-1]):17==R?(P=3+Vi(e,u,7),u+=3):18==R&&(P=11+Vi(e,u,127),u+=7);P--;)k[v++]=_}}var F=k.subarray(0,I),z=k.subarray(I);g=Wi(F),m=Wi(z),p=Li(F,g),h=Li(z,m)}else Xi(1);if(u>f){a&&Xi(0);break}}s&&c(d+131072);for(var O=(1<<g)-1,D=(1<<m)-1,M=u;;M=u){var B=(_=p[Gi(e,u)&O])>>4;if((u+=15&_)>f){a&&Xi(0);break}if(_||Xi(2),B<256)r[d++]=B;else{if(256==B){M=u,p=null;break}var K=B-254;if(B>264){var U=Ni[v=B-257];K=Vi(e,u,(1<<U)-1)+Oi[v],u+=U}var L=h[Gi(e,u)&D],$=L>>4;L||Xi(3),u+=15&L;z=Mi[$];if($>3){U=_i[$];z+=Gi(e,u)&(1<<U)-1,u+=U}if(u>f){a&&Xi(0);break}s&&c(d+131072);var H=d+K;if(d<z){var q=0-z,j=Math.min(z,H);for(q+d<0&&Xi(3);d<j;++d)r[d]=i[q+d]}for(;d<H;++d)r[d]=r[d-z]}}t.l=p,t.p=M,t.b=d,t.f=l,p&&(l=1,t.m=g,t.d=h,t.n=m)}while(!l);return d!=r.length&&n?function(e,t,r){return(null==r||r>e.length)&&(r=e.length),new Ci(e.subarray(t,r))}(r,0,d):r.subarray(0,d)},Qi=new Ci(0);function eo(e,t){var r,i,o=function(e){31==e[0]&&139==e[1]&&8==e[2]||Xi(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&&Xi(6,"invalid gzip data"),Zi(e.subarray(o,-8),{i:2},new Ci((i=(r=e).length,(r[i-4]|r[i-3]<<8|r[i-2]<<16|r[i-1]<<24)>>>0)),t)}function to(e,t){return Zi(e.subarray(((8!=(15&(r=e)[0])||r[0]>>4>7||(r[0]<<8|r[1])%31)&&Xi(6,"invalid zlib data"),1==(r[1]>>5&1)&&Xi(6,"invalid zlib data: "+(32&r[1]?"need":"unexpected")+" dictionary"),2+(r[1]>>3&4)),-4),{i:2},t,t);var r}function ro(e,t){return 31==e[0]&&139==e[1]&&8==e[2]?eo(e,t):8!=(15&e[0])||e[0]>>4>7||(e[0]<<8|e[1])%31?function(e,t){return Zi(e,{i:2},t,t)}(e,t):to(e,t)}var io="undefined"!=typeof TextDecoder&&new TextDecoder;try{io.decode(Qi,{stream:!0})}catch(Kg){}var oo,no,so,ao,co,lo={exports:{}};function uo(){if(no)return oo;no=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 oo=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 po=(co||(co=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!==Fe&&"env"in Fe&&(e=Fe.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=(ao||(ao=1,so=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=uo(),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}),so)(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}(lo,lo.exports)),lo.exports);const ho=ai(po),go=67324752,mo=134695760,fo=33639248,yo=101010256,bo={get:e=>(ui.get(e,6),{signature:pi.get(e,0),compressedSize:pi.get(e,8),uncompressedSize:pi.get(e,12)}),len:16},wo={get(e){const t=ui.get(e,6);return{signature:pi.get(e,0),minVersion:ui.get(e,4),dataDescriptor:!!(8&t),compressedMethod:ui.get(e,8),compressedSize:pi.get(e,18),uncompressedSize:pi.get(e,22),filenameLength:ui.get(e,26),extraFieldLength:ui.get(e,28),filename:null}},len:30},Io={get:e=>({signature:pi.get(e,0),nrOfThisDisk:ui.get(e,4),nrOfThisDiskWithTheStart:ui.get(e,6),nrOfEntriesOnThisDisk:ui.get(e,8),nrOfEntriesOfSize:ui.get(e,10),sizeOfCd:pi.get(e,12),offsetOfStartOfCd:pi.get(e,16),zipFileCommentLength:ui.get(e,20)}),len:22},To={get(e){const t=ui.get(e,8);return{signature:pi.get(e,0),minVersion:ui.get(e,6),dataDescriptor:!!(8&t),compressedMethod:ui.get(e,10),compressedSize:pi.get(e,20),uncompressedSize:pi.get(e,24),filenameLength:ui.get(e,28),extraFieldLength:ui.get(e,30),fileCommentLength:ui.get(e,32),relativeOffsetOfLocalHeader:pi.get(e,42),filename:null}},len:46};function So(e){const t=new Uint8Array(pi.len);return pi.put(t,0,e),t}const ko=ho("tokenizer:inflate"),Eo=262144,vo=So(mo),Ao=So(yo);class Co{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(Eo)}async isZip(){return await this.peekSignature()===go}peekSignature(){return this.tokenizer.peekToken(pi)}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]===Ao[0]&&r[i+1]===Ao[1]&&r[i+2]===Ao[2]&&r[i+3]===Ao[3])return e.fileInfo.size-t+i;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess())return void ko("Cannot reading central-directory without random-read support");ko("Reading central-directory...");const e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){ko("Central-directory 32-bit signature found");const r=await this.tokenizer.readToken(Io,t),i=[];this.tokenizer.setPosition(r.offsetOfStartOfCd);for(let e=0;e<r.nrOfEntriesOfSize;++e){const t=await this.tokenizer.readToken(To);if(t.signature!==fo)throw new Error("Expected Central-File-Header signature");t.filename=await this.tokenizer.readToken(new fi(t.filenameLength,"utf-8")),await this.tokenizer.ignore(t.extraFieldLength),await this.tokenizer.ignore(t.fileCommentLength),i.push(t),ko(`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=Eo;ko("Compressed-file-size unknown, scanning for next data-descriptor-signature....");let o=-1;for(;o<0&&r===Eo;){r=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),o=xo(this.syncBuffer.subarray(0,r),vo);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)}ko(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),i.handler&&await this.inflate(t,Ro(e),i.handler)}else i.handler?(ko(`Reading compressed-file-data: ${t.compressedSize} bytes`),o=new Uint8Array(t.compressedSize),await this.tokenizer.readBuffer(o),await this.inflate(t,o,i.handler)):(ko(`Ignoring compressed-file-data: ${t.compressedSize} bytes`),await this.tokenizer.ignore(t.compressedSize));if(ko(`Reading data-descriptor at pos=${this.tokenizer.position}`),t.dataDescriptor){if(134695760!==(await this.tokenizer.readToken(bo)).signature)throw new Error("Expected data-descriptor-signature at position "+(this.tokenizer.position-bo.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);ko(`Decompress filename=${e.filename}, compressed-size=${t.length}`);return r(ro(t))}async readLocalFileHeader(){const e=await this.tokenizer.peekToken(pi);if(e===go){const e=await this.tokenizer.readToken(wo);return e.filename=await this.tokenizer.readToken(new fi(e.filenameLength,"utf-8")),e}if(e===fo)return!1;if(3759263696===e)throw new Error("Encrypted ZIP");throw new Error("Unexpected signature")}}function xo(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 Ro(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 No(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 _o={get:(e,t)=>127&e[t+3]|e[t+2]<<7|e[t+1]<<14|e[t]<<21,len:4},Po=4100;function Fo(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 zo(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 Oo{constructor(e){re(this,"detectConfident",async e=>{if(this.buffer=new Uint8Array(Po),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(_o);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 Co(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=Fo(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=Fo(e))}else{t=t.slice(0,Math.max(0,i));const e=t.lastIndexOf('"'),o=t.slice(Math.max(0,e+1));r=Fo(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),zo(i,[79,112,117,115,72,101,97,100])?{ext:"opus",mime:"audio/ogg; codecs=opus"}:zo(i,[128,116,104,101,111,114,97])?{ext:"ogv",mime:"video/ogg"}:zo(i,[1,118,105,100,101,111,0])?{ext:"ogm",mime:"video/ogg"}:zo(i,[127,70,76,65,67])?{ext:"oga",mime:"audio/ogg"}:zo(i,[83,112,101,101,120,32,32])?{ext:"spx",mime:"audio/ogg"}:zo(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(li);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:No(i),len:No(o)}}async function c(t){for(;t>0;){const r=await a();if(17026===r.id){return(await e.readToken(new fi(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 u=new fi(4,"latin1").get(this.buffer,2);if(u.match("^d*")&&u>=1e3&&u<=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 fi(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 d(){return{length:await e.readToken(gi),type:await e.readToken(new fi(4,"latin1"))}}await e.ignore(8);do{const p=await d();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 fi(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(mi))}}for(await e.ignore(30);e.position+24<e.fileInfo.size;){const m=await g();let f=m.size-24;if(zo(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),zo(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(zo(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 fi(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 fi(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)}),re(this,"detectImprecise",async e=>{if(this.buffer=new Uint8Array(Po),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 vi(r,i)))}async fromBlob(e){return this.fromStream(e.stream())}async fromStream(e){const t=await Ai(e,this.tokenizerOptions);try{return await this.fromTokenizer(t)}finally{await t.close()}}async toDetectionStream(e,t){const{sampleSize:r=Po}=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 yi))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 zo(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?di:ui);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?di:ui);for(let r=0;r<t;++r){const t=await this.readTiffTag(e);if(t)return t}}async readTiffHeader(e){const t=(e?di:ui).get(this.buffer,2),r=(e?hi:pi).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?di:ui).get(this.buffer,8),r=(e?di:ui).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 Do=Object.create(null);Do.open="0",Do.close="1",Do.ping="2",Do.pong="3",Do.message="4",Do.upgrade="5",Do.noop="6";const Mo=Object.create(null);Object.keys(Do).forEach(e=>{Mo[Do[e]]=e});const Bo={type:"error",data:"parser error"},Ko="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),Uo="function"==typeof ArrayBuffer,Lo=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,$o=({type:e,data:t},r,i)=>Ko&&t instanceof Blob?r?i(t):Ho(t,i):Uo&&(t instanceof ArrayBuffer||Lo(t))?r?i(t):Ho(new Blob([t]),i):i(Do[e]+(t||"")),Ho=(e,t)=>{const r=new FileReader;return r.onload=function(){const e=r.result.split(",")[1];t("b"+(e||""))},r.readAsDataURL(e)};function qo(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let jo;const Wo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Vo="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let Lg=0;Lg<64;Lg++)Vo[Wo.charCodeAt(Lg)]=Lg;const Go="function"==typeof ArrayBuffer,Jo=(e,t)=>{if("string"!=typeof e)return{type:"message",data:Xo(e,t)};const r=e.charAt(0);if("b"===r)return{type:"message",data:Yo(e.substring(1),t)};return Mo[r]?e.length>1?{type:Mo[r],data:e.substring(1)}:{type:Mo[r]}:Bo},Yo=(e,t)=>{if(Go){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),u=new Uint8Array(l);for(t=0;t<a;t+=4)r=Vo[e.charCodeAt(t)],i=Vo[e.charCodeAt(t+1)],o=Vo[e.charCodeAt(t+2)],n=Vo[e.charCodeAt(t+3)],u[c++]=r<<2|i>>4,u[c++]=(15&i)<<4|o>>2,u[c++]=(3&o)<<6|63&n;return l})(e);return Xo(r,t)}return{base64:!0,data:e}},Xo=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,Zo=String.fromCharCode(30);function Qo(){return new TransformStream({transform(e,t){!function(e,t){Ko&&e.data instanceof Blob?e.data.arrayBuffer().then(qo).then(t):Uo&&(e.data instanceof ArrayBuffer||Lo(e.data))?t(qo(e.data)):$o(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 en;function tn(e){return e.reduce((e,t)=>e+t.length,0)}function rn(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 on(e){if(e)return function(e){for(var t in on.prototype)e[t]=on.prototype[t];return e}(e)}on.prototype.on=on.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},on.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},on.prototype.off=on.prototype.removeListener=on.prototype.removeAllListeners=on.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},on.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},on.prototype.emitReserved=on.prototype.emit,on.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},on.prototype.hasListeners=function(e){return!!this.listeners(e).length};const nn="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),sn="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function an(e,...t){return t.reduce((t,r)=>(e.hasOwnProperty(r)&&(t[r]=e[r]),t),{})}const cn=sn.setTimeout,ln=sn.clearTimeout;function un(e,t){t.useNativeTimers?(e.setTimeoutFn=cn.bind(sn),e.clearTimeoutFn=ln.bind(sn)):(e.setTimeoutFn=sn.setTimeout.bind(sn),e.clearTimeoutFn=sn.clearTimeout.bind(sn))}function dn(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 pn(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class hn extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}}class gn extends on{constructor(e){super(),this.writable=!1,un(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 hn(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=Jo(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 mn extends gn{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(Zo),i=[];for(let o=0;o<r.length;o++){const e=Jo(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)=>{$o(e,!1,e=>{i[n]=e,++o===r&&t(i.join(Zo))})})})(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]=pn()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let fn=!1;try{fn="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(Ug){}const yn=fn;function bn(){}class wn extends mn{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 In=class e extends on{constructor(e,t,r){super(),this.createRequest=e,un(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=an(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(Kg){}if("POST"===this._method)try{i.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(Kg){}try{i.setRequestHeader("Accept","*/*")}catch(Kg){}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(Kg){return void this.setTimeoutFn(()=>{this._onError(Kg)},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=bn,t)try{this._xhr.abort()}catch(Kg){}"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(In.requestsCount=0,In.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",Tn);else if("function"==typeof addEventListener){addEventListener("onpagehide"in sn?"pagehide":"unload",Tn,!1)}function Tn(){for(let e in In.requests)In.requests.hasOwnProperty(e)&&In.requests[e].abort()}const Sn=function(){const e=kn({xdomain:!1});return e&&null!==e.responseType}();function kn(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||yn))return new XMLHttpRequest}catch(Kg){}if(!t)try{return new(sn[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(Kg){}}const En="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class vn extends gn{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,r=En?{}:an(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(Ug){return this.emitReserved("error",Ug)}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;$o(r,this.supportsBinary,e=>{try{this.doWrite(r,e)}catch(Kg){}i&&nn(()=>{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]=pn()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const An=sn.WebSocket||sn.MozWebSocket;const Cn={websocket:class extends vn{createSocket(e,t,r){return En?new An(e,t,r):t?new An(e,t):new An(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends gn{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(Ug){return this.emitReserved("error",Ug)}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){en||(en=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(tn(r)<1)break;const e=rn(r,1);n=!(128&~e[0]),o=127&e[0],i=o<126?3:126===o?1:2}else if(1===i){if(tn(r)<2)break;const e=rn(r,2);o=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),i=3}else if(2===i){if(tn(r)<8)break;const e=rn(r,8),t=new DataView(e.buffer,e.byteOffset,e.length),n=t.getUint32(0);if(n>Math.pow(2,21)-1){a.enqueue(Bo);break}o=n*Math.pow(2,32)+t.getUint32(4),i=3}else{if(tn(r)<o)break;const e=rn(r,o);a.enqueue(Jo(n?e:en.decode(e),t)),i=0}if(0===o||o>e){a.enqueue(Bo);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),i=Qo();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&&nn(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this._transport)||void 0===e||e.close()}},polling:class extends wn{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=Sn&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new In(kn,this.uri(),e)}}},xn=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Rn=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Nn(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=xn.exec(e||""),n={},s=14;for(;s--;)n[Rn[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 _n="function"==typeof addEventListener&&"function"==typeof removeEventListener,Pn=[];_n&&addEventListener("offline",()=>{Pn.forEach(e=>e())},!1);class Fn extends on{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=Nn(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=Nn(t.host).host);un(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)),_n&&(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"})},Pn.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&&Fn.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",Fn.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+=dn(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,nn(()=>{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(Fn.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(),_n&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const e=Pn.indexOf(this._offlineEventListener);-1!==e&&Pn.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}Fn.protocol=4;class zn extends Fn{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;Fn.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;Fn.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 On=class extends zn{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=>Cn[e]).filter(e=>!!e)),super(e,r)}};const Dn="function"==typeof ArrayBuffer,Mn=Object.prototype.toString,Bn="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Mn.call(Blob),Kn="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Mn.call(File);function Un(e){return Dn&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||Bn&&e instanceof Blob||Kn&&e instanceof File}function Ln(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if(Ln(e[t]))return!0;return!1}if(Un(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return Ln(e.toJSON(),!0);for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&Ln(e[r]))return!0;return!1}function $n(e){const t=[],r=e.data,i=e;return i.data=Hn(r,t),i.attachments=t.length,{packet:i,buffers:t}}function Hn(e,t){if(!e)return e;if(Un(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]=Hn(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]=Hn(e[i],t));return r}return e}function qn(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 Wn=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Vn,Gn;(Gn=Vn||(Vn={}))[Gn.CONNECT=0]="CONNECT",Gn[Gn.DISCONNECT=1]="DISCONNECT",Gn[Gn.EVENT=2]="EVENT",Gn[Gn.ACK=3]="ACK",Gn[Gn.CONNECT_ERROR=4]="CONNECT_ERROR",Gn[Gn.BINARY_EVENT=5]="BINARY_EVENT",Gn[Gn.BINARY_ACK=6]="BINARY_ACK";function Jn(e){return"[object Object]"===Object.prototype.toString.call(e)}class Yn extends on{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===Vn.BINARY_EVENT;r||t.type===Vn.BINARY_ACK?(t.type=r?Vn.EVENT:Vn.ACK,this.reconstructor=new Xn(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!Un(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===Vn[r.type])throw new Error("unknown packet type "+r.type);if(r.type===Vn.BINARY_EVENT||r.type===Vn.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(!Yn.isPayloadValid(r.type,i))throw new Error("invalid payload");r.data=i}return r}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(Kg){return!1}}static isPayloadValid(e,t){switch(e){case Vn.CONNECT:return Jn(t);case Vn.DISCONNECT:return void 0===t;case Vn.CONNECT_ERROR:return"string"==typeof t||Jn(t);case Vn.EVENT:case Vn.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===Wn.indexOf(t[0]));case Vn.ACK:case Vn.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Xn{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=qn(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Zn=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Yn,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==Vn.EVENT&&e.type!==Vn.ACK||!Ln(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===Vn.EVENT?Vn.BINARY_EVENT:Vn.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==Vn.BINARY_EVENT&&e.type!==Vn.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=$n(e),r=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(r),i}},get PacketType(){return Vn},protocol:5},Symbol.toStringTag,{value:"Module"}));function Qn(e,t,r){return e.on(t,r),function(){e.off(t,r)}}const es=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class ts extends on{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=[Qn(e,"open",this.onopen.bind(this)),Qn(e,"packet",this.onpacket.bind(this)),Qn(e,"error",this.onerror.bind(this)),Qn(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(es.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:Vn.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:Vn.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 Vn.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 Vn.EVENT:case Vn.BINARY_EVENT:this.onevent(e);break;case Vn.ACK:case Vn.BINARY_ACK:this.onack(e);break;case Vn.DISCONNECT:this.ondisconnect();break;case Vn.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:Vn.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:Vn.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 rs(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}rs.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)},rs.prototype.reset=function(){this.attempts=0},rs.prototype.setMin=function(e){this.ms=e},rs.prototype.setMax=function(e){this.max=e},rs.prototype.setJitter=function(e){this.jitter=e};class is extends on{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,un(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 rs({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||Zn;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 On(this.uri,this.opts);const t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const i=Qn(t,"open",function(){r.onopen(),e&&e()}),o=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},n=Qn(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(Qn(e,"ping",this.onping.bind(this)),Qn(e,"data",this.ondata.bind(this)),Qn(e,"error",this.onerror.bind(this)),Qn(e,"close",this.onclose.bind(this)),Qn(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(Kg){this.onclose("parse error",Kg)}}ondecoded(e){nn(()=>{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 ts(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 os={};function ns(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=Nn(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=os[o]&&n in os[o].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||s?a=new is(i,t):(os[o]||(os[o]=new is(i,t)),a=os[o]),r.query&&!t.query&&(t.query=r.queryKey),a.socket(r.path,t)}Object.assign(ns,{Manager:is,Socket:ts,io:ns,connect:ns});const ss=class e{constructor(e){if(re(this,"client"),re(this,"config"),re(this,"logger",ii.getInstance()),re(this,"socket",null),re(this,"socketConnected",!1),re(this,"connectionMode","auto"),re(this,"wsBaseUrl",null),this.config=e,!e.apiKey)throw new oi("API key is required");if(!e.network)throw new oi("Network is required");const t={"x-api-key":e.apiKey,"Content-Type":"application/json"};this.client=Kr.create({baseURL:"https://v2-api.tier.bot/api",headers:t}),this.logger=ii.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 Kr.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 oi("Unable to fetch file metadata")}}getMimeType(t){const r=t.toLowerCase().split(".").pop();if(!r)throw new oi("File must have an extension");const i=e.VALID_MIME_TYPES[r];if(!i)throw new oi(`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 oi("holderId is required");if(!e.VALID_MODES.includes(t.mode))throw new oi(`Invalid mode: ${t.mode}. Must be one of: ${e.VALID_MODES.join(", ")}`);if("hashinal"===t.mode&&!t.jsonFileURL&&!t.metadataObject)throw new oi("Hashinal mode requires either jsonFileURL or metadataObject");if(t.onlyJSONCollection&&"hashinal-collection"!==t.mode)throw new oi("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 oi("Base64 data is required");const r=t.base64.replace(/^data:.*?;base64,/,"");if(Math.ceil(.75*r.length)>e.MAX_BASE64_SIZE)throw new oi(`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 oi("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 oi("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=ge.from(t,"base64"),i=await async function(e,t){return new Oo(t).fromBuffer(e)}(r);return(null==i?void 0:i.mime)||"application/octet-stream"}catch(Ug){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 oi(`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 oi("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 oi)throw o;if(Kr.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,u="string"==typeof t.privateKey;let d;if(l&&u)d=(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&&u){const e=u?s.detectKeyTypeFromString(t.privateKey):void 0;d="ed25519"===(null==e?void 0:e.detectedType)?i.PrivateKey.fromStringED25519(t.privateKey):i.PrivateKey.fromStringECDSA(t.privateKey)}else d=t.privateKey;n.setOperator(t.accountId,d);const p=i.TransferTransaction.fromBytes(ge.from(e,"base64")),h=await p.sign(d),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(ge.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(u){throw this.logger.error("WebSocket inscription failed, falling back to HTTP:",u),u}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=ns(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(Kg){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",u),null==(r=this.socket)||r.off("inscription-error",d)};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 u=e=>{l(),i({jobId:n,transactionId:s,topicId:e.topicId||e.topic_id,topic_id:e.topicId||e.topic_id,status:"completed",completed:!0})},d=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",u),this.socket.on("inscription-error",d),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=ns(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 oi("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,r=e.completed||"completed"===e.status.toLowerCase();return{...e,completed:r,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 ni(e).authenticate()}static async createWithAuth(t){const r="client"===t.type?new si({...t,logger:ii.getInstance()}):new ni(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(Ug){this.logger.warn(`Error in progress callback: ${Ug}`)}};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;const l=o.completed||"completed"===o.status.toLowerCase();void 0!==o.messages&&void 0!==o.maxMessages&&o.maxMessages>0?(a=Math.min(95,5+o.messages/o.maxMessages*90),l&&(a=100)):"processing"===o.status?a=10:l&&(a=100),c(l?"completed":"confirming",l?"Inscription completed successfully":`Processing inscription (${o.status})`,a,{status:o.status,messagesProcessed:o.messages,maxMessages:o.maxMessages,messageCount:o.messages,completed:l,confirmedMessages:o.confirmedMessages,result:o});const u="hashinal"===o.mode,d="hashinal-collection"===o.mode,p="6"===(null==(n=o.fileStandard)?void 0:n.toString());if(d&&l&&(!i||l))return c("completed","Inscription verification complete",100,{result:o}),o;if(u&&o.topic_id&&o.jsonTopicId&&(!i||l))return c("completed","Inscription verification complete",100,{result:o}),o;if(!u&&!p&&o.topic_id&&(!i||l))return c("completed","Inscription verification complete",100,{result:o}),o;if(p&&o.topic_id&&o.jsonTopicId&&o.registryTopicId&&(!i||l))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 oi("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),Kr.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}}};re(ss,"VALID_MODES",["file","upload","hashinal","hashinal-collection"]),re(ss,"MAX_BASE64_SIZE",2097152),re(ss,"MAX_URL_FILE_SIZE",104857600),re(ss,"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 as=ss;class cs{constructor(e={}){this.module=e.module||"Progress",this.callback=e.callback,this.logger=e.logger||new P({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 cs.instance?(e.callback&&cs.instance.setCallback(e.callback),e.module&&cs.instance.setModule(e.module),e.logger&&cs.instance.setLogger(e.logger),void 0!==e.minPercent&&cs.instance.setMinPercent(e.minPercent),void 0!==e.maxPercent&&cs.instance.setMaxPercent(e.maxPercent)):cs.instance=new cs(e),cs.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 cs({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(Ug){this.logger.warn(`Error in progress callback: ${Ug}`)}}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 ls 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,ls)}}const us=(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)}),ds=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},ps=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},hs=e=>e.tokenMint?`Mint ${e.tokenMint.amount} tokens for token ${e.tokenMint.tokenId}`:e.humanReadableType,gs=e=>e.tokenBurn?`Burn ${e.tokenBurn.amount} tokens for token ${e.tokenBurn.tokenId}`:e.humanReadableType,ms=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},fs=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},ys=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},bs=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},ws=e=>e.fileAppend?`Append to File ${e.fileAppend.fileId||"(Unknown ID)"}`:e.humanReadableType,Is=e=>e.fileUpdate?`Update File ${e.fileUpdate.fileId||"(Unknown ID)"}`:e.humanReadableType,Ts=e=>e.fileDelete?`Delete File ${e.fileDelete.fileId||"(Unknown ID)"}`:e.humanReadableType,Ss=e=>e.consensusUpdateTopic?`Update Topic ${e.consensusUpdateTopic.topicId||"(Unknown ID)"}`:e.humanReadableType,ks=e=>e.consensusDeleteTopic?`Delete Topic ${e.consensusDeleteTopic.topicId||"(Unknown ID)"}`:e.humanReadableType,Es=e=>e.tokenFreeze?`Freeze Token ${e.tokenFreeze.tokenId} for Account ${e.tokenFreeze.accountId}`:e.humanReadableType,vs=e=>e.tokenUnfreeze?`Unfreeze Token ${e.tokenUnfreeze.tokenId} for Account ${e.tokenUnfreeze.accountId}`:e.humanReadableType,As=e=>e.tokenGrantKyc?`Grant KYC for Token ${e.tokenGrantKyc.tokenId} to Account ${e.tokenGrantKyc.accountId}`:e.humanReadableType,Cs=e=>e.tokenRevokeKyc?`Revoke KYC for Token ${e.tokenRevokeKyc.tokenId} from Account ${e.tokenRevokeKyc.accountId}`:e.humanReadableType,xs=e=>e.tokenPause?`Pause Token ${e.tokenPause.tokenId}`:e.humanReadableType,Rs=e=>e.tokenUnpause?`Unpause Token ${e.tokenUnpause.tokenId}`:e.humanReadableType,Ns=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},_s=e=>e.tokenDelete?`Delete Token ${e.tokenDelete.tokenId}`:e.humanReadableType,Ps=e=>e.tokenAssociate?`Associate Account ${e.tokenAssociate.accountId} with Tokens: ${(e.tokenAssociate.tokenIds||[]).join(", ")}`:e.humanReadableType,Fs=e=>e.tokenDissociate?`Dissociate Account ${e.tokenDissociate.accountId} from Tokens: ${(e.tokenDissociate.tokenIds||[]).join(", ")}`:e.humanReadableType,zs=e=>e.cryptoDelete?`Delete Account ${e.cryptoDelete.deleteAccountId}`:e.humanReadableType,Os=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},Ds=e=>e.cryptoUpdateAccount?`Update Account ${e.cryptoUpdateAccount.accountIdToUpdate||"(Unknown ID)"}`:e.humanReadableType,Ms=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},Bs=e=>{if(e.cryptoDeleteAllowance){return`Delete ${(e.cryptoDeleteAllowance.nftAllowancesToRemove||[]).length} NFT Crypto Allowance(s)`}return e.humanReadableType},Ks=e=>{if(e.contractCreate){let t="Create Contract";return e.contractCreate.memo&&(t+=` (Memo: ${e.contractCreate.memo})`),t}return e.humanReadableType},Us=e=>e.contractUpdate?`Update Contract ${e.contractUpdate.contractIdToUpdate||"(Unknown ID)"}`:e.humanReadableType,Ls=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},$s=e=>e.tokenUpdate?`Update Token ${e.tokenUpdate.tokenId||"(Unknown ID)"}`:e.humanReadableType,Hs=e=>e.tokenFeeScheduleUpdate?`Update Fee Schedule for Token ${e.tokenFeeScheduleUpdate.tokenId||"(Unknown ID)"}`:e.humanReadableType,qs=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},Ws=e=>e.scheduleSign?"Sign Schedule":e.humanReadableType,Vs=e=>e.scheduleDelete?"Delete Schedule":e.humanReadableType,Gs=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,Js=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,Ys=e=>"Network Freeze",Xs=e=>"Ethereum Transaction",Zs=e=>e.uncheckedSubmit&&e.uncheckedSubmit.topicId?`Unchecked Submit to topic ${e.uncheckedSubmit.topicId}`:"Unchecked Submit",Qs=e=>"Create Node",ea=e=>"Update Node",ta=e=>"Delete Node",ra=e=>`Atomic Batch (${Array.isArray(e.atomicBatch?.transactions)?e.atomicBatch.transactions.length:0} transaction(s))`,ia={CRYPTOTRANSFER:{fn:ds},cryptoTransfer:{fn:ds},CONTRACTCALL:{fn:ps},contractCall:{fn:ps},TOKENMINT:{fn:hs},tokenMint:{fn:hs},TOKENBURN:{fn:gs},tokenBurn:{fn:gs},TOKENCREATE:{fn:ms},tokenCreation:{fn:ms},TOPICCREATE:{fn:fs},consensusCreateTopic:{fn:fs},CONSENSUSSUBMITMESSAGE:{fn:ys},consensusSubmitMessage:{fn:ys},TOPICUPDATE:{fn:Ss},consensusUpdateTopic:{fn:Ss},TOPICDELETE:{fn:ks},consensusDeleteTopic:{fn:ks},FILECREATE:{fn:bs},fileCreate:{fn:bs},FILEAPPEND:{fn:ws},fileAppend:{fn:ws},FILEUPDATE:{fn:Is},fileUpdate:{fn:Is},FILEDELETE:{fn:Ts},fileDelete:{fn:Ts},TOKENUPDATE:{fn:$s},tokenUpdate:{fn:$s},TOKENFEESCHEDULEUPDATE:{fn:Hs},tokenFeeScheduleUpdate:{fn:Hs},TOKENFREEZE:{fn:Es},tokenFreeze:{fn:Es},TOKENUNFREEZE:{fn:vs},tokenUnfreeze:{fn:vs},TOKENGRANTKYC:{fn:As},tokenGrantKyc:{fn:As},TOKENREVOKEKYC:{fn:Cs},tokenRevokeKyc:{fn:Cs},TOKENPAUSE:{fn:xs},tokenPause:{fn:xs},TOKENUNPAUSE:{fn:Rs},tokenUnpause:{fn:Rs},TOKENWIPE:{fn:Ns},TOKENWIPEACCOUNT:{fn:Ns},tokenWipe:{fn:Ns},tokenWipeAccount:{fn:Ns},TOKENDELETE:{fn:_s},tokenDelete:{fn:_s},TOKENASSOCIATE:{fn:Ps},tokenAssociate:{fn:Ps},TOKENDISSOCIATE:{fn:Fs},tokenDissociate:{fn:Fs},ACCOUNTDELETE:{fn:zs},cryptoDelete:{fn:zs},ACCOUNTCREATE:{fn:Os},cryptoCreateAccount:{fn:Os},ACCOUNTUPDATE:{fn:Ds},cryptoUpdateAccount:{fn:Ds},APPROVEALLOWANCE:{fn:Ms},cryptoApproveAllowance:{fn:Ms},DELETEALLOWANCE:{fn:Bs},cryptoDeleteAllowance:{fn:Bs},CONTRACTCREATE:{fn:Ks},contractCreate:{fn:Ks},CONTRACTUPDATE:{fn:Us},contractUpdate:{fn:Us},CONTRACTDELETE:{fn:Ls},contractDelete:{fn:Ls},TOKENAIRDROP:{fn:qs},tokenAirdrop:{fn:qs},SCHEDULECREATE:{fn:js},scheduleCreate:{fn:js},SCHEDULESIGN:{fn:Ws},scheduleSign:{fn:Ws},SCHEDULEDELETE:{fn:Vs},scheduleDelete:{fn:Vs},SYSTEMDELETE:{fn:Gs},systemDelete:{fn:Gs},SYSTEMUNDELETE:{fn:Js},systemUndelete:{fn:Js},FREEZE:{fn:Ys},freeze:{fn:Ys},ETHEREUMTRANSACTION:{fn:Xs},ethereumTransaction:{fn:Xs},UNCHECKEDSUBMIT:{fn:Zs},uncheckedSubmit:{fn:Zs},NODECREATE:{fn:Qs},nodeCreate:{fn:Qs},NODEUPDATE:{fn:ea},nodeUpdate:{fn:ea},NODEDELETE:{fn:ta},nodeDelete:{fn:ta},ATOMICBATCH:{fn:ra},atomicBatch:{fn:ra}},oa=e=>{const t=ia[e.type];if(t){if(t.fn)return t.fn(e);if(t.template)return us(t.template,e)}const r=ia[e.humanReadableType];if(r){if(r.fn)return r.fn(e);if(r.template)return us(r.template,e)}return"cryptoTransfer"===e.type||"CRYPTOTRANSFER"===e.type?ds(e):e.contractCall?ps(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 na(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=>na(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=>na(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 sa(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 aa(e,t){const r=sa(e);return!(!r||!r[t])}class ca{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=na(e.adminKey),t.kycKey=na(e.kycKey),t.freezeKey=na(e.freezeKey),t.wipeKey=na(e.wipeKey),t.supplyKey=na(e.supplyKey),t.feeScheduleKey=na(e.feeScheduleKey),t.pauseKey=na(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=na(e.adminKey),t.kycKey=na(e.kycKey),t.freezeKey=na(e.freezeKey),t.wipeKey=na(e.wipeKey),t.supplyKey=na(e.supplyKey),t.feeScheduleKey=na(e.feeScheduleKey),t.pauseKey=na(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(aa(e,"tokenAirdrop")){const t=sa(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(Kg){}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 la{static parseConsensusCreateTopic(e){if(!e)return;const t={};return e.memo&&(t.memo=e.memo),t.adminKey=na(e.adminKey),t.submitKey=na(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=na(e.adminKey):t.adminKey=void 0,null===e.submitKey?(t.clearSubmitKey=!0,t.submitKey=void 0):e.submitKey?t.submitKey=na(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 ua{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(aa(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=na({keyList:r})}return t._expirationTime&&(e.expirationTime=t._expirationTime.toString()),t._memo&&(e.memo=t._memo),{type:"FILECREATE",humanReadableType:"File Create",fileCreate:e}}if(aa(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(aa(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=na({keyList:r})}return t._expirationTime&&(e.expirationTime=t._expirationTime.toString()),t._memo&&(e.memo=t._memo),{type:"FILEUPDATE",humanReadableType:"File Update",fileUpdate:e}}if(aa(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=na({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=na({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 da{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=na(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=na(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 pa{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(aa(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=na(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(aa(e,"contractUpdateInstance")){const e={contractIdToUpdate:t._contractId.toString()};return t._memo&&(e.memo=t._memo),t._adminKey&&(e.adminKey=na(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(aa(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=na(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=na(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 ha{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(aa(e,"utilPrng")){const e={};return t._range&&0!==t._range&&(e.range=t._range),{type:"PRNG",humanReadableType:"Pseudo Random Number",utilPrng:e}}if(aa(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(aa(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(aa(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 ga{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(aa(e,"scheduleCreate")){return{type:"SCHEDULECREATE",humanReadableType:"Schedule Create",scheduleCreate:{scheduledTransactionBody:globalThis.Buffer.from(t._scheduledTransaction).toString("base64"),memo:t._scheduleMemo,adminKey:t._adminKey?na(t._adminKey):void 0,payerAccountId:t._payerAccountId?.toString(),expirationTime:t._expirationTime?.toString(),waitForExpiry:t._waitForExpiry||!1}}}if(aa(e,"scheduleSign")){return{type:"SCHEDULESIGN",humanReadableType:"Schedule Sign",scheduleSign:{scheduleId:t._scheduleId.toString()}}}if(aa(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=na(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 ma={TOKENCREATE:{bodyField:"tokenCreation",parser:ca.parseTokenCreate,resultField:"tokenCreation"},TOKENMINT:{bodyField:"tokenMint",parser:ca.parseTokenMint,resultField:"tokenMint"},TOKENBURN:{bodyField:"tokenBurn",parser:ca.parseTokenBurn,resultField:"tokenBurn"},TOKENUPDATE:{bodyField:"tokenUpdate",parser:ca.parseTokenUpdate,resultField:"tokenUpdate"},TOKENDELETE:{bodyField:"tokenDeletion",parser:ca.parseTokenDelete,resultField:"tokenDelete"},TOKENASSOCIATE:{bodyField:"tokenAssociate",parser:ca.parseTokenAssociate,resultField:"tokenAssociate"},TOKENDISSOCIATE:{bodyField:"tokenDissociate",parser:ca.parseTokenDissociate,resultField:"tokenDissociate"},TOKENFREEZE:{bodyField:"tokenFreeze",parser:ca.parseTokenFreeze,resultField:"tokenFreeze"},TOKENUNFREEZE:{bodyField:"tokenUnfreeze",parser:ca.parseTokenUnfreeze,resultField:"tokenUnfreeze"},TOKENGRANTKYC:{bodyField:"tokenGrantKyc",parser:ca.parseTokenGrantKyc,resultField:"tokenGrantKyc"},TOKENREVOKEKYC:{bodyField:"tokenRevokeKyc",parser:ca.parseTokenRevokeKyc,resultField:"tokenRevokeKyc"},TOKENPAUSE:{bodyField:"tokenPause",parser:ca.parseTokenPause,resultField:"tokenPause"},TOKENUNPAUSE:{bodyField:"tokenUnpause",parser:ca.parseTokenUnpause,resultField:"tokenUnpause"},TOKENWIPEACCOUNT:{bodyField:"tokenWipe",parser:ca.parseTokenWipeAccount,resultField:"tokenWipeAccount"},TOKENFEESCHEDULEUPDATE:{bodyField:"tokenFeeScheduleUpdate",parser:ca.parseTokenFeeScheduleUpdate,resultField:"tokenFeeScheduleUpdate"},TOKENAIRDROP:{bodyField:"tokenAirdrop",parser:ca.parseTokenAirdropFromProto,resultField:"tokenAirdrop"},TOPICCREATE:{bodyField:"consensusCreateTopic",parser:la.parseConsensusCreateTopic,resultField:"consensusCreateTopic"},CONSENSUSSUBMITMESSAGE:{bodyField:"consensusSubmitMessage",parser:la.parseConsensusSubmitMessage,resultField:"consensusSubmitMessage"},TOPICUPDATE:{bodyField:"consensusUpdateTopic",parser:la.parseConsensusUpdateTopic,resultField:"consensusUpdateTopic"},TOPICDELETE:{bodyField:"consensusDeleteTopic",parser:la.parseConsensusDeleteTopic,resultField:"consensusDeleteTopic"},ACCOUNTCREATE:{bodyField:"cryptoCreateAccount",parser:da.parseCryptoCreateAccount,resultField:"cryptoCreateAccount"},ACCOUNTUPDATE:{bodyField:"cryptoUpdateAccount",parser:da.parseCryptoUpdateAccount,resultField:"cryptoUpdateAccount"},ACCOUNTDELETE:{bodyField:"cryptoDelete",parser:da.parseCryptoDelete,resultField:"cryptoDelete"},CRYPTOTRANSFER:{bodyField:"cryptoTransfer",parser:e=>{const t={transfers:[],tokenTransfers:[]};return da.parseCryptoTransfers(e,t),t},resultField:"transfers",spreadResult:!0},APPROVEALLOWANCE:{bodyField:"cryptoApproveAllowance",parser:da.parseCryptoApproveAllowance,resultField:"cryptoApproveAllowance"},DELETEALLOWANCE:{bodyField:"cryptoDeleteAllowance",parser:da.parseCryptoDeleteAllowance,resultField:"cryptoDeleteAllowance"},FILECREATE:{bodyField:"fileCreate",parser:ua.parseFileCreate,resultField:"fileCreate"},FILEUPDATE:{bodyField:"fileUpdate",parser:ua.parseFileUpdate,resultField:"fileUpdate"},FILEDELETE:{bodyField:"fileDelete",parser:ua.parseFileDelete,resultField:"fileDelete"},FILEAPPEND:{bodyField:"fileAppend",parser:ua.parseFileAppend,resultField:"fileAppend"},CONTRACTCREATE:{bodyField:"contractCreateInstance",parser:pa.parseContractCreate,resultField:"contractCreate"},CONTRACTUPDATE:{bodyField:"contractUpdateInstance",parser:pa.parseContractUpdate,resultField:"contractUpdate"},CONTRACTDELETE:{bodyField:"contractDeleteInstance",parser:pa.parseContractDelete,resultField:"contractDelete"},CONTRACTCALL:{bodyField:"contractCall",parser:pa.parseContractCall,resultField:"contractCall"},ETHEREUMTRANSACTION:{bodyField:"ethereumTransaction",parser:pa.parseEthereumTransaction,resultField:"ethereumTransaction"},SCHEDULECREATE:{bodyField:"scheduleCreate",parser:ga.parseScheduleCreateFromProto,resultField:"scheduleCreate"},SCHEDULESIGN:{bodyField:"scheduleSign",parser:ga.parseScheduleSignFromProto,resultField:"scheduleSign"},SCHEDULEDELETE:{bodyField:"scheduleDelete",parser:ga.parseScheduleDeleteFromProto,resultField:"scheduleDelete"},PRNG:{bodyField:"utilPrng",parser:ha.parseUtilPrng,resultField:"utilPrng"},FREEZE:{bodyField:"freeze",parser:ha.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:ca.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 fa={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"}},ya={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"},ba={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 wa(e){for(const[t,r]of Object.entries(fa))if(e[t])return r;return{type:"UNKNOWN",humanReadableType:"Unknown Transaction"}}function Ia(e){return ya[e]||"Unknown Transaction"}class Ta{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 ls(`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(u){if(a=u instanceof Error?u:new Error(String(u)),c++,!r||c>n){if(i)throw new ls("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(d){}}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=ca.parseFromTransactionObject(e),a=da.parseFromTransactionObject(e),c=la.parseFromTransactionObject(e),l=ua.parseFromTransactionObject(e),u=pa.parseFromTransactionObject(e),d=ga.parseFromTransactionObject(e),p=ha.parseFromTransactionObject(e),h=[r,a,c,l,u,d,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 wa(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 wa(e).type}static getHumanReadableType(e){return Ia(e)}static getTransactionSummary(e){return oa(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 ls("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",u={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(u,c,a,s),u}catch(r){throw new ls("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 ls("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[ca.parseFromTransactionObject(e),da.parseFromTransactionObject(e),la.parseFromTransactionObject(e),ua.parseFromTransactionObject(e),pa.parseFromTransactionObject(e),ga.parseFromTransactionObject(e),ha.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&&da.parseCryptoTransfers(e.cryptoTransfer,t),e.cryptoDelete&&(t.cryptoDelete=da.parseCryptoDelete(e.cryptoDelete)),e.cryptoCreateAccount&&(t.cryptoCreateAccount=da.parseCryptoCreateAccount(e.cryptoCreateAccount)),e.cryptoUpdateAccount&&(t.cryptoUpdateAccount=da.parseCryptoUpdateAccount(e.cryptoUpdateAccount)),e.cryptoApproveAllowance&&(t.cryptoApproveAllowance=da.parseCryptoApproveAllowance(e.cryptoApproveAllowance)),e.cryptoDeleteAllowance&&(t.cryptoDeleteAllowance=da.parseCryptoDeleteAllowance(e.cryptoDeleteAllowance)),e.contractCall&&(t.contractCall=pa.parseContractCall(e.contractCall)),e.contractCreateInstance&&(t.contractCreate=pa.parseContractCreate(e.contractCreateInstance)),e.contractUpdateInstance&&(t.contractUpdate=pa.parseContractUpdate(e.contractUpdateInstance)),e.contractDeleteInstance&&(t.contractDelete=pa.parseContractDelete(e.contractDeleteInstance)),e.tokenCreation&&(t.tokenCreation=ca.parseTokenCreate(e.tokenCreation)),e.tokenMint&&(t.tokenMint=ca.parseTokenMint(e.tokenMint)),e.tokenBurn&&(t.tokenBurn=ca.parseTokenBurn(e.tokenBurn)),e.tokenUpdate&&(t.tokenUpdate=ca.parseTokenUpdate(e.tokenUpdate)),e.tokenFeeScheduleUpdate&&(t.tokenFeeScheduleUpdate=ca.parseTokenFeeScheduleUpdate(e.tokenFeeScheduleUpdate)),e.tokenFreeze&&(t.tokenFreeze=ca.parseTokenFreeze(e.tokenFreeze)),e.tokenUnfreeze&&(t.tokenUnfreeze=ca.parseTokenUnfreeze(e.tokenUnfreeze)),e.tokenGrantKyc&&(t.tokenGrantKyc=ca.parseTokenGrantKyc(e.tokenGrantKyc)),e.tokenRevokeKyc&&(t.tokenRevokeKyc=ca.parseTokenRevokeKyc(e.tokenRevokeKyc)),e.tokenPause&&(t.tokenPause=ca.parseTokenPause(e.tokenPause)),e.tokenUnpause&&(t.tokenUnpause=ca.parseTokenUnpause(e.tokenUnpause)),e.tokenWipe&&(t.tokenWipeAccount=ca.parseTokenWipeAccount(e.tokenWipe)),e.tokenDeletion&&(t.tokenDelete=ca.parseTokenDelete(e.tokenDeletion)),e.tokenAssociate&&(t.tokenAssociate=ca.parseTokenAssociate(e.tokenAssociate)),e.tokenDissociate&&(t.tokenDissociate=ca.parseTokenDissociate(e.tokenDissociate)),e.tokenAirdrop&&(t.tokenAirdrop=ca.parseTokenAirdropFromProto(e.tokenAirdrop)),e.consensusCreateTopic&&(t.consensusCreateTopic=la.parseConsensusCreateTopic(e.consensusCreateTopic)),e.consensusSubmitMessage&&(t.consensusSubmitMessage=la.parseConsensusSubmitMessage(e.consensusSubmitMessage)),e.consensusUpdateTopic&&(t.consensusUpdateTopic=la.parseConsensusUpdateTopic(e.consensusUpdateTopic)),e.consensusDeleteTopic&&(t.consensusDeleteTopic=la.parseConsensusDeleteTopic(e.consensusDeleteTopic)),e.fileCreate&&(t.fileCreate=ua.parseFileCreate(e.fileCreate)),e.fileAppend&&(t.fileAppend=ua.parseFileAppend(e.fileAppend)),e.fileUpdate&&(t.fileUpdate=ua.parseFileUpdate(e.fileUpdate)),e.fileDelete&&(t.fileDelete=ua.parseFileDelete(e.fileDelete)),e.utilPrng&&(t.utilPrng=ha.parseUtilPrng(e.utilPrng))}static parseTransactionBodyDetails(e,t){const r={},i=ma[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(ma).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=ca.extractTokenCreationFromTransaction(r);i&&(e[t]=i)}else if("tokenAirdrop"===t&&"TOKENAIRDROP"===e.type){const i=ca.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 Sa="undefined"!=typeof window&&void 0!==window.document;const ka=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()}},Ea=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 va(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=Ea.get(o);if(n)return n;let s;return s=t.apiKey?new as({apiKey:t.apiKey,network:e.network||"mainnet",connectionMode:i}):await as.createWithAuth({type:"server",accountId:e.accountId,privateKey:"string"==typeof e.privateKey?e.privateKey:e.privateKey.toString(),network:e.network||"mainnet",connectionMode:i}),Ea.set(o,s),s}let Aa={};const Ca=e=>{if(!e.includes("@"))return e;const t=e?.split("@");return`${t[0]}-${t[1].replace(".","-")}`};const xa=1e3;async function Ra(e){if(Sa)throw new Error("File path operations are not supported in browser environment. Use buffer input type instead.");if(await async function(){if(!Sa&&!Aa.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");Aa.readFileSync=e.readFileSync,Aa.basename=r.basename,Aa.extname=r.extname}}catch(e){console.warn("Node.js modules not available, file path operations will be disabled")}}(),!Aa.readFileSync||!Aa.basename||!Aa.extname)throw new Error("Node.js file system modules are not available. Cannot read file from path.");try{const r=Aa.readFileSync(e),i=r.toString("base64"),o=Aa.basename(e);let n="application/octet-stream";try{const e=await l.fileTypeFromBuffer(r);e&&(n=e.mime)}catch(t){const r=Aa.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 Na(e){return{accountId:e.accountId,privateKey:"string"==typeof e.privateKey?e.privateKey:e.privateKey.toString(),network:e.network}}async function _a(e,t,r,i){const o=P.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 Da(e,t,r,i);let n;if("hashinal"===r.mode&&r.metadata&&Oa(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 as({apiKey:r.apiKey,network:t.network||"mainnet",connectionMode:"auto"});else{o.debug("Initializing InscriptionSDK with server auth");const e=Na(t);n=await as.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 Ra(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=Na(t),l=await n.inscribeAndExecute(a,c),u=l.jobId||l.tx_id||l.transactionId||"",d=l.transactionId||u||"",p=Ca(u),h=Ca(d),g=Ca(p||h||u||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 Ma(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 Pa(h,t.network||"mainnet",r.logging?.level)}}return{confirmed:!1,result:{...l,jobId:g,transactionId:h},sdk:n,costSummary:await Pa(h,t.network||"mainnet",r.logging?.level)}}catch(n){throw o.error("Error during inscription process",n),n}}async function Pa(e,t,r){const i=P.getInstance({module:"InscriberCost",level:r??"info"}),o=new q(t,i),n=Ca(e),s=n.split("-")[0];for(let c=0;c<3;c++)try{const e=await o.getTransaction(n);if(!e){c<2&&await F(xa);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 F(xa);continue}const i=new u(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 F(xa)}}async function Fa(e,t,r,i){const o=P.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 Da(e,n,r,i)}"hashinal"===r.mode&&r.metadata&&Oa(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 as({apiKey:r.apiKey,network:r.network||"mainnet",connectionMode:"websocket"})):(o.debug("Initializing InscriptionSDK with client auth (websocket)"),s=await as.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 Ra(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 u=Ca(l.tx_id||l.id||""),d=Ca(u||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 Ma(s,d,r.waitMaxAttempts,r.waitIntervalMs,r.progressCallback);return o.info("Inscription confirmation received",{jobId:d}),{confirmed:!0,result:{jobId:d,transactionId:d,topic_id:l.topic_id,status:l.status,completed:l.completed},inscription:e,sdk:s,costSummary:await Pa(d,r.network||"mainnet",r.logging?.level)}}return{confirmed:!1,result:{jobId:d,transactionId:d,topic_id:l.topic_id,status:l.status,completed:l.completed},sdk:s,costSummary:await Pa(d,r.network||"mainnet",r.logging?.level)}}catch(n){throw o.error("Error during inscription process",n),n}}async function za(e,t){const r=P.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 as({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 as.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 Oa(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 Da(e,t,r,i){const o=P.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=ka.createCacheKey(e,t,r);return ka.get(i)}(e,t,r);if(n)return o.debug("Returning cached quote"),{confirmed:!1,quote:!0,result:n};"hashinal"===r.mode&&r.metadata&&Oa(r.metadata,o);const s=await va(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 Ra(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 u=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 Ta.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=ka.createCacheKey(e,t,r);ka.set(o,i,6e5)}(e,t,r,u),o.info("Successfully generated inscription quote",{totalCostHbar:u.totalCostHbar}),{confirmed:!1,quote:!0,result:u}}catch(n){throw o.error("Error generating inscription quote",n),n}}async function Ma(e,t,r=30,i=4e3,o){const n=P.getInstance({module:"Inscriber"}),s=Ca(t),a=new cs({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(Kg){return n.debug("Falling back to standard waitForInscription method",{error:Kg}),a.verifying("Verifying inscription status",50,{error:Kg}),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 Ba(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 Ka=(e=>(e.REGISTER_CONFIG="register-config",e.REGISTER="register",e))(Ka||{}),Ua=(e=>(e.EVM="evm",e.WASM="wasm",e))(Ua||{});const La=r.z.object({name:r.z.string().optional(),type:r.z.string()}),$a=r.z.object({name:r.z.string(),inputs:r.z.array(La),outputs:r.z.array(La),stateMutability:r.z.enum(["view","pure"]),type:r.z.literal("function")}),Ha=r.z.enum(["number","string","bool"]),qa=r.z.object({p:r.z.literal("hcs-7"),m:r.z.string().optional()}),ja=qa.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:$a})}),Wa=qa.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(Ha)}),outputType:r.z.object({type:r.z.literal("string"),format:r.z.literal("topic-id")})})}),Va=qa.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())}),Ga=r.z.union([ja,Wa,Va]);class Ja{constructor(e){this.network=e.network,this.logger=e.logger||P.getInstance({level:e.logLevel||"info",module:"HCS7Client",silent:e.silent}),this.mirrorNode=new q(this.network,this.logger,e.mirrorNodeUrl?{customUrl:e.mirrorNodeUrl}:void 0)}generateRegistryMemo(e){return`hcs-7:indexed:${e}`}createConfigMessage(e){return e.config.type===Ua.EVM?{p:"hcs-7",op:Ka.REGISTER_CONFIG,t:Ua.EVM,c:{contractAddress:e.config.contractAddress,abi:e.config.abi},m:e.memo}:{p:"hcs-7",op:Ka.REGISTER_CONFIG,t:Ua.WASM,c:{wasmTopicId:e.config.wasmTopicId,inputType:e.config.inputType,outputType:e.config.outputType},m:e.memo}}createMetadataMessage(e){return{p:"hcs-7",op:Ka.REGISTER,t_id:e.metadataTopicId,m:e.memo,d:{weight:e.weight,tags:e.tags,...e.data||{}}}}validateMessage(e){const t=Ga.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=Ga.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 Ya(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 Xa(e){return W({memo:`hcs-7:indexed:${e.ttl}`,submitKey:e.submitKey,adminKey:e.adminKey,operatorPublicKey:e.operatorPublicKey})}function Za(e){const t={p:"hcs-7",...e.message};return V({topicId:e.topicId,message:JSON.stringify(t),transactionMemo:e.transactionMemo})}class Qa{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 ec(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 tc(e){const t=Object.create(P.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 rc(e){return e instanceof P}async function ic(e,t,r){const i=new q(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 oc="hcs-21",nc=1024,sc=1e3,ac=/^(?:hcs:\/\/1\/0\.0\.\d+|ipfs:\/\/\S+|ar:\/\/\S+|oci:\/\/\S+|https?:\/\/\S+)$/,cc=/^(?:0\.0\.\d+|hcs:\/\/1\/0\.0\.\d+(?:\/\d+)?|ipfs:\/\/\S+|ar:\/\/\S+|oci:\/\/\S+|https?:\/\/\S+)$/;var lc=(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))(lc||{});const uc=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)}),dc=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()),pc=r.z.object({p:r.z.literal(oc),op:r.z.enum(["register","update","delete"]),adapter_id:r.z.string().min(1),entity:r.z.string().min(1),package:uc,manifest:r.z.string().regex(ac,"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:dc,state_model:r.z.string().min(1).optional(),signature:r.z.string().min(1).optional()}),hc=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")})}),gc=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()}),mc=r.z.union([hc,gc]);var fc=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTONOMOUS=1]="AUTONOMOUS",e))(fc||{}),yc=(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))(yc||{});const bc=r.z.nativeEnum(yc),wc=r.z.union([bc,r.z.string()]),Ic=r.z.union([r.z.string(),r.z.number(),r.z.boolean(),r.z.null()]),Tc=r.z.lazy(()=>r.z.union([Ic,r.z.array(Tc),r.z.record(Tc)])),Sc=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(Tc).optional(),aiAgent:r.z.object({type:r.z.nativeEnum(fc),creator:r.z.string().optional(),model:r.z.string().optional(),capabilities:r.z.array(bc).optional()}).optional(),uaid:r.z.string().optional()}).catchall(Tc),kc=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()}),Ec=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(kc)}),vc=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()}),Ac=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(Tc).optional(),submittedAt:r.z.string()}),Cc=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:Ac.optional(),responder:Ac.optional()}),xc=r.z.object({enabled:r.z.boolean(),algorithm:r.z.string(),requireCiphertext:r.z.boolean(),requester:vc.nullable().optional(),responder:vc.nullable().optional(),handshake:Cc.nullable().optional()}),Rc=r.z.object({messageId:r.z.string(),role:r.z.enum(["user","agent"]),content:r.z.string(),timestamp:r.z.string(),cipherEnvelope:Ec.optional(),metadata:r.z.record(Tc).optional()}),Nc=r.z.record(r.z.union([r.z.array(Tc),r.z.record(Tc),Tc])).optional(),_c=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(wc),endpoints:r.z.union([r.z.record(Tc),r.z.array(r.z.string())]).optional(),metadata:r.z.record(Tc).optional(),metadataFacet:Nc,profile:Sc.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(),Pc=r.z.object({hits:r.z.array(_c),total:r.z.number(),page:r.z.number(),limit:r.z.number()}),Fc=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()}),zc=r.z.object({registries:r.z.array(r.z.string())}),Oc=r.z.object({searches:r.z.array(r.z.string())}),Dc=r.z.object({agent:_c}),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(Tc).nullable().optional(),skills:r.z.array(r.z.string()).optional()}),history:r.z.array(Rc).optional().default([]),historyTtlSeconds:r.z.number().nullable().optional(),encryption:xc.nullable().optional()}),Bc=r.z.object({sessionId:r.z.string(),uaid:r.z.string().nullable().optional(),message:r.z.string(),timestamp:r.z.string(),rawResponse:Tc.optional(),content:r.z.string().optional(),history:r.z.array(Rc).optional(),historyTtlSeconds:r.z.number().nullable().optional(),encrypted:r.z.boolean().optional()}),Kc=r.z.object({sessionId:r.z.string(),history:r.z.array(Rc),historyTtlSeconds:r.z.number()});r.z.object({preserveEntries:r.z.number().int().min(0).optional()}).strict();const Uc=r.z.object({sessionId:r.z.string(),history:r.z.array(Rc),summaryEntry:Rc,preservedEntries:r.z.array(Rc),historyTtlSeconds:r.z.number(),creditsDebited:r.z.number(),metadata:r.z.record(Tc).optional()}),Lc=r.z.object({sessionId:r.z.string(),encryption:xc.nullable()}),$c=r.z.object({sessionId:r.z.string(),handshake:Cc}),Hc=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()}),qc=r.z.object({challengeId:r.z.string(),message:r.z.string(),expiresAt:r.z.string()}),jc=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()}),Wc=r.z.object({key:r.z.string(),apiKey:jc,accountId:r.z.string(),network:r.z.string(),networkCanonical:r.z.string().optional()}),Vc=r.z.object({protocols:r.z.array(r.z.string())}),Gc=r.z.object({protocol:r.z.string().nullable()}),Jc=r.z.object({hits:r.z.array(_c),total:r.z.number(),page:r.z.number().optional(),limit:r.z.number().optional()}),Yc=r.z.union([r.z.string(),r.z.number()]),Xc=r.z.object({capabilities:r.z.array(Yc).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:Xc.optional(),limit:r.z.number().int().min(1).max(100).optional(),offset:r.z.number().int().min(0).optional()}).strict();const Zc=r.z.object({agent:_c,score:r.z.number().optional(),highlights:r.z.record(r.z.array(r.z.string())).optional()}),Qc=r.z.object({hits:r.z.array(Zc),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()}),el=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()}),tl=r.z.object({storageMode:r.z.string(),vectorStatus:el}),rl=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()}),il=r.z.object({p50:r.z.number(),p90:r.z.number(),p95:r.z.number(),p99:r.z.number()}),ol=r.z.object({http:r.z.object({requestsTotal:r.z.number(),activeConnections:r.z.number(),requestDuration:il}),search:r.z.object({queriesTotal:r.z.number(),queryDuration:il}),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:il}),cache:r.z.object({hits:r.z.number(),misses:r.z.number(),hitRate:r.z.number()}),websocket:r.z.object({connections:r.z.number()})}),nl=r.z.object({uaid:r.z.string(),valid:r.z.boolean(),formats:r.z.array(r.z.string())}),sl=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(Ic).optional(),createdAt:r.z.string()}),al=r.z.object({connected:r.z.boolean(),connection:sl.optional(),adapter:r.z.string().optional(),agentId:r.z.string().optional()}),cl=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()}),ll=r.z.object({id:r.z.string(),name:r.z.string(),type:r.z.string(),endpoint:r.z.string().optional(),capabilities:r.z.array(wc),registry:r.z.string().optional(),protocol:r.z.string().optional(),profile:Sc.optional(),nativeId:r.z.string().optional(),metadata:r.z.record(Tc).optional()}),ul=r.z.object({tId:r.z.string().nullable(),sizeBytes:r.z.number().optional()}),dl=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(),pl=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(Tc).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()}),hl=r.z.object({base:r.z.number(),additional:r.z.number(),total:r.z.number()}),gl=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(),ml=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(),fl=r.z.object({id:r.z.string(),label:r.z.string(),networks:r.z.array(ml)}),yl=r.z.object({registries:r.z.array(fl)}),bl=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:ll,openConvAI:r.z.object({compatible:r.z.boolean(),hcs11Profile:Sc.optional(),bridgeEndpoint:r.z.string().optional()}).optional(),profile:ul.optional(),profileRegistry:dl.nullable().optional(),hcs10Registry:gl.nullable().optional(),credits:hl.optional(),additionalRegistries:r.z.array(pl).optional(),additionalRegistryCredits:r.z.array(pl).optional(),additionalRegistryCostPerRegistry:r.z.number().optional()}),wl=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:ll,openConvAI:r.z.object({compatible:r.z.boolean(),hcs11Profile:Sc.optional(),bridgeEndpoint:r.z.string().optional()}).optional(),profile:ul.optional(),profileRegistry:dl.nullable().optional(),hcs10Registry:gl.nullable().optional(),credits:hl,additionalRegistries:r.z.array(pl),additionalRegistryCredits:r.z.array(pl).optional(),additionalRegistryCostPerRegistry:r.z.number().optional()}),Il=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:ll,openConvAI:r.z.object({compatible:r.z.boolean(),hcs11Profile:Sc.optional(),bridgeEndpoint:r.z.string().optional()}).optional(),profile:ul.optional(),profileRegistry:dl.nullable().optional(),hcs10Registry:gl.nullable().optional(),credits:hl.optional(),additionalRegistries:r.z.array(pl).optional(),additionalRegistryCredits:r.z.array(pl).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)}),Tl=r.z.union([bl,wl,Il]),Sl=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(Tc).optional(),lastUpdated:r.z.string()}),kl=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(),Sl),errors:r.z.array(r.z.string()).optional()}),El=r.z.object({progress:kl}),vl=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()}),Al=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()}),Cl=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(),xl=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(Tc).optional(),settlement:Cl.optional()}).optional()}),Rl=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()}),Nl=r.z.object({adapters:r.z.array(r.z.string())}),_l=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:Tc.optional().nullable()}),Pl=r.z.object({categories:r.z.array(_l)}),Fl=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:Tc.nullable().optional(),signature:r.z.string().nullable().optional(),manifest:Tc.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:Tc.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:_l.optional()}).passthrough(),zl=r.z.object({network:r.z.string(),adapters:r.z.array(Fl)}),Ol=r.z.object({category:_l});r.z.object({adapter:r.z.record(Tc),declaration:pc,transactionId:r.z.string().optional().nullable(),category:_l});const Dl=r.z.object({submissionId:r.z.string(),status:r.z.string().optional(),network:r.z.string().optional(),message:r.z.string().optional()}).passthrough(),Ml=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:Tc.optional(),resultPayload:Tc.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()}),Bl=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()}),Kl=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())}),Ul=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:Bl.optional(),capabilities:Kl,enabled:r.z.boolean(),priority:r.z.number(),status:r.z.enum(["running","stopped"])}),Ll=r.z.object({adapters:r.z.array(Ul)}),$l=r.z.object({value:r.z.union([r.z.string(),r.z.number(),r.z.boolean()]),label:r.z.string()}),Hl=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($l).optional()}),ql=r.z.object({facets:r.z.array(Hl)});let jl;function Wl(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 Vl(e){try{return await import(e)}catch(t){if(Wl(e,t))return null;throw t}}async function Gl(e){if(Sa)return Vl(e);const t=await async function(){if(void 0!==jl)return jl;if(Sa)return jl=null,jl;try{const e="undefined"!=typeof global?global:globalThis,t=e.process?.mainModule?.require??e.require;jl="function"==typeof t&&"function"==typeof t.resolve?t:null}catch{jl=null}return jl}();if(t)try{return t(e)}catch(r){if(!Wl(e,r))throw r}return Vl(e)}const Jl="https://hol.org/registry/api/v1",Yl=/application\/json/i,Xl=e=>{let t=e.length;for(;t>0&&47===e.charCodeAt(t-1);)t-=1;return t===e.length?e:e.slice(0,t)},Zl=()=>"function"==typeof DOMException?new DOMException("Aborted","AbortError"):new Error("The operation was aborted"),Ql=e=>e.trim().toLowerCase(),eu=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:eu(e));if("object"==typeof e){const t={};return Object.entries(e).forEach(([e,r])=>{void 0!==r&&(t[e]=eu(r))}),t}throw new TypeError("Only JSON-compatible values are supported")},tu=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),ru=e=>{const t=eu(e);if(tu(t))return t;throw new TypeError("Expected JSON object value")},iu=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},ou=e=>{const t={profile:ru(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=ru(e.metadata)),t};class nu extends Error{constructor(e,t){super(e),this.status=t.status,this.statusText=t.statusText,this.body=t.body}}class su extends Error{constructor(e,t,r){super(e),this.cause=t,this.rawValue=r}}class au{constructor(e={}){this.encryptionBootstrapPromise=null;const{baseUrl:t=Jl,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:Jl;try{const e=new URL(Xl(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=Xl(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=Ql(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 au(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=Ql(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 nu("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(!Yl.test(i)){const e=await r.text();throw new su("Expected JSON response from registry broker",e)}return await r.json()}async extractErrorBody(e){const t=e.headers?.get("content-type")??"";if(Yl.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 su(`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 Zl()}else await new Promise((r,i)=>{const o=setTimeout(()=>{t&&t.removeEventListener("abort",n),r()},e),n=()=>{clearTimeout(o),t?.removeEventListener("abort",n),i(Zl())};if(t){if(t.aborted)return clearTimeout(o),void i(Zl());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=p.randomBytes(32),t=h.secp256k1.getPublicKey(e,!0);return{privateKey:a.Buffer.from(e).toString("hex"),publicKey:a.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(a.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?a.Buffer.from(o,"utf8").toString("base64"):void 0;o&&i.setAAD(a.Buffer.from(o,"utf8"));const s=a.Buffer.concat([i.update(a.Buffer.from(e.plaintext,"utf8")),i.final()]),c=i.getAuthTag();return{algorithm:"aes-256-gcm",ciphertext:a.Buffer.concat([s,c]).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=a.Buffer.from(e.envelope.ciphertext,"base64"),i=a.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(a.Buffer.from(e.envelope.associatedData,"base64")),s.setAuthTag(n);return a.Buffer.concat([s.update(o),s.final()]).toString(e.encoding??"utf8")}normalizeSharedSecret(e){if(a.Buffer.isBuffer(e))return a.Buffer.from(e);if(e instanceof Uint8Array)return a.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?a.Buffer.from(r,"hex"):a.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 a.Buffer.from(t,"hex")}extractInsufficientCreditsDetails(e){if(!(e instanceof nu)||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:tu(e)&&"string"==typeof e.error?e.error:tu(e)&&"string"==typeof e.message?e.message:void 0}shouldAutoTopUpHistory(e,t){if(!this.historyAutoTopUp||void 0===e.historyTtlSeconds)return!1;if(!(t instanceof nu))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 cu(e,t){const r=await e.requestJson("/encryption/keys",{method:"POST",headers:{"content-type":"application/json"},body:t});return e.parseWithSchema(r,Hc,"register encryption key response")}async function lu(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=h.secp256k1.getPublicKey(r,!0);return a.Buffer.from(i).toString("hex")}(e,r);return{publicKey:t,privateKey:r}}return null}async function uu(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 lu(e,t);if(!i)throw new Error("Unable to resolve encryption public key for auto-registration");return await cu(e,{keyType:t.keyType??"secp256k1",publicKey:i.publicKey,...r}),i}const du=new WeakMap;async function pu(e){const[{default:t},r,i]=await Promise.all([import("axios"),Gl("x402-axios"),Gl("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 hu(e){const t=Math.ceil(1e8*e);if(t<=0)throw new Error("Calculated purchase amount must be positive");return t/1e8}async function gu(e,t){const r=await e.requestJson("/register",{method:"POST",body:ou(t),headers:{"content-type":"application/json"}});return e.parseWithSchema(r,Tl,"register agent response")}function mu(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 fu(e){return!Number.isFinite(e)||e<=0?0:Math.max(Math.ceil(e),1)}async function yu(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=fu(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=mu(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(au.prototype,"encryption",{get(){const e=du.get(this);if(e)return e;const t={registerKey:e=>cu(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 uu(e,{...t,uaid:t.uaid})}(this,e)};return du.set(this,t),t}}),au.prototype.bootstrapEncryptionOptions=async function(e){return e?.autoRegister&&!1!==e.autoRegister.enabled?uu(this,e.autoRegister):null},au.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=p.randomBytes(32),r=a.Buffer.from(t).toString("hex"),i=h.secp256k1.getPublicKey(t,!0),o=a.Buffer.from(i).toString("hex"),n=e.envVar??"RB_ENCRYPTION_PRIVATE_KEY",s=e.envPath?b.resolve(e.envPath):void 0;if(s){const t=await(async()=>{const e=await Gl("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}},au.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,Pc,"search response")},au.prototype.stats=async function(){const e=await this.requestJson("/stats",{method:"GET"});return this.parseWithSchema(e,Fc,"stats response")},au.prototype.registries=async function(){const e=await this.requestJson("/registries",{method:"GET"});return this.parseWithSchema(e,zc,"registries response")},au.prototype.getAdditionalRegistries=async function(){const e=await this.requestJson("/register/additional-registries",{method:"GET"});return this.parseWithSchema(e,yl,"additional registry catalog response")},au.prototype.popularSearches=async function(){const e=await this.requestJson("/popular",{method:"GET"});return this.parseWithSchema(e,Oc,"popular searches response")},au.prototype.listProtocols=async function(){const e=await this.requestJson("/protocols",{method:"GET"});return this.parseWithSchema(e,Vc,"protocols response")},au.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,Gc,"detect protocol response")},au.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,Jc,"registry search response")},au.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,Qc,"vector search response")}catch(t){if(t instanceof nu&&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}},au.prototype.searchStatus=async function(){const e=await this.requestJson("/search/status",{method:"GET"});return this.parseWithSchema(e,tl,"search status response")},au.prototype.websocketStats=async function(){const e=await this.requestJson("/websocket/stats",{method:"GET"});return this.parseWithSchema(e,rl,"websocket stats response")},au.prototype.metricsSummary=async function(){const e=await this.requestJson("/metrics",{method:"GET"});return this.parseWithSchema(e,ol,"metrics summary response")},au.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,ql,"search facets response")},au.prototype.adapters=async function(){const e=await this.requestJson("/adapters",{method:"GET"});return this.parseWithSchema(e,Nl,"adapters response")},au.prototype.adaptersDetailed=async function(){const e=await this.requestJson("/adapters/details",{method:"GET"});return this.parseWithSchema(e,Ll,"adapter details response")},au.prototype.adapterRegistryCategories=async function(){const e=await this.requestJson("/adapters/registry/categories",{method:"GET"});return this.parseWithSchema(e,Pl,"adapter registry categories response")},au.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,zl,"adapter registry adapters response")},au.prototype.createAdapterRegistryCategory=async function(e){const t=await this.requestJson("/adapters/registry/categories",{method:"POST",headers:{"content-type":"application/json"},body:ru(e)});return this.parseWithSchema(t,Ol,"adapter registry create category response").category},au.prototype.submitAdapterRegistryAdapter=async function(e){const t=await this.requestJson("/adapters/registry/adapters",{method:"POST",headers:{"content-type":"application/json"},body:ru(e)});return this.parseWithSchema(t,Dl,"adapter registry submit adapter response")},au.prototype.adapterRegistrySubmissionStatus=async function(e){const t=await this.requestJson(`/adapters/registry/submissions/${encodeURIComponent(e)}`,{method:"GET"});return this.parseWithSchema(t,Ml,"adapter registry submission status response")},au.prototype.purchaseCreditsWithHbar=async function(e){const t={accountId:e.accountId,payerKey:e.privateKey,hbarAmount:hu(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,Al,"credit purchase response")},au.prototype.getX402Minimums=async function(){const e=await this.requestJson("/credits/purchase/x402/minimums",{method:"GET"});return this.parseWithSchema(e,Rl,"x402 minimums response")},au.prototype.purchaseCreditsWithX402=async function(e){const{createPaymentClient:t,decodePaymentResponse:r}=await pu(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,xl,"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}},au.prototype.buyCreditsWithX402=async function(e){const t=e.network??"base",{createX402Signer:r}=await pu(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})},au.prototype.resolveUaid=async function(e){const t=await this.requestJson(`/resolve/${encodeURIComponent(e)}`,{method:"GET"});return this.parseWithSchema(t,Dc,"resolve UAID response")},au.prototype.registerAgent=async function(e,t){const r=t?.autoTopUp??this.registrationAutoTopUp;if(!r)return gu(this,e);await yu(this,e,r);let i=!1;for(;;)try{return await gu(this,e)}catch(o){if(this.extractInsufficientCreditsDetails(o)&&!i){await yu(this,e,r),i=!0;continue}throw o}},au.prototype.getRegistrationQuote=async function(e){const t=await this.requestJson("/register/quote",{method:"POST",body:ou(e),headers:{"content-type":"application/json"}});return this.parseWithSchema(t,vl,"registration quote response")},au.prototype.updateAgent=async function(e,t){const r=await this.requestJson(`/register/${encodeURIComponent(e)}`,{method:"PUT",body:ou(t),headers:{"content-type":"application/json"}});return this.parseWithSchema(r,Tl,"update agent response")},au.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,El,"registration progress response").progress}catch(r){if(r instanceof nu&&404===r.status)return null;throw r}},au.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 Zl();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 nu("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)}},au.prototype.validateUaid=async function(e){const t=await this.requestJson(`/uaids/validate/${encodeURIComponent(e)}`,{method:"GET"});return this.parseWithSchema(t,nl,"UAID validation response")},au.prototype.getUaidConnectionStatus=async function(e){const t=await this.requestJson(`/uaids/connections/${encodeURIComponent(e)}/status`,{method:"GET"});return this.parseWithSchema(t,al,"UAID connection status")},au.prototype.closeUaidConnection=async function(e){await this.request(`/uaids/connections/${encodeURIComponent(e)}`,{method:"DELETE"})},au.prototype.dashboardStats=async function(){const e=await this.requestJson("/dashboard/stats",{method:"GET"});return this.parseWithSchema(e,cl,"dashboard stats response")};const bu=e=>e.trim().toLowerCase(),wu=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"}]]),Iu={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},Tu=new Map(Object.entries(Iu).map(([e,t])=>[t,e])),Su=e=>{const t=bu(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=Iu[t];void 0!==e&&(i=e,r=t)}else Tu.has(i)&&(r=Tu.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}},ku=e=>{if("string"!=typeof e||0===e.trim().length)throw new Error("Ledger network is required.");const t=bu(e);return t.startsWith("hedera:")||t.includes("hedera-")||t.includes("hedera_")||"mainnet"===t||"testnet"===t?(e=>{const t=bu(e),r=wu.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):Su(t)},Eu=e=>new Error(`${e} is not supported by the in-memory signer`),vu=e=>{const t=Cu(),{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 Eu("getAccountBalance")},getAccountInfo:async()=>{throw Eu("getAccountInfo")},getAccountRecords:async()=>{throw Eu("getAccountRecords")},signTransaction:async e=>{throw Eu("signTransaction")},checkTransaction:async e=>{throw Eu("checkTransaction")},populateTransaction:async e=>{throw Eu("populateTransaction")},call:async e=>{throw Eu("call")}}};let Au=null;const Cu=()=>{if(Au)return Au;const e=function(e){if(Sa)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(!Wl(e,t))throw t}return null}("@hashgraph/sdk");if(e)return Au=e,e;throw new Error("@hashgraph/sdk is required for ledger signing. Install it as a dependency to enable createPrivateKeySigner.")};au.prototype.createLedgerChallenge=async function(e){const t=ku(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,qc,"ledger challenge response")},au.prototype.verifyLedgerChallenge=async function(e){const t=ku(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,Wc,"ledger verification response");return this.setLedgerApiKey(n.key),n},au.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=a.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:a.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})},au.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:u}=e,d=ku(r),p=l?` for ${l}`:"",h={accountId:t,network:d.canonical,expiresInMinutes:a};if(o)h.sign=o;else if(i)h.signer=i;else if(n){if("hedera"!==d.kind||!d.hederaNetwork)throw new Error("hederaPrivateKey can only be used with hedera:mainnet or hedera:testnet networks.");h.signer=vu({accountId:t,privateKey:n,network:d.hederaNetwork})}else{if(!s)throw new Error("Provide a signer, sign function, hederaPrivateKey, or evmPrivateKey to authenticate with the ledger.");{if("evm"!==d.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})}}u?.info?.(`Authenticating ledger account ${t} (${d.canonical})${p}...`);const g=await this.authenticateWithLedger(h);return c&&this.setDefaultHeader("x-account-id",g.accountId),u?.info?.(`Ledger authentication complete${p}. Issued key prefix: ${g.apiKey.prefix}…${g.apiKey.lastFour}`),g};const xu=new WeakMap;function Ru(e){const t=xu.get(e);if(t)return t;const r=new Map;return xu.set(e,r),r}function Nu(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()))))}au.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,Kc,"chat history snapshot response");return this.attachDecryptedHistory(e,i,t)},au.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}},au.prototype.registerConversationContextForEncryption=function(e){const t={sessionId:e.sessionId,sharedSecret:a.Buffer.from(e.sharedSecret),identity:e.identity?{...e.identity}:void 0},r=Ru(this),i=r.get(e.sessionId)??[],o=i.findIndex(e=>Nu(e.identity,t.identity));o>=0?i[o]=t:i.push(t),r.set(e.sessionId,i)},au.prototype.resolveDecryptionContext=function(e,t){if(t?.sharedSecret)return{sessionId:e,sharedSecret:this.normalizeSharedSecret(t.sharedSecret),identity:t.identity};const r=Ru(this).get(e);if(!r||0===r.length)return null;if(t?.identity){const e=r.find(e=>Nu(e.identity,t.identity));if(e)return e}return r[0]},au.prototype.decryptHistoryEntryFromContext=function(e,t,r){const i=t.cipherEnvelope;if(!i)return t.content;const o=a.Buffer.from(r.sharedSecret);try{return this.encryption.decryptCipherEnvelope({envelope:i,sharedSecret:o})}catch(n){return null}};class _u extends Error{constructor(e,t){super("Encryption is not enabled for this session"),this.sessionId=e,this.summary=t}}class Pu{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 _u(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 _u(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 Fu=new WeakMap,zu=new WeakMap;function Ou(e){const t=Fu.get(e);if(t)return t;const r=new Pu(e);return Fu.set(e,r),r}Object.defineProperty(au.prototype,"chat",{get(){const e=zu.get(this);if(e)return e;const t=Ou(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 zu.set(this,r),r}}),au.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=iu(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){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}},au.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")},au.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=Ou(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 _u){if("required"===t)throw r;return this.createPlaintextConversationHandle(r.sessionId,r.summary??null,e.auth,{uaid:e.uaid})}throw r}},au.prototype.acceptConversation=async function(e){const t=e.encryption?.preference??"preferred";if("disabled"===t)return this.createPlaintextConversationHandle(e.sessionId,null);try{const t=Ou(this);return await t.acceptSession({sessionId:e.sessionId,responderUaid:e.responderUaid,handshakeTimeoutMs:e.encryption?.handshakeTimeoutMs,pollIntervalMs:e.encryption?.pollIntervalMs})}catch(r){if(r instanceof _u&&"required"!==t)return this.createPlaintextConversationHandle(e.sessionId,null,void 0,{uaid:e.responderUaid});throw r}},au.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}},au.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,Uc,"chat history compaction response")},au.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,Lc,"session encryption status response")},au.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,$c,"encryption handshake response").handshake},au.prototype.sendMessage=async function(e){const t={message:e.message};void 0!==e.streaming&&(t.streaming=e.streaming),e.auth&&(t.auth=iu(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=ru(r));const i=await this.requestJson("/chat/message",{method:"POST",body:t,headers:{"content-type":"application/json"}});return this.parseWithSchema(i,Bc,"chat message response")},au.prototype.endSession=async function(e){await this.request(`/chat/session/${encodeURIComponent(e)}`,{method:"DELETE"})};class Du{constructor(e="info"){this.defaultEndpoint="https://kiloscribe.com/api/inscription-cdn",this.logger=P.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 q(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(Kg){const t=`Error resolving HRL for content and type: ${Kg.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(Kg){const t=`Error resolving HRL reference: ${Kg.message}`;throw this.logger.error(t),new Error(t)}}}class Mu{constructor(e){this.nodeHash=e}update(e){return this.nodeHash.update(e),this}digest(e){return this.nodeHash.digest(e)}}class Bu{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 Ku{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 Uu(){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 Lu(){return"undefined"==typeof window}class $u{constructor(e){this.nodeHmac=e}update(e){return this.nodeHmac.update(e),this}digest(e){return this.nodeHmac.digest(e)}}class Hu{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 qu{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 ju{constructor(){try{const e="crypto";this.crypto=require(e)}catch(e){throw new Error("Node.js crypto module not available")}}createHash(e){return new Mu(this.crypto.createHash(e))}createHmac(e,t){return new $u(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 Wu{createHash(e){return new Bu(e)}createHmac(e,t){return new Hu(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 Vu{createHash(e){return new Ku(e)}createHmac(e,t){return new qu(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 Gu(){switch(Uu().preferredAPI){case"node":try{return new ju}catch{return new Vu}case"web":return new Wu;default:return new Vu}}const Ju=["mainnet","testnet","previewnet","devnet"];function Yu(e){return Ju.includes(e)}const Xu=/^hedera:(mainnet|testnet|previewnet|devnet):\d+\.\d+\.\d+(?:-[a-zA-Z0-9]{5})?$/;function Zu(e){return Xu.test(e)}function Qu(e,t){if(!Yu(e))throw new Error("Invalid Hedera network");if(t.startsWith("hedera:")){if(Zu(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 ed(e){if(!Zu(e))throw new Error("Invalid Hedera CAIP-10");const[,t,r]=e.match(/^hedera:([^:]+):(.+)$/);return{network:t,accountId:r}}const td=/^eip155:(\d+):(0x[0-9a-fA-F]{39,40})$/;function rd(e){return td.test(e)}function id(e,t){const r=`eip155:${"number"==typeof e?String(e):e}:${t.startsWith("0x")?t:`0x${t}`}`;if(!rd(r))throw new Error("Invalid EIP-155 CAIP-10");return r}var od=(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))(od||{}),nd=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTONOMOUS=1]="AUTONOMOUS",e))(nd||{}),sd=(e=>(e[e.REST=0]="REST",e[e.WEBSOCKET=1]="WEBSOCKET",e[e.GRPC=2]="GRPC",e))(sd||{}),ad=(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))(ad||{}),cd=(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))(cd||{}),ld=(e=>(e.DNS="dns",e.SIGNATURE="signature",e.CHALLENGE="challenge",e))(ld||{}),ud=(e=>(e.PUBLIC="PUBLIC",e.CONTROLLED="CONTROLLED",e.FEE_BASED="FEE_BASED",e))(ud||{});const dd={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},pd=r.z.object({platform:r.z.string().min(1),handle:r.z.string().min(1)}),hd=r.z.object({type:r.z.nativeEnum(nd),capabilities:r.z.array(r.z.nativeEnum(ad)).min(1),model:r.z.string().min(1),creator:r.z.string().optional()}),gd=r.z.object({url:r.z.string().min(1),transport:r.z.enum(["stdio","sse"])}),md=r.z.object({type:r.z.nativeEnum(ld),value:r.z.string(),dns_field:r.z.string().optional(),challenge_path:r.z.string().optional()}),fd=r.z.object({minVersion:r.z.string().optional()}),yd=r.z.object({name:r.z.string().min(1),description:r.z.string().min(1)}),bd=r.z.object({name:r.z.string().min(1),description:r.z.string().min(1)}),wd=r.z.object({version:r.z.string().min(1),connectionInfo:gd,services:r.z.array(r.z.nativeEnum(cd)).min(1),description:r.z.string().min(1),verification:md.optional(),host:fd.optional(),capabilities:r.z.array(r.z.string()).optional(),resources:r.z.array(yd).optional(),tools:r.z.array(bd).optional(),maintainer:r.z.string().optional(),repository:r.z.string().optional(),docs:r.z.string().optional()}),Id=r.z.object({version:r.z.string().min(1),type:r.z.nativeEnum(od),display_name:r.z.string().min(1),alias:r.z.string().optional(),bio:r.z.string().optional(),socials:r.z.array(pd).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()}),Td=Id.extend({type:r.z.literal(od.PERSONAL),language:r.z.string().optional(),timezone:r.z.string().optional()}),Sd=Id.extend({type:r.z.literal(od.AI_AGENT),aiAgent:hd}),kd=Id.extend({type:r.z.literal(od.MCP_SERVER),mcpServer:wd}),Ed=r.z.object({version:r.z.string(),type:r.z.literal(od.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()}),vd=r.z.union([Td,Sd,kd,Ed]);class Ad{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=P.getInstance({level:e.logLevel||"info",module:"HCS-11",silent:e.silent}),this.mirrorNode=new q(this.network,this.logger),this.auth.privateKey?(this.operatorCtx=ee({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:od.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:od.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:od.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:od.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:od.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=vd.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 cs({module:"HCS11-Image",logger:this.logger,callback:o});n.preparing("Preparing to inscribe image",0);const s=w.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 Fa({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 _a({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:Ba(c.inscription)}),{imageTopicId:Ba(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 cs({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 _a(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 Fa(r,this.auth.signer,n)}if(!c.confirmed||!Ba(c.inscription))return o.failed("Failed to inscribe profile content"),{profileTopicId:"",transactionId:"",success:!1,error:"Failed to inscribe profile content"};const l=Ba(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&&Yu(this.network))try{const{HCS14Client:t}=await Promise.resolve().then(()=>Xp),r=new t({client:this.client}),i=await r.createDid({method:"hedera",client:this.client}),o=Qu(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(Kg){this.logger.warn("Hiero registrar not available; skipping UAID generation for profile",Kg)}}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 cs({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[ad.TEXT_GENERATION];for(const r of e){const e=dd[r.toLowerCase()];void 0===e||t.includes(e)||t.push(e)}return 0===t.length&&t.push(ad.TEXT_GENERATION),t}getAgentTypeFromMetadata(e){return"autonomous"===e.type?nd.AUTONOMOUS:nd.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=vd.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=vd.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=vd.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 Cd{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 Ad({network:t,auth:{operatorId:"0.0.0"}});i?.info(`Fetching profile by account ID ${e} on ${t}`),await F(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(Kg){return{registrations:[],error:`Error fetching registrations: ${Kg.message}`,success:!1}}}}function xd(e,t){return`hcs-10:op:${e}:${t}`}function Rd(e){var t,r;return W({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 Nd(e){return W({memo:e.memoOverride??`hcs-10:0:${e.ttl}:1`,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function _d(e){var t,r,i;return W({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 Pd(e){var t,r;return W({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 Fd(e){const t={p:"hcs-10",op:"connection_request",operator_id:e.operatorId,m:e.memo};return V({topicId:e.inboundTopicId,message:JSON.stringify(t),transactionMemo:xd(3,1)})}function zd(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 V({topicId:e.inboundTopicId,message:JSON.stringify(t),transactionMemo:xd(4,1)})}function Od(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 V({topicId:e.outboundTopicId,message:JSON.stringify(t),transactionMemo:xd(3,2)})}function Dd(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 V({topicId:e.outboundTopicId,message:JSON.stringify(t),transactionMemo:xd(4,2)})}function Md(e){const t={p:"hcs-10",op:"message",operator_id:e.operatorId,data:e.data,m:e.memo};return V({topicId:e.connectionTopicId,message:JSON.stringify(t),transactionMemo:xd(6,3)})}function Bd(e){const t={p:"hcs-10",op:"register",account_id:e.accountId,...e.inboundTopicId?{inbound_topic_id:e.inboundTopicId}:{},m:e.memo};return V({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:xd(0,0)})}var Kd=(e=>(e.INBOUND="inbound",e.OUTBOUND="outbound",e.CONNECTION="connection",e.REGISTRY="registry",e))(Kd||{});class Ud extends Cd{constructor(e){super(),this.network=e.network,this.logger=P.getInstance({level:e.logLevel||"info",module:"HCS10-BaseClient",prettyPrint:e.prettyPrint,silent:e.silent}),this.mirrorNode=new q(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(Kg){throw this.logger.error("Failed to fetch account",Kg),Kg}}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=Ld.getInstance().get(r);if(t)return this.logger.debug(`Cache hit for profile: ${e}`),t}try{const t=new Ad({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 Ld.getInstance().set(r,l),l}catch(Kg){if(n<i){this.logger.info(`Error retrieving profile for account ${e}, retrying in ${o}ms... (${Kg.message})`),n++,await new Promise(e=>setTimeout(e,o));continue}const r=`Failed to retrieve profile: ${Kg.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(Kg){const t=Kg,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(Kg){const t=`Failed to retrieve outbound messages: ${Kg.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(Kg){const t=`Failed to check connection created: ${Kg.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 Du(this.logger.getLevel());if(!r.isValidHRL(e))return e;return(await r.resolveHRL(e,{network:this.network,returnRaw:t})).content}catch(Kg){const t=`Error resolving HRL reference: ${Kg.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 Du(this.logger.getLevel());return await r.getContentWithType(e,{network:this.network,returnRaw:t})}catch(Kg){const t=`Error resolving HRL reference with type: ${Kg.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=Fd({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 u=await this.retrieveCommunicationTopics(o);if(!u)throw new Error("Failed to retrieve outbound topic");const d=l.topicSequenceNumber?.toNumber();if(!d)throw new Error("Failed to get response sequence number");const p=`${e}@${s}`,h=Od({outboundTopicId:u.outboundTopic,operatorId:p,connectionRequestId:d,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=Dd({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(){Ld.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(Kg){const t=Kg,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 Ld{constructor(){this.CACHE_TTL=36e5,this.cache=new Map,this.cacheExpiry=new Map}static getInstance(){return Ld.instance||(Ld.instance=new Ld),Ld.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 $d extends Error{constructor(e,t){super(e),this.payloadSize=t,this.name="PayloadSizeError"}}class Hd extends Error{constructor(e){super(e),this.name="AccountCreationError"}}class qd extends Error{constructor(e){super(e),this.name="TopicCreationError"}}class jd extends Error{constructor(e){super(e),this.name="ConnectionConfirmationError"}}class Wd{constructor(){this.config={},this.logger=P.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=ud.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===ud.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 Vd extends Ud{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=P.getInstance({level:e.logLevel||"info",module:"HCS-SDK",silent:e.silent}),this.operatorAccountId=e.operatorId,this.operatorCtx=ee({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 Ad({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 Hd("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(Kd.INBOUND,{accountId:e,ttl:r}),t){case ud.PUBLIC:o=!1;break;case ud.CONTROLLED:o=!0;break;case ud.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=Rd({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 cs({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 Wd;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,u,d;if(o=c,e.setInboundTopicId(s),e.setOutboundTopicId(a),r){const t=e.build();l=t.existingPfpTopicId||o.pfpTopicId,u=t.pfpBuffer,d=t.pfpFileName||"pfp.png"}else{const t=e.build();l=o.pfpTopicId,u=t.pfpBuffer,d=t.pfpFileName}!l&&u&&d?l=await this.handleProfilePictureCreation(u,d,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(Kg){const t=Kg,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 u=this.hcs11Client.getAgentTypeFromMetadata({type:n.type||"autonomous"}),d=n.socials?Object.entries(n.socials).filter(([e,t])=>t).map(([e,t])=>({platform:e,handle:t})):void 0,p=this.hcs11Client.createAIAgentProfile(e,u,o,n.model||"unknown",{alias:e.toLowerCase().replace(/\s+/g,"_"),bio:t,profileImage:l?`hcs://1/${l}`:void 0,socials:d,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(Kg){const t=Kg,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 ic(i,this.network,this.logger)}catch(Kg){const t=`Error getting exempt keys: ${Kg.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 u;try{const t=_d({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});u=i}else{const{topicId:e}=await this.executeTopicCreateTransaction({transaction:t});u=e}this.logger.info(`Created new connection topic ID: ${u}`)}catch(f){const e=`Failed to create connection topic: ${f}`;throw this.logger.error(e),new qd(e)}const d=`${e}@${s}`,p=await this.confirmConnection(e,u,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:u,operatorId:m,memo:`Connection established with ${t}`}),{connectionTopicId:u,confirmedConnectionSequenceNumber:p,operatorId:d}}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=zd({inboundTopicId:e,connectionTopicId:t,connectedAccountId:r,operatorId:s,connectionId:i,memo:o}),l=await this.submitPayload(c,void 0,n,a.requiresFee),u=l.topicSequenceNumber?.toNumber();if(!u)throw new jd("Failed to confirm connection: sequence number is null");return u}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(!Ba(i))throw new Error("Failed to inscribe large message content");a.data=`hcs://1/${Ba(i)}`,this.logger.info(`Large message inscribed with topic ID: ${Ba(i)}`)}catch(u){const e=`Error inscribing large message: ${u.message}`;throw this.logger.error(e),new Error(e)}}this.logger.info("Submitting message to connection topic",a);const l=Md({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=W({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 $d("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 $d("Payload size exceeds 1000 bytes limit",s);const a=V({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=w.lookup(t)||"application/octet-stream",o=this.operatorCtx.operatorKey,n=await as.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 _a({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 Vd({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 Q({mirrorNode:this.mirrorNode,logger:this.logger}),l=await i.resolveOperatorKey(c.accountId,c.privateKey),u=l.privateKey.publicKey.toString();a=new Vd({network:r.network,operatorId:c.accountId,operatorPrivateKey:l.privateKey.toString(),operatorPublicKey:u,keyType:l.keyType,logLevel:"info",guardedRegistryBaseUrl:n}),o&&o({stage:"preparing",message:"Initialized agent client",progressPercent:25,details:{state:s}});let d=s.outboundTopicId,p=s.inboundTopicId,h=s.pfpTopicId,g=s.profileTopicId;if(!d||!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}}})});d=t.outboundTopicId,p=t.inboundTopicId,h=t.pfpTopicId,g=t.profileTopicId,s.outboundTopicId=d,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:${d}`)||s.createdResources.push(`outbound:${d}`),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:d,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(Kg){const r=Kg,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(Kg){const t=Kg,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=Bd({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 ud.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`),ud.FEE_BASED}return ud.CONTROLLED}catch(Kg){const t=`Error determining topic type: ${Kg.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=m.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=Nd({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=Rd({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,ud.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:u,profileTopicId:d}=t;if(c)this.logger.info(`Using existing outbound topic ID: ${c}`);else{const t=Nd({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===ud.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}}})),!u&&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}}});u=(await this.inscribePfp(n,s)).pfpTopicId,this.logger.info(`Profile picture inscribed with topic ID: ${u}`),a&&a({stage:"preparing",message:"Profile picture inscribed",progressPercent:55,details:{outboundTopicId:c,inboundTopicId:l,pfpTopicId:u,state:{currentStage:"pfp",completedPercentage:55}}})}else u&&this.logger.info(`Using existing profile picture with topic ID: ${u}`);return{inboundTopicId:l,outboundTopicId:c,pfpTopicId:u,profileTopicId:d}}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=Z(c.privateKey),t=("ed25519"===e.detectedType?i.PrivateKey.fromStringED25519(c.privateKey):i.PrivateKey.fromStringECDSA(c.privateKey)).publicKey.toString();a=new Vd({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 Q({mirrorNode:this.mirrorNode,logger:this.logger}),u=await l.resolveOperatorKey(c.accountId,c.privateKey);e.setExistingAccount(c.accountId,c.privateKey);const d=("ed25519"===u.keyType?i.PrivateKey.fromStringED25519(c.privateKey):i.PrivateKey.fromStringECDSA(c.privateKey)).publicKey.toString();a=new Vd({network:r.network,operatorId:c.accountId,operatorPrivateKey:c.privateKey,operatorPublicKey:d,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(Kg){const r=Kg,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 _a({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=Ba(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,u=Pd({ttl:t,metadataTopicId:e,adminKey:i,submitKey:o,operatorPublicKey:this.client.operatorPublicKey||l.publicKey}),{topicId:d,response:p}=await this.executeTopicCreateTransaction({transaction:u});return c&&c({stage:"completed",message:"Registry topic created successfully",progressPercent:100,details:{topicId:d,metadataTopicId:e,transactionId:p.transactionId.toString()}}),this.logger.info(`Registry topic created successfully: ${d}`),{success:!0,topicId:d,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 Gd="undefined"!=typeof window;var Jd=(e=>(e[e.ACTION=0]="ACTION",e[e.ASSEMBLY=2]="ASSEMBLY",e[e.HASHLINKS=3]="HASHLINKS",e))(Jd||{});class Yd{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:Jd[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:Jd[this.registryType]}),"getOperatorAccountId"in this.client)o=await _a({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 Fa({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:Jd[this.registryType]})}getStats(){return{entryCount:this.entries.size,lastSync:this.lastSyncTimestamp,topicId:this.topicId,registryType:Jd[this.registryType]}}}const Xd=r.z.object({p:r.z.literal("hcs-12")}),Zd=r.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid Hedera address format"),Qd=r.z.string().regex(/^[a-f0-9]{64}$/,"Invalid SHA-256 hash format"),ep=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()}),tp=r.z.object({source_t_id:Zd,source_hash:Qd,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:Qd,source_structure:ep}),rp=r.z.lazy(()=>r.z.object({type:r.z.string().optional(),required:r.z.array(r.z.string()).optional(),properties:r.z.record(rp).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()})),ip=r.z.object({p:r.z.literal("hcs-12"),op:r.z.literal("register"),t_id:Zd,hash:Qd,wasm_hash:Qd,js_t_id:Zd.optional(),js_hash:Qd.optional(),interface_version:r.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid version format").optional(),info_t_id:Zd.optional(),source_verification:tp.optional(),previous_version:r.z.string().optional(),migration_notes:r.z.string().optional(),validation_rules:r.z.record(rp).optional(),m:r.z.string().optional()}),op=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:Zd.optional()});r.z.enum(["register","add-action","add-block","update"]);const np=Xd.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()}),sp=Xd.extend({op:r.z.literal("add-action"),t_id:Zd,alias:r.z.string(),config:r.z.any().optional(),data:Zd.optional()}),ap=Xd.extend({op:r.z.literal("add-block"),block_t_id:Zd,actions:r.z.record(r.z.string(),Zd).optional(),attributes:r.z.record(r.z.any()).optional(),children:r.z.array(r.z.string()).optional(),data:Zd.optional()}),cp=Xd.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:Zd,source_hash:Qd,description:r.z.string().optional()});const lp=r.z.discriminatedUnion("op",[np,sp,ap,cp]),up=np,dp=Xd.extend({op:r.z.literal("register"),t_id:Zd,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 pp(e){return ip.parse(e)}function hp(e){return lp.parse(e)}function gp(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 mp extends Yd{constructor(e,t,r,i){super(e,t,Jd.ACTION,r,i),this.actionsByHash=new Map,this.cryptoAdapter=Gu()}async registerWithWasm(e,t,r){let i,o;if(Lu()){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 za(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 za(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(Lu())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 za(t.t_id,{accountId:this.client.getOperatorAccountId(),privateKey:this.client.getOperatorPrivateKey(),network:this.networkType});else{const{accountId:r}=await this.client.getAccountAndSigner();e=await za(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(Lu())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{pp(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 fp{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 Du,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 Du,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 yp extends Yd{constructor(e,t,r,i){super(e,t,Jd.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{hp(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 bp extends Yd{constructor(e,t,r,i){super(e,t,Jd.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=gp(e,dp);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 wp{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 Ip{constructor(e){this.network=e.network,this.logger=e.logger||P.getInstance({level:e.logLevel||"info",module:"HCS12-BaseClient",prettyPrint:e.prettyPrint,silent:e.silent}),this.mirrorNode=new q(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 fp(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 yp(this.network,this.logger,e,this);await t.sync();return new wp(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 wp(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 Tp{constructor(){this.block={apiVersion:3},this.attributes={},this.supports={},this.actions={},this.logger=new P({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 Tp).setName(e).setTitle(t).setCategory("formatting").enableCommonSupports()}static createInteractiveBlock(e,t){return(new Tp).setName(e).setTitle(t).setCategory("widgets").enableCommonSupports()}static createWidgetBlock(e,t){return this.createInteractiveBlock(e,t)}static createContainerBlock(e,t){return(new Tp).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 Sp{constructor(e,t){this.wasmCache=new Map,this.logger=e,this.network=t,this.hrlResolver=new Du}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(Kg){throw URL.revokeObjectURL(o),Kg}}}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 kp{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(Kg){this.logger.warn("Failed to parse data-attributes",{uri:n,attributes:o[2],error:Kg.message})}const c=s.match(/data-actions=(['"])((?:(?!\1).)*)\1/s);let l;if(c)try{const e=c[2];l=JSON.parse(e)}catch(Kg){this.logger.warn("Failed to parse data-actions",{uri:n,actions:c[2],error:Kg.message})}const u=s.match(/data-loading=['"]([^'"]+)['"]/),d=u?.[1]||"eager";t.push({element:r,uri:n,...i,attributes:a,actions:l,loading:d,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 Ep{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 vp={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"}},Ap={ACTIONS:{},BLOCKS:{},ASSEMBLIES:{}};const Cp=/^[a-z0-9][a-z0-9-]*$/,xp=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 Rp(e){return e.trim()}function Np(e){return e.trim().toLowerCase()}function _p(e){const t=xp.parse(e);if("hcs-10"===t.protocol.trim().toLowerCase()&&!Zu(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()&&!rd(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:Np(t.registry),name:Rp(t.name),version:Rp(t.version),protocol:Np(t.protocol),nativeId:Rp(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 Pp="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function Fp(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+=Pp[r[o]];return i}function zp(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=Pp.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 Op(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 Dp(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"+Fp(globalThis.Buffer.from(c,"utf8"))));const l=Op(a);return l?`uaid:did:${s};${l}`:`uaid:did:${s}`}function Mp(e,t,r){return"string"==typeof e?Dp(e,t):async function(e,t,r){const{normalized:i,canonicalJson:o}=_p(e),n=Gu().createHash("sha384").update(globalThis.Buffer.from(o,"utf8")).digest(),s=await Promise.resolve(n),a=Fp(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||{}):{},u=c?Op(l):"";return u?`uaid:aid:${a};${u}`:`uaid:aid:${a}`}(e,t,r)}function Bp(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 Kp=["@hiero-did-sdk","resolver"].join("/");let Up=null;class Lp{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 Up||(Up=Gl(Kp).then(e=>e?.resolveDID??null)),Up}();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 $p{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=Bp(e);if("uaid"!==t.method)return null;const r=t.params.src;if(r){const e=globalThis.Buffer.from(zp(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 Hp=new $p;function qp(){Hp.register(new Lp)}class jp{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 Wp=new jp,Vp=["@hiero-did-sdk","registrar"].join("/");let Gp=null;class Jp{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 Gp||(Gp=Gl(Vp).then(e=>e?.createDID??null)),Gp}();if(!t)throw new Error("Hiero registrar unavailable. Ensure @hiero-did-sdk/registrar is installed.");return(await t({},{client:e.client})).did}}class Yp{constructor(e){this.registry=e?.registry??Hp,this.issuers=new jp,this.registerHederaIssuer(),this.registerHederaResolver(),this.logger=P.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=ee({network:e,operatorId:t,operatorKey:r,mirrorNode:new q(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 Jp)}async createDid(e){return this.issuers.issue(e)}canonicalizeAgentData(e){return _p(e)}createUaid(e,t,r){return"string"==typeof e?Mp(e,t):Mp(e,t,r)}parseHcs14Did(e){return Bp(e)}isHederaNetwork(e){return Yu(e)}isHederaCaip10(e){return Zu(e)}toHederaCaip10(e,t){return Qu(e,t)}parseHederaCaip10(e){return ed(e)}isEip155Caip10(e){return rd(e)}toEip155Caip10(e,t){return id(e,t)}getResolverRegistry(){return this.registry}registerHederaResolver(){this.registry.register(new Lp)}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=Qu(this.network,this.operatorId)}if(!r&&"hcs-10"===i&&this.network&&this.operatorId)try{if(!this.hcs10Client&&this.operatorPrivateKey&&(this.hcs10Client=new Vd({network:this.network,operatorId:this.operatorId,operatorPrivateKey:this.operatorPrivateKey,silent:!0})),this.hcs10Client)r=await this.hcs10Client.getOperatorId();else{const e=new Ad({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:Bp(n)}}}const Xp=Object.freeze(Object.defineProperty({__proto__:null,CanonicalAgentDataSchema:xp,HCS14Client:Yp,HCS14_PROTOCOL_REGEX:Cp,HederaHieroIssuer:Jp,HieroDidResolver:Lp,IssuerRegistry:jp,ResolverRegistry:$p,canonicalizeAgentData:_p,createUaid:Mp,defaultIssuerRegistry:Wp,defaultResolverRegistry:Hp,isEip155Caip10:rd,isHederaCaip10:Zu,isHederaNetwork:Yu,parseHcs14Did:Bp,parseHederaCaip10:ed,registerDefaultResolvers:qp,toEip155Caip10:id,toHederaCaip10:Qu},Symbol.toStringTag,{value:"Module"}));function Zp(e){return`hcs://1/${e}`}class Qp{constructor(e){this.network=e.network,this.logger=e.logger||P.getInstance({level:e.logLevel||"info",module:"HCS5Client",silent:e.silent}),this.mirrorNode=new q(this.network,this.logger)}}function eh(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 th=(e=>(e.REGISTER="register",e.UPDATE="update",e.DELETE="delete",e.MIGRATE="migrate",e))(th||{}),rh=(e=>(e[e.INDEXED=0]="INDEXED",e[e.NON_INDEXED=1]="NON_INDEXED",e))(rh||{});const ih=r.z.string().regex(/^\d+\.\d+\.\d+$/,{message:"Topic ID must be in Hedera format (e.g., '0.0.123456')"}),oh=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()}),nh=oh.extend({op:r.z.literal("register"),t_id:ih,metadata:r.z.string().optional()}),sh=oh.extend({op:r.z.literal("update"),uid:r.z.string(),t_id:ih,metadata:r.z.string().optional()}),ah=oh.extend({op:r.z.literal("delete"),uid:r.z.string()}),ch=oh.extend({op:r.z.literal("migrate"),t_id:ih,metadata:r.z.string().optional()}),lh=r.z.discriminatedUnion("op",[nh,sh,ah,ch]);class uh{constructor(e){this.network=e.network,this.logger=e.logger||P.getInstance({level:e.logLevel||"info",module:"HCS2Client",silent:e.silent}),this.mirrorNode=new q(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 lh.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:th.REGISTER,t_id:e,metadata:t,m:r}}createUpdateMessage(e,t,r,i,o="hcs-2"){return{p:o,op:th.UPDATE,t_id:e,uid:t,metadata:r,m:i}}createDeleteMessage(e,t,r="hcs-2"){return{p:r,op:th.DELETE,uid:e,m:t}}createMigrateMessage(e,t,r,i="hcs-2"){return{p:i,op:th.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===rh.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===rh.INDEXED?o:n?[n]:[],latestEntry:n}}}function dh(e){var t,r;return W({memo:e.memoOverride??(t=e.registryType,r=e.ttl,`hcs-2:${t}:${r}`),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function ph(e){const t={p:"hcs-2",op:th.REGISTER,t_id:e.targetTopicId,metadata:e.metadata,m:e.memo};return V({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})}const hh=class e extends uh{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=ee({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??rh.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=dh({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 u=await l.execute(this.client),d=(await u.getReceipt(this.client)).topicId;if(!d)throw new Error("Failed to create registry: No topic ID in receipt");const p=d.toString();return this.registryTypeCache.set(p,t),this.logger.info(`Created registry topic: ${p} (${t===rh.INDEXED?"Indexed":"Non-indexed"}, TTL: ${r}s)`),{success:!0,topicId:p,transactionId:u.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(th.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!==rh.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(th.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!==rh.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(th.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(th.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===rh.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===rh.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=V({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}};hh.operationAnalyticsCode={[th.REGISTER]:0,[th.UPDATE]:1,[th.DELETE]:2,[th.MIGRATE]:3};let gh=hh;class mh extends uh{constructor(e){super({network:e.network,logLevel:e.logLevel,silent:e.silent,mirrorNodeUrl:e.mirrorNodeUrl,logger:e.logger}),this.hwc=e.hwc,Sa?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??rh.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=X.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=X.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===rh.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!==th.REGISTER)throw new Error(`Invalid operation type: ${r.op}, expected ${th.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!==rh.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!==rh.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=V({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 fh={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*))$/},yh=r.z.string().regex(fh.HEDERA_ACCOUNT_REGEX,"Invalid Hedera account ID format"),bh=r.z.string().regex(/^\d+$/,"Must be a valid number").max(fh.MAX_NUMBER_LENGTH,`Max ${fh.MAX_NUMBER_LENGTH} digits`),wh=r.z.string().min(1,"Tick cannot be empty").transform(e=>e.toLowerCase().trim()),Ih=r.z.object({p:r.z.literal("hcs-20"),m:r.z.string().optional()}),Th=Ih.extend({op:r.z.literal("deploy"),name:r.z.string().min(1).max(fh.MAX_NAME_LENGTH),tick:wh,max:bh,lim:bh.optional(),metadata:r.z.string().max(fh.MAX_METADATA_LENGTH).optional()}),Sh=Ih.extend({op:r.z.literal("mint"),tick:wh,amt:bh,to:yh}),kh=Ih.extend({op:r.z.literal("burn"),tick:wh,amt:bh,from:yh}),Eh=Ih.extend({op:r.z.literal("transfer"),tick:wh,amt:bh,from:yh,to:yh}),vh=Ih.extend({op:r.z.literal("register"),name:r.z.string().min(1).max(fh.MAX_NAME_LENGTH),metadata:r.z.string().max(fh.MAX_METADATA_LENGTH).optional(),private:r.z.boolean(),t_id:yh}),Ah=r.z.discriminatedUnion("op",[Th,Sh,kh,Eh,vh]);class Ch extends Error{constructor(e){super(e),this.name="HCS20Error"}}class xh extends Ch{constructor(e,t){super(e),this.tick=t,this.name="PointsDeploymentError"}}class Rh extends Ch{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 Nh extends Ch{constructor(e,t,r,i,o){super(e),this.tick=t,this.from=r,this.amount=i,this.availableBalance=o,this.name="PointsBurnError"}}class _h extends Ch{constructor(e,t){super(e),this.validationErrors=t,this.name="PointsValidationError"}}class Ph extends Ch{constructor(e,t){super(e),this.topicId=t,this.name="TopicRegistrationError"}}class Fh extends Ch{constructor(e){super(`Invalid Hedera account format: ${e}`),this.account=e,this.name="InvalidAccountFormatError"}}class zh{constructor(e){this.logger=e.logger||new P({module:"HCS20Client"}),this.network="mainnet"===e.network?"mainnet":"testnet",this.mirrorNode=new q(this.network,this.logger,e.mirrorNodeUrl?{customUrl:e.mirrorNodeUrl}:void 0),this.registryTopicId=e.registryTopicId||fh.REGISTRY_TOPIC_ID,this.publicTopicId=e.publicTopicId||fh.PUBLIC_TOPIC_ID}validateMessage(e){try{return Ah.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(!fh.HEDERA_ACCOUNT_REGEX.test(e))throw new Fh(e);return e}return e.toString()}topicToString(e){if("string"==typeof e){if(!fh.HEDERA_ACCOUNT_REGEX.test(e))throw new Fh(e);return e}return e.toString()}}function Oh(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 V({topicId:e.topicId,message:JSON.stringify(t)})}function Dh(e){const t={p:"hcs-20",op:"mint",tick:e.tick.toLowerCase().trim(),amt:e.amt,to:e.to,m:e.memo};return V({topicId:e.topicId,message:JSON.stringify(t)})}function Mh(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 V({topicId:e.topicId,message:JSON.stringify(t)})}function Bh(e){const t={p:"hcs-20",op:"burn",tick:e.tick.toLowerCase().trim(),amt:e.amt,from:e.from,m:e.memo};return V({topicId:e.topicId,message:JSON.stringify(t)})}function Kh(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 V({topicId:e.registryTopicId,message:JSON.stringify(t)})}class Uh extends Error{constructor(e,t){super(e),this.code=t,this.name="HCS21ValidationError"}}function Lh(e){const t=e.indexed??0,r=e.type??lc.ADAPTER_REGISTRY;if(e.metaTopicId&&!cc.test(e.metaTopicId))throw new Uh("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 $h(e){return W({memo:Lh({ttl:e.ttl,indexed:e.indexed,type:e.type,metaTopicId:e.metaTopicId}),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function Hh(e){const t=JSON.stringify(e.declaration),r=globalThis.Buffer.byteLength(t,"utf8");if(r>sc)throw new Uh(`HCS-21 payload exceeds safe limit of 1000 bytes (${r}); Hedera cap is 1024`,"size_exceeded");return V({topicId:e.topicId,message:JSON.stringify(e.declaration),transactionMemo:e.transactionMemo})}class qh{constructor(e){this.network=e.network,this.logger=e.logger||new P({level:"info",module:"HCS-21"}),this.mirrorNode=new q(this.network,this.logger,{customUrl:e.mirrorNodeUrl})}buildDeclaration(e){const t={p:oc,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=pc.parse(t);return this.assertSizeLimit(r),r}catch(t){const e=t instanceof Error?t.message:"Invalid adapter declaration";throw new Uh(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===oc)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>sc)throw new Uh(`HCS-21 payload exceeds safe limit of 1000 bytes (${r}); Hedera cap is 1024`,"size_exceeded")}}function jh(e){if(Array.isArray(e))return e.map(jh);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]=jh(i);return r}return e}function Wh(e){const t=jh(e);return JSON.stringify(t)}function Vh(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 Gh(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 Jh{constructor(e){this.network=e.network,this.logger=e.logger||new P({module:"HCS-15",level:e.logLevel||"info"}),this.mirrorNode=new q(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(Kg){return this.logger.warn("verifyPetalAccount failed",{error:String(Kg)}),!1}}}var Yh=(e=>(e[e.COMMUNICATION=0]="COMMUNICATION",e[e.TRANSACTION=1]="TRANSACTION",e[e.STATE=2]="STATE",e))(Yh||{}),Xh=(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))(Xh||{});class Zh extends Error{constructor(e,t){super(e),this.code=t,this.name="FloraError"}}function Qh(e){const t=function(e){return`hcs-16:${e.floraAccountId}:${e.topicType}`}({floraAccountId:e.floraAccountId,topicType:e.topicType}),r=W({memo:t,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey});return e.autoRenewAccountId&&r.setAutoRenewAccountId(i.AccountId.fromString(e.autoRenewAccountId)),r}function eg(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 tg(e){const t={p:"hcs-16",op:e.op,operator_id:e.operatorId,...e.body||{}};return V({topicId:e.topicId,message:JSON.stringify(t)})}function rg(e){return tg({topicId:e.topicId,operatorId:e.operatorId,op:Xh.FLORA_CREATED,body:{flora_account_id:e.floraAccountId,topics:e.topics}})}function ig(e){return tg({topicId:e.topicId,operatorId:e.operatorId,op:Xh.TRANSACTION,body:{schedule_id:e.scheduleId,data:e.data,m:e.data}})}function og(e){return tg({topicId:e.topicId,operatorId:e.operatorId,op:Xh.STATE_UPDATE,body:{hash:e.hash,epoch:e.epoch,timestamp:(new Date).toISOString()}})}function ng(e){return tg({topicId:e.topicId,operatorId:e.operatorId,op:Xh.FLORA_JOIN_REQUEST,body:{candidate_account_id:e.candidateAccountId}})}function sg(e){return tg({topicId:e.topicId,operatorId:e.operatorId,op:Xh.FLORA_JOIN_VOTE,body:{candidate_account_id:e.candidateAccountId,approve:e.approve}})}function ag(e){return tg({topicId:e.topicId,operatorId:e.operatorId,op:Xh.FLORA_JOIN_ACCEPTED,body:{members:e.members,epoch:e.epoch}})}class cg{constructor(e){this.network=e.network,this.logger=e.logger||new P({level:"info",module:"HCS-16"}),this.mirrorNode=new q(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:Qh({floraAccountId:e.floraAccountId,topicType:Yh.COMMUNICATION,adminKey:e.keyList,submitKey:e.submitList,autoRenewAccountId:e.autoRenewAccountId}),transaction:Qh({floraAccountId:e.floraAccountId,topicType:Yh.TRANSACTION,adminKey:e.keyList,submitKey:e.submitList,autoRenewAccountId:e.autoRenewAccountId}),state:Qh({floraAccountId:e.floraAccountId,topicType:Yh.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!==Yh.COMMUNICATION&&i!==Yh.TRANSACTION&&i!==Yh.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:u,...d}=s,p=d.op,h=d.operator_id;if(t?.opFilter&&p!==t.opFilter)continue;if("string"!=typeof h)continue;const g=d;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 lg=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 ug extends Error{constructor(e,t){super(e),this.code=t,this.name="StateHashError"}}var dg=(e=>(e[e.STATE=0]="STATE",e))(dg||{});function pg(e){return`hcs-17:0:${e}`}function hg(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 gg{constructor(e){this.network=e.network,this.logger=e.logger||new P({level:e.logLevel||"info",module:"HCS-17"}),this.mirrorNode=new q(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=lg.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 pg(e)}async validateHCS17Topic(e){try{const t=hg((await this.mirrorNode.getTopicInfo(e)).memo);return t?t.type!==dg.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(Kg){return{valid:!1,error:String(Kg)}}}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(Ug){this.logger.debug(`Failed to parse HCS-17 message: ${Ug}`)}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=p.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=p.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=p.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 mg(e){return W({memo:pg(e.ttl),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function fg(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 V({topicId:e.topicId,message:JSON.stringify(t),transactionMemo:e.transactionMemo})}var yg=(e=>(e.ANNOUNCE="announce",e.PROPOSE="propose",e.RESPOND="respond",e.COMPLETE="complete",e.WITHDRAW="withdraw",e))(yg||{});function bg(e){return"object"==typeof e&&null!==e}function wg(e){return"string"==typeof e}function Ig(e){return"number"==typeof e&&Number.isFinite(e)}function Tg(e){if(!bg(e))return!1;if("hcs-18"!==e.p)return!1;if(!wg(e.op))return!1;const t=e.op;return!!["announce","propose","respond","complete","withdraw"].includes(t)&&"data"in e}var Sg=(e=>(e.IDLE="idle",e.ANNOUNCED="announced",e.PROPOSING="proposing",e.FORMING="forming",e.ACTIVE="active",e.WITHDRAWN="withdrawn",e))(Sg||{});class kg extends Error{constructor(e,t){super(e),this.code=t,this.name="DiscoveryError"}}function Eg(e,t){return t&&t.trim().length>0?t:e&&e>0?`hcs-18:0:${e}`:"hcs-18:0"}function vg(e){return W({memo:Eg(e.ttlSeconds,e.memoOverride),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function Ag(e){const t="string"==typeof e.transactionMemo&&e.transactionMemo.length>0?e.transactionMemo:`hcs-18:op:${function(e){switch(e){case yg.ANNOUNCE:return 0;case yg.PROPOSE:return 1;case yg.RESPOND:return 2;case yg.COMPLETE:return 3;case yg.WITHDRAW:return 4;default:return 0}}(e.message.op)}`;return(new i.TopicMessageSubmitTransaction).setTopicId(e.topicId).setMessage(JSON.stringify(e.message)).setTransactionMemo(t)}function Cg(e){return{p:"hcs-18",op:yg.ANNOUNCE,data:e}}function xg(e){return{p:"hcs-18",op:yg.PROPOSE,data:e}}function Rg(e){return{p:"hcs-18",op:yg.RESPOND,data:e}}function Ng(e){return{p:"hcs-18",op:yg.COMPLETE,data:e}}function _g(e){return{p:"hcs-18",op:yg.WITHDRAW,data:e}}class Pg{constructor(e){this.network=e.network,this.logger=e.logger||P.getInstance({module:"HCS-18"}),this.mirrorNode=new q(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 Fg=(e=>(e.FIXED_FEE="FIXED_FEE",e.FRACTIONAL_FEE="FRACTIONAL_FEE",e.ROYALTY_FEE="ROYALTY_FEE",e))(Fg||{});class zg{constructor(e){this.customFees=[],this.logger=e.logger,this.mirrorNode=new q(e.network,e.logger),this.defaultCollectorAccountId=e.defaultCollectorAccountId||""}static forHbar(e,t,r,i,o=[]){return new zg({network:r,logger:i,defaultCollectorAccountId:t}).addHbarFee(e,t,o)}static async forToken(e,t,r,i,o,n=[],s){const a=new zg({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:Fg.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:Fg.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 Og{constructor(){this.resolver=null,this.onUnavailableCallbacks=[],this.logger=P.getInstance({module:"ContentResolverRegistry"})}static getInstance(){return Og._instance||(Og._instance=new Og),Og._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 Dg=Og.getInstance();class Mg{constructor(){this.contentStore=null,this.logger=P.getInstance({module:"ContentStoreService"})}static getInstance(){return Mg._instance||(Mg._instance=new Mg),Mg._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 Bg=Mg.getInstance();exports.AIAgentCapability=ad,exports.AIAgentDetailsSchema=hd,exports.AIAgentProfileSchema=Sd,exports.AIAgentType=nd,exports.AccountCreationError=Hd,exports.ActionBuilder=class{constructor(e){this.cryptoAdapter=Gu(),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(Lu())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(Lu())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(Lu())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=mp,exports.AgentBuilder=Wd,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 P({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=wp,exports.AssemblyRegistry=yp,exports.BaseProfileSchema=Id,exports.BaseRegistry=Yd,exports.BlockBuilder=Tp,exports.BlockLoader=fp,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 kp(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 Sp(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(Kg){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 Ep(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 zh{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 mh({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 mh({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 _h("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 _h("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 Ph(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=mh,exports.BrowserHCSClient=class extends Ud{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=P.getInstance({level:t,module:"HCS-Browser",prettyPrint:e.prettyPrint,silent:e.silent}),Gd)try{const{accountId:t,signer:r}=this.getAccountAndSigner();this.hcs11Client=new Ad({network:e.network,auth:{operatorId:t,signer:r},logLevel:e.logLevel,silent:e.silent})}catch(Ug){this.logger.warn(`Failed to initialize HCS11Client: ${Ug}`)}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(!Ba(i))throw new Error("Failed to inscribe large message content");n.data=`hcs://1/${Ba(i)}`,this.logger.info(`Large message inscribed with topic ID: ${Ba(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),u=this._generateHcs10Memo(Kd.CONNECTION,{ttl:n,inboundTopicId:e,connectionId:r}),d=(new i.TopicCreateTransaction).setTopicMemo(u).setAutoRenewAccountId(i.AccountId.fromString(s)).setAdminKey(l).setSubmitKey(l);this.logger.debug("Executing topic creation transaction");const p=await this.hwc.executeTransactionWithErrorHandling(d,!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 cs({module:"ProfileCreate",logger:this.logger,callback:r});try{const r=e instanceof Wd;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,u;if(o=a,e.setInboundTopicId(n),e.setOutboundTopicId(s),r){const t=e.build();c=t.existingPfpTopicId||o.pfpTopicId,l=t.pfpBuffer,u=t.pfpFileName||"pfp.png"}else{const t=e.build();c=o.pfpTopicId,l=t.pfpBuffer,u=t.pfpFileName}!c&&l&&u?c=await this.handleProfilePictureCreation(l,u,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 d="";o.outboundTopicId&&(d=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:d,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 u=await this.hcs11Client.createAndInscribeProfile(l,s?.updateAccountMemo??!0,{progressCallback:e=>c?.report({...e,progressPercent:e.progressPercent??0})});if(!u.success){a&&a.failed(`Failed to inscribe ${e?"agent":"person"} profile`,{error:u.error});let t=`Failed to inscribe ${e?"agent":"person"} profile`;throw u.error&&(t=u.error),new Error(t)}i.profileTopicId=u.profileTopicId,i.createdResources&&i.createdResources.push(`profile:${u.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 cs({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,u=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:u}),{...a,confirmed:u,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 cs({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 u=l?.progressCallback,d=new cs({module:"StoreHCS11Profile",logger:this.logger,callback:u});d.preparing("Preparing agent profile data",0);let p=c;if(!p&&s&&a){const e=d.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:d.failed("Failed to inscribe profile picture, continuing without PFP")}else c?d.preparing(`Using existing profile picture: ${c}`,30):d.preparing("No profile picture provided",30);if(!this.hcs11Client)return d.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"});d.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=d.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?(d.completed("Profile stored successfully",{profileTopicId:y.profileTopicId}),{profileTopicId:y.profileTopicId,pfpTopicId:p,success:!0,transactionId:y.transactionId||""}):(d.failed("Failed to inscribe profile"),{profileTopicId:"",success:!1,error:y.error||"Failed to inscribe profile",transactionId:y.transactionId||""})}catch(u){return this.logger.error(`Error storing HCS11 profile: ${u.message}`),{profileTopicId:"",success:!1,error:u.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 u=c.result;return u?.topicId?{success:!0,topicId:u.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=w.lookup(t)||"application/octet-stream",s=await as.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 Fa({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 cs({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(Kd.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(Kd.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=xp,exports.ConnectionConfirmationError=jd,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=P.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=Dg,exports.ContentResolverRegistryImpl=Og,exports.ContentStoreService=Bg,exports.CustomFeeType=Fg,exports.DiscoveryError=kg,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=yg,exports.DiscoveryState=Sg,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 Qa,this.logger=P.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 u=t?.decodeFunctionResult(s.c.abi.name,l.result);let d={values:[]};u&&s.c.abi.outputs?.forEach((e,t)=>{const r=ec(u[t],e.type);d.values.push(r),e.name&&(d[e.name]=r)}),await this.cache.set(e,JSON.stringify(d)),o[s.c.abi.name]=d,r[s.c.abi.name]=d}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=sd,exports.FallbackCryptoAdapter=Vu,exports.FallbackHashAdapter=Ku,exports.FallbackHmacAdapter=qu,exports.FeeConfigBuilder=zg,exports.FloraBuilder=class{constructor(){this.config={version:"1.0",type:3},this.logger=P.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=Zh,exports.FloraOperation=Xh,exports.FloraTopicType=Yh,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=z,exports.HCS10BaseClient=Ud,exports.HCS10Cache=Ld,exports.HCS10Client=Vd,exports.HCS11Client=Ad,exports.HCS11ProfileSchema=vd,exports.HCS12BaseClient=Ip,exports.HCS12BrowserClient=class extends Ip{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 mp(this.network,this.logger,this.actionRegistryTopicId,this),this._blockLoader=new fp(this.network,this.logger,this),this._assemblyRegistry=new yp(this.network,this.logger,this._assemblyRegistryTopicId,this),this._hashLinksRegistry=new bp(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={[Jd.ACTION]:"hcs-12:1:60:0",[Jd.ASSEMBLY]:"hcs-12:1:60:2",[Jd.HASHLINKS]:"hcs-12:1:60:3"}[e];this.logger.info("Creating registry topic via wallet",{registryType:Jd[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),u=await l.getReceiptWithSigner(n);if(!u.topicId)throw new Error("Failed to create topic: topicId is null");const d=u.topicId.toString();switch(this.logger.info("Registry topic created via wallet",{topicId:d,registryType:Jd[e]}),e){case Jd.ACTION:this.actionRegistryTopicId=d;break;case Jd.ASSEMBLY:this._assemblyRegistryTopicId=d;case Jd.HASHLINKS:}return d}async createAssemblyTopic(){this.logger.info("Creating new assembly topic");return await this.createRegistryTopic(Jd.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=w.lookup(t)||"application/octet-stream",s=await as.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 Fa({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 Ip{constructor(e){super(e),this.operatorAccountId=e.operatorId,this.operatorCtx=ee({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 mp(this.network,this.logger,this.actionRegistryTopicId,this),this._blockLoader=new fp(this.network,this.logger,this),this._assemblyRegistry=new yp(this.network,this.logger,this._assemblyRegistryTopicId,this),this._hashLinksRegistry=new bp(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={[Jd.ACTION]:"hcs-12:1:60:0",[Jd.ASSEMBLY]:"hcs-12:1:60:2",[Jd.HASHLINKS]:"hcs-12:1:60:3"}[e];this.logger.info("Creating registry topic",{registryType:Jd[e],memo:i});const o=W({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:Jd[e]}),e){case Jd.ACTION:this.actionRegistryTopicId=a;break;case Jd.ASSEMBLY:this._assemblyRegistryTopicId=a;case Jd.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=V({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=w.lookup(t)||"application/octet-stream",o=await as.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 _a({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=Yp,exports.HCS14_PROTOCOL_REGEX=Cp,exports.HCS15BaseClient=Jh,exports.HCS15BrowserClient=class extends Jh{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=Vh({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?.(),u=`0x${o.toEvmAddress()}`;return this.logger.info("Created HCS-15 base account (browser)",{accountId:l,evmAddress:u}),{accountId:l,privateKey:r,privateKeyHex:r.toStringRaw(),publicKey:o,evmAddress:u}}async createPetalAccount(e){const t=this.requireSigner(),r=Gh({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 Jh{constructor(e){super(e),this.operatorId=i.AccountId.fromString(e.operatorId),this.operatorCtx=ee({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=Vh({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=Gh({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=cg,exports.HCS16BrowserClient=class extends cg{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=Qh({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=rg(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async sendTransaction(e){const t=this.getSigner(),r=ig(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=og(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=eg({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:u,state:d}=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 u.freezeWithSigner(t)).executeWithSigner(t)).getReceiptWithSigner(t),g=await(await(await d.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=rg({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=ng(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async sendFloraJoinVote(e){const t=this.getSigner(),r=sg(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async sendFloraJoinAccepted(e){const t=this.getSigner(),r=ag(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}},exports.HCS16Client=class extends cg{constructor(e){super({network:e.network,logger:e.logger}),this.operatorId=i.AccountId.fromString(e.operatorId);const t=new q(e.network,this.logger);this.operatorCtx=ee({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=Qh({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=rg(e);return(await t.execute(this.client)).getReceipt(this.client)}async sendTransaction(e){const t=ig(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=og(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=eg({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}),u=await a.execute(this.client).then(e=>e.getReceipt(this.client)),d=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:u.topicId.toString(),transaction:d.topicId.toString(),state:p.topicId.toString()}}}async publishFloraCreated(e){const t=rg({topicId:e.communicationTopicId,operatorId:e.operatorId,floraAccountId:e.floraAccountId,topics:e.topics});return(await t.execute(this.client)).getReceipt(this.client)}},exports.HCS17BaseClient=gg,exports.HCS17BrowserClient=class extends gg{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=mg({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=fg({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=fg({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 gg{constructor(e){super(e),this.operatorId=i.AccountId.fromString(e.operatorId),this.operatorCtx=ee({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=mg({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=fg({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=fg({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=dg,exports.HCS18BaseClient=Pg,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=Cg(e.data);return this.submit(e.discoveryTopicId,t)}async propose(e){const t=xg(e.data);return this.submit(e.discoveryTopicId,t)}async respond(e){const t=Rg(e.data);return this.submit(e.discoveryTopicId,t)}async complete(e){const t=Ng(e.data);return this.submit(e.discoveryTopicId,t)}async withdraw(e){const t=_g(e.data);return this.submit(e.discoveryTopicId,t)}},exports.HCS18Client=class extends Pg{constructor(e){super({network:e.network,logger:P.getInstance({level:e.logLevel||"info",module:"HCS-18",silent:e.silent})}),this.operatorCtx=ee({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=vg({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=Cg(e.data),r=Ag({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=xg(e.data),r=Ag({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=Rg(e.data),r=Ag({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=Ng(e.data),r=Ag({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=_g(e.data),r=Ag({topicId:e.discoveryTopicId,message:t,transactionMemo:e.memo}),i=await r.execute(this.client);return await i.getReceipt(this.client)}},exports.HCS20BaseClient=zh,exports.HCS20BurnMessageSchema=kh,exports.HCS20Client=class extends zh{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=ee({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 gh({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 gh({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 xh("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 _h("Invalid deploy message",n.errors);const s=Oh({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=Dh({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 Rh("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=Mh({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 Nh("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=Bh({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 _h("Invalid register message",i.errors);if(!this.registryTopicId)throw new xh("Registry topic not available",e.name);t?.({stage:"submitting",percentage:50});const o=Kh({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 F(2e3)}this.logger.warn(`Transaction ${t} not found on mirror node after ${r} attempts`)}},exports.HCS20DeployMessageSchema=Th,exports.HCS20Error=Ch,exports.HCS20MessageSchema=Ah,exports.HCS20MintMessageSchema=Sh,exports.HCS20PointsIndexer=class{constructor(e,t,r){this.isProcessing=!1,this.lastIndexedSequence=new Map,this.logger=t||new P({level:"info",module:"HCS20PointsIndexer"}),this.mirrorNode=new q(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||fh.PUBLIC_TOPIC_ID:null,o=r?e?.registryTopicId||fh.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||fh.PUBLIC_TOPIC_ID:null,o=r?e?.registryTopicId||fh.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=Ah.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),u=l?(BigInt(l.balance)+s).toString():e.amt;c.set(e.to,{tick:o,accountId:e.to,balance:u,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=vh,exports.HCS20TransferMessageSchema=Eh,exports.HCS20_CONSTANTS=fh,exports.HCS21BaseClient=qh,exports.HCS21BrowserClient=class extends qh{constructor(e){super({network:e.network,logger:e.logger}),this.hwc=e.hwc}async createRegistryTopic(e){const{publicKey:t}=await this.getSignerContext(),r=$h({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 Uh("Failed to create HCS-21 registry topic","invalid_payload");return o.topicId.toString()}async createAdapterVersionPointerTopic(e){const{publicKey:t}=await this.getSignerContext(),r=dh({registryType:rh.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 Uh("Failed to create HCS-2 registry version topic","invalid_payload");return o.topicId.toString()}async createRegistryDiscoveryTopic(e){const{publicKey:t}=await this.getSignerContext(),r=dh({registryType:rh.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 Uh("Failed to create registry-of-registries topic","invalid_payload");return o.topicId.toString()}async createAdapterCategoryTopic(e){const{publicKey:t}=await this.getSignerContext(),r=$h({ttl:e.ttl,indexed:e.indexed??0,type:lc.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 Uh("Failed to create adapter category topic","invalid_payload");return o.topicId.toString()}async publishVersionPointer(e){const t=ph({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 Uh("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 Uh("Version pointer topic has no messages","invalid_payload");const r=t.t_id;if("string"!=typeof r||0===r.length)throw new Uh("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=ph({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 Uh("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=ph({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 Uh("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=Hh({topicId:e.topicId,declaration:t,transactionMemo:e.transactionMemo}),{receipt:o,transactionId:n}=await this.executeWithWallet(r);if(o.status!==i.Status.Success)throw new Uh("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 Uh("Wallet is not connected","invalid_payload");const r=await this.hwc.requestAccount(t),o=r?.key?.key;if(!o)throw new Uh("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 qh{constructor(e){const t=e.logger||new P({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=ee({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=mc.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 _a({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 Uh("Failed to inscribe HCS-21 metadata","invalid_payload");const s=n.inscription.jsonTopicId||n.inscription.topic_id||Ba(n.inscription);if(!s)throw new Uh("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,u=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,...u}}async createRegistryTopic(e){await this.operatorCtx.ensureInitialized();const t=$h({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 Uh("Failed to create HCS-21 registry topic","invalid_payload");return o.topicId.toString()}async createAdapterVersionPointerTopic(e){await this.operatorCtx.ensureInitialized();const t=dh({registryType:rh.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 Uh("Failed to create HCS-2 registry version topic","invalid_payload");return o.topicId.toString()}async createRegistryDiscoveryTopic(e){await this.operatorCtx.ensureInitialized();const t=dh({registryType:rh.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 Uh("Failed to create registry-of-registries topic","invalid_payload");return o.topicId.toString()}async createAdapterCategoryTopic(e){await this.operatorCtx.ensureInitialized();const t=$h({ttl:e.ttl,indexed:e.indexed??0,type:lc.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 Uh("Failed to create adapter category topic","invalid_payload");return o.topicId.toString()}async publishVersionPointer(e){await this.operatorCtx.ensureInitialized();const t=ph({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 Uh("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 Uh("Version pointer topic has no messages","invalid_payload");const r=t.t_id;if("string"!=typeof r||0===r.length)throw new Uh("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=ph({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 Uh("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=ph({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 Uh("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=Hh({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 Uh("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 Uh("Unable to resolve manifest sequence number","invalid_payload");i=Number(t.sequence_number)}if(!Number.isFinite(i))throw new Uh("Invalid manifest sequence number","invalid_payload");const o=`hcs://1/${e}`;if(!ac.test(o))throw new Uh("Manifest pointer format is invalid","invalid_payload");return{pointer:o,sequenceNumber:i}}},exports.HCS21ManifestPointerPattern=ac,exports.HCS21MetadataPointerPattern=cc,exports.HCS21TopicIdPattern=/^0\.0\.\d+$/,exports.HCS21TopicType=lc,exports.HCS21ValidationError=Uh,exports.HCS21_MAX_MESSAGE_BYTES=nc,exports.HCS21_PROTOCOL=oc,exports.HCS21_SAFE_MESSAGE_BYTES=sc,exports.HCS2BaseClient=uh,exports.HCS2Client=gh,exports.HCS2Operation=th,exports.HCS2RegistryType=rh,exports.HCS5BrowserClient=class extends Qp{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=Zp(e.metadataTopicId),r=eh({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(Kg){return{success:!1,error:String(Kg)}}}async createHashinal(e){try{const t=this.getSigner(),r={...e.inscriptionOptions,mode:"hashinal",waitForConfirmation:!0,network:this.network},i=await Fa(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(Kg){return{success:!1,error:String(Kg)}}}},exports.HCS5Client=class extends Qp{constructor(e){super(e),this.operatorId=i.AccountId.fromString(e.operatorId),this.operatorCtx=ee({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=Zp(e.metadataTopicId),r=eh({tokenId:e.tokenId,metadata:t}),i=await r.freezeWith(this.client);if(e.supplyKey){const t=new Q({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(Kg){const t=Kg;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 _a(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(Kg){const t=Kg;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 Fa(r,this.signer,t),o=i.inscription?.jsonTopicId||Ba(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 Fa(t,this.signer,r),o=i.inscription?.jsonTopicId||Ba(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===D.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=ee({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=G({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=M(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 Q({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(Kg){return{success:!1,error:String(Kg)}}}async inscribeAndMint(e){try{await this.ensureInitialized();const t={...e.inscriptionOptions,mode:"hashinal",waitForConfirmation:!0},r=await _a(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(Kg){return{success:!1,error:String(Kg)}}}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 _a({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(Kg){return{success:!1,error:String(Kg)}}}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 _a(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(Kg){return{success:!1,error:String(Kg)}}}},exports.HCS6Operation=O,exports.HCS6RegistryType=D,exports.HCS7BaseClient=Ja,exports.HCS7BrowserClient=class extends Ja{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:Ya(i)}}catch(t){return this.logger.error("Failed to submit HCS-7 browser message",t),{success:!1,error:String(t)}}}},exports.HCS7Client=class extends Ja{constructor(e){super(e),this.closed=!1,this.operatorCtx=ee({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=Xa({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=Za({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=Ua,exports.HCS7Operation=Ka,exports.HRLResolver=Du,exports.HTSParser=ca,exports.HashLinkResolver=Ep,exports.HashLinkScanner=kp,exports.HashLinksRegistry=bp,exports.Hcs10MemoType=Kd,exports.HederaHieroIssuer=Jp,exports.HederaMirrorNode=q,exports.HieroDidResolver=Lp,exports.InboundTopicType=ud,exports.InsufficientBalanceError=class extends Ch{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=Fh,exports.InvalidMessageFormatError=class extends Ch{constructor(e,t){super(e),this.messageData=t,this.name="InvalidMessageFormatError"}},exports.InvalidNumberFormatError=class extends Ch{constructor(e,t){super(`Invalid number format for ${t}: ${e}`),this.value=e,this.field=t,this.name="InvalidNumberFormatError"}},exports.InvalidTickFormatError=class extends Ch{constructor(e){super(`Invalid tick format: ${e}`),this.tick=e,this.name="InvalidTickFormatError"}},exports.IssuerRegistry=jp,exports.KeyType=J,exports.KeyTypeDetector=X,exports.Logger=P,exports.MAINNET_EXAMPLES=Ap,exports.MCPServerBuilder=class{constructor(){this.config={mcpServer:{}},this.socials=[],this.logger=P.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:ld.DNS,value:e,dns_field:t};return this.config.mcpServer.verification=r,this}addVerificationSignature(e){this.config.mcpServer||(this.config.mcpServer={});const t={type:ld.SIGNATURE,value:e};return this.config.mcpServer.verification=t,this}addVerificationChallenge(e){this.config.mcpServer||(this.config.mcpServer={});const t={type:ld.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=cd,exports.MCPServerConnectionInfoSchema=gd,exports.MCPServerDetailsSchema=wd,exports.MCPServerHostSchema=fd,exports.MCPServerProfileSchema=kd,exports.MCPServerResourceSchema=yd,exports.MCPServerToolSchema=bd,exports.MCPServerVerificationSchema=md,exports.MapCache=Qa,exports.MintLimitExceededError=class extends Ch{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=ju,exports.NodeHashAdapter=Mu,exports.NodeHmacAdapter=$u,exports.PayloadSizeError=$d,exports.PersonBuilder=class{constructor(){this.config={version:"1.0",type:0},this.logger=P.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=Td,exports.PointsBurnError=Nh,exports.PointsDeploymentError=xh,exports.PointsMintError=class extends Ch{constructor(e,t,r,i){super(e),this.tick=t,this.requestedAmount=r,this.availableSupply=i,this.name="PointsMintError"}},exports.PointsNotFoundError=class extends Ch{constructor(e){super(`Points with tick "${e}" not found`),this.tick=e,this.name="PointsNotFoundError"}},exports.PointsTransferError=Rh,exports.PointsValidationError=_h,exports.ProfileType=od,exports.ProgressReporter=cs,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=P.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=Cd,exports.RegistryBrokerClient=au,exports.RegistryBrokerError=nu,exports.RegistryBrokerParseError=su,exports.RegistryType=Jd,exports.ResolverRegistry=$p,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 z,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(Lu())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=ga,exports.SocialLinkSchema=pd,exports.StateHashError=ug,exports.SupplyLimitExceededError=class extends Ch{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=vp,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=Ph,exports.TransactionParser=Ta,exports.TransactionParsingError=ls,exports.VerificationType=ld,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=P.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=Sp,exports.WasmValidator=class{constructor(e){this.cryptoAdapter=Gu(),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(Lu())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 d=1;d<n.length;d++){const e=n[d].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 u=r.match(/functions:(\d+)/);u&&(l=parseInt(u[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=Wu,exports.WebHashAdapter=Bu,exports.WebHmacAdapter=Hu,exports.accountIdsToExemptKeys=ic,exports.actionRegistrationSchema=ip,exports.adapterConfigContextSchema=dc,exports.adapterDeclarationSchema=pc,exports.adapterManifestSchema=hc,exports.adapterPackageSchema=uc,exports.assemblyMessageSchema=lp,exports.assemblyRegistrationSchema=up,exports.baseMessageSchema=oh,exports.blockRegistrationSchema=op,exports.buildHcs10ConfirmConnectionTx=zd,exports.buildHcs10CreateConnectionTopicTx=_d,exports.buildHcs10CreateInboundTopicTx=Rd,exports.buildHcs10CreateOutboundTopicTx=Nd,exports.buildHcs10CreateRegistryTopicTx=Pd,exports.buildHcs10OutboundConnectionCreatedRecordTx=Dd,exports.buildHcs10OutboundConnectionRequestRecordTx=Od,exports.buildHcs10RegistryDeleteTx=function(e){const t={p:"hcs-10",op:"delete",uid:e.uid,m:e.memo};return V({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:xd(1,0)})},exports.buildHcs10RegistryMigrateTx=function(e){const t={p:"hcs-10",op:"migrate",t_id:e.targetTopicId,m:e.memo};return V({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:xd(2,0)})},exports.buildHcs10RegistryRegisterTx=Bd,exports.buildHcs10SendMessageTx=Md,exports.buildHcs10SubmitConnectionRequestTx=Fd,exports.buildHcs12AddActionToAssemblyTx=function(e){return V({topicId:e.assemblyTopicId,message:JSON.stringify(e.operation)})},exports.buildHcs12AddBlockToAssemblyTx=function(e){return V({topicId:e.assemblyTopicId,message:JSON.stringify(e.operation)})},exports.buildHcs12CreateRegistryTopicTx=function(e){var t;return W({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 V({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 V({topicId:e.topicId,message:t,transactionMemo:e.transactionMemo})},exports.buildHcs12UpdateAssemblyTx=function(e){return V({topicId:e.assemblyTopicId,message:JSON.stringify(e.operation)})},exports.buildHcs15BaseAccountCreateTx=Vh,exports.buildHcs15PetalAccountCreateTx=Gh,exports.buildHcs16CreateAccountTx=eg,exports.buildHcs16CreateFloraTopicTx=Qh,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=rg,exports.buildHcs16FloraJoinAcceptedTx=ag,exports.buildHcs16FloraJoinRequestTx=ng,exports.buildHcs16FloraJoinVoteTx=sg,exports.buildHcs16MessageTx=tg,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=og,exports.buildHcs16TransactionTx=ig,exports.buildHcs17CreateTopicTx=mg,exports.buildHcs17MessageTx=fg,exports.buildHcs18AnnounceMessage=Cg,exports.buildHcs18CompleteMessage=Ng,exports.buildHcs18CreateDiscoveryTopicTx=vg,exports.buildHcs18DiscoveryMemo=Eg,exports.buildHcs18ProposeMessage=xg,exports.buildHcs18RespondMessage=Rg,exports.buildHcs18SubmitDiscoveryMessageTx=Ag,exports.buildHcs18WithdrawMessage=_g,exports.buildHcs1Hrl=Zp,exports.buildHcs20BurnTx=Bh,exports.buildHcs20DeployTx=Oh,exports.buildHcs20MintTx=Dh,exports.buildHcs20RegisterTx=Kh,exports.buildHcs20SubmitMessageTx=function(e){const t="string"==typeof e.payload?e.payload:JSON.stringify(e.payload);return V({topicId:e.topicId,message:t,transactionMemo:e.transactionMemo})},exports.buildHcs20TransferTx=Mh,exports.buildHcs21CreateRegistryTx=$h,exports.buildHcs21MessageTx=Hh,exports.buildHcs21RegistryMemo=Lh,exports.buildHcs2CreateRegistryTx=dh,exports.buildHcs2DeleteTx=function(e){const t={p:"hcs-2",op:th.DELETE,uid:e.uid,m:e.memo};return V({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})},exports.buildHcs2MigrateTx=function(e){const t={p:"hcs-2",op:th.MIGRATE,t_id:e.targetTopicId,metadata:e.metadata,m:e.memo};return V({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})},exports.buildHcs2RegisterTx=ph,exports.buildHcs2UpdateTx=function(e){const t={p:"hcs-2",op:th.UPDATE,uid:e.uid,t_id:e.targetTopicId,metadata:e.metadata,m:e.memo};return V({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})},exports.buildHcs5MintTx=eh,exports.buildHcs5MintWithHrlTx=function(e){const t=Zp(e.metadataTopicId);return eh({tokenId:e.tokenId,metadata:t,transactionMemo:e.transactionMemo})},exports.buildHcs6CreateRegistryTx=G,exports.buildHcs6Hrl=M,exports.buildHcs6RegisterEntryTx=function(e){const t={p:"hcs-6",op:O.REGISTER,t_id:e.targetTopicId,m:e.memo};return V({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})},exports.buildHcs7CreateRegistryTx=Xa,exports.buildHcs7EvmMessageTx=function(e){const t={p:"hcs-7",op:Ka.REGISTER_CONFIG,t:Ua.EVM,c:{contractAddress:e.config.contractAddress,abi:e.config.abi},m:e.config.memo??""};return Za({topicId:e.topicId,message:t,transactionMemo:e.transactionMemo})},exports.buildHcs7SubmitMessageTx=Za,exports.buildHcs7WasmMessageTx=function(e){const t={p:"hcs-7",op:Ka.REGISTER_CONFIG,t:Ua.WASM,c:{wasmTopicId:e.config.wasmTopicId,inputType:e.config.inputType,outputType:e.config.outputType},m:e.config.memo??""};return Za({topicId:e.topicId,message:t,transactionMemo:e.transactionMemo})},exports.canonicalize=Wh,exports.canonicalizeAgentData=_p,exports.canonicalizeLedgerNetwork=ku,exports.capabilityNameToCapabilityMap=dd,exports.createLoggerAdapter=tc,exports.createPrivateKeySigner=vu,exports.createUaid=Mp,exports.defaultIssuerRegistry=Wp,exports.defaultResolverRegistry=Hp,exports.deleteMessageSchema=ah,exports.detectCryptoEnvironment=Uu,exports.detectKeyTypeFromString=Z,exports.ensureLoggerType=function(e){return rc(e)?e:tc(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=pg,exports.generateHCS6RegistryMemo=H,exports.generateQuote=Da,exports.getCryptoAdapter=Gu,exports.getExampleTopics=function(e){return"mainnet"===e?Ap:vp},exports.getHumanReadableTransactionType=Ia,exports.getOrCreateSDK=va,exports.getParserConfig=function(e){return ma[e]},exports.getSchedulableTransactionType=function(e){for(const[t,r]of Object.entries(ba))if(e[t])return r;return"unknown"},exports.getSupportedTransactionTypes=function(){return Object.keys(ma)},exports.getTopicId=Ba,exports.getTransactionTypeFromBody=wa,exports.hash=async function(e,t="sha256"){const r=Gu().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=dp,exports.hcs17MessageSchema=lg,exports.hcs2MessageSchema=lh,exports.hcs6BaseMessageSchema=K,exports.hcs6MessageSchema=L,exports.hcs6RegisterMessageSchema=U,exports.hcs6TopicIdSchema=B,exports.hcs7MessageSchema=Ga,exports.humanReadableTypeRegistry=ya,exports.inscribe=_a,exports.inscribeWithSigner=Fa,exports.isAnnounceMessage=function(e){if(!Tg(e))return!1;const t=e;if("announce"!==t.op)return!1;if(!bg(t.data))return!1;const r=t.data;if(!wg(r.account))return!1;if(!bg(r.petal))return!1;const i=r.petal;return!(!wg(i.name)||!Ig(i.priority))&&(!!bg(r.capabilities)&&(!!function(e){return Array.isArray(e)&&e.every(wg)}(r.capabilities.protocols)&&!("valid_for"in r&&void 0!==r.valid_for&&null!==r.valid_for&&!Ig(r.valid_for))))},exports.isBrowser=Sa,exports.isCompleteMessage=function(e){if(!Tg(e))return!1;const t=e;if("complete"!==t.op)return!1;if(!bg(t.data))return!1;const r=t.data;if(!wg(r.proposer))return!1;if(!Ig(r.proposal_seq))return!1;if(!wg(r.flora_account))return!1;if(!bg(r.topics))return!1;const i=r.topics;return!!(wg(i.communication)&&wg(i.transaction)&&wg(i.state))},exports.isConcreteLogger=rc,exports.isCryptoAvailable=function(){return"none"!==Uu().preferredAPI},exports.isDiscoveryMessage=Tg,exports.isEip155Caip10=rd,exports.isHederaCaip10=Zu,exports.isHederaNetwork=Yu,exports.isPartialRegisterAgentResponse=e=>"partial"===e.status&&!1===e.success,exports.isPendingRegisterAgentResponse=e=>"pending"===e.status,exports.isProposeMessage=function(e){if(!Tg(e))return!1;const t=e;if("propose"!==t.op)return!1;if(!bg(t.data))return!1;const r=t.data;if(!wg(r.proposer))return!1;if(!function(e){return Array.isArray(e)}(r.members))return!1;if(!r.members.every(e=>{if(!bg(e))return!1;const t=e;return!!wg(t.account)&&(!(!("priority"in t)||!Ig(t.priority))&&!("announce_seq"in t&&void 0!==t.announce_seq&&null!==t.announce_seq&&!Ig(t.announce_seq)))}))return!1;if(!bg(r.config))return!1;const i=r.config;return!(!wg(i.name)||!Ig(i.threshold))},exports.isRespondMessage=function(e){if(!Tg(e))return!1;const t=e;if("respond"!==t.op)return!1;if(!bg(t.data))return!1;const r=t.data;return!!wg(r.responder)&&(!!Ig(r.proposal_seq)&&(!!wg(r.decision)&&!!["accept","reject"].includes(r.decision)))},exports.isSSREnvironment=Lu,exports.isSuccessRegisterAgentResponse=e=>!0===e.success&&"pending"!==e.status,exports.isTransactionTypeSupported=function(e){return e in ma},exports.isWithdrawMessage=function(e){if(!Tg(e))return!1;const t=e;if("withdraw"!==t.op)return!1;if(!bg(t.data))return!1;const r=t.data;return!!wg(r.account)&&(!!Ig(r.announce_seq)&&!("reason"in r&&void 0!==r.reason&&null!==r.reason&&!wg(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=mc,exports.migrateMessageSchema=ch,exports.normalizeTransactionId=Ca,exports.parseHCS17Memo=hg,exports.parseHcs14Did=Bp,exports.parseHederaCaip10=ed,exports.protoFieldToTypeRegistry=fa,exports.registerDefaultResolvers=qp,exports.registerMessageSchema=nh,exports.registryMetadataSchema=gc,exports.resolveTransactionSummary=oa,exports.retrieveInscription=za,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=ba,exports.setLoggerFactory=function(e){_=e,P.clearInstances()},exports.shouldUseReference=function(e){return("string"==typeof e?globalThis.Buffer.byteLength(e,"utf8"):e.length)>51200},exports.sleep=F,exports.toEip155Caip10=id,exports.toHederaCaip10=Qu,exports.topicIdSchema=ih,exports.transactionParserRegistry=ma,exports.transactionSummaryRegistry=ia,exports.updateMessageSchema=sh,exports.validateActionRegistration=pp,exports.validateAssemblyMessage=hp,exports.validateAssemblyRegistration=function(e){return up.parse(e)},exports.validateBlockRegistration=function(e){return op.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&&$(i)},exports.validateHCS6TTL=$,exports.validateHashLinksRegistration=function(e){return dp.parse(e)},exports.validateWithSchema=gp,exports.verifyArtifactDigest=function(e,t){const r=p.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=Wh(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=Wh(e),n=globalThis.Buffer.from(t,"base64");return i.PublicKey.fromString(r).verify(globalThis.Buffer.from(o,"utf8"),n)}catch{return!1}},exports.waitForInscriptionConfirmation=Ma;
11
11
  //# sourceMappingURL=standards-sdk.cjs.map